Skip to content

fix(daemon): retire macOS daemons whose login session died (#7936) - #9826

Merged
brennanb2025 merged 9 commits into
mainfrom
brennanb2025/fix-github-macos-logout
Jul 22, 2026
Merged

brennanb2025 merged 9 commits into
mainfrom
brennanb2025/fix-github-macos-logout

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Invariant (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 explicit unhealthy resolver verdict. Inconclusive PAM results and unknown resolver results preserve all PTYs.
  • Failure source: [Bug] macOS logout leaves orphaned PTYs → broken "Login incorrect" terminals on next login, needs reboot #7936 / macOS logout/login breaks Orca terminals — daemon restart needed, all tabs require /resume #9454; a GUI daemon survives loginwindow teardown and later creates login-prompt zombies with no network egress.
  • Oracle: the cache-bypassing PAM probe must conclusively reject three times; scutil --dns inside that same daemon must explicitly report no DNS configuration. A successful PAM verdict resets the rejection streak.
  • Gate: accepted gap for a real GUI logout, which cannot be fabricated without ending the development login session. Deterministic watch/provider tests and the mocked Electron lifecycle cover the state machine and recovery wiring; the real-oracle transition remains listed below.
  • Diagnostics: login-session-watch-armed, login-session-probe-rejected, login-session-retire-suppressed, login-session-probe-error, and login-session-dead-retire identify the trigger, verdict count, resolver result, and retirement.

Mechanism

  • New MacosLoginSessionDeathWatch, enabled only by the GUI launcher's --login-session-watch flag, 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.
  • An inconclusive pipe probe escalates once through the macOS system 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.
  • A conclusive rejection immediately disables the login wrapper, so the daemon stops creating login: zombies even before retirement completes.
  • Retirement is crash-style: session metadata remains unclean so the replacement daemon cold-restores scrollback; existing dead-endpoint recovery owns socket/pid cleanup and respawn.
  • Headless orca serve launches do not set the watch flag, preserving the SSH/disconnect lifetime contract. Non-darwin behavior is unchanged.

Provider and platform coverage

  • macOS local/daemon: covered by deterministic PAM classification, watch scheduling, authenticated-client/PTY-exit wiring, and mocked live Electron retirement/respawn QA.
  • SSH/headless serve: unaffected; the launcher omits the watch flag. An SSH-minted dead audit-session experiment continued to accept PAM and retained resolver configuration, consistent with its system-bootstrap lifetime.
  • Linux/Windows/WSL: unaffected behind the darwin runtime check; existing native smoke and terminal restart checks passed on the prior PR head.
  • Mobile/relay: transport and ownership are unchanged; they observe the same daemon endpoint retirement/recovery contract.

Performance budget

  • No startup await, session inventory, renderer work, or provider fanout was added. Probes run off the PTY spawn/hello response path.
  • Baseline polling is one PAM subprocess every two minutes (30/hour after startup). On this Mac, five healthy probes measured 0.16-0.19 seconds wall time each.
  • Suppressed retirement now returns to the two-minute cadence instead of running PAM plus scutil every 10 seconds indefinitely (30 rather than up to 360 probe cycles/hour in a stable mismatch).
  • A sustained PTY-exit burst is trailing-debounced into one probe. Authenticated client probes have a 30-second activity gap, and all non-startup probes share a five-second minimum gap.
  • Probe output is capped at 1 KiB; each child is bounded to four seconds; timers are unref'd and canceled by stop().
  • The PTY fallback is a short-lived system process rather than a daemon-owned native PTY; 50 sequential live probes held the daemon process at 47 file descriptors before and after.

Testing

  • pnpm typecheck
  • 7 touched-module suites: 184 tests passed
  • Focused PAM/watch/entry suites: 50 tests passed
  • Oxlint on touched files
  • oxfmt --check and git diff --check
  • Mocked Electron lifecycle: accepted baseline -> three rejected verdicts plus unhealthy resolver -> daemon exit -> dead-endpoint respawn -> working restored/new terminal
  • Live healthy PAM timing: five runs at 0.16-0.19 seconds; scutil --dns at 0.01-0.03 seconds
  • Live PTY fallback: accepted in 0.10 seconds; 50 sequential probes completed without file-descriptor growth (47 → 47)

Repository-wide pnpm lint reaches an unrelated pre-existing exhaustiveness error in src/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 unknown fail 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

  • A destructive real GUI logout was not performed on the development account. The production PAM/resolver transition is inferred from the field's Login incorrect plus zero-egress symptoms and the existing resolver-health implementation.
  • If a real dead GUI session makes both pipe and PTY PAM probes time out forever, this watch preserves the daemon rather than risking false retirement; fix(terminal): scope macOS daemons to login sessions #9684's next-startup identity fence remains the recovery path.
  • Daemons created before this build do not gain the launch flag until replaced; fix(terminal): scope macOS daemons to login sessions #9684 covers their next-login startup.
  • Between self-retirement and the next reply-bearing adapter operation, writes to an already-open pane can be dropped on the dead socket. Full logout normally closes the app, so startup recovery is the field path; proactive mid-use respawn remains follow-up scope.

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).
@coderabbitai

coderabbitai Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@brennanb2025, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 5 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 796f0dbd-c424-4dd1-8d57-72bd9deb2de4

📥 Commits

Reviewing files that changed from the base of the PR and between 4ecce8e and 78cdaf1.

📒 Files selected for processing (4)
  • src/main/daemon/daemon-authenticated-client-activity.test.ts
  • src/main/daemon/daemon-entry.ts
  • src/main/daemon/daemon-main.ts
  • src/main/daemon/daemon-server.ts
📝 Walkthrough

Walkthrough

Adds 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 --login-session-watch, constructs the watchdog for macOS GUI launches, starts it before readiness signaling, and supports probe-file verdicts. Tests cover probing, parsing, watchdog state transitions, scheduling, and error handling.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the core change: retiring macOS daemons when the login session dies.
Description check ✅ Passed The description covers the required sections and includes testing, review, security, and notes, with only minor formatting gaps.
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.

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.

…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.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

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 ORCA_E2E_LOGIN_SESSION_PROBE_FILE seam (second commit) and exercises everything else for real: dev build from this branch, throwaway userData profile, real daemon with --login-session-watch, real PTYs, driven via CDP.

Baseline — terminal on the watched daemon, working; watch armed at startup (login-session-watch-armed):

baseline

Mocked logout — verdict file flipped to dead at 20:28:22; daemon log:

03:28:24.218 login-session-probe-rejected  rejections=1  (trigger: periodic)
03:28:24.721 login-session-probe-rejected  rejections=2
03:28:25.222 login-session-probe-rejected  rejections=3
03:28:25.222 login-session-dead-retire     rejections=3 resolverHealth=unhealthy

Daemon pid 68634 exited 3s after the flip. No manual restart.

Recovery — next createOrAttach (New Terminal) triggered the adapter's dead-endpoint respawn: fresh daemon (pid 26160) forked, watch re-armed, new terminal fully functional:

recovered

App restart on the same profile — tabs restore against the healthy daemon and the shell works:

after-relaunch

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 createOrAttach/reply-bearing RPCs trigger the respawn). In the field the retirement almost always happens while the app is closed (logout), so this window is theoretical — but if we want mid-use retirement to heal instantly, a follow-up could have the adapter treat a dead socket on write as a respawn trigger too.

