Repository navigation
fix(daemon): retire macOS daemons whose login session died (#7936) - #9826
Conversation
A daemon that survives a full macOS logout is unsalvageable: its PAM context can no longer host login(1) spawns (every new PTY becomes a 'Login incorrect' prompt zombie) and its Mach bootstrap namespace has lost the system DNS resolver, so terminals it hosts have no egress. Today it also keeps the #9301 preflight's cached 'accepted' verdict, so it keeps wrapping spawns in login(1) forever; only a manual daemon restart recovers. GUI-spawned daemons now watch for login-session death from the inside: a fresh cache-bypassing PAM probe (triggered by PTY-exit bursts, fresh client hellos, and a slow periodic timer) must conclusively reject three consecutive times AND the in-process system resolver must be degraded; then the daemon exits crash-style so session meta stays unclean and the replacement daemon cold-restores scrollback. A conclusive rejection also flips the spawn-wrapper cache off immediately. Headless serve/SSH daemons never get the watch (they must survive their spawning session ending), and a session that never conclusively accepted login(1) never arms it — a PAM anomaly alone can't kill a healthy daemon (fast user switching keeps accepting, so switched-away sessions are preserved).
|
Warning Review limit reached
Next review available in: 5 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughAdds macOS login-session probes and a watchdog that schedules checks, tracks conclusive outcomes, verifies resolver health, and retires the daemon when required. PTY session reaping and authenticated client activity are forwarded to the watchdog. Daemon startup conditionally passes and parses 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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 |
…rdict file A dead macOS login session cannot be fabricated without root (PAM owns audit-session teardown), so live lifecycle QA drives the death watch's probe and resolver oracles from ORCA_E2E_LOGIN_SESSION_PROBE_FILE: 'alive' → accepted/healthy, 'dead' → rejected/unhealthy, anything else inconclusive — with compressed watch timing. Mirrors the existing ORCA_E2E_DAEMON_INIT_DELAY_MS seam; inert unless the env var is set.
Live Electron lifecycle QA — mocked dead session (reproduced + healed)A real dead login session needs root to fabricate, so QA drives the two oracles through the new Baseline — terminal on the watched daemon, working; watch armed at startup ( Mocked logout — verdict file flipped to Daemon pid 68634 exited 3s after the flip. No manual restart. Recovery — next App restart on the same profile — tabs restore against the healthy daemon and the shell works: Also observed, worth noting: between retirement and the next request/reply RPC, keystrokes into an existing pane are silently dropped (writes are fire-and-forget on the dead socket; only Unverified (needs a real dead session): that PAM's |
The conclusive-PAM-verdict trigger had one blind failure shape: login(1) hanging at the prompt past the probe bound (killed → inconclusive forever → the watch never fires). Three changes close it: - The death-watch probe gets its own 4s bound (the 500ms preflight bound exists for spawn-path latency, which doesn't apply off-path), so a slow-but-answering PAM stack isn't misread as a hang. - An inconclusive pipe probe escalates to a PTY-hosted probe via script(1) — a dead session's PAM stack may only misbehave under a real tty (the pipe-vs-PTY fidelity limit the preflight documents). - A streak of timeout-killed probes (which a live session never produces) is a second retirement trigger, at a higher threshold (5) and still gated on the degraded resolver, logged with a distinct cause so field logs discriminate the two paths. Every dead-session behavior — fast reject, prompt-then-EOF, or hang — now fires retirement; all inconclusive states still fail toward preserving the daemon.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/daemon/daemon-entry.ts (1)
143-167: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winStop the login-session watchdog on graceful shutdown to avoid a retirement race.
deathWatch.stop()is never called from the SIGTERM/SIGINTshutdown()path or fromonIdleShutdown. A scheduled/in-flight watchdog probe can still resolve and callonRetire()→process.exit(1)while a graceful shutdown is mid-flight (e.g. inside the 5sSHUTDOWN_TIMEOUT_MSwindow awaitingdaemon.shutdown()'s checkpoint/dispose logic), hard-killing the process before session checkpoints finish writing.runProbealready rechecksthis.stopped/this.retiredright after everyawait, so callingstop()is sufficient to safely cancel even an in-flight probe before it reachesonRetire. This is a real risk under the e2e timing overrides (rejectionRecheckMs: 500,periodicProbeMs: 2_000), which can retire within a couple of seconds.🛡️ Proposed fix
const shutdown = async (reason: string): Promise<void> => { // SIGTERM and SIGINT can both fire; guard against a double daemon.shutdown(). if (shuttingDown) { return } shuttingDown = true + deathWatch?.stop() daemonLog.log('shutdown', { reason })onIdleShutdown: () => { + deathWatch?.stop() shuttingDown = true daemonLog.log('shutdown', { reason: 'idle' }) daemonLog.close() process.exit(0) }Also applies to: 240-246
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: b9a1d4e2-82e8-4b9e-8ec2-4e0d9ef60be5
📒 Files selected for processing (12)
src/main/daemon/daemon-entry.test.tssrc/main/daemon/daemon-entry.tssrc/main/daemon/daemon-init.tssrc/main/daemon/daemon-main.tssrc/main/daemon/daemon-server.tssrc/main/daemon/macos-login-session-death-watch.test.tssrc/main/daemon/macos-login-session-death-watch.tssrc/main/daemon/terminal-host-options.tssrc/main/daemon/terminal-host.tssrc/main/index.tssrc/main/providers/macos-tcc-login-shell.test.tssrc/main/providers/macos-tcc-login-shell.ts
De-risking round: the trigger can no longer be defeated by any known dead-session behaviorThe residual risk was a single failure shape:
Coverage matrix now: fast conclusive reject → trigger 1; prompt-then-EOF (zero exit, no marker) → conclusive reject → trigger 1; hang under pipe but verdict under PTY → trigger 1 via escalation; hang under both → trigger 2. All inconclusive/ambiguous states still fail toward preserving the daemon, and both triggers require the armed baseline + degraded resolver. Live QA of the new trigger (same Electron rig, Deterministic coverage: 10 → 15 watch tests (timeout-streak retire, unarmed timeouts never count, conclusive verdicts reset the streak, resolver-healthy suppression with later re-verdict), 3 new probe tests (PTY escalation accept/reject, dual-timeout stays inconclusive). Full daemon suite: 1,004 passed. |
Real dead-session experiment (SSH-minted): a decisive negative with three useful conclusionsRan the staged experiment against a genuinely torn-down session: SSH to localhost minted a fresh audit session (asid 103920 vs the GUI's 100024), an orphaned probe survived its teardown (reparented to launchd), and for minutes afterward both PAM probes kept conclusively accepting and
Remaining validation is now passive: a 48h slow probe logger is parked in the GUI session on this dev machine; the next ordinary logout/login captures the real oracle transition (or proves orphans don't survive logout on this config — also decisive). Reporter's |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/daemon/daemon-entry.ts (1)
187-203: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftMake persistent
hangprobes eligible for retirement.Line 196 returns an inconclusive timeout, but
MacosLoginSessionDeathWatchonly reads resolver health after conclusive rejections; inconclusive outcomes merely reschedule. Therefore Lines 200-203 cannot retire a persistently hanging daemon. Add timeout-streak handling in the watch and test the thresholdedhangretirement path. This conflicts with the stated timeout-streak retirement objective.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: a331899a-bebe-4bd4-92e9-b75c280c60d8
📒 Files selected for processing (5)
src/main/daemon/daemon-entry.tssrc/main/daemon/macos-login-session-death-watch.test.tssrc/main/daemon/macos-login-session-death-watch.tssrc/main/providers/macos-tcc-login-shell.test.tssrc/main/providers/macos-tcc-login-shell.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/daemon/macos-login-session-death-watch.test.ts
- src/main/daemon/macos-login-session-death-watch.ts
|
Review follow-up pushed in
|
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/providers/macos-tcc-login-shell.ts (1)
215-227: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftSerialize cache-mutating probes to prevent stale results from re-enabling login wrapping.
probeMacosLoginSessionAlive()bypassesloginPreflightInFlight, whileloginPreflightSucceeds()may still have an earlier probe running. Both paths updatecachedLoginPreflightResult; an older accepted probe can therefore overwrite a newer conclusive rejection and causewrapShellSpawnForMacosTccAttribution()to keep creatinglogin:prompt zombies. Serialize these probes or guard cache updates with a monotonically increasing generation so only the newest result mutates shared state.
🧹 Nitpick comments (2)
src/main/providers/macos-login-session-pty-probe.ts (1)
4-11: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse Node path utilities for macOS binary paths.
Construct the binary paths with
path.posix.joinand interpolate those constants into the Expect script instead of hardcoding/separators.Proposed fix
+import { posix } from 'node:path' + -const MACOS_EXPECT_PATH = '/usr/bin/expect' +const MACOS_BIN_DIR = posix.join('/usr', 'bin') +const MACOS_EXPECT_PATH = posix.join(MACOS_BIN_DIR, 'expect') +const MACOS_LOGIN_PATH = posix.join(MACOS_BIN_DIR, 'login') +const MACOS_PRINTF_PATH = posix.join(MACOS_BIN_DIR, 'printf') ... - 'spawn -noecho /usr/bin/login -flpq $env(ORCA_LOGIN_PROBE_USERNAME) /usr/bin/printf ORCA_LOGIN_PREFLIGHT_OK; ' + + `spawn -noecho ${MACOS_LOGIN_PATH} -flpq $env(ORCA_LOGIN_PROBE_USERNAME) ${MACOS_PRINTF_PATH} ${LOGIN_PREFLIGHT_MARKER}; ` +As per coding guidelines, use
path.joinor Node/Electron path utilities instead of hardcoded separators.Source: Coding guidelines
src/main/providers/macos-login-session-pty-probe.test.ts (1)
53-53: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert the Ctrl-D teardown directive.
The mock invokes the callback independently of the generated script, so deleting
send "\\004"would still pass even though rejectedloginprobes can remain atlogin:until timeout.Proposed test assertion
expect(stdinEndMock).toHaveBeenCalledOnce() + const expectScript = execFileMock.mock.calls[0]?.[1]?.[1] + expect(expectScript).toContain('send "\\004"; expect eof')
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: cc76fa9e-c838-4030-966d-7aa5c39fca3f
📒 Files selected for processing (6)
src/main/daemon/daemon-entry.tssrc/main/daemon/macos-login-session-death-watch.test.tssrc/main/providers/macos-login-session-pty-probe.test.tssrc/main/providers/macos-login-session-pty-probe.tssrc/main/providers/macos-tcc-login-shell.test.tssrc/main/providers/macos-tcc-login-shell.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/main/providers/macos-tcc-login-shell.test.ts
- src/main/daemon/macos-login-session-death-watch.test.ts
- src/main/daemon/daemon-entry.ts
Deep review follow-upPushed Material fixes:
Verification on the merged branch:
The retirement oracle remains conservative: only three conclusive PAM rejections plus explicit resolver |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/daemon/daemon-init.test.ts (1)
451-452: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winHonor listener removal before dispatching queued events.
The microtask invokes
callbackunconditionally, so a listener removed before the microtask still fires. That differs from real socket behavior and can make cleanup/race tests pass or fail for the wrong reason. Check that the callback remains registered before invoking it.Proposed fix
- queueMicrotask(() => callback()) + queueMicrotask(() => { + if (handlers[event]?.includes(callback)) { + callback() + } + })
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: cde3e594-7250-439a-91ea-f5b36a8314d4
📒 Files selected for processing (15)
src/main/daemon/daemon-init.test.tssrc/main/daemon/daemon-init.tssrc/main/daemon/daemon-server.tssrc/main/daemon/macos-login-session-death-watch.test.tssrc/main/daemon/macos-login-session-death-watch.tssrc/main/daemon/terminal-host-options.tssrc/main/daemon/terminal-host.test.tssrc/main/daemon/terminal-host.tssrc/main/index.tssrc/main/network/macos-system-resolver-health.test.tssrc/main/network/macos-system-resolver-health.tssrc/main/providers/macos-login-session-pty-probe.test.tssrc/main/providers/macos-login-session-pty-probe.tssrc/main/providers/macos-tcc-login-shell.test.tssrc/main/providers/macos-tcc-login-shell.ts
🚧 Files skipped from review as they are similar to previous changes (7)
- src/main/daemon/terminal-host-options.ts
- src/main/daemon/terminal-host.ts
- src/main/providers/macos-login-session-pty-probe.test.ts
- src/main/index.ts
- src/main/providers/macos-tcc-login-shell.test.ts
- src/main/daemon/daemon-init.ts
- src/main/daemon/macos-login-session-death-watch.ts
Performance review follow-upPushed Finding: the client-activity hook ran for every accepted hello, including control-only Fix: login-session activity now fires only when a token-authenticated control + stream pair is complete. That preserves the post-login app reconnect signal while excluding one-shot internal health traffic. Deterministic count: the new protocol test fails on the previous implementation (control-only health probe: 1 callback; full app pair: 2) and now proves 0 and 1, respectively. Verification on
This removes routine health-probe subprocess churn without changing the retirement oracle, periodic backstop, PTY-exit trigger, GUI/headless boundary, or cold-restore behavior. |
…of a bare shell (#9454) (#10238) * fix(agent-status): resume finished agents after macOS logout instead of a bare shell (#9454) After the daemon-retirement fix (#9826) recovers terminals across a macOS logout, a running Claude Code (or other resumable TUI agent) that had finished its turn came back as a BARE SHELL — the user had to open a new tab and `claude --resume` in every worktree to get logged back in. Root cause: setAgentStatus writes a persisted 'live recovery' sleeping record (the cold-restore --resume anchor) for a live resumable agent, but drops it once the turn is 'done' — except for Pi, which was special-cased (retainsPiRecoveryIdentity). A finished Claude/Codex turn leaves the TUI alive and resumable at its prompt just like Pi, so an idle agent lost its anchor; a cold restore after an abrupt app death (logout) then found nothing to resume and dropped to a bare shell. Fix: generalize the Pi-only recovery-identity retention to every resumable TUI agent (isResumableTuiAgent), gated on a valid resume argv, so a finished agent keeps its persisted providerSession anchor and the already-shipped cold-restore --resume path brings it back logged in. Extends an existing pattern; no new subsystem. Reproduced + validated live in Electron via the login-session-death seam: idle Claude -> daemon retire -> app relaunch previously bare-shelled; now spawns 'claude --resume <session>' and restores the conversation logged in. * test(agent-status): update sleep-hygiene assertions for retained live recovery anchor (#9454)
…7936) (stablyai#9826) * fix(daemon): retire macOS daemons whose login session died (stablyai#7936) A daemon that survives a full macOS logout is unsalvageable: its PAM context can no longer host login(1) spawns (every new PTY becomes a 'Login incorrect' prompt zombie) and its Mach bootstrap namespace has lost the system DNS resolver, so terminals it hosts have no egress. Today it also keeps the stablyai#9301 preflight's cached 'accepted' verdict, so it keeps wrapping spawns in login(1) forever; only a manual daemon restart recovers. GUI-spawned daemons now watch for login-session death from the inside: a fresh cache-bypassing PAM probe (triggered by PTY-exit bursts, fresh client hellos, and a slow periodic timer) must conclusively reject three consecutive times AND the in-process system resolver must be degraded; then the daemon exits crash-style so session meta stays unclean and the replacement daemon cold-restores scrollback. A conclusive rejection also flips the spawn-wrapper cache off immediately. Headless serve/SSH daemons never get the watch (they must survive their spawning session ending), and a session that never conclusively accepted login(1) never arms it — a PAM anomaly alone can't kill a healthy daemon (fast user switching keeps accepting, so switched-away sessions are preserved). * test(daemon): e2e seam to drive login-session death oracles from a verdict file A dead macOS login session cannot be fabricated without root (PAM owns audit-session teardown), so live lifecycle QA drives the death watch's probe and resolver oracles from ORCA_E2E_LOGIN_SESSION_PROBE_FILE: 'alive' → accepted/healthy, 'dead' → rejected/unhealthy, anything else inconclusive — with compressed watch timing. Mirrors the existing ORCA_E2E_DAEMON_INIT_DELAY_MS seam; inert unless the env var is set. * fix(daemon): close the hang-shaped gap in login-session death detection The conclusive-PAM-verdict trigger had one blind failure shape: login(1) hanging at the prompt past the probe bound (killed → inconclusive forever → the watch never fires). Three changes close it: - The death-watch probe gets its own 4s bound (the 500ms preflight bound exists for spawn-path latency, which doesn't apply off-path), so a slow-but-answering PAM stack isn't misread as a hang. - An inconclusive pipe probe escalates to a PTY-hosted probe via script(1) — a dead session's PAM stack may only misbehave under a real tty (the pipe-vs-PTY fidelity limit the preflight documents). - A streak of timeout-killed probes (which a live session never produces) is a second retirement trigger, at a higher threshold (5) and still gated on the degraded resolver, logged with a distinct cause so field logs discriminate the two paths. Every dead-session behavior — fast reject, prompt-then-EOF, or hang — now fires retirement; all inconclusive states still fail toward preserving the daemon. * fix(daemon): keep login-session retirement conclusive * fix(daemon): stop login watch before clean shutdown * fix(daemon): make login-session PTY probe reliable * fix(daemon): close login-session watch races * fix(daemon): ignore health probes for login watch activity
…of a bare shell (stablyai#9454) (stablyai#10238) * fix(agent-status): resume finished agents after macOS logout instead of a bare shell (stablyai#9454) After the daemon-retirement fix (stablyai#9826) recovers terminals across a macOS logout, a running Claude Code (or other resumable TUI agent) that had finished its turn came back as a BARE SHELL — the user had to open a new tab and `claude --resume` in every worktree to get logged back in. Root cause: setAgentStatus writes a persisted 'live recovery' sleeping record (the cold-restore --resume anchor) for a live resumable agent, but drops it once the turn is 'done' — except for Pi, which was special-cased (retainsPiRecoveryIdentity). A finished Claude/Codex turn leaves the TUI alive and resumable at its prompt just like Pi, so an idle agent lost its anchor; a cold restore after an abrupt app death (logout) then found nothing to resume and dropped to a bare shell. Fix: generalize the Pi-only recovery-identity retention to every resumable TUI agent (isResumableTuiAgent), gated on a valid resume argv, so a finished agent keeps its persisted providerSession anchor and the already-shipped cold-restore --resume path brings it back logged in. Extends an existing pattern; no new subsystem. Reproduced + validated live in Electron via the login-session-death seam: idle Claude -> daemon retire -> app relaunch previously bare-shelled; now spawns 'claude --resume <session>' and restores the conversation logged in. * test(agent-status): update sleep-hygiene assertions for retained live recovery anchor (stablyai#9454)



Summary
Field follow-up to #7936 / #9454: after a full macOS logout and login, terminals can restore to
login:/ Login incorrect, new tabs can have zero egress, and only a manual daemon restart recovers them. The surviving daemon's PAM/login context and Mach bootstrap resolver are no longer usable, while the login-wrapper cache retains its birth-time accepted verdict.This PR makes GUI-spawned macOS daemons converge from inside the stale session. It complements #9684's next-startup fencing and covers logout while the app is closed without changing headless
orca serve, SSH, Linux, or Windows daemon behavior.Reliability contract
terminal-provider.login-session-retirement): a daemon may retire itself only after it previously proved login wrapping worked, then receives three consecutive conclusive PAM rejections and an explicitunhealthyresolver verdict. Inconclusive PAM results andunknownresolver results preserve all PTYs.scutil --dnsinside that same daemon must explicitly report no DNS configuration. A successful PAM verdict resets the rejection streak.login-session-watch-armed,login-session-probe-rejected,login-session-retire-suppressed,login-session-probe-error, andlogin-session-dead-retireidentify the trigger, verdict count, resolver result, and retirement.Mechanism
MacosLoginSessionDeathWatch, enabled only by the GUI launcher's--login-session-watchflag, re-runs the existing PAM preflight without its cache. Triggers are a trailing-debounced PTY-exit burst, authenticated client activity, and a two-minute periodic backstop.expect(1)binary to cover tty-sensitive PAM behavior. If both probes time out, the result remains inconclusive: repeated timeouts are not authority to orphan live terminals on slow or offline PAM hosts.login:zombies even before retirement completes.orca servelaunches do not set the watch flag, preserving the SSH/disconnect lifetime contract. Non-darwin behavior is unchanged.Provider and platform coverage
darwinruntime check; existing native smoke and terminal restart checks passed on the prior PR head.Performance budget
scutilevery 10 seconds indefinitely (30 rather than up to 360 probe cycles/hour in a stable mismatch).stop().Testing
pnpm typecheckoxfmt --checkandgit diff --checkscutil --dnsat 0.01-0.03 secondsRepository-wide
pnpm lintreaches an unrelated pre-existing exhaustiveness error insrc/renderer/src/components/skills/skill-freshness-group.tsx. A full daemon run reached 1,004 passing tests but the unrelated deleted-cwd test timed out under this workspace's unsupported Node 26; a minimal Node 26 reproduction hangs on deleting its own current directory, before any PR code is involved.Screenshots
Mocked lifecycle screenshots and daemon logs are attached in the PR comment titled Live Electron lifecycle QA — mocked dead session.
AI Review Report
Deep review covered false-retirement authority, timer/subprocess bounds, event-storm behavior, cache updates, authenticated-client wiring, shutdown/restore semantics, cross-platform and SSH exclusions, and diagnostics. The review removed timeout-only retirement, made resolver
unknownfail safe, backed suppressed verdicts off to normal cadence, and changed PTY exit handling to a true trailing debounce, and stops the watch before graceful shutdown so in-flight probes cannot interrupt checkpoints.Security Audit
No network-facing protocol or authentication change. Client activity is observed only after the existing daemon token and protocol checks pass. The E2E verdict-file seam is inert unless explicitly provided in the daemon environment and does not expose terminal data.
Residual gaps / Notes
Login incorrectplus zero-egress symptoms and the existing resolver-health implementation.