Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/staged/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ dirs = "7.0"
tauri-plugin-clipboard-manager = "2.4.1"
tauri-plugin-window-state = "2.5.0"
reqwest = { version = "0.13.5", features = ["json"] }
tokio = { version = "1.53.1", features = ["sync", "process", "io-util", "macros", "rt-multi-thread", "time", "fs"] }
tokio = { version = "1.53.1", features = ["sync", "process", "io-util", "macros", "rt-multi-thread", "time", "fs", "signal"] }
tauri-plugin-opener = "2"
tauri-plugin-dialog = "2"
tauri-plugin-process = "2"
Expand Down
70 changes: 70 additions & 0 deletions apps/staged/src-tauri/src/agent_watchdog.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
//! Making sure local agents never outlive Staged.
//!
//! Local agents run in sessions of their own, off Staged's terminal (see
//! `acp_client::agent_reaper`), so nothing stops them for free when Staged
//! goes. A session ending and a quit stop them through the driver; this
//! module covers the rest:
//!
//! - [`start`] starts the watchdog — this binary re-run with
//! [`WATCHDOG_ARG`] (see `main`) — which stops every agent still running
//! when Staged's end of its pipe closes, however Staged died: SIGKILL, an
//! abort, a crash, a panic, a signal.
//! - A fatal panic, and the end of every exit that goes through the event
//! loop, stop the agents in process should the watchdog not be running
//! ([`reap_now_if_unwatched`]).
//! - SIGINT, SIGTERM and SIGHUP quit through the ordinary shutdown (see
//! `app_lifecycle::exit_signals`), so sessions are recorded as stopped by
//! the quit rather than found orphaned on the next launch.

use std::thread::ThreadId;
use std::time::Duration;

pub use acp_client::agent_reaper::WATCHDOG_ARG;
use acp_client::agent_reaper::{reap_now_if_unwatched, start_watchdog};

/// How long agents get between SIGTERM and SIGKILL when Staged stops them
/// itself on its way out, with no watchdog to do it after the exit.
const IN_PROCESS_GRACE: Duration = Duration::from_millis(500);

/// Start the watchdog and the fatal-panic fallback. Call once, on the main
/// thread, before any agent can start. The outcome is for the log, which is
/// not set up yet.
pub fn start() -> Result<(), String> {
stop_agents_on_a_fatal_panic(std::thread::current().id());
let program = std::env::current_exe()
.map_err(|error| format!("cannot find Staged's own binary: {error}"))?;
start_watchdog(&program)
.map_err(|error| format!("cannot start {} {WATCHDOG_ARG}: {error}", program.display()))
}

/// Log what [`start`] returned.
pub fn log_start(started: &Result<(), String>) {
match started {
Ok(()) => log::info!("Agent reaper watchdog started"),
Err(error) => log::warn!(
"Agent reaper watchdog not started ({error}); agents will only be stopped on exits \
Staged sees"
),
}
}

/// The end of an exit Staged sees: stop whatever agents the shutdown left,
/// unless the watchdog will.
pub fn on_exit() {
if reap_now_if_unwatched(IN_PROCESS_GRACE) {
log::warn!("Stopped agents left running at exit without the watchdog");
}
}

/// A panic that ends the process — one on `main_thread`, or any when panics
/// abort — stops the agents in process when there is no watchdog. A panic on
/// another thread leaves Staged running, and its agents with it.
fn stop_agents_on_a_fatal_panic(main_thread: ThreadId) {
let report_panic = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
report_panic(info);
if cfg!(panic = "abort") || std::thread::current().id() == main_thread {
reap_now_if_unwatched(IN_PROCESS_GRACE);
}
}));
}
11 changes: 8 additions & 3 deletions apps/staged/src-tauri/src/app_lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@
//! **Quitting with sessions running asks first, then stops them cleanly.**
//! [`request_quit`] gates on active sessions and asks; [`shutdown_cleanup`]
//! cancels sessions with [`CompletionReason::AppQuit`] and stops actions. That
//! cancel is the only thing that shuts an agent down: ACP children are spawned
//! with `process_group(0)` and `kill_on_drop`, and `process::exit` runs no
//! destructors, so a bare exit leaves the agent CLIs running. Blox sessions are
//! cancel is what shuts an agent down cleanly: local ACP agents run in
//! sessions of their own, off Staged's terminal, and `process::exit` runs no
//! destructors. Whatever a quit leaves running — or a death the app never
//! sees, SIGKILL or a crash — the agent reaper's watchdog stops once the
//! process is gone (see [`crate::agent_watchdog`]); SIGINT, SIGTERM and SIGHUP
//! come through here as a quit (see [`exit_signals`]). Blox sessions are
//! the exception: their agent runs on the workstation, so a quit *detaches*
//! them instead — it kills only the local `blox acp` proxy, sending no
//! `session/cancel`, and leaves the row `disconnected` with the turn still
Expand Down Expand Up @@ -67,6 +70,8 @@ use crate::session_commands::{self, ActiveSessionInfo};
use crate::session_runner::SessionRegistry;
use crate::store::{CompletionReason, Session, SessionStatus, Store};

