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
9 changes: 9 additions & 0 deletions src/app/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
38 changes: 38 additions & 0 deletions src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Cell<usize>>,
Expand Down
5 changes: 5 additions & 0 deletions src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
127 changes: 114 additions & 13 deletions src/pane.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,26 @@ async fn publish_state_changed_event(
}
}

async fn publish_agent_presence_confirmed_missing(
state_events: mpsc::Sender<AppEvent>,
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 =
Expand Down Expand Up @@ -194,6 +214,7 @@ struct ProcessProbeInput {
foreground_pgid: Option<u32>,
last_foreground_pgid: Option<u32>,
has_process_probe: bool,
consecutive_misses: u8,
acquisition_age: Option<std::time::Duration>,
pending_foreground_shell_clear: bool,
pending_restore_probe: bool,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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))
Expand All @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}
}

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -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();
Expand All @@ -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,
Expand Down Expand Up @@ -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)]
Expand Down Expand Up @@ -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,
Expand All @@ -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 {
Expand Down Expand Up @@ -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);
Expand Down
52 changes: 52 additions & 0 deletions src/terminal/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,44 @@ impl TerminalState {
}
}

pub fn clear_agent_identity_after_confirmed_process_miss(
&mut self,
observed_at: Instant,
) -> Option<TerminalStateMutation> {
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,
Expand Down Expand Up @@ -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();
Expand Down
Loading