A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
keep the daemon running when a client closes (#3345)
ktc24ac227f11f
diff --git a/crates/pa-cli/src/interactive_mode/daemon.rs b/crates/pa-cli/src/interactive_mode/daemon.rsindex 96103d89f0..0bfb1727b5 100644--- a/crates/pa-cli/src/interactive_mode/daemon.rs+++ b/crates/pa-cli/src/interactive_mode/daemon.rs@@ -201,7 +201,12 @@ fn spawn_supervisor_detached(socket_path: &Path, spawn_cwd: &Path, exe: &Path) -// lease this daemon's workers write — TS `daemon-launch.ts`// deletes the same var before spawning the supervisor..env_remove(pa_daemon::lease::SESSION_LEASE_OWNER_ID_ENV);- // Detached: own process group, reaped by init, survives this CLI.+ // A daemon must not share the launching TUI's terminal session: a+ // session-wide terminal cleanup could hang it up after the TUI exits.+ // On Unix, setsid also creates its own process group.+ #[cfg(unix)]+ pa_core::platform::process::set_new_session(&mut command);+ #[cfg(not(unix))]pa_core::platform::process::set_new_process_group(&mut command);command.spawn()diff --git a/crates/pa-cli/src/update_flow/successor.rs b/crates/pa-cli/src/update_flow/successor.rsindex f496e2388a..bcb1298e8e 100644--- a/crates/pa-cli/src/update_flow/successor.rs+++ b/crates/pa-cli/src/update_flow/successor.rs@@ -70,6 +70,9 @@ pub fn spawn_supervisor(if let Some(roster_path) = roster_path {command.env(UPDATE_ROSTER_ENV, roster_path);}+ #[cfg(unix)]+ pa_core::platform::process::set_new_session(&mut command);+ #[cfg(not(unix))]pa_core::platform::process::set_new_process_group(&mut command);let child = command.spawn()diff --git a/crates/pa-cli/src/update_flow/update_command.rs b/crates/pa-cli/src/update_flow/update_command.rsindex 59fb532268..c657af5bb2 100644--- a/crates/pa-cli/src/update_flow/update_command.rs+++ b/crates/pa-cli/src/update_flow/update_command.rs@@ -211,7 +211,10 @@ pub async fn run_update_command(options: &UpdateCommandOptions) -> Result<i32> {.env_remove(pa_daemon::worker::WORKER_SOCKET_ENV).env_remove(pa_daemon::worker::WORKER_INSTANCE_ID_ENV).env_remove(pa_daemon::worker::WORKER_SCRIPT_ENV);- // Detached: own process group, reaped by init, survives this CLI.+ // The coordinator must survive the CLI and its terminal closing.+ #[cfg(unix)]+ pa_core::platform::process::set_new_session(&mut command);+ #[cfg(not(unix))]pa_core::platform::process::set_new_process_group(&mut command);let child = command.spawn().with_context(|| {format!(diff --git a/crates/pa-cli/tests/daemon_discovery_e2e.rs b/crates/pa-cli/tests/daemon_discovery_e2e.rsindex 3aef366c5f..288d670502 100644--- a/crates/pa-cli/tests/daemon_discovery_e2e.rs+++ b/crates/pa-cli/tests/daemon_discovery_e2e.rs@@ -48,6 +48,10 @@ const SCRUB_ENV: [&str; 9] = ["PRIME_AGENT_INTERNAL_SESSION_LEASE_OWNER_ID",];+/// Child-mode env var for the launcher test's re-exec'd client (below):+/// the socket the client must launch a supervisor on.+const LAUNCHER_CLIENT_SOCKET_ENV: &str = "PRIME_AGENT_TEST_LAUNCHER_CLIENT_SOCKET";+fn cli_binary() -> PathBuf {PathBuf::from(env!("CARGO_BIN_EXE_prime-agent"))}@@ -121,6 +125,179 @@ fn run_cli(root: &Path, args: &[&str]) -> Output {command.output().expect("spawn CLI binary")}+/// The same launcher used before the TUI attaches must create a supervisor+/// outside the TUI's terminal session. Otherwise closing that terminal can+/// hang up a daemon that still serves other clients.+///+/// The launching client is a separate process: this test binary re-exec'd+/// in the child mode below, with the fixture's state environment pinned on+/// its spawn the same way `spawn_daemon` pins its children. The supervisor+/// the client launches inherits that pinned environment — never this+/// process's ambient one, which on a dev box points at the real agent dir —+/// and afterwards the whole client process is gone, not just its runtime:+/// the terminal-close scenario. Only the supervisor it spawned may remain.+#[test]+fn interactive_launcher_detaches_supervisor_from_client_session() {+ use std::io::{BufRead as _, BufReader};++ let fixture = tempfile::tempdir().expect("fixture");+ let agent_dir = fixture.path().join("agent");+ let tmp_dir = fixture.path().join("tmp");+ let socket = fixture.path().join("launched.sock");+ std::fs::create_dir_all(&agent_dir).expect("agent dir");+ std::fs::create_dir_all(&tmp_dir).expect("tmp dir");+ let _daemon = DetachedDaemon {+ socket: socket.clone(),+ };++ let mut client = Command::new(std::env::current_exe().expect("test binary"));+ client+ .arg("--exact")+ .arg("launcher_client_child_mode")+ .current_dir(fixture.path())+ .env(LAUNCHER_CLIENT_SOCKET_ENV, &socket)+ .env("PRIME_AGENT_CODING_AGENT_DIR", &agent_dir)+ .env("TMPDIR", &tmp_dir)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ for key in SCRUB_ENV {+ client.env_remove(key);+ }+ // A supervisor killed at teardown must not leak its session workers+ // into later test binaries: the worker's supervisor-lost exit runs on+ // this short window instead of the 5-minute default.+ client.env(+ pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,+ "15000",+ );+ let client = client.output().expect("spawn launcher client");+ assert!(+ client.status.success(),+ "the launcher client failed: {}{}",+ String::from_utf8_lossy(&client.stdout),+ String::from_utf8_lossy(&client.stderr),+ );+ // The spawning client's process, runtime, and probe connection are gone.++ let stream = UnixStream::connect(&socket).expect("daemon socket");+ let mut hello = String::new();+ BufReader::new(stream)+ .read_line(&mut hello)+ .expect("read daemon hello");+ let hello: Value = serde_json::from_str(&hello).expect("parse daemon hello");+ let pid = hello["supervisorPid"].as_i64().expect("supervisor pid") as i32;+ assert_eq!(unsafe { libc::getsid(pid) }, pid, "daemon owns its session");+ assert_ne!(+ unsafe { libc::getsid(0) },+ pid,+ "daemon must not share the launching client's terminal session"+ );+ assert!(+ UnixStream::connect(&socket).is_ok(),+ "daemon remains available"+ );+}++/// Child mode for the test above (a plain `cargo test` run without the env+/// var passes trivially): this binary re-exec'd as the launching client —+/// run the real launcher (`ensure_daemon_running_with`, the interactive+/// mode's pre-TUI path) against the fixture socket and exit, leaving only+/// the detached supervisor behind.+#[test]+fn launcher_client_child_mode() {+ let Some(socket) = std::env::var_os(LAUNCHER_CLIENT_SOCKET_ENV) else {+ return;+ };+ let socket = PathBuf::from(socket);+ let spawn_cwd = std::env::current_dir().expect("cwd");+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .expect("runtime");+ runtime+ .block_on(pa_cli::ensure_daemon_running_with(+ &cli_binary(),+ &socket,+ &spawn_cwd,+ ))+ .expect("launch supervisor");+}++/// Cleanup for a daemon spawned by the interactive launcher rather than by+/// this test process's `Command`, including a failed assertion's unwind:+/// write the force-shutdown command over the wire, wait for the supervisor+/// to stop listening (its listener is torn down as it exits), and SIGKILL+/// it when the bound passes — a hung daemon must not leak into later test+/// binaries, nor outlive the fixture tempdir's removal below.+struct DetachedDaemon {+ socket: PathBuf,+}++impl Drop for DetachedDaemon {+ fn drop(&mut self) {+ // `None`: the daemon is already gone, or wedged before its hello+ // with no pid to kill — nothing left to clean up.+ let Some(pid) = run_shutdown_on_socket(&self.socket) else {+ return;+ };+ if socket_stops_accepting(&self.socket, Duration::from_secs(10)) {+ return;+ }+ // The shutdown was accepted but the supervisor never exited. The+ // supervisor owns its own session (the property under test), so the+ // process-group kill takes any session workers with it.+ // SAFETY: the pid comes from the shutdown handshake above; this+ // test's own fixture supervisor.+ unsafe {+ libc::kill(-pid, libc::SIGKILL);+ libc::kill(pid, libc::SIGKILL);+ }+ socket_stops_accepting(&self.socket, Duration::from_secs(5));+ }+}++/// Connect to the daemon on `socket`, read its hello for the supervisor+/// pid, and write the force-shutdown command. `None`: the daemon is+/// already gone, or wedged before its hello.+fn run_shutdown_on_socket(socket: &Path) -> Option<i32> {+ use std::io::{BufRead as _, BufReader, Write as _};+ let mut stream = UnixStream::connect(socket).ok()?;+ // A wedged daemon must not hang the cleanup handshake: the hello is+ // read under a short bound.+ stream.set_read_timeout(Some(Duration::from_secs(2))).ok()?;+ let mut hello = String::new();+ BufReader::new(stream.try_clone().ok()?)+ .read_line(&mut hello)+ .ok()?;+ let pid = serde_json::from_str::<Value>(&hello)+ .ok()?+ .get("supervisorPid")?+ .as_i64()? as i32;+ let command = serde_json::json!({+ "type": "command", "id": "test-cleanup",+ "protocol": { "name": "prime-agent.daemon", "version": pa_types::daemon::DAEMON_PROTOCOL_VERSION },+ "command": { "type": "shutdown", "force": true }+ });+ // The write is best-effort: a failed write leaves the kill path above+ // as the safety net.+ let _ = writeln!(stream, "{command}");+ Some(pid)+}++/// Wait until nothing accepts connections on `socket`, bounded; `false`+/// means the bound passed with the socket still live.+fn socket_stops_accepting(socket: &Path, bound: Duration) -> bool {+ let deadline = Instant::now() + bound;+ while UnixStream::connect(socket).is_ok() {+ if Instant::now() > deadline {+ return false;+ }+ std::thread::sleep(Duration::from_millis(50));+ }+ true+}+fn stdout(output: &Output) -> String {String::from_utf8_lossy(&output.stdout).into_owned()}