Skip to content

armgit / herdr

Public Imported from GitHub
0

the runtime your coding agents live on

fix: keep agent sessions while the agent is suspended or backgrounded (#4964)

Can Celik950d012cf0cf
diff --git a/src/app/agent_suspend_tests.rs b/src/app/agent_suspend_tests.rs
new file mode 100644
index 000000000..50546d25a
--- /dev/null
+++ b/src/app/agent_suspend_tests.rs
@@ -0,0 +1,285 @@
+//! Agent identity across foreground changes: real exits, relaunches, and
+//! an agent suspended behind the shell.
+
+use std::time::{Duration, Instant};
+
+use crate::agent_resume::AgentSessionRef;
+use crate::app::state::AppState;
+use crate::detect::{Agent, AgentState};
+use crate::events::AppEvent;
+use crate::layout::PaneId;
+use crate::terminal::TerminalId;
+
+fn adversarial_pane() -> (AppState, PaneId, TerminalId) {
+ let app = AppState::test_with_adversarial_identity_state();
+ let ws = &app.workspaces[0];
+ let pane_id = ws.tabs[ws.active_tab].root_pane;
+ let terminal_id = ws.panes[&pane_id].attached_terminal_id.clone();
+ (app, pane_id, terminal_id)
+}
+
+fn pi_session() -> AgentSessionRef {
+ AgentSessionRef::path(
+ std::env::current_dir()
+ .expect("cwd")
+ .join("takeover-pi.jsonl")
+ .display()
+ .to_string(),
+ )
+ .expect("pi session path")
+}
+
+fn claude_session() -> AgentSessionRef {
+ AgentSessionRef::id("2f0c0c2e-1647-4a4b-9a3e-0000000c1a0d").expect("claude session id")
+}
+
+fn detect(app: &mut AppState, pane_id: PaneId, agent: Agent, at: Instant) {
+ app.handle_app_event(AppEvent::AgentProcessDetected {
+ pane_id,
+ agent,
+ observed_at: at,
+ });
+}
+
+fn detection_state(
+ app: &mut AppState,
+ pane_id: PaneId,
+ agent: Option<Agent>,
+ process_exited: bool,
+ at: Instant,
+) {
+ app.handle_app_event(AppEvent::StateChanged {
+ pane_id,
+ agent,
+ state: AgentState::Idle,
+ visible_blocker: false,
+ visible_working: false,
+ process_exited,
+ observed_at: at,
+ });
+}
+
+/// The two events the detection loop publishes when the pane shell takes the
+/// foreground back from an agent whose process is gone.
+fn real_exit(app: &mut AppState, pane_id: PaneId, agent: Agent, at: Instant) {
+ detection_state(app, pane_id, Some(agent), true, at);
+ detection_state(app, pane_id, None, false, at + Duration::from_millis(1));
+}
+
+fn pi_report(app: &mut AppState, pane_id: PaneId, state: AgentState, seq: u64) {
+ app.handle_app_event(AppEvent::HookStateReported {
+ pane_id,
+ source: "herdr:pi".into(),
+ agent_label: "pi".into(),
+ state,
+ message: None,
+ seq: Some(seq),
+ session_ref: Some(pi_session()),
+ });
+}
+
+fn pi_session_report(
+ app: &mut AppState,
+ pane_id: PaneId,
+ session_start_source: Option<&str>,
+ seq: u64,
+) {
+ app.handle_app_event(AppEvent::AgentSessionReported {
+ pane_id,
+ source: "herdr:pi".into(),
+ agent_label: "pi".into(),
+ seq: Some(seq),
+ session_ref: Some(pi_session()),
+ session_start_source: session_start_source.map(str::to_string),
+ });
+}
+
+fn claude_session_report(app: &mut AppState, pane_id: PaneId, seq: u64) {
+ app.handle_app_event(AppEvent::AgentSessionReported {
+ pane_id,
+ source: "herdr:claude".into(),
+ agent_label: "claude".into(),
+ seq: Some(seq),
+ session_ref: Some(claude_session()),
+ session_start_source: Some("startup".into()),
+ });
+}
+
+fn session_value(app: &AppState, terminal_id: &TerminalId) -> Option<String> {
+ let terminal = &app.terminals[terminal_id];
+ terminal
+ .hook_authority
+ .as_ref()
+ .and_then(|authority| authority.session_ref.as_ref())
+ .or_else(|| {
+ terminal
+ .persisted_agent_session
+ .as_ref()
+ .map(|session| &session.session_ref)
+ })
+ .map(|session_ref| session_ref.value.clone())
+}
+
+fn name_agent(app: &mut AppState, terminal_id: &TerminalId, name: &str) {
+ app.terminals
+ .get_mut(terminal_id)
+ .expect("terminal")
+ .set_agent_name(name.into());
+}
+
+fn pi_with_live_authority(start: Instant) -> (AppState, PaneId, TerminalId) {
+ let (mut app, pane_id, terminal_id) = adversarial_pane();
+ detect(&mut app, pane_id, Agent::Pi, start);
+ pi_session_report(&mut app, pane_id, Some("startup"), 99);
+ pi_report(&mut app, pane_id, AgentState::Working, 100);
+ name_agent(&mut app, &terminal_id, "worker");
+ assert!(app.terminals[&terminal_id].full_lifecycle_hook_authority_active());
+ assert_eq!(session_value(&app, &terminal_id), Some(pi_session().value));
+ (app, pane_id, terminal_id)
+}
+
+fn claude_with_session(start: Instant) -> (AppState, PaneId, TerminalId) {
+ let (mut app, pane_id, terminal_id) = adversarial_pane();
+ detect(&mut app, pane_id, Agent::Claude, start);
+ claude_session_report(&mut app, pane_id, 1);
+ name_agent(&mut app, &terminal_id, "c1");
+ assert_eq!(
+ session_value(&app, &terminal_id),
+ Some(claude_session().value)
+ );
+ (app, pane_id, terminal_id)
+}
+
+#[test]
+fn real_exit_clears_claude_session_and_name() {
+ let start = Instant::now();
+ let (mut app, pane_id, terminal_id) = claude_with_session(start);
+
+ real_exit(
+ &mut app,
+ pane_id,
+ Agent::Claude,
+ start + Duration::from_secs(1),
+ );
+
+ let terminal = &app.terminals[&terminal_id];
+ assert_eq!(session_value(&app, &terminal_id), None);
+ assert_eq!(terminal.agent_name, None);
+ assert_eq!(terminal.effective_agent_label(), None);
+ app.assert_invariants_for_test();
+}
+
+#[test]
+fn real_exit_clears_pi_session_name_and_authority() {
+ let start = Instant::now();
+ let (mut app, pane_id, terminal_id) = pi_with_live_authority(start);
+
+ real_exit(&mut app, pane_id, Agent::Pi, start + Duration::from_secs(1));
+
+ let terminal = &app.terminals[&terminal_id];
+ assert_eq!(session_value(&app, &terminal_id), None);
+ assert!(terminal.hook_authority.is_none());
+ assert_eq!(terminal.agent_name, None);
+ assert_eq!(terminal.effective_agent_label(), None);
+ app.assert_invariants_for_test();
+}
+
+#[test]
+fn exit_then_different_agent_relaunch_drops_previous_identity() {
+ let start = Instant::now();
+ let (mut app, pane_id, terminal_id) = claude_with_session(start);
+
+ real_exit(
+ &mut app,
+ pane_id,
+ Agent::Claude,
+ start + Duration::from_secs(1),
+ );
+ detect(
+ &mut app,
+ pane_id,
+ Agent::Codex,
+ start + Duration::from_secs(2),
+ );
+
+ let terminal = &app.terminals[&terminal_id];
+ assert_eq!(session_value(&app, &terminal_id), None);
+ assert_eq!(terminal.agent_name, None);
+ assert_eq!(terminal.effective_agent_label(), Some("codex"));
+ app.assert_invariants_for_test();
+}
+
+#[test]
+fn exited_pi_session_is_not_replayed_into_a_relaunched_pi() {
+ let start = Instant::now();
+ let (mut app, pane_id, terminal_id) = pi_with_live_authority(start);
+
+ real_exit(&mut app, pane_id, Agent::Pi, start + Duration::from_secs(1));
+ detect(&mut app, pane_id, Agent::Pi, start + Duration::from_secs(2));
+ // A late report from the exited process still carries its old session.
+ pi_report(&mut app, pane_id, AgentState::Working, 101);
+
+ let terminal = &app.terminals[&terminal_id];
+ assert!(!terminal.full_lifecycle_hook_authority_active());
+ assert_eq!(session_value(&app, &terminal_id), None);
+ app.assert_invariants_for_test();
+}
+
+#[test]
+fn suspended_pi_keeps_session_name_and_authority_for_its_next_reports() {
+ let start = Instant::now();
+ let (mut app, pane_id, terminal_id) = pi_with_live_authority(start);
+
+ // While Pi's job is stopped behind the shell, detection publishes nothing.
+ // After `fg`, Pi re-announces its session on agent_start and reports state.
+ pi_session_report(&mut app, pane_id, None, 101);
+ pi_report(&mut app, pane_id, AgentState::Idle, 102);
+
+ let terminal = &app.terminals[&terminal_id];
+ assert!(terminal.full_lifecycle_hook_authority_active());
+ assert_eq!(terminal.state, AgentState::Idle);
+ assert_eq!(terminal.agent_name.as_deref(), Some("worker"));
+ assert_eq!(session_value(&app, &terminal_id), Some(pi_session().value));
+ app.assert_invariants_for_test();
+}
+
+/// The events detection publishes when a new process of the same agent kind
+/// replaces the previous one without the shell in between.
+fn same_kind_replacement(app: &mut AppState, pane_id: PaneId, agent: Agent, at: Instant) {
+ detection_state(app, pane_id, Some(agent), true, at);
+ detect(app, pane_id, agent, at + Duration::from_millis(1));
+}
+
+#[test]
+fn same_kind_replacement_drops_the_previous_claude_session() {
+ let start = Instant::now();
+ let (mut app, pane_id, terminal_id) = claude_with_session(start);
+
+ same_kind_replacement(
+ &mut app,
+ pane_id,
+ Agent::Claude,
+ start + Duration::from_secs(1),
+ );
+
+ assert_eq!(session_value(&app, &terminal_id), None);
+ assert_eq!(
+ app.terminals[&terminal_id].effective_agent_label(),
+ Some("claude")
+ );
+ app.assert_invariants_for_test();
+}
+
+#[test]
+fn same_kind_replacement_drops_the_previous_pi_session_and_authority() {
+ let start = Instant::now();
+ let (mut app, pane_id, terminal_id) = pi_with_live_authority(start);
+
+ same_kind_replacement(&mut app, pane_id, Agent::Pi, start + Duration::from_secs(1));
+ pi_report(&mut app, pane_id, AgentState::Working, 101);
+
+ let terminal = &app.terminals[&terminal_id];
+ assert!(!terminal.full_lifecycle_hook_authority_active());
+ assert_eq!(session_value(&app, &terminal_id), None);
+ app.assert_invariants_for_test();
+}
diff --git a/src/app/mod.rs b/src/app/mod.rs
index 1f70ecfdc..0f27446a2 100644
--- a/src/app/mod.rs
+++ b/src/app/mod.rs
@@ -5,6 +5,8 @@
pub(crate) mod actions;
mod agent_resume;
+#[cfg(test)]
+mod agent_suspend_tests;
pub(crate) mod agent_view;
mod agents;
pub(crate) use agents::{AGENT_START_SETTLE_DELAY, MAX_AGENT_START_TIMEOUT};
diff --git a/src/detect/mod.rs b/src/detect/mod.rs
index afdeed815..380a41fbd 100644
--- a/src/detect/mod.rs
+++ b/src/detect/mod.rs
@@ -247,6 +247,13 @@ pub fn identify_agent(process_name: &str) -> Option<Agent> {
}
pub fn identify_agent_in_job(job: &crate::platform::ForegroundJob) -> Option<(Agent, String)> {
+ identify_agent_process_in_job(job).map(|(agent, name, _)| (agent, name))
+}
+
+/// Like [`identify_agent_in_job`], plus the pid of the process that matched.
+pub fn identify_agent_process_in_job(
+ job: &crate::platform::ForegroundJob,
+) -> Option<(Agent, String, u32)> {
if let Some(process) = job
.processes
.iter()
@@ -255,12 +262,12 @@ pub fn identify_agent_in_job(job: &crate::platform::ForegroundJob) -> Option<(Ag
let candidate = normalized_process_name(process);
if let Some(agent) = identify_agent(&candidate) {
if agent != Agent::Letta || is_interactive_letta_process(process) {
- return Some((agent, candidate));
+ return Some((agent, candidate, process.pid));
}
}
}
- let mut best: Option<(u8, Agent, String)> = None;
+ let mut best: Option<(u8, Agent, String, u32)> = None;
for process in &job.processes {
let candidate = normalized_process_name(process);
@@ -273,12 +280,12 @@ pub fn identify_agent_in_job(job: &crate::platform::ForegroundJob) -> Option<(Ag
let score = process_priority(process, &candidate);
match &best {
- Some((best_score, _, _)) if *best_score >= score => {}
- _ => best = Some((score, agent, candidate)),
+ Some((best_score, ..)) if *best_score >= score => {}
+ _ => best = Some((score, agent, candidate, process.pid)),
}
}
- best.map(|(_, agent, name)| (agent, name))
+ best.map(|(_, agent, name, pid)| (agent, name, pid))
}
/// Detect the state of an agent from the live terminal tail snapshot.
diff --git a/src/pane.rs b/src/pane.rs
index 6e96e3b85..a48f77323 100644
--- a/src/pane.rs
+++ b/src/pane.rs
@@ -25,6 +25,7 @@ use crate::pty::actor::{PtyIoActor, PtyIoActorConfig, PtyIoActorHandle, PtyReadR
use crate::render_signal::RenderSignal;
mod agent_detection;
+mod background_agent;
mod cursor;
mod input;
mod kitty_keyboard;
@@ -40,6 +41,7 @@ use self::agent_detection::{
DetectionScreenReadInput, PendingIdleConfirmation, ScreenDetectionPublishInput,
AGENT_PENDING_IDLE_RECHECK, AGENT_STARTUP_GRACE_WINDOW,
};
+use self::background_agent::{AgentJobStatus, AgentJobTracker};
#[cfg(unix)]
pub use self::terminal::InputState;
use self::terminal::{GhosttyPaneTerminal, PaneTerminal};
@@ -443,6 +445,7 @@ fn foreground_member_cwd_different_from_shell(
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ForegroundShellAgentAction {
ObserveProbe,
+ HoldBackgroundAgent,
ReportProcessExit,
ReportReplacementProcess,
ClearAgent,
@@ -453,6 +456,7 @@ fn foreground_shell_agent_action(
new_agent: Option<Agent>,
foreground_is_pane_shell: bool,
process_exit_reported: bool,
+ agent_job: AgentJobStatus,
) -> ForegroundShellAgentAction {
let Some(previous_agent) = previous_agent else {
return ForegroundShellAgentAction::ObserveProbe;
@@ -466,9 +470,18 @@ fn foreground_shell_agent_action(
ForegroundShellAgentAction::ObserveProbe
};
}
+ if agent_job == AgentJobStatus::ReplacedInFront {
+ // The held agent's identity must not pass to the new process.
+ return ForegroundShellAgentAction::ReportProcessExit;
+ }
if new_agent.is_some() {
return ForegroundShellAgentAction::ObserveProbe;
}
+ match agent_job {
+ AgentJobStatus::Background => return ForegroundShellAgentAction::HoldBackgroundAgent,
+ AgentJobStatus::ExitedInBackground => return ForegroundShellAgentAction::ReportProcessExit,
+ AgentJobStatus::Unknown | AgentJobStatus::ReplacedInFront => {}
+ }
if foreground_is_pane_shell {
// Do not clear identity immediately. First publish an idle process-exit
@@ -504,6 +517,11 @@ fn apply_foreground_shell_agent_action(
agent_presence.observe_process_probe(previous_agent);
true
}
+ ForegroundShellAgentAction::HoldBackgroundAgent => {
+ *pending_foreground_shell_clear = false;
+ *foreground_shell_exit_reported = false;
+ agent_presence.observe_process_probe(previous_agent)
+ }
ForegroundShellAgentAction::ReportProcessExit => {
*pending_foreground_shell_clear = true;
false
@@ -521,6 +539,109 @@ fn apply_foreground_shell_agent_action(
}
}
+/// Process facts used to tell a backgrounded agent from an exited one.
+trait AgentProcessLiveness {
+ fn start_token(&self, pid: u32) -> Option<u64>;
+ fn live_process_group(&self, shell_pid: u32, pid: u32, start_token: u64) -> Option<u32>;
+}
+
+struct PlatformAgentProcesses;
+
+impl AgentProcessLiveness for PlatformAgentProcesses {
+ fn start_token(&self, pid: u32) -> Option<u64> {
+ crate::platform::process_start_token(pid)
+ }
+
+ fn live_process_group(&self, shell_pid: u32, pid: u32, start_token: u64) -> Option<u32> {
+ crate::platform::live_pane_process_group(shell_pid, pid, start_token)
+ }
+}
+
+/// One foreground probe result, after a suppressed agent has been filtered out.
+#[derive(Debug, Clone, Copy)]
+struct ForegroundAgentObservation {
+ shell_pid: u32,
+ agent: Option<Agent>,
+ agent_pid: Option<u32>,
+ process_group_id: Option<u32>,
+ foreground_is_pane_shell: bool,
+}
+
+/// Applies one foreground probe to the pane's agent presence. Returns the
+/// chosen action and whether the current agent changed.
+fn observe_foreground_agent(
+ agent_presence: &mut AgentDetectionPresence,
+ agent_job: &mut AgentJobTracker,
+ pending_foreground_shell_clear: &mut bool,
+ foreground_shell_exit_reported: &mut bool,
+ observation: ForegroundAgentObservation,
+ processes: &impl AgentProcessLiveness,
+ pane_id: PaneId,
+) -> (ForegroundShellAgentAction, bool) {
+ let previous_agent = agent_presence.current_agent();
+ let same_agent_in_front = previous_agent.is_some()
+ && observation.agent == previous_agent
+ && !*foreground_shell_exit_reported;
+ let agent_job_status = if same_agent_in_front
+ && agent_job.replaced_in_front(observation.agent_pid, |pid| processes.start_token(pid))
+ {
+ AgentJobStatus::ReplacedInFront
+ } else {
+ agent_job.status(
+ previous_agent.is_some()
+ && observation.agent.is_none()
+ && !*foreground_shell_exit_reported,
+ observation.shell_pid,
+ observation.process_group_id,
+ |shell_pid, pid, start_token| processes.live_process_group(shell_pid, pid, start_token),
+ )
+ };
+ let action = foreground_shell_agent_action(
+ previous_agent,
+ observation.agent,
+ observation.foreground_is_pane_shell,
+ *foreground_shell_exit_reported,
+ agent_job_status,
+ );
+ let changed = apply_foreground_shell_agent_action(
+ agent_presence,
+ action,
+ previous_agent,
+ observation.agent,
+ pending_foreground_shell_clear,
+ foreground_shell_exit_reported,
+ );
+ let was_in_background = agent_job.in_background();
+ agent_job.observe(
+ agent_job_status,
+ agent_presence.current_agent(),
+ observation.agent,
+ observation.agent_pid,
+ |pid| processes.start_token(pid),
+ );
+ if was_in_background != agent_job.in_background() {
+ info!(
+ pane = pane_id.raw(),
+ agent = ?agent_presence.current_agent(),
+ in_background = agent_job.in_background(),
+ "agent job foreground changed"
+ );
+ }
+ (action, changed)
+}
+
+/// Lifecycle-hook authority normally skips steady-state probes, but a held
+/// agent is invisible to its hooks once killed, so it keeps the probe cadence.
+fn should_check_foreground_process(
+ lifecycle_authority_active: bool,
+ agent_held_in_background: bool,
+ input: ProcessProbeInput,
+) -> bool {
+ (agent_held_in_background
+ || !should_skip_process_probe_for_lifecycle_authority(lifecycle_authority_active, input))
+ && should_probe_foreground_job(input)
+}
+
#[derive(Debug, Clone, Copy)]
struct ProcessProbeInput {
current_agent: Option<Agent>,
@@ -663,25 +784,28 @@ struct ProcessProbeResult {
process_group_id: Option<u32>,
foreground_is_pane_shell: bool,
agent: Option<Agent>,
+ /// The process that identified as `agent`, which need not lead its job.
+ agent_pid: Option<u32>,
process_name: Option<String>,
}
fn agent_hint_for_foreground_job_members(
job: &crate::platform::ForegroundJob,
read_hint: impl Fn(u32) -> Option<Agent>,
-) -> Option<Agent> {
+) -> Option<(Agent, u32)> {
read_hint(job.process_group_id)
+ .map(|agent| (agent, job.process_group_id))
.or_else(|| agent_hint_for_non_leader_foreground_job_members(job, read_hint))
}
fn agent_hint_for_non_leader_foreground_job_members(
job: &crate::platform::ForegroundJob,
read_hint: impl Fn(u32) -> Option<Agent>,
-) -> Option<Agent> {
+) -> Option<(Agent, u32)> {
job.processes
.iter()
.filter(|process| process.pid != job.process_group_id)
- .find_map(|process| read_hint(process.pid))
+ .find_map(|process| read_hint(process.pid).map(|agent| (agent, process.pid)))
}
fn identify_process_group_leader_in_job(
@@ -701,13 +825,13 @@ fn identify_process_group_leader_in_job(
fn process_probe_result(
job: &crate::platform::ForegroundJob,
pid: u32,
- agent: Agent,
- process_name: String,
+ (agent, process_name, agent_pid): (Agent, String, u32),
) -> ProcessProbeResult {
ProcessProbeResult {
process_group_id: Some(job.process_group_id),
foreground_is_pane_shell: job.processes.iter().any(|process| process.pid == pid),
agent: Some(agent),
+ agent_pid: Some(agent_pid),
process_name: Some(process_name),
}
}
@@ -715,15 +839,17 @@ fn process_probe_result(
fn hinted_process_probe_result(
job: &crate::platform::ForegroundJob,
pid: u32,
- read_hint: impl Fn(u32) -> Option<Agent>,
-) -> Option<ProcessProbeResult> {
- let agent = agent_hint_for_foreground_job_members(job, read_hint)?;
- Some(process_probe_result(
+ (agent, agent_pid): (Agent, u32),
+) -> ProcessProbeResult {
+ process_probe_result(
job,
pid,
- agent,
- crate::detect::agent_label(agent).to_string(),
- ))
+ (
+ agent,
+ crate::detect::agent_label(agent).to_string(),
+ agent_pid,
+ ),
+ )
}
fn probe_foreground_process_from_jobs(
@@ -734,42 +860,34 @@ fn probe_foreground_process_from_jobs(
read_hint: impl Fn(u32) -> Option<Agent> + Copy,
) -> ProcessProbeResult {
if let Some(job) = leader_job.as_ref() {
- if let Some(hinted) = hinted_process_probe_result(job, pid, read_hint) {
- return hinted;
+ if let Some(hinted) = agent_hint_for_foreground_job_members(job, read_hint) {
+ return hinted_process_probe_result(job, pid, hinted);
}
- if let Some((agent, process_name)) = crate::detect::identify_agent_in_job(job) {
- return process_probe_result(job, pid, agent, process_name);
+ if let Some(identified) = crate::detect::identify_agent_process_in_job(job) {
+ return process_probe_result(job, pid, identified);
}
}
let foreground_job = foreground_job();
if let Some(job) = foreground_job.as_ref() {
if let Some(agent) = read_hint(job.process_group_id) {
- return process_probe_result(
- job,
- pid,
- agent,
- crate::detect::agent_label(agent).to_string(),
- );
+ return hinted_process_probe_result(job, pid, (agent, job.process_group_id));
}
if let Some((agent, process_name)) = identify_process_group_leader_in_job(job) {
- return process_probe_result(job, pid, agent, process_name);
+ return process_probe_result(job, pid, (agent, process_name, job.process_group_id));
}
- if let Some(agent) = agent_hint_for_non_leader_foreground_job_members(job, read_hint) {
- return process_probe_result(
- job,
- pid,
- agent,
- crate::detect::agent_label(agent).to_string(),
- );
+ if let Some(hinted) = agent_hint_for_non_leader_foreground_job_members(job, read_hint) {
+ return hinted_process_probe_result(job, pid, hinted);
+ }
+ if let Some(identified) = crate::detect::identify_agent_process_in_job(job) {
+ return process_probe_result(job, pid, identified);
}
-
- let identified = crate::detect::identify_agent_in_job(job);
return ProcessProbeResult {
process_group_id: Some(job.process_group_id),
foreground_is_pane_shell: job.processes.iter().any(|process| process.pid == pid),
- agent: identified.as_ref().map(|(agent, _)| *agent),
- process_name: identified.map(|(_, process_name)| process_name),
+ agent: None,
+ agent_pid: None,
+ process_name: None,
};
}
@@ -777,6 +895,7 @@ fn probe_foreground_process_from_jobs(
process_group_id: foreground_pgid,
foreground_is_pane_shell: false,
agent: None,
+ agent_pid: None,
process_name: None,
}
}
@@ -831,6 +950,7 @@ fn spawn_basic_detection_task(
let mut pending_idle = PendingIdleConfirmation::default();
let mut last_codex_prompt_ready = false;
let mut last_self_reported_shell_check = None;
+ let mut agent_job = AgentJobTracker::default();
loop {
let sleep_duration = if pending_idle.active() {
@@ -863,6 +983,7 @@ fn spawn_basic_detection_task(
last_screen_scan_detection_content_seq = None;
agent_startup_grace_until = None;
pending_idle.clear();
+ agent_job = AgentJobTracker::default();
}
}
@@ -906,10 +1027,11 @@ fn spawn_basic_detection_task(
pending_restore_probe: false,
elapsed_since_process_check: now.duration_since(last_process_check),
};
- !should_skip_process_probe_for_lifecycle_authority(
+ should_check_foreground_process(
lifecycle_authority_active,
+ agent_job.in_background(),
process_probe_input,
- ) && should_probe_foreground_job(process_probe_input)
+ )
};
if should_check_process {
@@ -930,19 +1052,20 @@ fn spawn_basic_detection_task(
}
}
let previous_agent = agent_presence.current_agent();
- let foreground_action = foreground_shell_agent_action(
- previous_agent,
- new_agent,
- foreground_is_pane_shell,
- foreground_shell_exit_reported,
- );
- let changed = apply_foreground_shell_agent_action(
+ let (foreground_action, changed) = observe_foreground_agent(
&mut agent_presence,
- foreground_action,
- previous_agent,
- new_agent,
+ &mut agent_job,
&mut pending_foreground_shell_clear,
&mut foreground_shell_exit_reported,
+ ForegroundAgentObservation {
+ shell_pid: pid,
+ agent: new_agent,
+ agent_pid: new_agent.and(probe.agent_pid),
+ process_group_id,
+ foreground_is_pane_shell,
+ },
+ &PlatformAgentProcesses,
+ pane_id,
);
last_foreground_pgid = tracked_process_group_id;
if new_agent.is_some() {
@@ -992,7 +1115,9 @@ fn spawn_basic_detection_task(
&& agent.is_some()
&& !foreground_shell_exit_reported;
- if lifecycle_authority_active && !process_exited {
+ // The visible screen belongs to another job while the agent waits
+ // in the background, so it says nothing about the agent's state.
+ if (lifecycle_authority_active || agent_job.in_background()) && !process_exited {
pending_idle.clear();
continue;
}
@@ -2748,6 +2873,7 @@ impl PaneRuntime {
let mut pending_idle = PendingIdleConfirmation::default();
let mut last_codex_prompt_ready = false;
let mut last_self_reported_shell_check = None;
+ let mut agent_job = AgentJobTracker::default();
tokio::time::sleep(Duration::from_millis(50)).await;
@@ -2790,6 +2916,7 @@ impl PaneRuntime {
last_screen_scan_detection_content_seq = None;
agent_startup_grace_until = None;
pending_idle.clear();
+ agent_job = AgentJobTracker::default();
}
}
@@ -2859,10 +2986,11 @@ impl PaneRuntime {
foreground_pgid,
..process_probe_input
};
- !should_skip_process_probe_for_lifecycle_authority(
+ should_check_foreground_process(
lifecycle_authority_active,
+ agent_job.in_background(),
process_probe_input,
- ) && should_probe_foreground_job(process_probe_input)
+ )
};
let mut agent_changed = false;
@@ -2892,19 +3020,20 @@ impl PaneRuntime {
}
let previous_agent = agent_presence.current_agent();
- let foreground_action = foreground_shell_agent_action(
- previous_agent,
- new_agent,
- foreground_is_pane_shell,
- foreground_shell_exit_reported,
- );
- let changed = apply_foreground_shell_agent_action(
+ let (foreground_action, changed) = observe_foreground_agent(
&mut agent_presence,
- foreground_action,
- previous_agent,
- new_agent,
+ &mut agent_job,
&mut pending_foreground_shell_clear,
&mut foreground_shell_exit_reported,
+ ForegroundAgentObservation {
+ shell_pid: pid,
+ agent: new_agent,
+ agent_pid: new_agent.and(probe.agent_pid),
+ process_group_id,
+ foreground_is_pane_shell,
+ },
+ &PlatformAgentProcesses,
+ pane_id,
);
last_foreground_pgid = tracked_process_group_id;
if new_agent.is_some() {
@@ -2989,7 +3118,10 @@ impl PaneRuntime {
&& agent.is_some()
&& !foreground_shell_exit_reported;
- if lifecycle_authority_active && !process_exited {
+ // The visible screen belongs to another job while the agent
+ // waits in the background, so it says nothing about its state.
+ if (lifecycle_authority_active || agent_job.in_background()) && !process_exited
+ {
pending_idle.clear();
continue;
}
@@ -5104,11 +5236,23 @@ mod tests {
#[test]
fn foreground_shell_reports_process_exit_before_clearing_agent() {
assert_eq!(
- foreground_shell_agent_action(Some(Agent::Codex), None, true, false),
+ foreground_shell_agent_action(
+ Some(Agent::Codex),
+ None,
+ true,
+ false,
+ AgentJobStatus::Unknown
+ ),
ForegroundShellAgentAction::ReportProcessExit
);
assert_eq!(
- foreground_shell_agent_action(Some(Agent::Codex), None, true, true),
+ foreground_shell_agent_action(
+ Some(Agent::Codex),
+ None,
+ true,
+ true,
+ AgentJobStatus::Unknown
+ ),
ForegroundShellAgentAction::ClearAgent
);
}
@@ -5116,7 +5260,13 @@ mod tests {
#[test]
fn same_agent_after_reported_exit_is_a_replacement_process() {
assert_eq!(
- foreground_shell_agent_action(Some(Agent::Pi), Some(Agent::Pi), false, true),
+ foreground_shell_agent_action(
+ Some(Agent::Pi),
+ Some(Agent::Pi),
+ false,
+ true,
+ AgentJobStatus::Unknown
+ ),
ForegroundShellAgentAction::ReportReplacementProcess
);
}
@@ -5124,11 +5274,316 @@ mod tests {
#[test]
fn unknown_non_shell_foreground_job_is_not_immediate_clear_signal() {
assert_eq!(
- foreground_shell_agent_action(Some(Agent::Claude), None, false, false),
+ foreground_shell_agent_action(
+ Some(Agent::Claude),
+ None,
+ false,
+ false,
+ AgentJobStatus::Unknown
+ ),
ForegroundShellAgentAction::ObserveProbe
);
}
+ #[test]
+ fn shell_in_front_of_a_live_agent_job_holds_the_agent() {
+ for foreground_is_pane_shell in [true, false] {
+ assert_eq!(
+ foreground_shell_agent_action(
+ Some(Agent::Claude),
+ None,
+ foreground_is_pane_shell,
+ false,
+ AgentJobStatus::Background
+ ),
+ ForegroundShellAgentAction::HoldBackgroundAgent
+ );
+ }
+ }
+
+ #[test]
+ fn held_agent_job_exit_is_reported_behind_any_foreground_job() {
+ for foreground_is_pane_shell in [true, false] {
+ assert_eq!(
+ foreground_shell_agent_action(
+ Some(Agent::Pi),
+ None,
+ foreground_is_pane_shell,
+ false,
+ AgentJobStatus::ExitedInBackground
+ ),
+ ForegroundShellAgentAction::ReportProcessExit
+ );
+ }
+ }
+
+ /// Drives `observe_foreground_agent` the way the detection loops do, against
+ /// a fake process table of `pid -> (start token, process group)`.
+ mod held_agent {
+ use super::*;
+ use std::cell::RefCell;
+ use std::collections::HashMap;
+
+ pub(super) const SHELL: u32 = 10;
+ pub(super) const WRAPPER_JOB: u32 = 20;
+ pub(super) const AGENT_PID: u32 = 21;
+ const AGENT_START: u64 = 7_000;
+
+ #[derive(Default)]
+ pub(super) struct FakeProcesses(RefCell<HashMap<u32, (u64, u32)>>);
+
+ impl FakeProcesses {
+ pub(super) fn spawn(&self, pid: u32, start_token: u64, group: u32) {
+ self.0.borrow_mut().insert(pid, (start_token, group));
+ }
+
+ pub(super) fn exit(&self, pid: u32) {
+ self.0.borrow_mut().remove(&pid);
+ }
+ }
+
+ impl AgentProcessLiveness for FakeProcesses {
+ fn start_token(&self, pid: u32) -> Option<u64> {
+ self.0
+ .borrow()
+ .get(&pid)
+ .map(|(start_token, _)| *start_token)
+ }
+
+ fn live_process_group(
+ &self,
+ shell_pid: u32,
+ pid: u32,
+ start_token: u64,
+ ) -> Option<u32> {
+ assert_eq!(shell_pid, SHELL);
+ self.0
+ .borrow()
+ .get(&pid)
+ .filter(|(token, _)| *token == start_token)
+ .map(|(_, group)| *group)
+ }
+ }
+
+ pub(super) struct Pane {
+ pub(super) presence: AgentDetectionPresence,
+ pub(super) job: AgentJobTracker,
+ pub(super) processes: FakeProcesses,
+ pending_clear: bool,
+ exit_reported: bool,
+ }
+
+ impl Pane {
+ /// An agent process `AGENT_PID` under a wrapper that leads its job.
+ pub(super) fn with_agent(agent: Agent) -> Self {
+ let processes = FakeProcesses::default();
+ processes.spawn(WRAPPER_JOB, 6_000, WRAPPER_JOB);
+ processes.spawn(AGENT_PID, AGENT_START, WRAPPER_JOB);
+ let mut pane = Self {
+ presence: AgentDetectionPresence::from_agent(None),
+ job: AgentJobTracker::default(),
+ processes,
+ pending_clear: false,
+ exit_reported: false,
+ };
+ let (_, acquired) = pane.probe(Some(agent), WRAPPER_JOB);
+ assert!(acquired);
+ pane
+ }
+
+ pub(super) fn probe(
+ &mut self,
+ agent: Option<Agent>,
+ foreground_group: u32,
+ ) -> (ForegroundShellAgentAction, bool) {
+ self.probe_process(agent, AGENT_PID, foreground_group)
+ }
+
+ pub(super) fn probe_process(
+ &mut self,
+ agent: Option<Agent>,
+ agent_pid: u32,
+ foreground_group: u32,
+ ) -> (ForegroundShellAgentAction, bool) {
+ let result = observe_foreground_agent(
+ &mut self.presence,
+ &mut self.job,
+ &mut self.pending_clear,
+ &mut self.exit_reported,
+ ForegroundAgentObservation {
+ shell_pid: SHELL,
+ agent,
+ agent_pid: agent.map(|_| agent_pid),
+ process_group_id: Some(foreground_group),
+ foreground_is_pane_shell: foreground_group == SHELL,
+ },
+ &self.processes,
+ PaneId::from_raw(1),
+ );
+ // The loop publishes the pending exit before the next probe.
+ if self.pending_clear {
+ self.exit_reported = true;
+ }
+ result
+ }
+
+ pub(super) fn assert_held_while_shell_in_front(&mut self) {
+ for _ in 0..(AGENT_MISS_CONFIRMATION_ATTEMPTS + 2) {
+ assert_eq!(
+ self.probe(None, SHELL),
+ (ForegroundShellAgentAction::HoldBackgroundAgent, false)
+ );
+ }
+ assert!(self.job.in_background());
+ }
+
+ pub(super) fn assert_exit_reported_then_cleared(&mut self) {
+ assert_eq!(
+ self.probe(None, SHELL),
+ (ForegroundShellAgentAction::ReportProcessExit, false)
+ );
+ assert_eq!(
+ self.probe(None, SHELL),
+ (ForegroundShellAgentAction::ClearAgent, true)
+ );
+ assert_eq!(self.presence.current_agent(), None);
+ assert!(!self.job.in_background());
+ }
+ }
+ }
+
+ #[test]
+ fn suspend_command_and_resume_publish_no_agent_transition() {
+ let mut pane = held_agent::Pane::with_agent(Agent::Claude);
+
+ // ctrl-z: the shell is in front, the stopped agent is alive.
+ pane.assert_held_while_shell_in_front();
+ // A plain command runs in front of the stopped agent.
+ for _ in 0..(AGENT_MISS_CONFIRMATION_ATTEMPTS + 2) {
+ assert_eq!(
+ pane.probe(None, 30),
+ (ForegroundShellAgentAction::HoldBackgroundAgent, false)
+ );
+ }
+ // fg: the same agent is back in front.
+ assert_eq!(
+ pane.probe(Some(Agent::Claude), held_agent::WRAPPER_JOB),
+ (ForegroundShellAgentAction::ObserveProbe, false)
+ );
+ assert_eq!(pane.presence.current_agent(), Some(Agent::Claude));
+ assert!(!pane.job.in_background());
+
+ // A real exit afterwards still reports and clears.
+ pane.processes.exit(held_agent::AGENT_PID);
+ pane.processes.exit(held_agent::WRAPPER_JOB);
+ pane.assert_exit_reported_then_cleared();
+ }
+
+ #[test]
+ fn agent_killed_while_suspended_reports_its_exit() {
+ let mut pane = held_agent::Pane::with_agent(Agent::Pi);
+ pane.assert_held_while_shell_in_front();
+
+ // `kill -9 %1`: the whole stopped job is gone.
+ pane.processes.exit(held_agent::AGENT_PID);
+ pane.processes.exit(held_agent::WRAPPER_JOB);
+
+ pane.assert_exit_reported_then_cleared();
+ }
+
+ #[test]
+ fn held_agent_exit_is_reported_while_its_wrapper_survives() {
+ let mut pane = held_agent::Pane::with_agent(Agent::Pi);
+ pane.assert_held_while_shell_in_front();
+
+ // The agent dies; the wrapper that leads its job lives on.
+ pane.processes.exit(held_agent::AGENT_PID);
+
+ pane.assert_exit_reported_then_cleared();
+ }
+
+ #[test]
+ fn held_agent_pid_reused_by_another_process_reports_exit() {
+ let mut pane = held_agent::Pane::with_agent(Agent::Claude);
+ pane.assert_held_while_shell_in_front();
+
+ // The agent exits and an unrelated process in the same job gets its pid.
+ pane.processes.exit(held_agent::AGENT_PID);
+ pane.processes
+ .spawn(held_agent::AGENT_PID, 9_000, held_agent::WRAPPER_JOB);
+
+ pane.assert_exit_reported_then_cleared();
+ }
+
+ #[test]
+ fn same_kind_agent_started_in_front_of_a_held_one_replaces_it() {
+ let mut pane = held_agent::Pane::with_agent(Agent::Claude);
+ pane.assert_held_while_shell_in_front();
+
+ // A second Claude starts in front of the suspended one.
+ pane.processes.spawn(31, 9_000, 30);
+ assert_eq!(
+ pane.probe_process(Some(Agent::Claude), 31, 30),
+ (ForegroundShellAgentAction::ReportProcessExit, false)
+ );
+ assert_eq!(
+ pane.probe_process(Some(Agent::Claude), 31, 30),
+ (ForegroundShellAgentAction::ReportReplacementProcess, true)
+ );
+ assert!(!pane.job.in_background());
+ }
+
+ #[test]
+ fn same_kind_agent_reusing_the_held_pid_replaces_it() {
+ let mut pane = held_agent::Pane::with_agent(Agent::Claude);
+ pane.assert_held_while_shell_in_front();
+
+ pane.processes.exit(held_agent::AGENT_PID);
+ pane.processes.spawn(held_agent::AGENT_PID, 9_000, 30);
+
+ assert_eq!(
+ pane.probe(Some(Agent::Claude), 30),
+ (ForegroundShellAgentAction::ReportProcessExit, false)
+ );
+ assert_eq!(
+ pane.probe(Some(Agent::Claude), 30),
+ (ForegroundShellAgentAction::ReportReplacementProcess, true)
+ );
+ }
+
+ #[test]
+ fn held_agent_under_hook_authority_is_reprobed_on_the_identified_cadence() {
+ let mut pane = held_agent::Pane::with_agent(Agent::Pi);
+ pane.assert_held_while_shell_in_front();
+ pane.processes.exit(held_agent::AGENT_PID);
+ pane.processes.exit(held_agent::WRAPPER_JOB);
+
+ // Detection ticks every 300 ms; lifecycle hooks own the pane, and the
+ // foreground group stays the shell's, so only the cadence can probe.
+ let tick = std::time::Duration::from_millis(300);
+ let mut since_check = std::time::Duration::ZERO;
+ loop {
+ since_check += tick;
+ assert!(
+ since_check <= PROCESS_RECHECK_IDENTIFIED + tick,
+ "never reprobed"
+ );
+ let input = ProcessProbeInput {
+ current_agent: pane.presence.current_agent(),
+ foreground_pgid: Some(held_agent::SHELL),
+ last_foreground_pgid: Some(held_agent::SHELL),
+ elapsed_since_process_check: since_check,
+ ..process_probe_input()
+ };
+ if should_check_foreground_process(true, pane.job.in_background(), input) {
+ break;
+ }
+ }
+
+ assert!(since_check >= PROCESS_RECHECK_IDENTIFIED);
+ pane.assert_exit_reported_then_cleared();
+ }
+
#[tokio::test]
async fn first_agent_acquisition_keeps_osc_evidence_replacement_clears_it() {
let runtime = PaneRuntime::test_with_screen_bytes(80, 24, b"");
@@ -5146,7 +5601,13 @@ mod tests {
#[test]
fn reported_process_exit_clears_before_unknown_foreground_probe() {
assert_eq!(
- foreground_shell_agent_action(Some(Agent::Claude), None, false, true),
+ foreground_shell_agent_action(
+ Some(Agent::Claude),
+ None,
+ false,
+ true,
+ AgentJobStatus::Unknown
+ ),
ForegroundShellAgentAction::ClearAgent
);
}
@@ -5154,7 +5615,13 @@ mod tests {
#[test]
fn foreground_agent_job_is_not_clear_signal() {
assert_eq!(
- foreground_shell_agent_action(Some(Agent::Claude), Some(Agent::OpenCode), true, false,),
+ foreground_shell_agent_action(
+ Some(Agent::Claude),
+ Some(Agent::OpenCode),
+ true,
+ false,
+ AgentJobStatus::Unknown
+ ),
ForegroundShellAgentAction::ObserveProbe
);
}
@@ -5180,7 +5647,7 @@ mod tests {
agent_hint_for_foreground_job_members(&job, |pid| {
(pid == 42).then_some(Agent::Claude)
}),
- Some(Agent::Claude)
+ Some((Agent::Claude, 42))
);
}
@@ -5198,7 +5665,7 @@ mod tests {
agent_hint_for_foreground_job_members(&job, |pid| {
(pid == 100).then_some(Agent::Codex)
}),
- Some(Agent::Codex)
+ Some((Agent::Codex, 100))
);
}
@@ -5259,9 +5726,27 @@ mod tests {
);
assert_eq!(result.agent, Some(Agent::Codex));
+ assert_eq!(result.agent_pid, Some(99));
assert_eq!(result.process_name.as_deref(), Some("codex"));
}
+ #[test]
+ fn probe_reports_the_agent_process_behind_an_unrecognized_job_leader() {
+ let job = crate::platform::ForegroundJob {
+ process_group_id: 99,
+ processes: vec![
+ foreground_process(99, "some_wrapper"),
+ foreground_process(100, "claude"),
+ ],
+ };
+
+ let result = probe_foreground_process_from_jobs(42, Some(99), None, || Some(job), |_| None);
+
+ assert_eq!(result.agent, Some(Agent::Claude));
+ assert_eq!(result.agent_pid, Some(100));
+ assert_eq!(result.process_group_id, Some(99));
+ }
+
#[test]
fn non_leader_agent_hint_wins_when_leader_is_unidentified() {
let job = crate::platform::ForegroundJob {
diff --git a/src/pane/background_agent.rs b/src/pane/background_agent.rs
new file mode 100644
index 000000000..233c158a6
--- /dev/null
+++ b/src/pane/background_agent.rs
@@ -0,0 +1,281 @@
+//! Keeps an agent's identity while job control moves it out of the foreground.
+//!
+//! Suspending an agent with ctrl-z, or running a command in front of it, hands
+//! the terminal to another job while the agent process lives on. Treating that
+//! as an exit would drop the agent's session, name, and hook authority, and
+//! nothing would restore them when it returns.
+
+use crate::detect::Agent;
+
+/// Where the process that identified as the current agent is now, when the
+/// foreground probe no longer finds that agent.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(super) enum AgentJobStatus {
+ /// Untracked, still in the foreground, or gone without having been held.
+ Unknown,
+ /// Alive outside the foreground, such as a job stopped with ctrl-z.
+ Background,
+ /// Was held in the background and has since exited.
+ ExitedInBackground,
+ /// Was held, and a different process of the same agent kind is in front.
+ ReplacedInFront,
+}
+
+/// The identified agent process. The start token tells it apart from a later
+/// process that reuses its pid.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+struct AgentProcess {
+ pid: u32,
+ start_token: u64,
+}
+
+#[derive(Debug, Default)]
+pub(super) struct AgentJobTracker {
+ process: Option<AgentProcess>,
+ in_background: bool,
+}
+
+impl AgentJobTracker {
+ /// A held agent must be rechecked even when lifecycle-hook authority would
+ /// otherwise skip probing, so a job killed in the background is noticed.
+ pub(super) fn in_background(&self) -> bool {
+ self.in_background
+ }
+
+ /// `agent_missing` means the probe lost a current agent whose exit has not
+ /// been reported yet. Liveness is checked only then, never per render.
+ ///
+ /// `live_group(shell_pid, pid, start_token)` returns the process group of
+ /// that exact process while it is alive in the pane's terminal session.
+ pub(super) fn status(
+ &self,
+ agent_missing: bool,
+ shell_pid: u32,
+ foreground_group: Option<u32>,
+ live_group: impl FnOnce(u32, u32, u64) -> Option<u32>,
+ ) -> AgentJobStatus {
+ if !agent_missing {
+ return AgentJobStatus::Unknown;
+ }
+ let Some(process) = self.process else {
+ return AgentJobStatus::Unknown;
+ };
+ match live_group(shell_pid, process.pid, process.start_token) {
+ // An agent in the shell's own group was never a separate job, and
+ // one still in the foreground group is a plain miss.
+ Some(group) if group != shell_pid && Some(group) != foreground_group => {
+ AgentJobStatus::Background
+ }
+ Some(_) => AgentJobStatus::Unknown,
+ None if self.in_background => AgentJobStatus::ExitedInBackground,
+ None => AgentJobStatus::Unknown,
+ }
+ }
+
+ /// While an agent is held, a same-kind agent in front is that agent only
+ /// when its pid and start token match the held process.
+ pub(super) fn replaced_in_front(
+ &self,
+ identified_pid: Option<u32>,
+ start_token: impl FnOnce(u32) -> Option<u64>,
+ ) -> bool {
+ let Some(held) = self.process.filter(|_| self.in_background) else {
+ return false;
+ };
+ identified_pid
+ .is_none_or(|pid| pid != held.pid || start_token(pid) != Some(held.start_token))
+ }
+
+ pub(super) fn observe(
+ &mut self,
+ status: AgentJobStatus,
+ current_agent: Option<Agent>,
+ identified_agent: Option<Agent>,
+ identified_pid: Option<u32>,
+ start_token: impl FnOnce(u32) -> Option<u64>,
+ ) {
+ if current_agent.is_none() {
+ *self = Self::default();
+ } else if status == AgentJobStatus::ReplacedInFront {
+ // Keep holding until the held agent's exit has been reported.
+ } else if identified_agent == current_agent {
+ self.in_background = false;
+ // Reread every time: a new process may have reused the pid.
+ self.process = identified_pid.and_then(|pid| {
+ start_token(pid).map(|start_token| AgentProcess { pid, start_token })
+ });
+ } else if status == AgentJobStatus::Background {
+ self.in_background = true;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const SHELL: u32 = 10;
+ const WRAPPER_JOB: u32 = 20;
+ const AGENT_PID: u32 = 21;
+ const AGENT_START: u64 = 7_000;
+
+ fn acquired(agent: Agent) -> AgentJobTracker {
+ let mut tracker = AgentJobTracker::default();
+ tracker.observe(
+ AgentJobStatus::Unknown,
+ Some(agent),
+ Some(agent),
+ Some(AGENT_PID),
+ |pid| (pid == AGENT_PID).then_some(AGENT_START),
+ );
+ tracker
+ }
+
+ fn live_agent(shell: u32, pid: u32, start_token: u64) -> Option<u32> {
+ assert_eq!(shell, SHELL);
+ (pid == AGENT_PID && start_token == AGENT_START).then_some(WRAPPER_JOB)
+ }
+
+ #[test]
+ fn stopped_agent_behind_the_shell_is_in_background() {
+ let tracker = acquired(Agent::Claude);
+
+ assert_eq!(
+ tracker.status(true, SHELL, Some(SHELL), live_agent),
+ AgentJobStatus::Background
+ );
+ }
+
+ #[test]
+ fn agent_that_exited_in_front_is_unknown() {
+ let tracker = acquired(Agent::Claude);
+
+ assert_eq!(
+ tracker.status(true, SHELL, Some(SHELL), |_, _, _| None),
+ AgentJobStatus::Unknown
+ );
+ }
+
+ #[test]
+ fn liveness_is_only_checked_when_the_agent_went_missing() {
+ let tracker = acquired(Agent::Claude);
+ let no_check = |_: u32, _: u32, _: u64| -> Option<u32> { panic!("liveness checked") };
+
+ assert_eq!(
+ tracker.status(false, SHELL, Some(SHELL), no_check),
+ AgentJobStatus::Unknown
+ );
+ assert_eq!(
+ AgentJobTracker::default().status(true, SHELL, Some(SHELL), no_check),
+ AgentJobStatus::Unknown
+ );
+ }
+
+ #[test]
+ fn agent_still_in_the_foreground_group_is_not_held() {
+ let tracker = acquired(Agent::Claude);
+
+ assert_eq!(
+ tracker.status(true, SHELL, Some(WRAPPER_JOB), live_agent),
+ AgentJobStatus::Unknown
+ );
+ }
+
+ #[test]
+ fn agent_in_the_shell_group_is_never_held() {
+ let tracker = acquired(Agent::Pi);
+
+ assert_eq!(
+ tracker.status(true, SHELL, Some(30), |_, _, _| Some(SHELL)),
+ AgentJobStatus::Unknown
+ );
+ }
+
+ #[test]
+ fn agent_without_a_start_token_is_never_held() {
+ let mut tracker = AgentJobTracker::default();
+ tracker.observe(
+ AgentJobStatus::Unknown,
+ Some(Agent::Pi),
+ Some(Agent::Pi),
+ Some(AGENT_PID),
+ |_| None,
+ );
+
+ assert_eq!(
+ tracker.status(true, SHELL, Some(SHELL), |_, _, _| Some(WRAPPER_JOB)),
+ AgentJobStatus::Unknown
+ );
+ }
+
+ #[test]
+ fn reidentified_agent_refreshes_its_start_token() {
+ const REUSED_START: u64 = 9_000;
+ let mut tracker = acquired(Agent::Pi);
+ // A new Pi reused the pid between two probes.
+ tracker.observe(
+ AgentJobStatus::Unknown,
+ Some(Agent::Pi),
+ Some(Agent::Pi),
+ Some(AGENT_PID),
+ |_| Some(REUSED_START),
+ );
+
+ assert_eq!(
+ tracker.status(true, SHELL, Some(SHELL), |_, pid, token| {
+ (pid == AGENT_PID && token == REUSED_START).then_some(WRAPPER_JOB)
+ }),
+ AgentJobStatus::Background
+ );
+ }
+
+ #[test]
+ fn held_agent_is_replaced_only_by_a_different_process() {
+ let mut tracker = acquired(Agent::Claude);
+ assert!(
+ !tracker.replaced_in_front(Some(31), |_| Some(1)),
+ "not held"
+ );
+ let status = tracker.status(true, SHELL, Some(SHELL), live_agent);
+ tracker.observe(status, Some(Agent::Claude), None, None, |_| None);
+
+ assert!(!tracker.replaced_in_front(Some(AGENT_PID), |_| Some(AGENT_START)));
+ assert!(tracker.replaced_in_front(Some(31), |_| Some(AGENT_START)));
+ assert!(tracker.replaced_in_front(Some(AGENT_PID), |_| Some(9_000)));
+ assert!(tracker.replaced_in_front(Some(AGENT_PID), |_| None));
+ assert!(tracker.replaced_in_front(None, |_| Some(AGENT_START)));
+ }
+
+ #[test]
+ fn returning_agent_ends_the_hold() {
+ let mut tracker = acquired(Agent::Claude);
+ let status = tracker.status(true, SHELL, Some(SHELL), live_agent);
+ tracker.observe(status, Some(Agent::Claude), None, None, |_| None);
+ assert!(tracker.in_background());
+
+ tracker.observe(
+ AgentJobStatus::Unknown,
+ Some(Agent::Claude),
+ Some(Agent::Claude),
+ Some(AGENT_PID),
+ |_| None,
+ );
+
+ assert!(!tracker.in_background());
+ }
+
+ #[test]
+ fn cleared_agent_resets_the_tracker() {
+ let mut tracker = acquired(Agent::Pi);
+ let status = tracker.status(true, SHELL, Some(SHELL), live_agent);
+ tracker.observe(status, Some(Agent::Pi), None, None, |_| None);
+
+ tracker.observe(AgentJobStatus::Unknown, None, None, None, |_| None);
+
+ assert!(!tracker.in_background());
+ assert_eq!(
+ tracker.status(true, SHELL, Some(SHELL), live_agent),
+ AgentJobStatus::Unknown
+ );
+ }
+}
diff --git a/src/platform/fallback.rs b/src/platform/fallback.rs
index 1712d5271..2dc7772f6 100644
--- a/src/platform/fallback.rs
+++ b/src/platform/fallback.rs
@@ -230,6 +230,16 @@ pub fn session_processes(_child_pid: u32) -> Vec<u32> {
/// Unsupported platform stub.
pub fn signal_processes(_pids: &[u32], _signal: Signal) {}
+/// Unsupported platform stub.
+pub fn process_start_token(_pid: u32) -> Option<u64> {
+ None
+}
+
+/// Unsupported platform stub.
+pub fn live_pane_process_group(_shell_pid: u32, _pid: u32, _start_token: u64) -> Option<u32> {
+ None
+}
+
/// Unsupported platform stub.
pub fn process_exists(_pid: u32) -> bool {
false
diff --git a/src/platform/linux.rs b/src/platform/linux.rs
index 681ed68da..ea9b13ddb 100644
--- a/src/platform/linux.rs
+++ b/src/platform/linux.rs
@@ -664,6 +664,50 @@ pub fn foreground_process_group_id_for_tty_fd(fd: RawFd) -> Option<u32> {
(pgid > 0).then_some(pgid as u32)
}
+/// Start time of `pid` in clock ticks since boot. It tells a process apart
+/// from a later one that reuses its pid.
+pub fn process_start_token(pid: u32) -> Option<u64> {
+ process_job_stat(pid).map(|stat| stat.start_time)
+}
+
+/// Process group of `pid` while that same process, matched by its start
+/// token, is alive in the terminal session of the pane shell `shell_pid`.
+/// A stopped or backgrounded job still counts.
+pub fn live_pane_process_group(shell_pid: u32, pid: u32, start_token: u64) -> Option<u32> {
+ let stat = process_job_stat(pid)?;
+ let shell_session = process_job_stat(shell_pid)?.session;
+ (!matches!(stat.state, 'Z' | 'X')
+ && stat.start_time == start_token
+ && stat.session == shell_session
+ && stat.pgrp > 0)
+ .then_some(stat.pgrp as u32)
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+struct ProcessJobStat {
+ state: char,
+ pgrp: i32,
+ session: i32,
+ start_time: u64,
+}
+
+fn process_job_stat(pid: u32) -> Option<ProcessJobStat> {
+ let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
+ process_job_stat_from_stat(&stat)
+}
+
+fn process_job_stat_from_stat(stat: &str) -> Option<ProcessJobStat> {
+ let rest = stat.get(stat.rfind(')')? + 2..)?;
+ let fields: Vec<&str> = rest.split_whitespace().collect();
+ // After (comm): state(0) ppid(1) pgrp(2) session(3) ... starttime(19)
+ Some(ProcessJobStat {
+ state: fields.first()?.chars().next()?,
+ pgrp: fields.get(2)?.parse().ok()?,
+ session: fields.get(3)?.parse().ok()?,
+ start_time: fields.get(19)?.parse().ok()?,
+ })
+}
+
pub(super) fn socket_peer_pid(fd: RawFd) -> Option<u32> {
let mut cred: libc::ucred = unsafe { std::mem::zeroed() };
let mut len = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
@@ -1615,6 +1659,22 @@ mod tests {
);
}
+ #[test]
+ fn proc_stat_parsing_reads_job_fields_and_start_time() {
+ let stat =
+ "123 (node ) x) T 1 456 789 34816 456 4194560 1 2 3 4 5 6 7 8 20 0 11 0 987654 0 0";
+ assert_eq!(
+ process_job_stat_from_stat(stat),
+ Some(ProcessJobStat {
+ state: 'T',
+ pgrp: 456,
+ session: 789,
+ start_time: 987654,
+ })
+ );
+ assert_eq!(process_job_stat_from_stat("123 (short) S 1 456 789"), None);
+ }
+
#[test]
fn foreground_job_does_not_read_remote_memory_for_uninterruptible_members() {
let argv_reads = RefCell::new(Vec::new());
diff --git a/src/platform/macos.rs b/src/platform/macos.rs
index 39ffbfa0b..a92c76012 100644
--- a/src/platform/macos.rs
+++ b/src/platform/macos.rs
@@ -912,6 +912,30 @@ fn run_clipboard_command(command: &ClipboardCommand, bytes: &[u8]) -> bool {
child.wait().map(|status| status.success()).unwrap_or(false)
}
+/// Start time of `pid` in microseconds. It tells a process apart from a later
+/// one that reuses its pid.
+pub fn process_start_token(pid: u32) -> Option<u64> {
+ process_bsdinfo(pid).map(|info| bsdinfo_start_token(&info))
+}
+
+/// Process group of `pid` while that same process, matched by its start
+/// token, is alive on the terminal of the pane shell `shell_pid`. A stopped or
+/// backgrounded job still counts.
+pub fn live_pane_process_group(shell_pid: u32, pid: u32, start_token: u64) -> Option<u32> {
+ let process = process_bsdinfo(pid)?;
+ let shell = process_bsdinfo(shell_pid)?;
+ (process.pbi_status != libc::SZOMB
+ && bsdinfo_start_token(&process) == start_token
+ && process.e_tdev == shell.e_tdev)
+ .then_some(process.pbi_pgid)
+}
+
+fn bsdinfo_start_token(info: &libc::proc_bsdinfo) -> u64 {
+ info.pbi_start_tvsec
+ .saturating_mul(1_000_000)
+ .saturating_add(info.pbi_start_tvusec)
+}
+
pub(super) fn socket_peer_pid(fd: RawFd) -> Option<u32> {
let mut pid: libc::pid_t = 0;
let mut len = std::mem::size_of::<libc::pid_t>() as libc::socklen_t;
diff --git a/src/platform/mod.rs b/src/platform/mod.rs
index ba073ff09..2e7a601b0 100644
--- a/src/platform/mod.rs
+++ b/src/platform/mod.rs
@@ -607,6 +607,102 @@ fn child_exit_classification_only_checkpoints_interruptions() {
mod tests {
use super::*;
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn live_pane_process_group_rejects_processes_outside_the_pane_session() {
+ use std::os::unix::process::CommandExt;
+
+ let mut detached = std::process::Command::new("sleep");
+ detached.arg("30");
+ // SAFETY: setsid is async-signal-safe and touches only the child.
+ unsafe {
+ detached.pre_exec(|| {
+ libc::setsid();
+ Ok(())
+ });
+ }
+ let mut detached = detached.spawn().expect("spawn detached");
+ let token = process_start_token(detached.id()).expect("start token");
+ let mut gone = std::process::Command::new("true").spawn().expect("spawn");
+ let gone_pid = gone.id();
+ gone.wait().expect("reap");
+
+ assert_eq!(
+ live_pane_process_group(std::process::id(), detached.id(), token),
+ None,
+ "a live process in another terminal session"
+ );
+ assert_eq!(
+ live_pane_process_group(gone_pid, detached.id(), token),
+ None,
+ "a pane shell that is gone"
+ );
+ let _ = detached.kill();
+ let _ = detached.wait();
+ }
+
+ #[cfg(any(target_os = "linux", target_os = "macos"))]
+ #[test]
+ fn live_pane_process_group_follows_the_agent_process_not_its_job() {
+ use std::os::unix::process::CommandExt;
+
+ let shell_pid = std::process::id();
+ let mut wrapper = std::process::Command::new("sleep")
+ .arg("30")
+ .process_group(0)
+ .spawn()
+ .expect("spawn wrapper");
+ let job = wrapper.id();
+ let mut agent = std::process::Command::new("sleep")
+ .arg("30")
+ .process_group(job as i32)
+ .spawn()
+ .expect("spawn agent");
+ let agent_pid = agent.id();
+ let token = process_start_token(agent_pid).expect("agent start token");
+ let wrapper_token = process_start_token(job).expect("wrapper start token");
+
+ assert_eq!(
+ live_pane_process_group(shell_pid, agent_pid, token),
+ Some(job)
+ );
+ assert_eq!(
+ live_pane_process_group(shell_pid, agent_pid, token + 1),
+ None,
+ "a reused pid has a different start token"
+ );
+ unsafe {
+ libc::kill(agent_pid as libc::pid_t, libc::SIGSTOP);
+ }
+ assert_eq!(
+ live_pane_process_group(shell_pid, agent_pid, token),
+ Some(job)
+ );
+
+ unsafe {
+ libc::kill(agent_pid as libc::pid_t, libc::SIGKILL);
+ }
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
+ while live_pane_process_group(shell_pid, agent_pid, token).is_some()
+ && std::time::Instant::now() < deadline
+ {
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ assert_eq!(
+ live_pane_process_group(shell_pid, agent_pid, token),
+ None,
+ "an unreaped agent must not count as alive while its wrapper lives"
+ );
+ assert_eq!(
+ live_pane_process_group(shell_pid, job, wrapper_token),
+ Some(job)
+ );
+ agent.wait().expect("reap agent");
+ assert_eq!(live_pane_process_group(shell_pid, agent_pid, token), None);
+ let _ = wrapper.kill();
+ let _ = wrapper.wait();
+ }
+
#[test]
fn terminal_resize_signal_is_recorded_once_per_delivery() {
watch_terminal_resize_signal();
diff --git a/src/platform/windows.rs b/src/platform/windows.rs
index 1e2e66197..4ddbf09fe 100644
--- a/src/platform/windows.rs
+++ b/src/platform/windows.rs
@@ -1640,14 +1640,15 @@ fn select_pane_foreground_job_from_snapshot_with_runtime_inspection(
return Some(foreground_job_from_entry(shell));
}
- let Some(shell_runtime_marker) = runtime_marker(shell).filter(|marker| !marker.is_empty())
- else {
+ let Some(shell_runtime_marker) = pane_runtime_marker(shell, &mut runtime_marker) else {
return Some(foreground_job_from_entry(shell));
};
let matching_candidates: Vec<_> = escaped_agent_indices
.iter()
.map(|&index| &entries[index])
- .filter(|entry| runtime_marker(entry).as_deref() == Some(shell_runtime_marker.as_str()))
+ .filter(|entry| {
+ carries_pane_runtime_marker(entry, &shell_runtime_marker, &mut runtime_marker)
+ })
.collect();
let selected =
select_topmost_agent_chain_candidate(&matching_candidates, snapshot).unwrap_or(shell);
@@ -1665,6 +1666,69 @@ fn select_pane_foreground_job(
)
}
+/// Git Bash can start agents outside the pane shell's process tree. Those
+/// belong to the pane when they carry the runtime marker the shell got.
+fn pane_runtime_marker(
+ shell: &WindowsProcessEntry,
+ runtime_marker: &mut impl FnMut(&WindowsProcessEntry) -> Option<String>,
+) -> Option<String> {
+ runtime_marker(shell).filter(|marker| !marker.is_empty())
+}
+
+fn carries_pane_runtime_marker(
+ entry: &WindowsProcessEntry,
+ pane_marker: &str,
+ runtime_marker: &mut impl FnMut(&WindowsProcessEntry) -> Option<String>,
+) -> bool {
+ runtime_marker(entry).as_deref() == Some(pane_marker)
+}
+
+/// Whether foreground selection could pick `pid` for this pane: a descendant
+/// of the pane shell, or an escaped Git Bash agent with the pane's marker.
+fn process_belongs_to_pane(
+ shell_pid: u32,
+ pid: u32,
+ snapshot: &ProcessSnapshot,
+ shell_is_git_bash: impl FnOnce(&WindowsProcessEntry) -> bool,
+ mut runtime_marker: impl FnMut(&WindowsProcessEntry) -> Option<String>,
+) -> bool {
+ if process_is_ancestor(shell_pid, pid, snapshot) {
+ return true;
+ }
+ let (Some(shell), Some(entry)) = (snapshot.entry(shell_pid), snapshot.entry(pid)) else {
+ return false;
+ };
+ shell_is_git_bash(shell)
+ && process_entry_identifies_agent(entry)
+ && pane_runtime_marker(shell, &mut runtime_marker).is_some_and(|pane_marker| {
+ carries_pane_runtime_marker(entry, &pane_marker, &mut runtime_marker)
+ })
+}
+
+/// Creation time of `pid`. It tells a process apart from a later one that
+/// reuses its pid.
+pub fn process_start_token(pid: u32) -> Option<u64> {
+ ProcessIdentity::open(pid)?.creation_time()
+}
+
+/// Returns `pid` while that same process, matched by its creation time, is
+/// still running for the pane shell `shell_pid`. Windows has no job control,
+/// so the process stands in for its own group.
+pub fn live_pane_process_group(shell_pid: u32, pid: u32, start_token: u64) -> Option<u32> {
+ let identity = ProcessIdentity::open(pid)?;
+ if !identity.running() || identity.creation_time() != Some(start_token) {
+ return None;
+ }
+ process_belongs_to_pane(
+ shell_pid,
+ pid,
+ &cached_foreground_processes(),
+ |shell| process_is_git_bash(shell.pid),
+ |entry| process_runtime_marker(entry.pid),
+ )
+ .then_some(pid)
+}
+
fn process_entry_identifies_agent(entry: &WindowsProcessEntry) -> bool {
crate::detect::identify_agent(&entry.name).is_some()
|| crate::detect::identify_agent_in_job(&foreground_job_from_entry(entry)).is_some()
@@ -4262,6 +4326,50 @@ mod tests {
assert_eq!(job.processes[0].name, "bash.exe");
}
+ #[test]
+ fn windows_held_agent_must_still_belong_to_the_pane() {
+ let entries = vec![
+ test_entry(10, 1, "bash.exe", &[r"C:\Program Files\Git\bin\bash.exe"]),
+ test_entry(11, 10, "claude.exe", &["claude.exe"]),
+ test_entry(20, 99, "codex.exe", &["codex.exe"]),
+ test_entry(30, 98, "vim.exe", &["vim.exe"]),
+ test_entry(50, 77, "claude.exe", &["claude.exe"]),
+ ];
+ let snapshot = super::ProcessSnapshot::new(entries);
+ let marker = |pane: &'static str| {
+ move |entry: &super::WindowsProcessEntry| {
+ Some(if entry.pid == 10 { "pane-a" } else { pane }.to_string())
+ }
+ };
+ let belongs = |pid, git_bash, pane| {
+ super::process_belongs_to_pane(10, pid, &snapshot, |_| git_bash, marker(pane))
+ };
+
+ assert!(belongs(11, false, "pane-b"), "descendant of the shell");
+ assert!(
+ belongs(20, true, "pane-a"),
+ "escaped agent with the pane marker"
+ );
+ assert!(!belongs(20, true, "pane-b"), "marker from another pane");
+ assert!(
+ !belongs(20, false, "pane-a"),
+ "escape only applies to Git Bash"
+ );
+ assert!(!belongs(30, true, "pane-a"), "escaped non-agent process");
+ assert!(
+ !belongs(40, true, "pane-a"),
+ "process gone from the snapshot"
+ );
+ assert!(
+ !belongs(50, false, "pane-a"),
+ "agent whose parent chain no longer reaches the shell"
+ );
+ assert!(
+ !super::process_belongs_to_pane(60, 11, &snapshot, |_| true, marker("pane-a")),
+ "pane shell gone"
+ );
+ }
+
#[test]
fn windows_process_tree_rejects_ambiguous_runtime_marker_candidates() {
let entries = vec![