Skip to content

fix(pty): preserve detached Codex managed daemons during terminal teardown - #23834

Open
itxd wants to merge 3 commits into
stablyai:mainfrom
itxd:fix/preserve-codex-managed-daemon
Open

itxd wants to merge 3 commits into
stablyai:mainfrom
itxd:fix/preserve-codex-managed-daemon

Conversation

@itxd

@itxd itxd commented Sep 29, 2026 •

Copy link
Copy Markdown

ELI5

Closing the terminal that started Codex should not stop the shared backend used by other terminals. This change preserves the explicitly managed backend and its tools during descendant cleanup and checks for it before forced terminal-wide termination.

What Changed

  • Exclude detached codex app-server ... --managed-daemon and codex app-server daemon pid-update-loop subtrees from descendant signals.
  • Before forced termination, query command lines only for process-group leaders on the terminal's TTY. If a managed service shares that TTY, use the existing scoped root fallback instead of killing every group. Skipping just the daemon's own group would still kill its tools in other groups.
  • Keep full-host snapshots limited to process identity, ancestry, and executable names. Fetch full command lines only for Codex group-leader candidates, under the remaining original timeout, and verify identities before combining the results.
  • Read only target PID identities for the legacy delayed SIGKILL pass. Preserve upstream exit-verification and snapshot-coalescing behavior.
  • Merge upstream main to resolve the parser-refactor conflict.

Why

A managed backend can keep its launching CLI as its parent even after creating a separate process group. An ancestry-only cleanup therefore crosses an ownership boundary. A separate TTY-based force-kill path also needs protection when the backend retains that TTY.

The protection is deliberately conservative: TTY membership alone cannot tell which tool groups belong to the shared service. Ordinary agent descendants still use the existing descendant sweep. On a shared TTY, or when command inspection fails or is unsupported, forced terminal-wide cleanup falls back to the root; this can leave other terminal jobs alive rather than risk killing shared work.

Reading selected command lines avoids adding every tool's potentially large argument list to every whole-host snapshot. It does not eliminate all scan timeouts or claim a measured speedup on every host.

Linked Issue

Fixes #23833

Visual Proof

N/A — backend process lifecycle change with no rendered UI changes.

Testing

  • I manually tested live terminal closure locally
  • Automated tests added/updated

On macOS, 8 targeted Vitest files / 156 tests pass. Coverage includes shared-TTY force teardown, tools in separate groups, daemon maintenance, ordinary app-servers, unavailable/incomplete command queries, remaining timeout budgets, changed process identities, existing teardown/exit verification, and Windows job wiring. Signals are mocked; no live user session was terminated.

Changed files pass repository oxlint rules, the native code-quality configuration, oxfmt, and git diff --check. A read-only local ps check of the new two-stage query identified both managed services.

This checkout has no project dependencies installed. Tests used a temporary Vitest 4.1.5 installation with a minimal Node config (oxc.tsconfig: false), without repository-wide setup. Lint/format tools were oxlint 1.85.0 and oxfmt 0.70.0. The unavailable lint-staged commit hook was bypassed after these direct checks. No build, full project typecheck, frontend tests, Linux/Windows runtime test, remote connection, or destructive end-to-end reproduction was performed; broader verification remains for CI.

AI Disclosure

Prepared with OpenAI Codex (GPT-6).

Review

Recognition requires the known command forms and a process-group leader, not just the name codex. Executable paths containing whitespace and global flags preceding app-server remain outside this conservative matcher. Windows termination is unchanged. Pause/resume process-table queries retain their existing behavior. All inspection runs on the execution host; there are no wire changes or assumptions about git versus folder workspaces.

Agent skill upstream boundary

  • Not applicable; no upstream skill content copied.

Checklist

  • This PR is focused on shared-daemon teardown protection
  • I explained what changed and why
  • N/A for visual proof, with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path impact considered
  • Full project lint, typecheck, test, and build pass

@pullfrog

pullfrog Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

This run croaked 😵

The workflow encountered an error before any progress could be reported. Please check the link below for details.

Pullfrog  | Rerun failed job ➔ | View workflow run | via Pullfrog | 𝕏

@greptile-apps

greptile-apps Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 4/5

[High risk] Refactors process termination logic to preserve managed daemons.

The PR is not ready to merge because forced teardown can leave terminal jobs running on supported BusyBox systems.

Findings

  1. P1 BusyBox force teardown leaves jobs ▶
  2. P1 Force kill still reaches daemon ▶
  3. P2 Larger snapshots risk timeout ▶

Summary

The PR preserves recognized detached Codex managed-daemon subtrees during descendant and forced PTY teardown, and changes process-table capture to fetch full commands only where needed.

  • Adds daemon matching and teardown coverage on POSIX.
  • Introduces a BusyBox force-teardown regression: its unsupported ps -p query can leave ordinary jobs running.

