Skip to content

fix(computer): reap mac helper after client loss - #11425

Merged
nwparker merged 1 commit into
mainfrom
nwparker/computer-helper-session-lifecycle
Jul 29, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/computer-helper-session-lifecycle

Conversation

@nwparker

Copy link
Copy Markdown
Contributor

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 terminate request, but an unexpected sidecar exit only closed the socket; the helper stayed alive and the parent-owned orca-computer-use-* directory could be stranded.

The helper now treats a successfully authenticated socket as a live owner session:

  • the first authenticated request claims the helper session;
  • the helper terminates when the final authenticated connection closes;
  • unauthenticated or malformed connections cannot claim or retain it;
  • a helper that never receives an authenticated request exits after a 30-second startup deadline.

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

AgentSessionOwnership is 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:

  • a connection only registers after the existing token and peer-process checks both pass;
  • the helper still rejects invalid tokens and unauthorized peers through the existing response path;
  • multiple authenticated connections keep the helper alive until the last one closes;
  • clean shutdown still accepts the existing explicit terminate request;
  • the helper still does not unlink caller-supplied socket or token paths; the JavaScript owner retains directory cleanup authority;
  • permission/setup modes are unchanged because the deadline is scoped to --agent mode.

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 finally blocks 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:

  1. move macOS helper and Linux/Windows bridge spawn, deadlines, reap, and private temporary-directory ownership into a domain-specific main-process supervisor;
  2. fault-inject coordinator death at each provider lifecycle phase;
  3. convert the coordinator only after those descendant checks pass;
  4. measure packaged idle, peak, retained, and restart memory.

Testing

  • swift test --package-path native/computer-use-macos — 42 tests passed
  • pnpm build:computer-macos — release helper and app bundle built
  • pnpm verify:computer-native — Swift suite, native guardrails, helper bundle, and signature passed
  • pnpm lint — static analysis, reliability gates, max-lines ratchet, and repository verifiers passed
  • git diff --check
  • Real release-helper backstop: an unclaimed --agent process exited cleanly after 31.8 seconds with the expected deadline diagnostic

New 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:

  • unauthorized connections canceling the startup deadline or keeping the helper alive;
  • one connection terminating the helper while another authenticated connection remains;
  • file-descriptor reuse racing ownership cleanup;
  • malformed input claiming a session;
  • clean terminate behavior changing;
  • the deadline affecting permission windows or other helper modes;
  • helper-side deletion of caller-controlled paths;
  • macOS-only behavior leaking into Linux, Windows, WSL, SSH, git-worktree, or folder-workspace paths.

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

  • No authentication, token generation, socket permissions, TCC identity, executable path, network surface, dependency, or command execution changed.
  • Session ownership is recorded only after the existing token and trusted-peer checks pass.
  • Invalid tokens and unauthorized peers cannot cancel the startup backstop.
  • The helper continues to avoid unlinking caller-supplied paths.
  • The change narrows lifetime after authority loss; it does not grant new authority.

Screenshots

No UI change.

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The macOS agent now tracks authenticated socket connections through AgentSessionOwnership. SocketListener validates tokens and authorized peers, registers and disconnects connections under synchronization, and triggers session claim or close callbacks. AgentRuntime adds an unclaimed-session deadline, cancels it after authentication, and terminates when the claimed session closes. XCTest coverage validates ownership and disconnection behavior.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: reaping the macOS helper after client loss.
Description check ✅ Passed The description covers the required sections with summary, testing, review, security, and screenshots; Notes is the only minor omission.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 493f403 and 2faa6ba.

📒 Files selected for processing (3)
  • native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift
  • native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/AgentSessionOwnership.swift
  • native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AgentSessionOwnershipTests.swift

Comment on lines +3623 to +3625
private func isAuthenticated(request: Request, authorizedPeer: Bool) -> Bool {
guard let token else { return true }
return request.token == token && authorizedPeer

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 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.

Suggested change
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

Comment on lines +3603 to +3611
sessionLock.lock()
let claimed = sessionOwnership.registerConnection(
fd,
authenticated: isAuthenticated(request: request, authorizedPeer: authorizedPeer)
)
sessionLock.unlock()
if claimed {
onSessionClaimed()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

Comment on lines 3585 to +3594
private func handleConnection(_ fd: Int32) {
defer { close(fd) }
defer {
sessionLock.lock()
let shouldTerminate = sessionOwnership.disconnect(fd)
sessionLock.unlock()
close(fd)
if shouldTerminate {
onSessionClosed()
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

Comment on lines +7 to +13
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
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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-apps

greptile-apps Bot commented Jul 29, 2026

Copy link
Copy Markdown

Greptile Summary

This PR teaches the macOS computer-use helper to self-reap after its JavaScript socket owner disappears. It introduces AgentSessionOwnership, a small state machine that tracks authenticated socket connections, and wires it into SocketListener so the helper terminates when the last authenticated connection closes. A 30-second startup deadline kills the helper if no authenticated session is ever established.

  • AgentSessionOwnership records the first authenticated FD as the session claim and returns true from disconnect only when wasClaimed and the authenticated set is empty; FD-reuse safety is preserved by removing from the set before closing the descriptor.
  • AgentRuntime schedules the unclaimed-session DispatchWorkItem on the main queue and cancels it via onSessionClaimed; both cancel and execution are serialized on the main queue, eliminating the cancellation race.
  • There is a subtle edge case: after onSessionClosed queues the first NSApp.terminate, newly accepted connections (arriving before stop() sets isStopped) that authenticate will still be inserted into authenticatedConnections (even though registerConnection returns false), and their disconnect will trigger a second onSessionClosed — harmless in AppKit but worth hardening in registerConnection.

Confidence Score: 4/5

Safe 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.

Important Files Changed

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
Loading

Reviews (1): Last reviewed commit: "fix(computer): reap mac helper after cli..." | Re-trigger Greptile

@nwparker
nwparker merged commit 0349cb6 into main Jul 29, 2026
32 checks passed
@nwparker
nwparker deleted the nwparker/computer-helper-session-lifecycle branch July 29, 2026 23:17
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant