Skip to content

fix(staged): detach local agents from the terminal and stop them on every exit - #1128

Open
matt2e wants to merge 1 commit into
mainfrom
staged-signals
Open

matt2e wants to merge 1 commit into
mainfrom
staged-signals

Conversation

@matt2e

@matt2e matt2e commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

Staged, run from a terminal, could be stopped by the terminal (zsh: suspended (tty input/output)) when sessions were resumed, which looked like it was quitting. Local ACP agents shared Staged's terminal session, so an agent started through an interactive login shell (or any shell it started) could make itself the terminal's foreground process group. Staged was then stopped with SIGTTOU/SIGTTIN the next time it touched the terminal.

This PR starts each local agent in a session of its own, and makes every way out of Staged stop the agents and everything they started.

Detaching agents

  • Local agents call setsid() in pre_exec, so they lead their own session and have no controlling terminal.
  • Remote (Blox) proxies keep process_group(0), so the SIGINT the driver sends them still works.
  • libc moves to the cfg(unix) dependencies of acp-client.

Stopping agents on every exit

Detaching takes away the cleanup the terminal used to do (SIGINT on Ctrl-C, SIGHUP when it closes). A new acp_client::agent_reaper replaces it:

Exit path What happens
Session end, normal quit AgentGroup::stop sends SIGTERM to the agent's group and to every descendant, including children that left the group with their own setsid (found by walking ppid links in a libproc / /proc snapshot). After a 1 s grace it SIGKILLs whatever is left. Processes are remembered by (pid, start time), so a recycled pid is never signalled. An AgentGroup dropped without stop SIGKILLs its group.
SIGINT, SIGTERM, SIGHUP tokio signal handlers run the normal shutdown (shutdown_cleanup, then app.exit(128+n)). A second signal, or 15 s without exiting, forces process::exit.
SIGKILL, abort, crash, panic A watchdog process (below). With no watchdog, a fatal panic hook and RunEvent::Exit reap in process.

Watchdog

Staged re-execs its own binary with --staged-agent-reaper and keeps the write end of a pipe to the watchdog's stdin. Every group Staged starts or stops is announced over the pipe. When the pipe reaches EOF, the watchdog SIGTERMs every group still registered, waits 2 s, SIGKILLs them, and exits.

Why a pipe:

  • macOS has no PR_SET_PDEATHSIG, and nothing inside Staged runs after SIGKILL.
  • An agent seeing its stdin close says nothing about the tool shells and MCP servers it started.
  • The kernel closes Staged's end however Staged dies, so EOF cannot be fooled by pid reuse, and the same pipe carries the registrations.
  • The write end is O_CLOEXEC, so no agent inherits it and holds it open.

Hardening:

  • It runs in its own session, closes inherited descriptors, and ignores INT/TERM/HUP/QUIT/PIPE/TTIN/TTOU, so Ctrl-C, a closed terminal or a kill meant for Staged cannot take it down first.
  • It re-walks the watched groups every 500 ms. An agent can notice Staged's death and exit before the watchdog acts; its detached children are then re-parented to launchd, and only an earlier walk still ties them to it.
  • If it dies under a running Staged, it is restarted (up to 3 times) and every group is replayed.

Remote proxies are registered as remote groups. On Staged's death they get SIGKILL only, never SIGINT, so remote turns keep running, as on a quit.

Testing

  • cargo test -p acp-client: 451 passed, including new tests that use real processes. cargo clippy --all-targets -D warnings clean.
  • App crate: cargo test 4219 passed, cargo clippy -D warnings clean.
  • End to end against the real app binary with a fake claude-agent-acp that leaves behind a TERM-ignoring child and a setsid-detached grandchild pair, checked with ps. Agents led their own session with no tty. The whole tree was gone, and no watchdog was left, after each of: session end (the other session's tree untouched), Apple Event quit, SIGTERM, SIGINT, SIGHUP, terminal close via a pty, SIGKILL, SIGABRT, and killing the watchdog then SIGKILLing Staged.

Not tested end to end:

  • The original symptom: resuming every session under just run-web from a terminal.
  • The login-shell (zsh -i -l -s) spawn path. The run above used the direct launch path.
  • A real panic (same pipe mechanism; the in-process fallback is unit-tested).
  • Blox proxy cleanup (read through only).
  • Linux (only the /proc parsing is unit-tested).

Not covered

  • Staged and the watchdog both SIGKILLed at once (kill -9 -1, or a pkill -9 -f matching both).
  • A descendant that detaches and is orphaned within 500 ms of Staged's death.
  • Orphans of an earlier Staged are not reaped at startup. Telling them from the agents of a second running Staged would need persisted state.

🤖 Generated with Claude Code

…very exit

Local ACP agents now start in a session of their own (`setsid()` in
`pre_exec`), so they have no controlling terminal. Before, an agent
started through an interactive login shell (or any shell it started) shared
Staged's session and could make itself the terminal's foreground process
group. Staged, run from a terminal, was then stopped with SIGTTOU/SIGTTIN and
looked like it was "quitting" when sessions were resumed. Remote (Blox)
proxies keep `process_group(0)`, so the SIGINT the driver sends them still
works. `libc` moves to the `cfg(unix)` dependencies.

Detaching agents also takes away the cleanup the terminal used to do
(SIGHUP when it closes, SIGINT on Ctrl-C). So every way out of Staged now
stops agents explicitly, through a new `acp_client::agent_reaper`:

- Session end and normal quit: `AgentGroup::stop` sends SIGTERM to the
  agent's group (`kill(-pgid)`) and to every descendant, including children
  that left the group via `setsid` (found by walking ppid links in a
  libproc / `/proc` snapshot). It waits a 1 s grace, then SIGKILLs whatever
  is left. Processes are remembered by (pid, start time), so a recycled pid
  is never signalled. An `AgentGroup` dropped without `stop` (error paths)
  SIGKILLs its group.
- SIGINT, SIGTERM, SIGHUP: tokio signal handlers run the normal shutdown
  (`shutdown_cleanup`, then `app.exit(128+n)`). A second signal, or 15 s
  without exiting, forces `process::exit`.
- Panic: the watchdog below covers it. With no watchdog, a fatal panic hook
  and `RunEvent::Exit` reap in process (`reap_now_if_unwatched`).
- Hard death (SIGKILL, abort, crash): a watchdog process. Staged re-execs
  its own binary with `--staged-agent-reaper` and keeps the write end of a
  pipe to the watchdog's stdin. Every group Staged starts or stops is
  announced over it (`L`/`R`/`U <pgid>`). When the pipe reaches EOF, the
  watchdog SIGTERMs, waits 2 s, then SIGKILLs every group still
  registered, and exits.

Why a pipe-holding watchdog for hard death:
- macOS has no PR_SET_PDEATHSIG.
- An agent seeing its stdin close says nothing about the tool shells and
  MCP servers it started.
- Nothing inside Staged runs after SIGKILL.
- The kernel closes Staged's end of the pipe however Staged dies, so EOF is
  a death signal that pid reuse cannot fool. A kqueue NOTE_EXIT on Staged's
  pid could be fooled that way, and it would still need a separate channel
  for the registrations. The pipe carries them too.
- The write end is O_CLOEXEC, so no agent inherits it and holds it open.

How the watchdog is hardened:
- It runs in its own session.
- It ignores INT/TERM/HUP/QUIT/PIPE/TTIN/TTOU, set before exec, so Ctrl-C,
  a closed terminal or a `kill` meant for Staged cannot take it down first.
- It closes inherited descriptors.
- It re-walks the watched groups every 500 ms. An agent notices Staged's
  death at the same moment as the watchdog and may exit first. Its detached
  children are then re-parented to launchd, and only an earlier walk still
  ties them to it (found by the end-to-end run below).
- If it dies under a running Staged, it is restarted (up to 3 times) and
  every group is replayed.

Remote proxies are registered as remote groups. On Staged's death they get
SIGKILL only, never SIGINT, so remote turns keep running, as on a quit.
Their ordinary teardown stays with the driver.

Startup orphan reaping is not done. Telling an orphan of a previous Staged
from an agent of a concurrently running one would need persisted state. The
watchdog makes that state unnecessary for every case except the watchdog
and Staged being SIGKILLed together.

Verified against the real app binary with a fake `claude-agent-acp`, checked
with `ps`. The fake agent leaves behind a TERM-ignoring child and a
setsid-detached grandchild pair. Agents were checked to lead their own
session with no tty. For each exit path, the whole tree was gone after
Staged went and no watchdog was left:
- session end (the other session's tree was untouched);
- Cmd-Q / Apple Event quit;
- SIGTERM, SIGINT, SIGHUP;
- terminal close (SIGHUP via a pty);
- SIGKILL;
- SIGABRT;
- killing the watchdog, then SIGKILLing Staged (the watchdog was restarted).

Not covered:
- Staged and the watchdog both being SIGKILLed at once (`kill -9 -1`, or a
  `pkill -9 -f` that matches both).
- A descendant that detaches and is orphaned within 500 ms of Staged's
  death.

Signed-off-by: Matt Toohey <contact@matttoohey.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-03T09:19:25.322580Z e3f858b PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e3f858bb4c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

resolve_acp_working_dir(working_dir, true, self.remote_working_dir.as_deref())?;
let AttachProxy {
mut child,
_group,

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 Badge Move the attach proxy's reaper guard into its task

When reattaching to a Blox session, _group stays in attach_with_timing rather than being captured by the spawned async move task. Returning AttachedSession therefore drops the guard and sends Forget while the proxy is still running. If Staged subsequently crashes or is SIGKILLed, neither the watchdog nor the in-process registry knows about this proxy, so the newly added cleanup cannot stop it. Move the guard into the task and retain it through stop_proxy.

Useful? React with 👍 / 👎.

Comment on lines +95 to +100
let Err(error) = link.send(command) else {
return;
};
log::warn!("The agent reaper watchdog stopped listening ({error}); restarting it");
self.watchdog = None;
self.restart_watchdog();

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 Badge Monitor watchdog death independently of group announcements

If the watchdog dies while existing sessions continue running, it is only restarted when a later group registration or removal makes link.send fail. There is no periodic health check or child-exit monitor, and watchdog_running only checks status without restarting it. Consequently, killing the watchdog during a long-running session leaves Staged unprotected indefinitely; a subsequent crash or SIGKILL leaves the detached agents running. Monitor the watchdog independently of registration traffic and replay the groups when it is restarted.

Useful? React with 👍 / 👎.

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