Reviews (2) · Last reviewed commit: "fix(pty): guard shared-daemon force kill..."

}
visited.add(child.pid)
// Shared daemons own their entire subtree, including detached tools.
if (child.pgid === child.pid && isCodexManagedDaemon(child.command)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Force kill still reaches daemon

If the managed daemon retains the launching PTY's TTY, excluding it here protects it from the descendant sweep but not from force teardown. That path sends SIGKILL to every process group on the PTY's TTY, so an immediate or delayed force kill can still shut down the shared backend.

Comment thread src/main/pty-descendant-termination.ts Outdated
execFile(
'ps',
['-axo', 'pid=,ppid=,pgid=,lstart='],
['-axww', '-o', 'pid=,ppid=,pgid=,lstart=,command='],

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 Larger snapshots risk timeout

This now collects untruncated command text for every process, but the whole-host scan still has a one-second deadline. On a busy host, a scan that exceeds that deadline is discarded: teardown kills only the PTY root and leaves detached descendants running. A timeout during the later scan also prevents SIGKILL escalation.

@coderabbitai

coderabbitai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 2e0ab2b9-7316-4f54-a88d-ff1e32a0181e

📥 Commits

Reviewing files that changed from the base of the PR and between c49388c and be13a58.

📒 Files selected for processing (4)
  • src/main/pty-codex-managed-daemon.test.ts
  • src/main/pty-codex-managed-daemon.ts
  • src/main/pty-descendant-termination.test.ts
  • src/main/pty-descendant-termination.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

The change adds isCodexManagedDaemon and updates process-table parsing to retain command text. Descendant collection now excludes a managed daemon with pgid === pid and does not traverse its subtree. Tests cover command recognition, parsing, and exclusion from termination signals, including after process reparenting.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to be13a

The managed-daemon exclusion is mergeable after normal project checks; no concrete cleanup regression remains identified.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to be13a

The change protects a shared backend from terminal shutdown, but it may also let a terminal-launched process and its children survive shutdown if they appear to be that backend. The exposure appears limited to processes on the same host; broader access or privilege gain has not been established.

Retained concerns

  • Medium · security · inferred: A detached terminal descendant that presents a qualifying Codex command is treated as an independently owned daemon. If an untrusted descendant can present that command, it and its entire subtree can evade terminal teardown without daemon-provenance verification.
Security review details

Security Blast Radius

  • inferred — A false classification could preserve a terminal descendant and every process below it, including children in separate process groups. Evidence supports a host-session process-lifetime impact, not cross-tenant reach or privilege escalation.

Security Findings and Attack Paths

  • inferred — If a terminal-owned process can expose a matching command while leading its own process group, the new predicate skips it before TERM or delayed KILL targets are selected. Actual command impersonation in supported runtime environments remains unverified.

Trust Boundaries and Controls

  • observed — The classifier accepts two specific managed-daemon command forms, and exclusion also requires process-group leadership. The existing teardown checks root ownership; neither check proves that a matching child is a daemon created by the application.

Resilience and Maintainability Implications

  • observed — Delayed SIGKILL verifies start time and process group, whereas immediate SIGTERM uses snapshotted PIDs. The latter behavior is outside the changed selection logic and is not assessed as introduced by this PR.

Hardening Proposals

  • proposed — Where daemon-creation identity is available, bind the subtree exemption to verified daemon ownership rather than command text alone, while retaining the detached-subtree behavior needed by genuine shared daemons.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Issue [#23833] requires the POSIX sweep to preserve an explicitly managed Codex backend, its maintenance process, and their descendants, while still cleaning ordinary Codex CLI and stdio app-server pr…
Out of Scope Changes check ✅ Passed The changes stay within issue [#23833]. Command capture supports managed-daemon recognition. The larger process-table buffer and preserved start-time capture support reliable ownership checks and dela…
Title check ✅ Passed The title clearly identifies the primary change: preserving detached Codex managed daemons during terminal teardown.
Description check ✅ Passed The description is mostly complete. It includes the required change summary, rationale, linked issue, visual-proof explanation, testing details, AI disclosure, review notes, boundary declaration, and …
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch fix/preserve-codex-managed-daemon

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.

@itxd

itxd commented Sep 29, 2026

Copy link
Copy Markdown
Author

Addressed both findings in 47e3b86 and merged upstream main in 26c703e to resolve the conflict. Please re-review the updated patch.

P1 — force teardown: confirmed the separate TTY-wide SIGKILL path bypassed the original exclusion. The force path now inspects only the TTY's process-group leaders and uses the existing scoped root fallback when it finds a managed Codex service. It avoids the entire TTY-wide group sweep, protecting service tools that have their own groups as well as the daemon itself. Ordinary agent-owned descendants retain the descendant cleanup path. Missing, changed, truncated, timed-out, or unsupported command inspection also falls back conservatively; this may leave other terminal jobs alive. Pause/resume behavior is unchanged.

P2 — snapshot size: whole-host snapshots now capture executable names rather than full argument lists. Only Codex group-leader candidates receive a separate argv query, using the remaining original deadline and matching PID/start time/group/parent before merging. The legacy delayed SIGKILL pass queries only target identities. This reduces argument-list volume without simply increasing the timeout; it does not guarantee every busy-host scan will finish.

Validation: 8 targeted test files / 156 tests pass on macOS with mocked signals; repository oxlint and native code-quality checks pass for changed files, as do formatting and whitespace checks. Added tests cover shared-TTY services and tools, ordinary app-servers, command-query failures, deadline exhaustion, and identity changes. A read-only query also recognized the two local managed services. The PR body details the temporary test setup and remaining platform/CI checks. No live terminal closure, frontend testing, or project build was performed.

Comment on lines +123 to +129
...processTableSpec([
'-ww',
'-p',
[...new Set(leaders.map((row) => row.pid))].join(','),
'-o',
`${SELECTED_COLUMNS},command=`
]),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 BusyBox force teardown leaves jobs

On BusyBox systems where ps -p is unsupported, the initial PTY lookup falls back to a whole-table query, but this new command lookup still uses ps -p. It fails, so force teardown kills only the PTY root and leaves ordinary terminal jobs running, even when no managed Codex daemon is present. This lookup needs to respect the detected ps dialect.

This branch has not been deployed

No deployments
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.

Closing an agent terminal can terminate a shared Codex managed daemon

2 participants