#[cfg(unix)]
pub(crate) mod exit_signals;
pub(crate) mod window_raise;
pub mod window_reveal;
pub(crate) mod window_use;
Expand Down
73 changes: 73 additions & 0 deletions apps/staged/src-tauri/src/app_lifecycle/exit_signals.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
//! SIGINT, SIGTERM and SIGHUP: quit the way a confirmed quit does.
//!
//! Ctrl-C in the terminal Staged was started from, the terminal closing, or a
//! plain `kill`. Local agents no longer share Staged's terminal (they run in
//! sessions of their own), so those signals no longer reach them; and left to
//! their default action they would end Staged without recording anything,
//! leaving its sessions for the next launch to find orphaned. So the first
//! one runs [`shutdown_cleanup`] — no confirmation, the signal is the answer
//! — and exits. A second signal, or a shutdown that overruns
//! [`FORCED_EXIT_AFTER`], exits at once; the agent reaper's watchdog stops
//! whatever agents are left once the process is gone.

use std::time::Duration;

use tauri::AppHandle;
use tokio::signal::unix::{signal, Signal, SignalKind};

use super::shutdown_cleanup;

/// How long a signalled quit may take before the process exits anyway. Well
/// past the shutdown's own budgets, which are what a healthy quit spends.
const FORCED_EXIT_AFTER: Duration = Duration::from_secs(15);

/// Start listening for the signals. Call from inside the async runtime's
/// reach (`setup`), once.
pub(crate) fn install(app: &AppHandle) {
let app = app.clone();
tauri::async_runtime::spawn(async move {
let listeners = (
signal(SignalKind::interrupt()),
signal(SignalKind::terminate()),
signal(SignalKind::hangup()),
);
let (Ok(mut interrupt), Ok(mut terminate), Ok(mut hangup)) = listeners else {
log::warn!("Cannot listen for SIGINT/SIGTERM/SIGHUP; they will end Staged at once");
return;
};

let (name, number) = next_signal(&mut interrupt, &mut terminate, &mut hangup).await;
log::info!("Received {name}; quitting and stopping sessions");
let quitting = app.clone();
std::thread::spawn(move || {
shutdown_cleanup(&quitting);
quitting.exit(128 + number);
});

let why = tokio::select! {
(name, _) = next_signal(&mut interrupt, &mut terminate, &mut hangup) => {
format!("received {name} again")
}
() = tokio::time::sleep(FORCED_EXIT_AFTER) => {
format!("the quit took longer than {}s", FORCED_EXIT_AFTER.as_secs())
}
};
log::warn!("Exiting at once: {why}");
crate::agent_watchdog::on_exit();
log::logger().flush();
crate::app_log::flush_terminal();
std::process::exit(128 + number);
});
}

async fn next_signal(
interrupt: &mut Signal,
terminate: &mut Signal,
hangup: &mut Signal,
) -> (&'static str, i32) {
tokio::select! {
_ = interrupt.recv() => ("SIGINT", libc::SIGINT),
_ = terminate.recv() => ("SIGTERM", libc::SIGTERM),
_ = hangup.recv() => ("SIGHUP", libc::SIGHUP),
}
}
7 changes: 7 additions & 0 deletions apps/staged/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub mod acp_tools;
pub mod acp_tools_reconciler;
pub mod actions;
pub mod agent;
pub mod agent_watchdog;
pub mod app_lifecycle;
mod app_log;
pub mod background_sync;
Expand Down Expand Up @@ -1920,6 +1921,8 @@ pub fn run() {
// to the page in an initialization script, and windows are built before
// `setup` runs; it starts answering in `setup`. The script names the
// address only to the app's own pages, whose origin the config decides.
// First, so no agent can start unwatched.
let agent_watchdog = agent_watchdog::start();
let context = tauri::generate_context!();
let media_index = Arc::new(note_media::serving::MediaIndex::default());
let media_stream = note_media::stream::MediaStream::bind();
Expand Down Expand Up @@ -2502,6 +2505,9 @@ pub fn run() {
}

app.handle().plugin(app_log::plugin())?;
agent_watchdog::log_start(&agent_watchdog);
#[cfg(unix)]
app_lifecycle::exit_signals::install(app.handle());
Ok(())
})
.on_menu_event(|app, event| {
Expand Down Expand Up @@ -2878,6 +2884,7 @@ pub fn run() {
// the agent and action child processes.
tauri::RunEvent::Exit => {
app_lifecycle::shutdown_cleanup(app_handle);
agent_watchdog::on_exit();
// Every exit through this loop passes here last.
app_log::flush_terminal();
}
Expand Down
10 changes: 10 additions & 0 deletions apps/staged/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,15 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

fn main() {
// The agent reaper's watchdog is this binary re-run (see
// `staged_lib::agent_watchdog`); it must not start the app.
#[cfg(unix)]
if std::env::args_os().nth(1).as_deref()
== Some(std::ffi::OsStr::new(
staged_lib::agent_watchdog::WATCHDOG_ARG,
))
{
acp_client::agent_reaper::run_watchdog();
}
staged_lib::run();
}
2 changes: 0 additions & 2 deletions crates/acp-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,4 @@ tokio = { version = "1", features = ["test-util"] }

[target.'cfg(unix)'.dependencies]
nix = { version = "0.31", features = ["signal"] }

[target.'cfg(target_os = "macos")'.dependencies]
libc = "0.2"
Loading