Unverified (needs a real dead session): that PAM's login -flpq conclusively rejects and scutil --dns degrades in an actual post-logout session — i.e. the real-oracle behavior the mock stands in for. A root-created disposable login session experiment is staged for that, and the reporter's daemon.log would confirm it from the field.

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.

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

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 win

Stop the login-session watchdog on graceful shutdown to avoid a retirement race.

deathWatch.stop() is never called from the SIGTERM/SIGINT shutdown() path or from onIdleShutdown. A scheduled/in-flight watchdog probe can still resolve and call onRetire() → process.exit(1) while a graceful shutdown is mid-flight (e.g. inside the 5s SHUTDOWN_TIMEOUT_MS window awaiting daemon.shutdown()'s checkpoint/dispose logic), hard-killing the process before session checkpoints finish writing. runProbe already rechecks this.stopped/this.retired right after every await, so calling stop() is sufficient to safely cancel even an in-flight probe before it reaches onRetire. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 261a7b7 and 1753a89.

📒 Files selected for processing (12)
  • src/main/daemon/daemon-entry.test.ts
  • src/main/daemon/daemon-entry.ts
  • src/main/daemon/daemon-init.ts
  • src/main/daemon/daemon-main.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/macos-login-session-death-watch.test.ts
  • src/main/daemon/macos-login-session-death-watch.ts
  • src/main/daemon/terminal-host-options.ts
  • src/main/daemon/terminal-host.ts
  • src/main/index.ts
  • src/main/providers/macos-tcc-login-shell.test.ts
  • src/main/providers/macos-tcc-login-shell.ts

@brennanb2025

Copy link
Copy Markdown
Contributor Author

De-risking round: the trigger can no longer be defeated by any known dead-session behavior

The residual risk was a single failure shape: login(1) hanging at the prompt past the probe bound in a dead session → probe killed → inconclusive forever → watch never fires. Commit 54e9bad9f2 closes it three ways:

  1. Dedicated 4s probe bound for the death watch (the 500ms preflight bound exists for spawn-path latency, which doesn't apply off-path) — a slow-but-answering PAM stack is no longer misread as a hang.
  2. PTY escalation: an inconclusive pipe probe re-runs under script(1)'s PTY, covering the tty-sensitive-PAM divergence the preflight's own comments warn about.
  3. Hang-shaped second trigger: a streak of 5 timeout-killed probes (a live session answers in milliseconds, even under load) retires the daemon, still gated on the degraded resolver, logged with a distinct cause: probe-timeouts so field logs discriminate the paths.

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, hang verdict): 5 × login-session-probe-timeout at 500ms intervals → login-session-dead-retire cause=probe-timeouts resolverHealth=unhealthy → daemon exited 4s after the flip.

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.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Real dead-session experiment (SSH-minted): a decisive negative with three useful conclusions

Ran 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 scutil --dns stayed configured.

  1. No false-retirement risk from non-GUI session death. An orphan of a dead SSH session keeps a working PAM/DNS context — so even if the watch were ever armed near SSH-shaped lifecycles (it's excluded by design), the oracles wouldn't fire. This is protective evidence for the SSH persistence use case.
  2. launchctl print pid/<orphan> keeps reporting the dead session's original asid — relevant to fix(terminal): scope macOS daemons to login sessions #9684: a post-logout daemon will report its stale asid to the process-identity guard and be correctly fenced (noting there).
  3. The GUI logout is the special case. What breaks a surviving daemon isn't audit-session death per se — it's loginwindow destroying the per-session Mach bootstrap namespace, which GUI sessions have and SSH sessions don't (they ride the system bootstrap; that's exactly why Orca's remote daemons survive disconnects). This sharpens the fix's model: the oracles' production-observed failures ("Login incorrect" in the reporter's terminals; the pre-existing resolver-health machinery built for dead-session daemons) are specific to the GUI-teardown state, which cannot be fabricated without an actual logout.

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 daemon.log remains the equivalent field artifact.

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

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 lift

Make persistent hang probes eligible for retirement.

Line 196 returns an inconclusive timeout, but MacosLoginSessionDeathWatch only 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 thresholded hang retirement 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1753a89 and ebdd072.

📒 Files selected for processing (5)
  • src/main/daemon/daemon-entry.ts
  • src/main/daemon/macos-login-session-death-watch.test.ts
  • src/main/daemon/macos-login-session-death-watch.ts
  • src/main/providers/macos-tcc-login-shell.test.ts
  • src/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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review follow-up pushed in c41fb06363:

  • Fixed the graceful-shutdown race by stopping the login-session watch before SIGTERM/SIGINT checkpoint teardown and idle retirement. Added a deterministic test showing an in-flight resolver result cannot retire after stop().
  • Intentionally did not restore timeout-streak retirement. The probe contract marks timeouts inconclusive, and slow/offline enterprise PAM can exceed the bound while DNS is unavailable; promoting that combination to process.exit(1) could orphan healthy PTYs. Three conclusive PAM rejections plus explicit resolver unhealthy still retire for the reported Login incorrect path; dual-timeout sessions fail safe and retain fix(terminal): scope macOS daemons to login sessions #9684 as the next-startup recovery path.

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

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 lift

Serialize cache-mutating probes to prevent stale results from re-enabling login wrapping.

probeMacosLoginSessionAlive() bypasses loginPreflightInFlight, while loginPreflightSucceeds() may still have an earlier probe running. Both paths update cachedLoginPreflightResult; an older accepted probe can therefore overwrite a newer conclusive rejection and cause wrapShellSpawnForMacosTccAttribution() to keep creating login: 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 value

Use Node path utilities for macOS binary paths.

Construct the binary paths with path.posix.join and 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.join or 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 win

Assert the Ctrl-D teardown directive.

The mock invokes the callback independently of the generated script, so deleting send "\\004" would still pass even though rejected login probes can remain at login: 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

📥 Commits

Reviewing files that changed from the base of the PR and between ebdd072 and de7d2ef.

📒 Files selected for processing (6)
  • src/main/daemon/daemon-entry.ts
  • src/main/daemon/macos-login-session-death-watch.test.ts
  • src/main/providers/macos-login-session-pty-probe.test.ts
  • src/main/providers/macos-login-session-pty-probe.ts
  • src/main/providers/macos-tcc-login-shell.test.ts
  • src/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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Deep review follow-up

Pushed 657cdcfc1e and merged current main in 4ecce8ef47 after auditing the detector, spawn-wrapper cache, scheduler, subprocess cleanup, cold-restore path, GUI/headless launch boundary, and the latest terminal-generation refactor.

Material fixes:

  • Recovery trigger retention: client hellos and PTY-exit signals that arrive inside the probe gap or during an armed probe now retain exactly one bounded follow-up. Previously they could be dropped, leaving a post-login stale daemon undiscovered until the two-minute periodic backstop.
  • No stale cache overwrite or duplicate startup child: the death watch reuses the in-flight startup PAM warmup and fences overlapping spawn-path results, so an older acceptance cannot re-enable login(1) after a newer death rejection. Deterministic coverage also proves startup uses one PAM child rather than two.
  • Lifecycle cleanup: watcher stop now aborts in-flight pipe/PTY probes and the corroborating scutil child, removes listeners, and prevents PTY fallback after cancellation. This closes the orphan-process window when graceful shutdown exits before a probe timeout.
  • Production wiring: tests now prove the GUI launch option forwards --login-session-watch, the default/headless path omits it, and reaped PTYs reach the watch callback after the current-main terminal host refactor.

Verification on the merged branch:

  • pnpm typecheck — pass
  • 16 focused daemon/provider/network suites — 226 passed
  • full src/main/daemon suite — 994 passed, with only the two known deleted-cwd timeouts under unsupported Node 26 (same pre-existing Node/runtime issue, before PR code)
  • touched-file oxlint + oxfmt — pass
  • max-lines ratchet — pass, no new bypasses
  • reliability-gate manifest check — pass
  • repository-wide pnpm lint reaches the same unrelated pre-existing switch-exhaustiveness error in skill-freshness-group.tsx

The retirement oracle remains conservative: only three conclusive PAM rejections plus explicit resolver unhealthy can retire an armed daemon; timeouts and resolver unknown still preserve PTYs.

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

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 win

Honor listener removal before dispatching queued events.

The microtask invokes callback unconditionally, 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

📥 Commits

Reviewing files that changed from the base of the PR and between de7d2ef and 4ecce8e.

📒 Files selected for processing (15)
  • src/main/daemon/daemon-init.test.ts
  • src/main/daemon/daemon-init.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/macos-login-session-death-watch.test.ts
  • src/main/daemon/macos-login-session-death-watch.ts
  • src/main/daemon/terminal-host-options.ts
  • src/main/daemon/terminal-host.test.ts
  • src/main/daemon/terminal-host.ts
  • src/main/index.ts
  • src/main/network/macos-system-resolver-health.test.ts
  • src/main/network/macos-system-resolver-health.ts
  • src/main/providers/macos-login-session-pty-probe.test.ts
  • src/main/providers/macos-login-session-pty-probe.ts
  • src/main/providers/macos-tcc-login-shell.test.ts
  • src/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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Performance review follow-up

Pushed 78cdaf1e64 after tracing every login-watch trigger back to its callers.

Finding: the client-activity hook ran for every accepted hello, including control-only health-check / resolver-health-check sockets. The resolver check runs before fresh macOS PTYs, so ordinary new-terminal creation could consume the 30-second activity budget and launch an unnecessary PAM subprocess. A full app connection also invoked the hook twice (control + stream).

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 78cdaf1e64:

  • pnpm typecheck — pass
  • 19 focused daemon/provider/network/history suites — 424 passed
  • touched-file oxlint and oxfmt — pass
  • reliability-gate manifest, max-lines ratchet, and diff checks — pass
  • live PAM pipe probe — 0.04–0.06s across five runs
  • exact Expect-owned PTY fallback — 100/100 accepted, zero failures

This removes routine health-probe subprocess churn without changing the retirement oracle, periodic backstop, PTY-exit trigger, GUI/headless boundary, or cold-restore behavior.

@brennanb2025
brennanb2025 merged commit 8dc1ca4 into main Jul 22, 2026
8 checks passed
brennanb2025 added a commit that referenced this pull request Jul 24, 2026
…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)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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)
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