Ignore closed agents when changing directories (#40625)

## Why

Closed agent channels can retain stale in-progress turns, which can incorrectly
block `/cd` or cause unnecessary background-terminal checks.

## What changed

- Mark agents closed whenever a `thread/closed` notification is routed, including
  for inactive event channels.
- Exclude closed agents from running-turn detection and background-terminal checks
  during working-directory changes.

## Testing

Cover directory-change recovery with both a routed close notification and a
replay-only closed thread that contains a stale in-progress turn.

GitOrigin-RevId: 1072456056f8c1a1b751a52635470b0be160d76c
This commit is contained in:
Benjamin Carlsson authored and copyberry committed 2026-08-25 15:15:06 +00:00
1 parent f832b2fe7b
commit 34c5303f49
3 files changed
+65 -7

No files matched your search

@@ -2484,6 +2484,48 @@ async fn changing_directory_preserves_project_trust_permissions_history_and_hook
assert!(output.contains(expected), "{path}");
app.clear_committed_mcp_inventory_loading();
}
let tracked = server.start_thread(&app.config).await?;
let closed = tracked.session.thread_id;
let channel = ThreadEventChannel::new_with_session(
THREAD_EVENT_CHANNEL_CAPACITY,
tracked.session,
tracked.turns,
);
app.thread_event_channels.insert(closed, channel);
app.agent_navigation.mark_closed(child);
for has_stale_replay_turn in [false, true] {
app.agent_navigation.upsert(
closed, /*agent_nickname*/ None, /*agent_role*/ None,
/*is_closed*/ false,
);
let channel = app.thread_event_channels.get_mut(&closed).expect("channel");
channel.store.lock().await.set_turns(vec![test_turn(
"stale-turn",
TurnStatus::InProgress,
Vec::new(),
)]);
if has_stale_replay_turn {
channel.mark_replay_only();
app.agent_navigation.mark_closed(closed);
} else {
app.enqueue_thread_notification(closed, thread_closed_notification(closed))
.await?;
}
requests.lock().expect("request recorder lock").clear();
app.change_working_directory(&mut tui, &mut server, failed.clone().abs())
.await;
assert_eq!(
recorded_params(&requests, "thread/backgroundTerminals/list"),
vec![json!({"threadId": original.to_string(), "cursor": null, "limit": 1})],
);
let output = history().join("");
insta::allow_duplicates! {
assert_snapshot!(output, @"■ Failed to change: thread/fork failed during TUI bootstrap: thread/fork failed: forced thread/name/set failure (code -32603)");
}
}
app.agent_navigation.upsert(
child, /*agent_nickname*/ None, /*agent_role*/ None, /*is_closed*/ false,
);
app.set_approvals_reviewer_in_app_and_widget(ApprovalsReviewer::AutoReview);
app.runtime_permission_profile_override =
Some(RuntimePermissionProfileOverride::from_config(&app.config));
+3 -1
View File
@@ -1017,6 +1017,7 @@ impl App {
None
};
let is_turn_started = matches!(notification, ServerNotification::TurnStarted(_));
let is_thread_closed = matches!(notification, ServerNotification::ThreadClosed(_));
let notification_status_change = SideParentStatusChange::for_notification(&notification);
let (sender, store) = {
let channel = self.ensure_thread_channel(thread_id);
@@ -1034,7 +1035,6 @@ impl App {
ServerNotification::TurnCompleted(notification) => {
guard.active_turn_id() == Some(notification.turn.id.as_str())
}
ServerNotification::ThreadClosed(_) => true,
_ => false,
};
let notification = if guard.active {
@@ -1053,6 +1053,8 @@ impl App {
};
if is_turn_started {
self.agent_navigation.mark_running(thread_id);
} else if is_thread_closed {
self.mark_agent_picker_thread_closed(thread_id);
} else if turn_stopped {
self.agent_navigation.mark_stopped(thread_id);
}
+20 -6
View File
@@ -29,13 +29,25 @@ impl App {
return self.working_directory_error("MCP inventory is still loading.");
}
let agents = self.agent_navigation.ordered_threads();
let closed_agents: HashSet<_> = agents
.iter()
.filter_map(|(id, agent)| agent.is_closed.then_some(*id))
.collect();
let active = self.thread_event_channels.iter().any(|(id, channel)| {
let store = channel.store.try_lock();
*id != thread_id && !store.is_ok_and(|store| store.active_turn_id().is_none())
*id != thread_id
&& !closed_agents.contains(id)
&& !channel
.store
.try_lock()
.is_ok_and(|store| store.active_turn_id().is_none())
});
if active || agents.iter().any(|(t, a)| *t != thread_id && a.is_running) {
return self.working_directory_error("Cannot change: another agent is running.");
}
let open_agents: Vec<_> = agents
.iter()
.filter_map(|(id, agent)| (!agent.is_closed).then_some(*id))
.collect();
let mut config = match self.rebuild_config_for_cwd(cwd.to_path_buf()).await {
Ok(config) => config,
Err(err) => return self.working_directory_error(format!("Cannot load {cwd:?}: {err}")),
@@ -96,10 +108,12 @@ impl App {
{
return self.working_directory_error("Conversation history is not saved.");
}
let mut ids: HashSet<_> = channels.keys().copied().collect();
for (id, agent) in self.agent_navigation.ordered_threads() {
ids.extend((!agent.is_closed).then_some(id));
}
let mut ids: HashSet<_> = channels
.keys()
.copied()
.filter(|id| !closed_agents.contains(id))
.collect();
ids.extend(open_agents);
let descendants = ids.iter().copied().filter(|id| *id != thread_id);
for tracked_id in std::iter::once(thread_id).chain(descendants) {
let request = ClientRequest::ThreadBackgroundTerminalsList {