Skip to content

fix(terminal): harden macOS login-preflight spawn path (#9301 follow-ups) - #9606

Merged
brennanb2025 merged 3 commits into
mainfrom
brennanb2025/agent-slack-followups
Jul 20, 2026
Merged

brennanb2025 merged 3 commits into
mainfrom
brennanb2025/agent-slack-followups

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Follow-ups to the two-pass review on #9301 (fix(terminal): bypass rejected macOS login sessions). I re-derived each finding's severity from the code rather than trusting the review labels. None are release blockers; these are low-likelihood robustness, observability, and bounded-work fixes.

What's fixed

F1 — transient probe failures recover without taxing every spawn (macos-tcc-login-shell.ts)
The probe returns {ok, conclusive, reason}. Only a conclusive PAM verdict caches permanently. A probe killed by our SIGKILL timeout / ETIMEDOUT / maxBuffer is inconclusive: it fails open to a direct shell, then retries with 5-second exponential backoff capped at 5 minutes. This preserves self-healing without adding a 500 ms wait and a login(1) subprocess to every terminal spawn when the environmental failure persists.

F2 — degrade is diagnosable (daemon-entry.ts)
prepareMacosTccLoginShell() returns the outcome; the daemon emits a structured macos-login-preflight {ok, reason} log on degrade, since detached daemons destroy stderr and lose the console.warn.

F3 — concurrent same-session-id spawn is coalesced before process launch (local-pty-provider.ts)
After the only async preparation boundary, the loser re-checks the stable session ID and attaches to the winner before calling node-pty. This avoids both an orphan and the prior follow-up's redundant spawn-then-kill subprocess. The winning PTY receives the later request's resize and retains its native/WSL metadata.

F4 — pending daemon preparation follows connection ownership (daemon-server.ts)
Preparations carry their clientId; control- or stream-socket loss cancels only that client's pending work. Reconnect handoff also cancels the old owner's preparation synchronously, covering the same-ID socket-replacement path where the stale close handler intentionally does nothing. Other clients' preparations are unaffected.

F7
Warm the PAM probe at daemon startup (mirrors warmPwshAvailabilityCache); document the pipe-vs-PTY probe fidelity limit; preserve SessionNotFoundError when kill has no pending preparation.

Deliberately not fixed

  • F5 (orphan sweep misses in-flight spawns): self-limits to the next reload, and a complete fix needs generation ownership for in-flight local work.
  • F6 (hibernated v22 wake bypasses v23 preflight): inherent to legacy attach; self-heals once daemons are v23.
  • F7 error-name unification: cosmetic cross-layer churn.

Reliability and performance contract

  • Invariant: a fresh terminal reaches the configured shell; a rejected/hung PAM probe never strands the PTY at login:. One stable local session ID owns at most one native PTY, and a disconnected/replaced daemon client cannot create a later orphan.
  • Failure sources: transient or persistent PAM timeout, concurrent same-ID local spawn, control- or stream-socket loss during preparation, and same-client-ID reconnect before the stale close event.
  • Oracle: deterministic tests count execFile, node-pty spawn, resize, and daemon subprocess calls. Persistent failures attempt at t=0, 5s, and 15s rather than every spawn; two concurrent local requests produce one native spawn; a lost owner's control or stream socket and reconnect replacement produce zero subprocesses after ownership cancellation, while unrelated clients continue.
  • Gate: focused provider/daemon unit coverage is the deterministic gate. The existing real macOS Electron run covers the healthy spawn/reattach path; live PAM-timeout and socket-replacement fault injection remain accepted gaps.
  • Provider/platform coverage: macOS local and daemon paths are covered. The stable-ID coalescing path is platform-neutral and retains Windows/WSL metadata semantics. SSH/remote and mobile/relay do not execute this local/daemon preflight path and are unaffected.
  • Diagnostics: detached-daemon degradation is recorded as structured metadata without PAM output or account details.
  • Performance budget: no polling, timers, global session inventories, or provider fanout were added. Retry state is O(1), probes remain in-flight deduplicated, retry frequency is exponentially bounded, and concurrent same-ID requests now launch one native process instead of two.

Tests

  • 139/139 focused tests across macOS preflight, local PTY, daemon server, and client ownership suites.
  • 11 adjacent terminal/daemon/provider suites passed, including session teardown, terminal host, daemon adapter respawn/reattach, subprocess, entry/main, and IPC.
  • pnpm run typecheck:node passed.
  • Changed-file oxlint, React Doctor lint, oxfmt, and git diff --check passed.
  • Existing Electron dev-build macOS happy-path evidence is attached below.

…ups)

Follow-ups to the #9301 two-pass review. Re-derived severities: none are
release blockers; these are low-likelihood robustness/observability fixes.

F1 macos-tcc-login-shell: only cache a conclusive PAM verdict. A probe our
own SIGKILL timeout / ETIMEDOUT / maxBuffer killed proves nothing about PAM,
so it no longer sticks the whole process into direct-spawn — it fails open
for that spawn, re-probes next time, and self-heals once PAM answers.

F2 daemon-entry: prepareMacosTccLoginShell returns the outcome; the daemon
emits a structured macos-login-preflight {ok, reason} log on degrade, since
detached daemons destroy stderr and lose the console.warn.

F3 local-pty-provider: an atomic guard before the tracking write coalesces a
concurrent same-session-id spawn onto the winner instead of orphaning an
untracked, unkillable PTY.

F4 daemon-server: preparations carry their clientId; a control-socket close
cancels only that client's pending preps, so a mid-preflight disconnect no
longer leaves a durable orphan daemon PTY.

F7 warm the PAM probe at daemon startup (mirrors warmPwshAvailabilityCache);
note the pipe-vs-PTY probe fidelity limit; test that kill with no pending
prep still surfaces SessionNotFoundError.

