From 8c028c1ce0f87ad90989aa07c1b975bd7e239b3b Mon Sep 17 00:00:00 2001 From: Seth <40871381+sethalan@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:30:00 -0800 Subject: [PATCH] Run the quit cleanup on a plain kill, Ctrl+C and a closing terminal AI Assisted --- plan2code-app/src-tauri/src/agent_manager.rs | 3 +- .../src-tauri/src/console_supervisor.rs | 26 ++ plan2code-app/src-tauri/src/lib.rs | 3 + plan2code-app/src-tauri/src/log.rs | 10 + plan2code-app/src-tauri/src/main.rs | 22 +- plan2code-app/src-tauri/src/term_signal.rs | 134 +++++++++ plan2code-app/src-tauri/tests/term_signal.rs | 263 ++++++++++++++++++ 7 files changed, 458 insertions(+), 3 deletions(-) create mode 100644 plan2code-app/src-tauri/src/log.rs create mode 100644 plan2code-app/src-tauri/src/term_signal.rs create mode 100644 plan2code-app/src-tauri/tests/term_signal.rs diff --git a/plan2code-app/src-tauri/src/agent_manager.rs b/plan2code-app/src-tauri/src/agent_manager.rs index 4b38032..0caa121 100644 --- a/plan2code-app/src-tauri/src/agent_manager.rs +++ b/plan2code-app/src-tauri/src/agent_manager.rs @@ -11,6 +11,7 @@ use std::thread; use serde::Serialize; use crate::agents::{agent_launch_spec, Agent, PermissionMode}; +use crate::log; use crate::pty_host::{PtyHost, StartOptions}; #[derive(Clone, Debug, PartialEq, Eq, Serialize)] @@ -734,7 +735,7 @@ impl Shared { // the log, since the bar's reason is gone once a new agent starts. if let Some((choice, _)) = &inner.last_start { if let Some(line) = exit_log_line(choice.kind.id(), &reason) { - eprintln!("{line}"); + log::line(&line); } } inner.state = AgentState::Ended { reason }; diff --git a/plan2code-app/src-tauri/src/console_supervisor.rs b/plan2code-app/src-tauri/src/console_supervisor.rs index b911eea..c7ff274 100644 --- a/plan2code-app/src-tauri/src/console_supervisor.rs +++ b/plan2code-app/src-tauri/src/console_supervisor.rs @@ -120,6 +120,13 @@ fn node_command(console_dir: &Path) -> Command { use std::os::windows::process::CommandExt; command.creation_flags(0x08000000); // CREATE_NO_WINDOW } + // Ctrl+C and a closing terminal signal the app's whole process group: a stop running there + // would end before it stopped its console. + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + command.process_group(0); + } command } @@ -895,6 +902,25 @@ mod tests { assert_eq!(*stopped.lock().unwrap(), vec!["s1"]); } + #[cfg(unix)] + #[test] + fn a_console_call_runs_in_a_process_group_of_its_own() { + // Ctrl+C and a closing terminal signal the app's whole group: a stop + // already running there ended before it stopped its console. + let console = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console"); + let mut child = node_command(&console) + .arg("help") + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .expect("node starts"); + let pid = child.id() as i32; + // SAFETY: getpgid only reads; the child is not waited for yet, so its id is its own. + let group = unsafe { libc::getpgid(pid) }; + let _ = child.wait(); + assert_eq!(group, pid); + } + #[test] fn the_apps_stop_calls_pass_force() { let args = stop_args("20261101-120000-abcdef"); diff --git a/plan2code-app/src-tauri/src/lib.rs b/plan2code-app/src-tauri/src/lib.rs index adf28ca..27bf150 100644 --- a/plan2code-app/src-tauri/src/lib.rs +++ b/plan2code-app/src-tauri/src/lib.rs @@ -7,6 +7,7 @@ pub mod attention; pub mod brief; pub mod console_supervisor; pub mod handoff; +pub mod log; pub mod loop_commit; pub mod loop_driver; pub mod loop_notify; @@ -28,5 +29,7 @@ pub mod session_reader; pub mod settings; #[cfg(windows)] pub mod task_dialog; +#[cfg(unix)] +pub mod term_signal; pub mod ui_confirm; pub mod versions; diff --git a/plan2code-app/src-tauri/src/log.rs b/plan2code-app/src-tauri/src/log.rs new file mode 100644 index 0000000..9a5153c --- /dev/null +++ b/plan2code-app/src-tauri/src/log.rs @@ -0,0 +1,10 @@ +//! Lines for the app's log, its stderr, on the paths a quit takes. `eprintln!` panics when the +//! write fails, as it does once the terminal the app was started from has closed: the quit's +//! cleanup would end at its first line, with the app still open. + +use std::io::Write; + +/// Writes one line, or nothing when the log cannot be written to. +pub fn line(text: &str) { + let _ = writeln!(std::io::stderr(), "{text}"); +} diff --git a/plan2code-app/src-tauri/src/main.rs b/plan2code-app/src-tauri/src/main.rs index 671f2d0..e166131 100644 --- a/plan2code-app/src-tauri/src/main.rs +++ b/plan2code-app/src-tauri/src/main.rs @@ -16,6 +16,7 @@ use plan2code_app_lib::console_supervisor::{ use plan2code_app_lib::console_supervisor::{ find_console_dir, stop_announced_on_end, stop_console_session, }; +use plan2code_app_lib::log; use plan2code_app_lib::loop_driver::{self, Hooks, LastLoop, LoopFacts, LoopSlot}; use plan2code_app_lib::models; use plan2code_app_lib::node_check; @@ -370,7 +371,9 @@ fn stop_announced_console(project_dir: &std::path::Path, sid: &str) { let stopped = find_console_dir() .and_then(|console_dir| stop_console_session(&console_dir, project_dir, sid)); if let Err(error) = stopped { - eprintln!("plan2code: could not stop the console {sid}: {error}"); + log::line(&format!( + "plan2code: could not stop the console {sid}: {error}" + )); } } @@ -843,7 +846,9 @@ fn shutdown_with(state: &AppState) { if let Some(mut console) = guard.take() { if let Err(error) = stop_supervised(state, &mut console) { let sid = &console.session().sid; - eprintln!("plan2code: could not stop the console {sid}: {error}"); + log::line(&format!( + "plan2code: could not stop the console {sid}: {error}" + )); } } } @@ -2219,6 +2224,19 @@ fn main() { } #[cfg(target_os = "macos")] build_mac_menu(app)?; + // A plain `kill`, Ctrl+C or a closed terminal runs the quit cleanup, then exits, + // instead of ending the app with its consoles still running. `shutdown`, not + // `quit_app`: a signal never starts a pending update's restart. + #[cfg(unix)] + { + let handle = app.handle().clone(); + if let Err(error) = plan2code_app_lib::term_signal::on_terminate(move || { + shutdown(&handle); + handle.exit(0); + }) { + eprintln!("plan2code: a signal may skip the quit cleanup: {error}"); + } + } spawn_node_check(app.handle().clone()); Ok(()) }) diff --git a/plan2code-app/src-tauri/src/term_signal.rs b/plan2code-app/src-tauri/src/term_signal.rs new file mode 100644 index 0000000..418e12f --- /dev/null +++ b/plan2code-app/src-tauri/src/term_signal.rs @@ -0,0 +1,134 @@ +//! SIGTERM (a plain `kill`), SIGINT (Ctrl+C) and SIGHUP (the terminal closed) end a process at +//! once by default, so the app's quit cleanup never ran and the consoles its agents had opened +//! kept running. Here they are caught instead and handed to a thread of its own, which runs the +//! cleanup it was given, once. The handler only writes one byte to a pipe, which a signal handler +//! may safely do; the thread does the work. +//! A second SIGTERM or SIGINT ends the process at once, so a cleanup that stalls never leaves a +//! plain `kill` unable to end the app. A repeated SIGHUP does not: closing a terminal can send it +//! twice at once, from the shell and from the terminal itself, and the commands the cleanup runs +//! ignore it too. +//! Unix only: Windows has none of these to catch. + +use std::io; +use std::sync::atomic::{AtomicBool, AtomicI32, Ordering}; + +/// The signals that run the cleanup. +const SIGNALS: [libc::c_int; 3] = [libc::SIGTERM, libc::SIGINT, libc::SIGHUP]; + +static INSTALLED: AtomicBool = AtomicBool::new(false); +static CAUGHT: AtomicBool = AtomicBool::new(false); +static WRITE_END: AtomicI32 = AtomicI32::new(-1); + +#[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))] +unsafe fn errno() -> *mut libc::c_int { + libc::__error() +} + +#[cfg(any(target_os = "linux", target_os = "android"))] +unsafe fn errno() -> *mut libc::c_int { + libc::__errno_location() +} + +extern "C" fn on_signal(signal: libc::c_int) { + if CAUGHT.swap(true, Ordering::SeqCst) { + if signal != libc::SIGHUP { + // SAFETY: raise is async-signal-safe. SA_RESETHAND has put this signal's default + // action back, so it ends the process as the handler returns. + unsafe { libc::raise(signal) }; + } + return; + } + let fd = WRITE_END.load(Ordering::Relaxed); + if fd < 0 { + return; + } + let byte = 1u8; + // SAFETY: write is async-signal-safe, and the end is non-blocking, so it never hangs the + // handler. errno is put back, since the code the signal interrupted may be about to read it. + unsafe { + let saved = *errno(); + libc::write(fd, (&byte as *const u8).cast(), 1); + *errno() = saved; + } +} + +fn last_error(what: &str) -> io::Error { + let error = io::Error::last_os_error(); + io::Error::new(error.kind(), format!("{what}: {error}")) +} + +/// Runs `cleanup` on a thread of its own the first time the process gets SIGTERM, SIGINT or +/// SIGHUP, instead of the process ending there; a second SIGTERM or SIGINT ends it. A signal the +/// process was started with ignored (`nohup` ignores SIGHUP) stays ignored. Once per process: a +/// second call is an error and changes nothing. +pub fn on_terminate(cleanup: impl FnOnce() + Send + 'static) -> io::Result<()> { + if INSTALLED.swap(true, Ordering::SeqCst) { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "the signal handler is already installed", + )); + } + let mut ends = [0; 2]; + // SAFETY: pipe fills the two-element array it is given. + if unsafe { libc::pipe(ends.as_mut_ptr()) } != 0 { + return Err(last_error("pipe")); + } + let [read_end, write_end] = ends; + // SAFETY: fcntl on the two descriptors just made. Close-on-exec keeps them out of the + // agents and consoles the app starts. + unsafe { + libc::fcntl(read_end, libc::F_SETFD, libc::FD_CLOEXEC); + libc::fcntl(write_end, libc::F_SETFD, libc::FD_CLOEXEC); + let flags = libc::fcntl(write_end, libc::F_GETFL); + libc::fcntl(write_end, libc::F_SETFL, flags | libc::O_NONBLOCK); + } + WRITE_END.store(write_end, Ordering::SeqCst); + std::thread::Builder::new() + .name("quit-signal".into()) + .spawn(move || { + let mut byte = 0u8; + loop { + // SAFETY: a one-byte read into a local; it blocks until the handler writes. + let read = unsafe { libc::read(read_end, (&mut byte as *mut u8).cast(), 1) }; + if read == 1 { + break; + } + if read < 0 && io::Error::last_os_error().kind() == io::ErrorKind::Interrupted { + continue; + } + // The pipe failed: no cleanup can be signalled any more, so none runs. + return; + } + // For the commands the cleanup runs, which start with this process's ignored signals: + // a repeated SIGHUP would end one before it has done its work. + // SAFETY: ignoring a signal installs no handler. + unsafe { libc::signal(libc::SIGHUP, libc::SIG_IGN) }; + cleanup(); + })?; + for signal in SIGNALS { + // SAFETY: a zeroed sigaction is a valid one to read the current action into, and, with the + // handler set and an empty mask, to install. SA_RESTART resumes the calls the signal + // interrupts elsewhere in the app, and SA_RESETHAND puts the default action back once the + // handler has run, so a second one ends the app; SIGHUP goes without it. + unsafe { + let mut action: libc::sigaction = std::mem::zeroed(); + if libc::sigaction(signal, std::ptr::null(), &mut action) != 0 { + return Err(last_error("sigaction")); + } + if action.sa_sigaction == libc::SIG_IGN { + continue; + } + action = std::mem::zeroed(); + action.sa_sigaction = on_signal as extern "C" fn(libc::c_int) as libc::sighandler_t; + action.sa_flags = libc::SA_RESTART; + if signal != libc::SIGHUP { + action.sa_flags |= libc::SA_RESETHAND; + } + libc::sigemptyset(&mut action.sa_mask); + if libc::sigaction(signal, &action, std::ptr::null_mut()) != 0 { + return Err(last_error("sigaction")); + } + } + } + Ok(()) +} diff --git a/plan2code-app/src-tauri/tests/term_signal.rs b/plan2code-app/src-tauri/tests/term_signal.rs new file mode 100644 index 0000000..d75173a --- /dev/null +++ b/plan2code-app/src-tauri/tests/term_signal.rs @@ -0,0 +1,263 @@ +//! The signals that end the app against the handler that turns them into its quit cleanup. A +//! file of its own, so the handler lives in a test process of its own: without it, a signal below +//! ends the whole process and the run fails. The handler installs once per process, so every +//! other case runs in a child: this test binary again, running only `signal_child`. +#![cfg(unix)] + +use std::io::{BufRead, BufReader, IsTerminal, Write}; +use std::os::fd::{FromRawFd, OwnedFd}; +use std::os::unix::process::ExitStatusExt; +use std::process::{Child, Command, ExitStatus, Stdio}; +use std::sync::mpsc::channel; +use std::time::{Duration, Instant}; + +use plan2code_app_lib::{log, term_signal}; + +/// Names the case, and is set only in the child process a test starts. +const CHILD: &str = "P2C_TERM_SIGNAL_CHILD"; + +/// The child's exit codes: its cleanup ran to the end, or it did not when it should have. +const CLEANED: i32 = 0; +const NOT_CLEANED: i32 = 3; + +#[test] +fn a_sigterm_runs_the_cleanup_instead_of_ending_the_process() { + let (tx, rx) = channel(); + term_signal::on_terminate(move || { + let _ = tx.send(()); + }) + .expect("the handler installs"); + raise(libc::SIGTERM); + rx.recv_timeout(Duration::from_secs(5)) + .expect("the cleanup ran after SIGTERM"); + // A second install is refused: one signal, one cleanup. + assert!(term_signal::on_terminate(|| {}).is_err()); +} + +#[test] +fn ctrl_c_and_a_closed_terminal_run_the_cleanup_too() { + for case in ["sigint", "sighup"] { + let status = outcome(child(case).spawn().expect("the child starts")); + assert_eq!(status.code(), Some(CLEANED), "{case}: {status:?}"); + } +} + +#[test] +fn a_second_signal_ends_the_app_while_its_cleanup_still_runs() { + // A cleanup that stalls must not leave a plain `kill` or Ctrl+C unable to + // end the app, whichever signal started it. + for (case, ends_by) in [ + ("sigterm twice", libc::SIGTERM), + ("sigint twice", libc::SIGINT), + ("sighup then sigterm", libc::SIGTERM), + ] { + let status = outcome(child(case).spawn().expect("the child starts")); + assert_eq!(status.signal(), Some(ends_by), "{case}: {status:?}"); + } +} + +#[test] +fn a_repeated_sighup_lets_the_cleanup_finish() { + // Closing a terminal can send it twice at once: zsh passes it on to the + // program in front, and the terminal's own hangup sends it again. + let status = outcome(child("sighup twice").spawn().expect("the child starts")); + assert_eq!(status.code(), Some(CLEANED), "{status:?}"); +} + +#[test] +fn a_signal_the_app_was_started_with_ignored_stays_ignored() { + // `nohup` starts a program with SIGHUP ignored, to outlive its terminal. + let status = outcome(child("ignored sighup").spawn().expect("the child starts")); + assert_eq!(status.code(), Some(CLEANED), "{status:?}"); +} + +#[test] +fn a_command_the_cleanup_runs_outlives_a_repeated_sighup() { + // The cleanup stops consoles by running `node`, which the second SIGHUP of + // a closed terminal would end before it stopped anything. + let status = outcome(child("command").spawn().expect("the child starts")); + assert_eq!(status.code(), Some(CLEANED), "{status:?}"); +} + +#[test] +fn a_cleanup_that_logs_after_its_terminal_is_gone_still_finishes() { + for case in ["sighup, closed terminal", "sigterm, closed terminal"] { + logs_to_a_closed_terminal(case); + } +} + +/// Runs the child on a terminal of its own, and closes that terminal once the +/// child has its handler. +fn logs_to_a_closed_terminal(case: &str) { + let (mut master, mut slave) = (-1, -1); + // SAFETY: openpty fills the two descriptors; the name and settings are optional. + let opened = unsafe { + libc::openpty( + &mut master, + &mut slave, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + }; + assert_eq!(opened, 0, "openpty: {}", std::io::Error::last_os_error()); + // SAFETY: both descriptors were just opened, and nothing else owns them. Close-on-exec keeps + // the terminal's other end out of the child, which would hold it open. + let (master, slave) = unsafe { + libc::fcntl(master, libc::F_SETFD, libc::FD_CLOEXEC); + (OwnedFd::from_raw_fd(master), OwnedFd::from_raw_fd(slave)) + }; + let mut child = child(case) + .stdout(Stdio::piped()) + .stderr(Stdio::from(slave)) + .spawn() + .expect("the child starts"); + let stdout = child.stdout.take().expect("the child's stdout is piped"); + let ready = BufReader::new(stdout) + .lines() + .map_while(Result::ok) + .any(|line| line.ends_with("ready")); + assert!(ready, "the child installed the handler"); + drop(master); + let status = outcome(child); + assert_eq!(status.code(), Some(CLEANED), "{case}: {status:?}"); +} + +fn raise(signal: libc::c_int) { + // SAFETY: raise only sends this process a signal. + assert_eq!(unsafe { libc::raise(signal) }, 0); +} + +/// This test binary again, running only `signal_child` on `case`. +fn child(case: &str) -> Command { + let mut command = Command::new(std::env::current_exe().expect("the test binary")); + command + .args(["--exact", "signal_child", "--test-threads=1", "--nocapture"]) + .env(CHILD, case) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + command +} + +/// How the child ended, within 30 s. +fn outcome(mut child: Child) -> ExitStatus { + let deadline = Instant::now() + Duration::from_secs(30); + loop { + if let Some(status) = child.try_wait().expect("the child can be waited on") { + return status; + } + if Instant::now() > deadline { + let _ = child.kill(); + let _ = child.wait(); + panic!("the child neither ended nor exited within 30 s"); + } + std::thread::sleep(Duration::from_millis(50)); + } +} + +/// Not a check on its own: the child process of the tests above. Run any other +/// way, it returns at once. +#[test] +fn signal_child() { + let Some(case) = std::env::var_os(CHILD) else { + return; + }; + // A signal this run was started with ignored (`nohup`, a script's `&`) + // would stay ignored, and no case below means that one. + for signal in [libc::SIGTERM, libc::SIGINT, libc::SIGHUP] { + // SAFETY: putting a signal's default action back installs no handler. + unsafe { libc::signal(signal, libc::SIG_DFL) }; + } + match case.to_str().expect("a case name") { + "sigint" => cleans_up_after(&[libc::SIGINT]), + "sighup" => cleans_up_after(&[libc::SIGHUP]), + "sighup twice" => cleans_up_after(&[libc::SIGHUP, libc::SIGHUP]), + "sigterm twice" => ends_during_the_cleanup(libc::SIGTERM, libc::SIGTERM), + "sigint twice" => ends_during_the_cleanup(libc::SIGINT, libc::SIGINT), + "sighup then sigterm" => ends_during_the_cleanup(libc::SIGHUP, libc::SIGTERM), + "ignored sighup" => ignores_sighup(), + "command" => runs_a_command_through_a_sighup(), + "sighup, closed terminal" => logs_after_its_terminal_closed(libc::SIGHUP), + "sigterm, closed terminal" => logs_after_its_terminal_closed(libc::SIGTERM), + other => panic!("no such case: {other}"), + } +} + +/// The cleanup takes a moment, so a signal that ends the app would cut it short. +fn cleans_up_after(signals: &[libc::c_int]) { + term_signal::on_terminate(|| { + std::thread::sleep(Duration::from_millis(300)); + std::process::exit(CLEANED); + }) + .expect("the handler installs"); + for signal in signals { + raise(*signal); + } + std::thread::sleep(Duration::from_secs(5)); + std::process::exit(NOT_CLEANED); +} + +fn ends_during_the_cleanup(first: libc::c_int, second: libc::c_int) { + let (tx, rx) = channel(); + term_signal::on_terminate(move || { + let _ = tx.send(()); + // A cleanup that never finishes. + loop { + std::thread::sleep(Duration::from_secs(60)); + } + }) + .expect("the handler installs"); + raise(first); + rx.recv_timeout(Duration::from_secs(5)) + .expect("the first signal started the cleanup"); + raise(second); + // Still running: the second signal was swallowed. + std::thread::sleep(Duration::from_secs(2)); + std::process::exit(NOT_CLEANED); +} + +fn ignores_sighup() { + // SAFETY: ignoring a signal installs no handler. + unsafe { libc::signal(libc::SIGHUP, libc::SIG_IGN) }; + term_signal::on_terminate(|| std::process::exit(NOT_CLEANED)).expect("the handler installs"); + raise(libc::SIGHUP); + std::thread::sleep(Duration::from_secs(1)); + std::process::exit(CLEANED); +} + +fn runs_a_command_through_a_sighup() { + term_signal::on_terminate(|| { + let status = Command::new("/bin/sh") + .args(["-c", "kill -HUP $$; exit 0"]) + .status() + .expect("sh runs"); + std::process::exit(if status.success() { + CLEANED + } else { + NOT_CLEANED + }); + }) + .expect("the handler installs"); + raise(libc::SIGHUP); + std::thread::sleep(Duration::from_secs(5)); + std::process::exit(NOT_CLEANED); +} + +fn logs_after_its_terminal_closed(signal: libc::c_int) { + assert!(std::io::stderr().is_terminal(), "stderr is a terminal"); + term_signal::on_terminate(|| { + log::line("a line from the cleanup"); + std::process::exit(CLEANED); + }) + .expect("the handler installs"); + println!("ready"); + // Closed once a write fails: macOS reports neither a hangup nor a lost terminal here. + let deadline = Instant::now() + Duration::from_secs(10); + while std::io::stderr().write_all(b".").is_ok() { + assert!(Instant::now() < deadline, "the terminal never closed"); + std::thread::sleep(Duration::from_millis(10)); + } + raise(signal); + std::thread::sleep(Duration::from_secs(5)); + std::process::exit(NOT_CLEANED); +}