Run the quit cleanup on a plain kill, Ctrl+C and a closing terminal

AI Assisted
This commit is contained in:
Seth committed 2026-12-05 00:10:44 -08:00
1 parent 6a93395148
commit 8c028c1ce0
7 files changed
+458 -3

No files matched your search

+2 -1
View File
@@ -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 };
@@ -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");
+3
View File
@@ -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;
+10
View File
@@ -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}");
}
+20 -2
View File
@@ -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(())
})
+134
View File
@@ -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(())
}