Deliberately skipped F5 (self-limits to next reload; a real fix needs
speculative in-flight-generation tracking) and F6 (inherent to legacy
v22 attach; self-heals once daemons are v23).
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Manual verification (Electron dev build, macOS)

Launched this branch's dev build (tigerfish @ brennanb2025/agent-slack-followups) via the electron skill (CDP-attached), added this repo, activated the worktree, and drove real terminals. Goal: confirm the happy path my changes touch — macOS shells spawn wrapped in /usr/bin/login (the login-preflight path) — still works and that F1/F3 don't regress normal spawn/reattach.

What was exercised through the real UI:

1. Fresh spawn #1 — live shell, no Login incorrect / login:. The preflight hit the conclusive-accept path (F1), the wrapper produced a working interactive zsh. Typed a command; it executed (ORCA-PTY-LIVE-MARKER / done). The dropped leading w in hoami is my automation's first-keystroke-before-focus race, not a product issue — the shell clearly received and ran the rest.

Terminal 1 fresh spawn, live

2. Fresh spawn #2 — second new terminal tab, also live (SECOND-TERMINAL-LIVE + pwd). A second independent fresh spawn through the same preflight/wrapper path.

Terminal 2 fresh spawn, live

3. Reattach — switched back to Terminal 1; history preserved, no respawn. Exercises the existing-PTY reattach early-return (the path the F3 guard sits just past).

Terminal 1 reattach, history preserved

Coverage honesty

The four behavioral fixes are edge cases not reachable through normal UI — a transient 500 ms probe timeout (F1), the daemon degrade log (F2), a concurrent same-session-id spawn race (F3), and a mid-preflight control-socket disconnect (F4). Those are covered by the added unit tests (137/137), not by this manual run. What the manual run proves is that the common spawn + reattach path is intact on macOS after these changes — i.e. no regression to the thing #9301 originally fixed.

@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The macOS login preflight now returns structured outcomes, caches conclusive results, and applies retry backoff to transient failures. Daemon PTY preparations are associated with client IDs and canceled on reconnects or socket closures. Daemon startup and PTY preparation use a shared preflight wrapper with failure logging. Local PTY spawning now reattaches to PTYs created by concurrent requests, preserving mappings and applying requested resizing. Tests cover preflight caching, recovery, cancellation, replacement clients, and concurrent PTY launches.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed but omits required Screenshots, AI Review Report, Security Audit, and Notes sections from the template. Add the missing template sections, including screenshots or no visual change, an AI review with cross-platform checks, a security audit, and platform-specific notes.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title is concise and accurately summarizes the main change: hardening the macOS login-preflight spawn path.
✨ 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.

🧹 Nitpick comments (1)
src/main/daemon/daemon-preflight-client-replacement.test.ts (1)

55-61: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Prevent test hangs by handling socket errors.

Awaiting socket.once without an error handler can cause the test to hang indefinitely (until the test runner times out) if the socket emits an error, such as if the server fails to listen or unexpectedly drops the connection. Consider rejecting the promises on error to ensure a fast, transparent test failure.

💡 Proposed refactor to add error listeners
-      await new Promise<void>((resolve) => socket.once('connect', resolve))
+      await new Promise<void>((resolve, reject) => {
+        socket.once('connect', resolve)
+        socket.once('error', reject)
+      })
       socket.write(
         encodeNdjson({ type: 'hello', version: PROTOCOL_VERSION, token, clientId, role })
       )
-      await new Promise<void>((resolve) => socket.once('data', () => resolve()))
+      await new Promise<void>((resolve, reject) => {
+        socket.once('data', () => resolve())
+        socket.once('error', reject)
+      })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: e097517b-a0bb-496f-a07c-68d5527d53cd

📥 Commits

Reviewing files that changed from the base of the PR and between 675604c and 565477c.

📒 Files selected for processing (2)
  • src/main/daemon/daemon-preflight-client-replacement.test.ts
  • src/main/daemon/daemon-server.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/daemon/daemon-server.ts

@brennanb2025
brennanb2025 merged commit 51aab1c into main Jul 20, 2026
8 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…follow-ups) (stablyai#9606)

* fix(terminal): harden macOS login-preflight spawn path (stablyai#9301 follow-ups)

Follow-ups to the stablyai#9301 two-pass review. Re-derived severities: none are
release blockers; these are low-likelihood robustness/observability fixes.

F1 macos-tcc-login-shell: only cache a conclusive PAM verdict. A probe our
own SIGKILL timeout / ETIMEDOUT / maxBuffer killed proves nothing about PAM,
so it no longer sticks the whole process into direct-spawn — it fails open
for that spawn, re-probes next time, and self-heals once PAM answers.

F2 daemon-entry: prepareMacosTccLoginShell returns the outcome; the daemon
emits a structured macos-login-preflight {ok, reason} log on degrade, since
detached daemons destroy stderr and lose the console.warn.

F3 local-pty-provider: an atomic guard before the tracking write coalesces a
concurrent same-session-id spawn onto the winner instead of orphaning an
untracked, unkillable PTY.

F4 daemon-server: preparations carry their clientId; a control-socket close
cancels only that client's pending preps, so a mid-preflight disconnect no
longer leaves a durable orphan daemon PTY.

F7 warm the PAM probe at daemon startup (mirrors warmPwshAvailabilityCache);
note the pipe-vs-PTY probe fidelity limit; test that kill with no pending
prep still surfaces SessionNotFoundError.

Deliberately skipped F5 (self-limits to next reload; a real fix needs
speculative in-flight-generation tracking) and F6 (inherent to legacy
v22 attach; self-heals once daemons are v23).

* fix(terminal): bound preflight recovery work

* fix(terminal): cancel preflight when daemon stream closes
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