From 7945a5b2ee500c31fcef1a5053a2e6ab51c796b1 Mon Sep 17 00:00:00 2001 From: fwhskr <310062135+fwhskr@users.noreply.github.com> Date: Sun, 30 Aug 2026 20:37:03 +0300 Subject: [PATCH] fix(agent): decay stale identity after process misses --- src/app/actions.rs | 9 +++ src/app/mod.rs | 38 +++++++++++++ src/events.rs | 5 ++ src/pane.rs | 127 +++++++++++++++++++++++++++++++++++++----- src/terminal/state.rs | 52 +++++++++++++++++ 5 files changed, 218 insertions(+), 13 deletions(-) diff --git a/src/app/actions.rs b/src/app/actions.rs index 95e634beadb..c1739a10152 100644 --- a/src/app/actions.rs +++ b/src/app/actions.rs @@ -2032,6 +2032,15 @@ impl AppState { }) .into_iter() .collect(), + AppEvent::AgentPresenceConfirmedMissing { + pane_id, + observed_at, + } => self + .update_terminal_state(pane_id, |terminal| { + terminal.clear_agent_identity_after_confirmed_process_miss(observed_at) + }) + .into_iter() + .collect(), AppEvent::HookStateReported { pane_id, source, diff --git a/src/app/mod.rs b/src/app/mod.rs index 18d52bfc3dd..6f1277be5b5 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -1475,6 +1475,44 @@ mod tests { ) } + #[test] + fn non_agent_tui_is_absent_from_agent_list_after_restore_identity_decay() { + let mut app = test_app(); + app.state.workspaces.push(Workspace::test_new("lazygit")); + app.state.ensure_test_terminals(); + let pane_id = app.state.workspaces[0].tabs[0].root_pane; + let terminal_id = app.state.workspaces[0] + .pane_state(pane_id) + .expect("test pane should exist") + .attached_terminal_id + .clone(); + + assert!( + app.collect_agent_infos().is_empty(), + "fresh TUI is not an agent" + ); + + let terminal = app + .state + .terminals + .get_mut(&terminal_id) + .expect("test terminal should exist"); + terminal.set_detected_state(Some(Agent::Pi), AgentState::Idle); + terminal.set_hook_authority("herdr:pi".into(), "pi".into(), AgentState::Idle, None, None); + assert_eq!(app.collect_agent_infos().len(), 1); + + app.state + .handle_app_event(AppEvent::AgentPresenceConfirmedMissing { + pane_id, + observed_at: Instant::now(), + }); + + assert!( + app.collect_agent_infos().is_empty(), + "a non-agent TUI must leave the agents section after restore validation" + ); + } + #[derive(Clone, Default)] struct FakePrefixInputSource { switch_calls: Rc>, diff --git a/src/events.rs b/src/events.rs index 2b33bebb84b..b2988ae7b6f 100644 --- a/src/events.rs +++ b/src/events.rs @@ -38,6 +38,11 @@ pub enum AppEvent { process_exited: bool, observed_at: Instant, }, + /// The process probe confirmed that no known agent owns the pane. + AgentPresenceConfirmedMissing { + pane_id: PaneId, + observed_at: Instant, + }, /// Hook-authoritative agent state was reported for a pane. HookStateReported { pane_id: PaneId, diff --git a/src/pane.rs b/src/pane.rs index 248f5bb1307..e2d86a7ba7d 100644 --- a/src/pane.rs +++ b/src/pane.rs @@ -111,6 +111,26 @@ async fn publish_state_changed_event( } } +async fn publish_agent_presence_confirmed_missing( + state_events: mpsc::Sender, + pane_id: PaneId, + observed_at: std::time::Instant, +) { + if let Err(e) = state_events + .send(AppEvent::AgentPresenceConfirmedMissing { + pane_id, + observed_at, + }) + .await + { + warn!( + pane = pane_id.raw(), + err = %e, + "failed to deliver confirmed missing agent event" + ); + } +} + const AGENT_MISS_CONFIRMATION_ATTEMPTS: u8 = 6; const PROCESS_RECHECK_IDENTIFIED: std::time::Duration = std::time::Duration::from_secs(5); const PROCESS_RECHECK_MISSING_FOREGROUND_GROUP: std::time::Duration = @@ -194,6 +214,7 @@ struct ProcessProbeInput { foreground_pgid: Option, last_foreground_pgid: Option, has_process_probe: bool, + consecutive_misses: u8, acquisition_age: Option, pending_foreground_shell_clear: bool, pending_restore_probe: bool, @@ -233,6 +254,12 @@ fn should_probe_foreground_job(input: ProcessProbeInput) -> bool { } } + if input.consecutive_misses > 0 { + return !input.has_process_probe + || foreground_group_changed + || input.elapsed_since_process_check >= PROCESS_RECHECK_IDENTIFIED; + } + if input.current_agent.is_none() { return !input.has_process_probe || foreground_group_changed @@ -455,9 +482,6 @@ fn spawn_basic_detection_task( let content = terminal.detection_text(); let content_changed = content != last_detection_text; last_detection_text.clone_from(&content); - if crate::detect::should_skip_state_update(agent, &content) { - continue; - } let foreground_pgid = (pid > 0) .then(|| crate::detect::foreground_process_group_id(pid)) @@ -480,6 +504,7 @@ fn spawn_basic_detection_task( foreground_pgid, last_foreground_pgid, has_process_probe, + consecutive_misses: agent_presence.consecutive_misses, acquisition_age: acquisition_started_at .map(|started| now.duration_since(started)), pending_foreground_shell_clear: false, @@ -515,6 +540,14 @@ fn spawn_basic_detection_task( agent = agent_presence.current_agent(); agent_changed = previous_agent != agent; } + if agent_presence.process_probe_confirmed_missing() { + publish_agent_presence_confirmed_missing(state_events.clone(), pane_id, now) + .await; + } + } + + if crate::detect::should_skip_state_update(agent, &content) { + continue; } let Some(detection) = detection_update_for_publish(agent, &content, false) else { @@ -612,20 +645,23 @@ impl AgentDetectionPresence { true } None => { - if self.current_agent.is_none() { - self.consecutive_misses = 0; - return false; - } self.consecutive_misses = self.consecutive_misses.saturating_add(1); if self.consecutive_misses < AGENT_MISS_CONFIRMATION_ATTEMPTS { return false; } - self.current_agent = None; - self.consecutive_misses = 0; - true + if self.current_agent.is_some() { + self.current_agent = None; + true + } else { + false + } } } } + + fn process_probe_confirmed_missing(&self) -> bool { + self.consecutive_misses >= AGENT_MISS_CONFIRMATION_ATTEMPTS + } } // --------------------------------------------------------------------------- @@ -1564,9 +1600,6 @@ impl PaneRuntime { let content = terminal.detection_text(); let content_changed = content != last_detection_text; last_detection_text.clone_from(&content); - if detect::should_skip_state_update(agent_presence.current_agent(), &content) { - continue; - } let foreground_pgid = (pid > 0) .then(|| detect::foreground_process_group_id(pid)) .flatten(); @@ -1588,6 +1621,7 @@ impl PaneRuntime { foreground_pgid, last_foreground_pgid, has_process_probe, + consecutive_misses: agent_presence.consecutive_misses, acquisition_age: acquisition_started_at .map(|started| now.duration_since(started)), pending_foreground_shell_clear, @@ -1676,9 +1710,21 @@ impl PaneRuntime { } agent_changed = true; } + if agent_presence.process_probe_confirmed_missing() { + publish_agent_presence_confirmed_missing( + state_events.clone(), + pane_id, + now, + ) + .await; + } } } + if detect::should_skip_state_update(agent, &content) { + continue; + } + let pid = child_pid.load(Ordering::Acquire); // Keep the terminal restore side effect separate from render notification state. #[allow(clippy::collapsible_if)] @@ -2678,6 +2724,7 @@ mod tests { foreground_pgid: Some(42), last_foreground_pgid: Some(42), has_process_probe: true, + consecutive_misses: 0, acquisition_age: None, pending_foreground_shell_clear: false, pending_restore_probe: false, @@ -2690,6 +2737,21 @@ mod tests { assert!(!should_probe_foreground_job(process_probe_input())); } + #[test] + fn confirmed_missing_presence_keeps_periodic_process_probe_alive() { + assert!(!should_probe_foreground_job(ProcessProbeInput { + consecutive_misses: 1, + elapsed_since_process_check: PROCESS_RECHECK_IDENTIFIED + - std::time::Duration::from_millis(1), + ..process_probe_input() + })); + assert!(should_probe_foreground_job(ProcessProbeInput { + consecutive_misses: AGENT_MISS_CONFIRMATION_ATTEMPTS, + elapsed_since_process_check: PROCESS_RECHECK_IDENTIFIED, + ..process_probe_input() + })); + } + #[test] fn unidentified_foreground_group_change_runs_full_process_probe() { assert!(should_probe_foreground_job(ProcessProbeInput { @@ -3022,14 +3084,53 @@ mod tests { !changed, "miss {attempt} should stay in the confirmation window" ); + assert!(!presence.process_probe_confirmed_missing()); assert_eq!(presence.current_agent(), Some(Agent::Pi)); } let changed = presence.observe_process_probe(None); assert!(changed, "last confirmation miss should clear the agent"); + assert!(presence.process_probe_confirmed_missing()); + assert_eq!(presence.current_agent(), None); + } + + #[test] + fn no_agent_presence_reaches_confirmation_without_a_conflicting_agent() { + let mut presence = AgentDetectionPresence::from_agent(None); + + for attempt in 1..AGENT_MISS_CONFIRMATION_ATTEMPTS { + assert!(!presence.observe_process_probe(None), "miss {attempt}"); + assert!(!presence.process_probe_confirmed_missing()); + } + + assert!(!presence.observe_process_probe(None)); + assert!(presence.process_probe_confirmed_missing()); assert_eq!(presence.current_agent(), None); } + #[test] + fn confirmed_missing_presence_clears_stale_hook_identity() { + let mut terminal = crate::terminal::TerminalState::new( + crate::terminal::TerminalId::alloc(), + "/tmp".into(), + ); + terminal.set_hook_authority("herdr:pi".into(), "pi".into(), AgentState::Idle, None, None); + let mut presence = AgentDetectionPresence::from_agent(None); + + for attempt in 1..AGENT_MISS_CONFIRMATION_ATTEMPTS { + assert!(!presence.observe_process_probe(None), "miss {attempt}"); + assert!(!presence.process_probe_confirmed_missing()); + } + assert!(!presence.observe_process_probe(None)); + assert!(presence.process_probe_confirmed_missing()); + terminal + .clear_agent_identity_after_confirmed_process_miss(std::time::Instant::now()) + .expect("confirmed process miss should clear stale identity"); + + assert_eq!(terminal.effective_agent_label(), None); + assert!(!terminal.is_agent_terminal()); + } + #[tokio::test] async fn state_changed_event_waits_for_queue_space_instead_of_dropping() { let (tx, mut rx) = mpsc::channel(1); diff --git a/src/terminal/state.rs b/src/terminal/state.rs index 0b96250f1f4..57565fadb95 100644 --- a/src/terminal/state.rs +++ b/src/terminal/state.rs @@ -234,6 +234,44 @@ impl TerminalState { } } + pub fn clear_agent_identity_after_confirmed_process_miss( + &mut self, + observed_at: Instant, + ) -> Option { + if !self.hook_authority_not_newer_than(observed_at) { + return None; + } + + let previous_agent_label = self.effective_agent_label().map(str::to_string); + let previous_known_agent = self.effective_known_agent(); + let previous_state = self.state; + let previous_presentation = + self.effective_presentation_for_state_at(previous_state, observed_at); + let previous_session = self.current_session_identity_for_persistence(); + + self.detected_agent = None; + self.fallback_state = AgentState::Unknown; + self.fallback_visible_blocker = false; + self.fallback_visible_idle = false; + self.fallback_visible_working = false; + self.fallback_observed_at = Some(observed_at); + self.hook_authority = None; + self.stale_hook_idle_since = None; + self.persisted_agent_session = None; + + Some(TerminalStateMutation { + effective_state_change: self.recompute_effective_state( + previous_agent_label, + previous_known_agent, + previous_state, + previous_presentation, + observed_at, + ), + session_ref_changed: previous_session + != self.current_session_identity_for_persistence(), + }) + } + #[cfg(test)] pub fn set_hook_authority( &mut self, @@ -1524,6 +1562,20 @@ mod tests { assert_eq!(terminal.state, AgentState::Unknown); } + #[test] + fn confirmed_missing_process_probe_clears_hook_identity_without_conflicting_agent() { + let mut terminal = test_terminal(); + terminal.set_hook_authority("herdr:pi".into(), "pi".into(), AgentState::Idle, None, None); + + let mutation = terminal + .clear_agent_identity_after_confirmed_process_miss(Instant::now()) + .expect("stale identity should be cleared"); + + assert!(mutation.effective_state_change.is_some()); + assert_eq!(terminal.effective_agent_label(), None); + assert!(!terminal.is_agent_terminal()); + } + #[test] fn detected_agent_clear_clears_matching_working_hook_authority() { let mut terminal = test_terminal();