Repository navigation
fix(terminal): harden macOS login-preflight spawn path (#9301 follow-ups) - #9606
Conversation
…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).
Manual verification (Electron dev build, macOS)Launched this branch's dev build ( What was exercised through the real UI: 1. Fresh spawn #1 — live shell, no 2. Fresh spawn #2 — second new terminal tab, also 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). Coverage honestyThe 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. |
📝 WalkthroughWalkthroughThe 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)
✅ Passed checks (3 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.
🧹 Nitpick comments (1)
src/main/daemon/daemon-preflight-client-replacement.test.ts (1)
55-61: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valuePrevent test hangs by handling socket errors.
Awaiting
socket.oncewithout 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
📒 Files selected for processing (2)
src/main/daemon/daemon-preflight-client-replacement.test.tssrc/main/daemon/daemon-server.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/daemon/daemon-server.ts
…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



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 alogin(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 structuredmacos-login-preflight {ok, reason}log on degrade, since detached daemons destroy stderr and lose theconsole.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; preserveSessionNotFoundErrorwhenkillhas no pending preparation.Deliberately not fixed
Reliability and performance contract
login:. One stable local session ID owns at most one native PTY, and a disconnected/replaced daemon client cannot create a later orphan.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.Tests
pnpm run typecheck:nodepassed.git diff --checkpassed.