Repository navigation
fix(computer): reap mac helper after client loss - #11425
Conversation
📝 WalkthroughWalkthroughThe macOS agent now tracks authenticated socket connections through 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 1d50e2c6-dff4-431f-93d4-ede28462aabb
📒 Files selected for processing (3)
native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swiftnative/computer-use-macos/Sources/OrcaComputerUseMacOSCore/AgentSessionOwnership.swiftnative/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AgentSessionOwnershipTests.swift
| private func isAuthenticated(request: Request, authorizedPeer: Bool) -> Bool { | ||
| guard let token else { return true } | ||
| return request.token == token && authorizedPeer |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Require an authorized peer in tokenless mode.
Line 3624 returns true without checking authorizedPeer. Any process able to connect can therefore send a decodable request, claim ownership, cancel the deadline, and affect helper lifecycle when no token is configured.
Proposed fix
private func isAuthenticated(request: Request, authorizedPeer: Bool) -> Bool {
+ guard authorizedPeer else { return false }
guard let token else { return true }
- return request.token == token && authorizedPeer
+ return request.token == token
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| private func isAuthenticated(request: Request, authorizedPeer: Bool) -> Bool { | |
| guard let token else { return true } | |
| return request.token == token && authorizedPeer | |
| private func isAuthenticated(request: Request, authorizedPeer: Bool) -> Bool { | |
| guard authorizedPeer else { return false } | |
| guard let token else { return true } | |
| return request.token == token |
| sessionLock.lock() | ||
| let claimed = sessionOwnership.registerConnection( | ||
| fd, | ||
| authenticated: isAuthenticated(request: request, authorizedPeer: authorizedPeer) | ||
| ) | ||
| sessionLock.unlock() | ||
| if claimed { | ||
| onSessionClaimed() | ||
| } |
There was a problem hiding this comment.
Redundant lock acquisition on every request per connection
registerConnection is called inside the while let line loop, so it runs for every inbound request on an already-registered connection. After the first authenticated request inserts the FD, subsequent calls hit authenticatedConnections.insert(fd), get inserted = false, and return early — but they still acquire sessionLock, perform the set operation, and release the lock on every message. A connection-level var hasClaimed = false flag would let the call-site skip the lock entirely for subsequent requests on the same FD, keeping the hot path lock-free.
| private func handleConnection(_ fd: Int32) { | ||
| defer { close(fd) } | ||
| defer { | ||
| sessionLock.lock() | ||
| let shouldTerminate = sessionOwnership.disconnect(fd) | ||
| sessionLock.unlock() | ||
| close(fd) | ||
| if shouldTerminate { | ||
| onSessionClosed() | ||
| } | ||
| } |
There was a problem hiding this comment.
onSessionClosed can fire redundantly during the termination window
Between the moment the last authenticated connection closes (triggering onSessionClosed → async NSApp.terminate) and the moment applicationWillTerminate runs and calls stop(), the accept loop on its background thread can still accept new connections. If any such connection authenticates (registerConnection inserts the FD into authenticatedConnections even when wasClaimed = true), it will be tracked. When it eventually disconnects, disconnect sees wasClaimed && isEmpty → true and invokes onSessionClosed a second time, queuing another NSApp.terminate(nil). AppKit handles repeated terminate calls safely, so this has no observable failure, but the redundant callbacks are a side-effect of the accept loop not being stopped before the first onSessionClosed returns.
| public mutating func registerConnection(_ connection: Int32, authenticated: Bool) -> Bool { | ||
| guard authenticated else { return false } | ||
| let inserted = authenticatedConnections.insert(connection).inserted | ||
| guard inserted, !wasClaimed else { return false } | ||
| wasClaimed = true | ||
| return true | ||
| } |
There was a problem hiding this comment.
Post-
wasClaimed connections are inserted but semantically unowned
When wasClaimed is already true (session was previously claimed and closed), a new authenticated connection will still be inserted into authenticatedConnections (the insert succeeds), even though registerConnection returns false and onSessionClaimed is never fired. The consequence is that this late-arriving FD will cause disconnect to return true when it closes (if it happens to be the last entry), triggering another onSessionClosed. This is the root of the termination-window race noted on main.swift. Inserting the FD only when !wasClaimed (or guard !wasClaimed before the insert) would prevent tracking connections that arrive after ownership has already been relinquished.
Greptile SummaryThis PR teaches the macOS computer-use helper to self-reap after its JavaScript socket owner disappears. It introduces
Confidence Score: 4/5Safe to merge; the authentication boundary and FD-reuse protection are correct, and all findings are non-blocking edge cases. The core state machine logic is sound — registerConnection and disconnect are correctly lock-protected, the FD is removed from the set before being closed (preventing descriptor-reuse from evicting a newer session), and the deadline cancellation is correctly serialized on the main queue. The one structural concern is that registerConnection still inserts the FD into authenticatedConnections when wasClaimed is already true, which means connections accepted in the brief window between the first onSessionClosed dispatch and stop() setting isStopped can cause redundant onSessionClosed callbacks. These extra NSApp.terminate calls are benign in AppKit but represent an unintended code path. Files Needing Attention: AgentSessionOwnership.swift — the registerConnection guard ordering means post-termination connections are still tracked; worth a follow-up guard on !wasClaimed before the insert.
|
| Filename | Overview |
|---|---|
| native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/AgentSessionOwnership.swift | New state machine tracking authenticated socket connections; logic is correct for the common case but inserts post-wasClaimed FDs into the set, enabling redundant onSessionClosed callbacks in a short termination window. |
| native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift | Wires up the 30-second unclaimed-session deadline and session-closed callbacks correctly; minor redundancy in per-request registerConnection calls and a small window where new connections can be accepted between first onSessionClosed and stop() being invoked. |
| native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AgentSessionOwnershipTests.swift | Good unit test coverage for the new state machine: unclaimed disconnect, unauthenticated connection, single authenticated disconnect, multi-connection drain, and duplicate registration are all covered. |
Sequence Diagram
sequenceDiagram
participant JS as JS Sidecar
participant AR as AgentRuntime
participant SL as SocketListener
participant ASO as AgentSessionOwnership
participant MQ as Main Queue
AR->>MQ: asyncAfter(30s, timeout)
AR->>SL: start()
SL->>SL: acceptLoop()
JS->>SL: "connect (fd=12)"
SL->>SL: "handleConnection(fd=12)"
SL->>SL: check authorizedPeer
JS->>SL: send request (valid token)
SL->>ASO: registerConnection(12, authenticated: true)
ASO-->>SL: true (first claim)
SL->>MQ: "async { timeout.cancel() }"
MQ->>MQ: timeout.cancel()
JS->>SL: send more requests
SL->>ASO: registerConnection(12, authenticated: true)
ASO-->>SL: false (already inserted)
JS->>SL: disconnect (EOF)
SL->>ASO: disconnect(12)
ASO-->>SL: true (last auth connection)
SL->>SL: "close(fd=12)"
SL->>MQ: "async { NSApp.terminate(nil) }"
MQ->>AR: applicationWillTerminate
AR->>AR: unclaimedSessionTimeout?.cancel()
AR->>SL: stop()
SL->>SL: "isStopped=true, close(socketFd)"
note over SL: accept loop exits on next iteration
alt Unclaimed session (no JS connection in 30s)
MQ->>MQ: timeout fires → NSApp.terminate(nil)
MQ->>AR: applicationWillTerminate
AR->>SL: stop()
end
Reviews (1): Last reviewed commit: "fix(computer): reap mac helper after cli..." | Re-trigger Greptile
Summary
This is the first lifecycle prerequisite for moving the computer-use coordinator from an always-on Electron-as-Node child to a worker thread.
The detached macOS computer-use helper previously kept accepting connections indefinitely when its JavaScript socket owner disappeared. Graceful sidecar shutdown sent an explicit
terminaterequest, but an unexpected sidecar exit only closed the socket; the helper stayed alive and the parent-ownedorca-computer-use-*directory could be stranded.The helper now treats a successfully authenticated socket as a live owner session:
This reduces current orphan risk and establishes the self-reaping half of the lifecycle contract needed by a future worker migration. It does not convert the sidecar yet; Python/PowerShell operation supervision and parent-owned temporary-directory cleanup remain separate prerequisite work.
Lifecycle and failure contract
AgentSessionOwnershipis a small testable state machine in the native core target. The socket listener serializes access with its own lock and removes a connection from ownership before closing the file descriptor, preventing descriptor reuse from removing a newer session.The existing security and cleanup boundaries are preserved:
terminaterequest;--agentmode.The 30-second unclaimed-session deadline is intentionally longer than the JavaScript client's 10-second connection deadline. It is a failure backstop, not a normal startup race winner.
Why this precedes the worker conversion
Terminating a worker does not run its provider
finallyblocks and does not automatically terminate external processes. The computer-use coordinator cannot safely move until every external descendant has an owner outside the disposable worker or a self-reaping contract.This PR handles macOS socket-owner disappearance. Follow-up PRs will:
Testing
swift test --package-path native/computer-use-macos— 42 tests passedpnpm build:computer-macos— release helper and app bundle builtpnpm verify:computer-native— Swift suite, native guardrails, helper bundle, and signature passedpnpm lint— static analysis, reliability gates, max-lines ratchet, and repository verifiers passedgit diff --check--agentprocess exited cleanly after 31.8 seconds with the expected deadline diagnosticNew tests cover unauthenticated disconnects, unclaimed disconnects, the final authenticated disconnect, multiple authenticated connections, and duplicate registration.
The full authenticated socket flow retains its LaunchServices/bundle-identity check and remains covered by the permission-bearing macOS computer-use e2e lane; the security check was not relaxed for a headless test harness.
AI Review Report
The review traced the change from native agent startup through peer/token authentication, request dispatch, socket EOF, application termination, and caller-owned path cleanup.
Checked risks:
terminatebehavior changing;No unresolved correctness or maintainability findings remain within this prerequisite's scope. A native provider call that itself never returns still requires the planned main-process supervisor; this PR does not claim that broader gate is complete.
Security Audit
Screenshots
No UI change.