Return to the command center while archiving a task (#61619)

## Why

Archiving the current task waits for the server response before returning to the command center, blocking navigation while the request is pending.

## What changed

- Run the archive request in the background after side chat and voice cleanup, hiding the task while it is pending.
- Preserve drafts and approvals until archiving succeeds. On failure, show an error and make the task visible again.
- Keep archive completions across reconnects and route dynamic tool replies through their original reply handles.
- Show `Archiving…` during side chat cleanup. On exit, wait up to five seconds for pending archives and report failures or unconfirmed outcomes.

## Testing

Add coverage for navigation before the archive response, success and failure handling across event channel replacement, preserved drafts, side chat cleanup failures, and exit warnings.

GitOrigin-RevId: 7b6e35cb11159f5be1d0b9fb2082dbd8c7826a94
This commit is contained in:
Benjamin Carlsson
2026-11-15 07:28:15 +00:00
committed by copyberry
parent b016cd1847
commit 02e745f3a0
21 changed files with 498 additions and 102 deletions
+8 -1
View File
@@ -788,7 +788,11 @@ fn handle_app_exit(
};
let update_action = exit_info.update_action;
if !matches!(update_action, Some(UpdateAction::Daemon(_))) {
if matches!(update_action, Some(UpdateAction::Daemon(_))) {
for warning in exit_info.archive_warnings {
eprintln!("{warning}");
}
} else {
let color_enabled = supports_color::on(Stream::Stdout).is_some();
for line in exit_info.format_exit_messages(color_enabled) {
println!("{line}");
@@ -3880,6 +3884,7 @@ enabled = true
thread_id,
thread_name: thread_name.map(str::to_string),
}),
archive_warnings: Vec::new(),
disconnect_info: None,
update_action: None,
exit_reason: ExitReason::UserRequested,
@@ -3892,6 +3897,7 @@ enabled = true
token_usage: TokenUsage::default(),
thread_id: None,
resume_hint: None,
archive_warnings: Vec::new(),
disconnect_info: None,
update_action: None,
exit_reason: ExitReason::UserRequested,
@@ -3952,6 +3958,7 @@ enabled = true
token_usage: TokenUsage::default(),
thread_id: Some(ThreadId::from_string("123e4567-e89b-12d3-a456-426614174000").unwrap()),
resume_hint: None,
archive_warnings: Vec::new(),
disconnect_info: None,
update_action: None,
exit_reason: ExitReason::Fatal("boom".to_string()),
+2
View File
@@ -487,6 +487,7 @@ pub struct AppExitInfo {
pub thread_id: Option<ThreadId>,
pub resume_hint: Option<ResumableThread>,
pub disconnect_info: Option<DisconnectInfo>,
pub archive_warnings: Vec<String>,
pub update_action: Option<UpdateAction>,
pub exit_reason: ExitReason,
}
@@ -497,6 +498,7 @@ impl AppExitInfo {
token_usage: TokenUsage::default(),
thread_id: None,
resume_hint: None,
archive_warnings: Vec::new(),
disconnect_info: None,
update_action: None,
exit_reason: ExitReason::Fatal(message.into()),
+11 -2
View File
@@ -47,6 +47,9 @@ pub(super) struct AgentsOverviewState {
pub(super) removed_threads: HashSet<ThreadId>,
/// Local visibility only; activity and metadata refreshes never reveal hidden roots.
pub(super) hidden_threads: HashSet<ThreadId>,
/// Hide pending archives; retain their outcomes if shutdown beats event dispatch.
pub(super) pending_archives:
HashMap<ThreadId, tokio::sync::oneshot::Receiver<Result<(), String>>>,
pub(super) unread: HashSet<ThreadId>,
pub(super) last_messages: HashMap<ThreadId, String>,
pub(super) usage: HashMap<ThreadId, super::agents_overview_usage::AgentsOverviewUsage>,
@@ -461,7 +464,9 @@ impl App {
.map(|i| view.rows[i].thread_id)
.collect();
matches.retain(|id, _| {
visible.contains(id) || self.agents_overview.hidden_threads.contains(id)
visible.contains(id)
|| self.agents_overview.hidden_threads.contains(id)
|| self.agents_overview.pending_archives.contains_key(id)
});
}
view.load_search_matches(/*additional*/ 0);
@@ -530,7 +535,11 @@ impl App {
threads.push(target.clone());
}
}
threads.retain(is_visible_in_agents_overview);
threads.retain(|thread| {
is_visible_in_agents_overview(thread)
&& !ThreadId::from_string(&thread.id)
.is_ok_and(|id| self.agents_overview.pending_archives.contains_key(&id))
});
for thread in &mut threads {
if thread.parent_thread_id.is_none()
&& let SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
@@ -682,19 +682,25 @@ impl App {
app_server_client.thread_tool_transport(),
crate::dynamic_tools_mcp::ThreadToolTransport::Mcp(_)
);
let archiving =
thread_id.is_some_and(|id| self.agents_overview.pending_archives.contains_key(&id));
if !tui_tool
|| requires_mcp
|| archiving
|| codex_protocol::ThreadId::from_string(&params.thread_id)
.is_ok_and(|thread_id| self.abandoned_side_threads.contains(&thread_id))
{
let response = crate::dynamic_tools::failure_response(if requires_mcp {
"TUI task tools require the approval-gated MCP server"
} else if archiving {
"Source task is being archived"
} else {
"TUI dynamic tools require an active task in the TUI namespace"
});
self.app_event_tx.send(AppEvent::DynamicToolCallCompleted {
request_id: request_id.clone(),
response,
reply: Some(buffered_request.reply),
});
return;
}
@@ -713,6 +719,7 @@ impl App {
.and_then(|thread_id| ThreadId::from_string(thread_id).ok())
.is_none_or(|thread_id| app_server_client.task_tools_available(thread_id));
let params = params.clone();
let reply = buffered_request.reply;
let mut thread_start_params =
crate::app_server_session::thread_start_params_from_config(
&self.config,
@@ -751,6 +758,7 @@ impl App {
app_event_tx.send(AppEvent::DynamicToolCallCompleted {
request_id,
response,
reply: Some(reply),
});
});
self.dynamic_tool_tasks
+115 -47
View File
@@ -104,6 +104,7 @@ impl App {
| AppEvent::ManagedWorktreeCreated(_)
| AppEvent::AgentsOverviewWorktreeCreated(_)
| AppEvent::AgentsOverviewPinToggled { .. }
| AppEvent::ArchiveFinished { .. }
| AppEvent::OpenAgentsOverview
| AppEvent::ShowMoreAgentsOverview
| AppEvent::AgentsOverviewThreadsLoaded { .. }
@@ -453,14 +454,16 @@ impl App {
AppEvent::DynamicToolCallCompleted {
request_id,
response,
reply,
} => {
self.dynamic_tool_tasks.remove(&request_id);
match serde_json::to_value(response) {
Ok(result) => {
if let Err(error) = app_server
.resolve_server_request(request_id.clone(), result)
.await
{
let result = match reply {
Some(reply) => reply.resolve(result).await,
None => app_server.resolve_server_request(request_id.clone(), result).await,
};
if let Err(error) = result {
tracing::warn!(?request_id, %error, "failed to resolve dynamic tool call");
}
}
@@ -654,6 +657,37 @@ impl App {
AppEvent::ArchiveCurrentThread => {
return self.archive_current_thread(tui, app_server).await;
}
AppEvent::ArchiveFinished { backend_id, thread_id, result } => {
if self.agents_overview.pending_archives.remove(&thread_id).is_some() {
match result {
Ok(()) => {
// The server already closed the archived task and canceled its requests.
let source = thread_id.to_string();
for (_, (_, task)) in self.dynamic_tool_tasks.extract_if(|_, (thread, _)| *thread == source) {
task.abort();
}
self.discard_thread_local_state(thread_id).await;
if backend_id == app_server.backend_id() {
self.agents_overview.input_states.remove(&thread_id);
}
self.agents_overview.dispatched_requests.remove(&thread_id);
self.track_agents_overview_notification(&ServerNotification::ThreadArchived(
codex_app_server_protocol::ThreadArchivedNotification {
thread_id: source,
},
));
}
Err(error) => {
self.agents_overview.refresh_thread_ids.insert(thread_id);
self.add_agents_overview_error(format!("Failed to archive thread {thread_id}: {error}"));
}
}
self.repaint_agents_overview();
if backend_id == app_server.backend_id() && !self.reconnect.offline {
self.refresh_changed_agents_overview_threads(app_server);
}
}
}
AppEvent::DeleteCurrentThread => {
return self.delete_current_thread(tui, app_server).await;
}
@@ -729,7 +763,7 @@ impl App {
} else {
None
};
self.retain_subscriptions_for_fork();
self.retain_thread_subscriptions();
match self
.replace_chat_widget_with_app_server_thread(
tui,
@@ -3305,6 +3339,8 @@ impl App {
AppEvent::AgentsOverviewThreadsLoaded { request_id, result } => {
self.apply_agents_overview_thread_refresh(app_server, request_id, result);
}
AppEvent::SelectAgentsOverviewThread { thread_id }
if self.agents_overview.pending_archives.contains_key(&thread_id) => {}
AppEvent::SelectAgentsOverviewThread { thread_id } => {
match self
.select_agents_overview_thread(tui, app_server, thread_id)
@@ -4236,7 +4272,12 @@ impl App {
app_server: &mut AppServerSession,
mode: ExitMode,
) -> AppRunControl {
for (request_id, (_, task)) in self.dynamic_tool_tasks.drain() {
for (request_id, (source, task)) in self.dynamic_tool_tasks.drain() {
if ThreadId::from_string(&source)
.is_ok_and(|id| self.agents_overview.pending_archives.contains_key(&id))
{
continue;
}
task.abort();
let response = crate::dynamic_tools::failure_response(
"TUI disconnected while handling a dynamic tool call",
@@ -4304,21 +4345,10 @@ impl App {
}
}
async fn return_to_agents_after_removal(
&mut self,
tui: &mut tui::Tui,
app_server: &mut AppServerSession,
thread_id: ThreadId,
) -> Result<()> {
self.discard_thread_local_state(thread_id).await;
self.agents_overview.input_states.remove(&thread_id);
self.agents_overview.dispatched_requests.remove(&thread_id);
self.reset_for_thread_switch(tui)?;
async fn reset_after_leaving_thread(&mut self, tui: &mut tui::Tui) {
self.pending_thread_switch_resets += 1;
self.app_event_tx
.send(AppEvent::ResetTranscriptForThreadSwitch);
self.detach_current_thread_for_navigation(app_server, /*destination*/ None)
.await;
self.reset_thread_event_state().await;
let init = self.chatwidget_init_for_forked_or_resumed_thread(
tui,
@@ -4326,8 +4356,6 @@ impl App {
/*initial_user_message*/ None,
);
self.replace_chat_widget(ChatWidget::new_with_app_event(init));
self.open_agents_overview(app_server);
Ok(())
}
pub(super) async fn archive_current_thread(
@@ -4348,36 +4376,70 @@ impl App {
return Ok(AppRunControl::Continue);
}
if !self
let show_progress = !self.side_threads.is_empty() && {
let subtree = self.known_thread_subtree(thread_id);
self.side_threads
.values()
.any(|side| subtree.contains(&side.parent_thread_id))
};
if show_progress {
self.chat_widget
.set_footer_hint_override(Some(vec![("Archiving…".into(), String::new())]));
// Cleanup waits outside the event loop. Paint before sending its first request.
let screen_size = tui.terminal.last_known_screen_size;
if let Err(error) = self.render_chat_widget_frame(tui, screen_size) {
tracing::warn!(%error, "failed to render archive progress");
}
}
let cleaned_up = self
.shutdown_side_threads(app_server, Some(thread_id))
.await
{
.await;
if show_progress {
self.chat_widget.set_footer_hint_override(/*items*/ None);
}
if !cleaned_up {
return Ok(AppRunControl::Continue);
}
let result = async {
self.stop_voice_for_removed_thread(app_server, thread_id)
.await?;
app_server.thread_archive(thread_id).await
if let Err(error) = self
.stop_voice_for_removed_thread(app_server, thread_id)
.await
{
self.chat_widget
.add_error_message(format!("Failed to archive current thread: {error}"));
return Ok(AppRunControl::Continue);
}
.await;
Ok(match result {
Ok(()) => {
self.track_agents_overview_notification(&ServerNotification::ThreadArchived(
codex_app_server_protocol::ThreadArchivedNotification {
thread_id: thread_id.to_string(),
},
));
self.return_to_agents_after_removal(tui, app_server, thread_id)
.await?;
AppRunControl::Continue
}
Err(err) => {
self.chat_widget
.add_error_message(format!("Failed to archive current thread: {err}"));
AppRunControl::Continue
}
})
self.capture_session_inputs(app_server.backend_id()).await;
// Keep the target subscribed and retain its approvals until the archive resolves.
self.retain_thread_subscriptions();
self.reset_for_thread_switch(tui)?;
self.reset_after_leaving_thread(tui).await;
let mut server = app_server.request_view();
let backend_id = server.backend_id();
let tx = self.saved_openings.tx.clone();
let (outcome_tx, outcome_rx) = tokio::sync::oneshot::channel();
let mut archive = Box::pin(async move {
let result = server
.thread_archive(thread_id)
.await
.map_err(|error| error.to_string());
let _ = outcome_tx.send(result.clone());
tx.send(AppEvent::ArchiveFinished {
backend_id,
thread_id,
result,
});
});
// Start queueing the archive before the overview starts its refresh.
if futures::poll!(archive.as_mut()).is_pending() {
tokio::spawn(archive);
}
self.agents_overview
.pending_archives
.insert(thread_id, outcome_rx);
self.open_agents_overview(app_server);
Ok(AppRunControl::Continue)
}
pub(super) async fn delete_current_thread(
@@ -4420,8 +4482,14 @@ impl App {
thread_id: thread_id.to_string(),
},
));
self.return_to_agents_after_removal(tui, app_server, thread_id)
.await?;
self.discard_thread_local_state(thread_id).await;
self.agents_overview.input_states.remove(&thread_id);
self.agents_overview.dispatched_requests.remove(&thread_id);
self.reset_for_thread_switch(tui)?;
self.detach_current_thread_for_navigation(app_server, /*destination*/ None)
.await;
self.reset_after_leaving_thread(tui).await;
self.open_agents_overview(app_server);
AppRunControl::Continue
}
Err(err) => {
+22 -1
View File
@@ -22,6 +22,26 @@ pub struct DisconnectInfo {
}
impl App {
pub(super) async fn finish_pending_archives(
&mut self,
deadline: tokio::time::Instant,
) -> Vec<String> {
let mut warnings = Vec::new();
for (thread_id, outcome) in self.agents_overview.pending_archives.drain() {
match tokio::time::timeout_at(deadline, outcome).await {
Ok(Ok(Ok(()))) => {}
Ok(Ok(Err(error))) => {
warnings.push(format!("Failed to archive thread {thread_id}: {error}"));
}
Ok(Err(_)) | Err(_) => {
warnings.push(format!("Archive of thread {thread_id} was not confirmed."));
}
}
}
warnings.sort();
warnings
}
pub(super) fn exit_info(&self, exit_reason: ExitReason) -> AppExitInfo {
let thread_id = self.chat_widget.thread_id().or(self.primary_thread_id);
let disconnect_info = thread_id.and_then(|_| {
@@ -66,6 +86,7 @@ impl App {
self.chat_widget.rollout_path().as_deref(),
),
disconnect_info,
archive_warnings: Vec::new(),
update_action: self.pending_update_action,
exit_reason,
}
@@ -82,7 +103,7 @@ impl AppExitInfo {
command
}
};
let mut lines = Vec::new();
let mut lines = self.archive_warnings;
if let Some(disconnect) = self.disconnect_info
&& let Some(thread_id) = self.thread_id
{
@@ -103,6 +103,14 @@ impl App {
target_session: &SessionTarget,
source: ResumeSource<'_>,
) -> std::result::Result<PreparedResume, AppRunControl> {
if self
.agents_overview
.pending_archives
.contains_key(&target_session.thread_id)
{
self.add_session_picker_error("This task is still being archived.".into());
return Err(AppRunControl::Continue);
}
if let Some(owner) = self.backend_registry.owner(target_session.thread_id)
&& let Err(error) = target_session.ensure_backend(owner)
{
+1 -1
View File
@@ -88,7 +88,7 @@ pub(super) async fn continue_with_rewrite(
if let Some(input) = app.chat_widget.capture_thread_input_state() {
app.agents_overview.input_states.insert(thread_id, input);
}
app.retain_subscriptions_for_fork();
app.retain_thread_subscriptions();
attached_fork = Some(fork_id);
app.replace_chat_widget_with_app_server_thread(
tui,
@@ -627,6 +627,13 @@ impl App {
app_server: &mut AppServerSession,
thread_id: ThreadId,
) -> Result<()> {
if self
.agents_overview
.pending_archives
.contains_key(&thread_id)
{
return Ok(());
}
if self
.side_threads
.get(&thread_id)
+1
View File
@@ -584,6 +584,7 @@ impl App {
response: crate::dynamic_tools::failure_response(
"Source task was closed while handling a dynamic tool call",
),
reply: None,
});
task.abort();
false
+2 -2
View File
@@ -24,8 +24,8 @@ struct Flight {
pub(super) struct Openings {
active: HashMap<(BackendId, ThreadId), Flight>,
// The app event channel rotates on reconnect. This pair has the lifetime of the flights.
tx: AppEventSender,
// Background completions survive app event channel rotation on reconnect.
pub(super) tx: AppEventSender,
completions: mpsc::UnboundedReceiver<AppEvent>,
}
+20 -3
View File
@@ -1376,7 +1376,9 @@ See the Codex keymap documentation for supported actions and examples."
break Err(err.into());
}
}
if app.pending_open_resume_picker {
// Process archive completions before the picker can list or mutate those threads.
if app.pending_open_resume_picker && app.agents_overview.pending_archives.is_empty()
{
app.pending_open_resume_picker = false;
match Box::pin(app.open_resume_picker_for_backends(tui, &mut backends)).await {
Ok(AppRunControl::Continue) => {}
@@ -1513,6 +1515,12 @@ See the Codex keymap documentation for supported actions and examples."
AppRunControl::Continue
}
Some(event) = app.saved_openings.next_event(&mut app_event_rx) => {
if let AppEvent::ArchiveFinished { backend_id, thread_id, result: Ok(()) } = &event
&& *backend_id != displayed_owner
&& let Some(slot) = backends.slot(*backend_id)
{
backends.parked_inputs_mut(slot).remove(thread_id);
}
let switch_backend = match &event {
AppEvent::ChooseNewSessionCheckout { name } | AppEvent::NewSession { name }
if multi_backend => app.other_new_session_backend(&backends).await
@@ -1819,6 +1827,10 @@ See the Codex keymap documentation for supported actions and examples."
cancellation.cancel();
}
app.chat_widget.mention_usage_mut().flush().await;
// Closing a remote or embedded connection can abandon an outstanding archive.
let archive_warnings = app
.finish_pending_archives(tokio::time::Instant::now() + Duration::from_secs(/*secs*/ 5))
.await;
if let Err(err) = backends.shutdown().await {
tracing::warn!(error = %err, "failed to shut down embedded app server");
}
@@ -1844,9 +1856,14 @@ See the Codex keymap documentation for supported actions and examples."
if let Err(clear_err) = clear_result {
tracing::warn!(error = %clear_err, "failed to clear terminal UI");
}
return Err(err);
if archive_warnings.is_empty() {
return Err(err);
}
return Err(err.wrap_err(archive_warnings.join("\n")));
}
};
Ok(app.exit_info(exit_reason))
let mut info = app.exit_info(exit_reason);
info.archive_warnings = archive_warnings;
Ok(info)
}
}
+1
View File
@@ -390,6 +390,7 @@ pub(super) async fn handle_model_migration_prompt_if_needed(
token_usage: TokenUsage::default(),
thread_id: None,
resume_hint: None,
archive_warnings: Vec::new(),
disconnect_info: None,
update_action: None,
exit_reason: ExitReason::UserRequested,
@@ -223,6 +223,19 @@ async fn daemon_disconnect_exit_summary_includes_reconnect_and_stop_instructions
let thread_id = prepare_running_local_daemon(&mut app)?;
app.keymap.agents.stop = vec![crate::key_hint::plain(KeyCode::F(10))];
let mut exit_info = app.exit_info(ExitReason::UserRequested);
let (rejected, outcome) = tokio::sync::oneshot::channel();
app.agents_overview
.pending_archives
.insert(thread_id, outcome);
rejected.send(Err("permission denied".to_string())).unwrap();
let pending_id = ThreadId::new();
let (_pending, outcome) = tokio::sync::oneshot::channel();
app.agents_overview
.pending_archives
.insert(pending_id, outcome);
exit_info.archive_warnings = app
.finish_pending_archives(tokio::time::Instant::now())
.await;
exit_info.token_usage = TokenUsage {
input_tokens: 10,
output_tokens: 2,
@@ -232,7 +245,8 @@ async fn daemon_disconnect_exit_summary_includes_reconnect_and_stop_instructions
let output = exit_info
.format_exit_messages(/*color_enabled*/ false)
.join("\n")
.replace(&thread_id.to_string(), "THREAD_ID");
.replace(&thread_id.to_string(), "THREAD_ID")
.replace(&pending_id.to_string(), "PENDING_ID");
assert_snapshot!("daemon_disconnect_exit", output);
Ok(())
}
@@ -208,6 +208,12 @@ async fn lifecycle_actions_stop_parked_voice_before_removing_owner() -> Result<(
match action {
AgentsOverviewAction::Archive => {
Box::pin(app.archive_current_thread(&mut tui, &mut server)).await?;
app.agents_overview
.pending_archives
.remove(&root)
.expect("archive started")
.await?
.expect("archive succeeded");
}
AgentsOverviewAction::Delete => {
Box::pin(app.delete_current_thread(&mut tui, &mut server)).await?;
@@ -2285,6 +2285,7 @@ fn spawn_approved_task_tool_call(
app_event_tx.send(AppEvent::DynamicToolCallCompleted {
request_id,
response,
reply: None,
});
});
}
@@ -2402,38 +2403,232 @@ async fn external_transport_registers_dynamic_tools_and_finds_task_mentions() ->
}
#[tokio::test]
async fn archive_current_thread_reports_success_only_after_archiving() -> Result<()> {
async fn embedded_archive_completes_after_opening_command_center() -> Result<()> {
let (mut app, _codex_home) = make_history_test_app().await?;
let thread_id = ThreadId::from_string(
&create_fake_rollout(
&app.config.codex_home,
"2026-08-25T01-00-00",
"2026-08-25T01:00:00Z",
"archive me",
Some(&app.config.model_provider_id),
/*git_info*/ None,
)
.expect("create rollout"),
)?;
let mut app_server = crate::start_embedded_app_server_for_picker(&app.config).await?;
let thread_id = create_history_rollout(&app.config, ThreadHistoryMode::Legacy, "archive me")?;
let mut server = crate::start_embedded_app_server_for_picker(&app.config).await?;
let mut tui = crate::tui::test_support::make_test_tui()?;
app.active_thread_id = Some(ThreadId::new());
assert_matches!(
app.archive_current_thread(&mut tui, &mut app_server)
.await?,
AppRunControl::Continue
);
let (_tx, mut events) = tokio::sync::mpsc::unbounded_channel();
app.active_thread_id = Some(thread_id);
assert_matches!(
app.archive_current_thread(&mut tui, &mut app_server)
.await?,
AppRunControl::Continue
);
Box::pin(app.archive_current_thread(&mut tui, &mut server)).await?;
assert!(app.chat_widget.active_view_is(AGENTS_OVERVIEW_VIEW_ID));
app_server.shutdown().await?;
assert_matches!(
app.saved_openings.next_event(&mut events).await,
Some(AppEvent::ArchiveFinished { thread_id: id, result: Ok(()), .. }) if id == thread_id
);
server.shutdown().await?;
Ok(())
}
#[tokio::test]
async fn archive_opens_command_center_before_the_server_replies() -> Result<()> {
use crate::app::agents_overview::tests::overview_thread;
use codex_app_server_client::AppServerClient;
use codex_app_server_client::CloudClient;
use codex_app_server_client::CloudOperation;
use futures::FutureExt;
for (mode, succeeded) in [
(crate::ThreadParamsMode::Cloud, true),
(crate::ThreadParamsMode::Remote, false),
] {
let (mut app, old_events, _ops) = make_test_app_with_channels().await;
let (client, mut commands, _server_events) = CloudClient::channel(/*capacity*/ 1);
let mut server = AppServerSession::new(
crate::backend_id::BackendId::new(),
AppServerClient::Cloud(client),
mode,
);
app.app_server_target = if mode == crate::ThreadParamsMode::Cloud {
AppServerTarget::Cloud
} else {
AppServerTarget::Remote {
endpoint: crate::resolve_remote_addr("ws://127.0.0.1:4500")?,
}
};
let thread_id = ThreadId::from_string("11111111-1111-4111-8111-111111111111")?;
let other_id = ThreadId::new();
for (id, name) in [(thread_id, "Archive me"), (other_id, "Keep me")] {
app.agents_overview.threads.insert(
id,
Some(overview_thread(
id,
/*parent_thread_id*/ None,
name,
ThreadStatus::Idle,
)),
);
}
let session = test_thread_session(thread_id, app.config.cwd.to_path_buf());
app.enqueue_primary_thread_session(session.clone(), Vec::new())
.await?;
app.chat_widget.handle_thread_session(session);
app.ensure_thread_channel(other_id);
app.chat_widget.insert_str("Unsent draft");
let input = app.chat_widget.capture_thread_input_state().expect("draft");
let tool_id = AppServerRequestId::Integer(123);
app.dynamic_tool_tasks.insert(
tool_id.clone(),
(thread_id.to_string(), tokio::spawn(std::future::pending())),
);
let mut tui = crate::tui::test_support::make_test_tui()?;
assert_matches!(
Box::pin(app.handle_event(&mut tui, &mut server, AppEvent::ArchiveCurrentThread))
.now_or_never()
.expect("the confirmation must not wait for the archive RPC")?,
AppRunControl::Continue
);
assert!(app.chat_widget.active_view_is(AGENTS_OVERVIEW_VIEW_ID));
assert_eq!(app.current_displayed_thread_id(), None);
assert_eq!(app.agents_overview.visible_thread_ids, [other_id]);
assert_eq!(
app.agents_overview.input_states.get(&thread_id),
Some(&input)
);
let command = commands
.try_recv()
.expect("archive queued ahead of refresh");
assert!(matches!(
command.operation,
CloudOperation::Request(request)
if matches!(request.as_ref(), ClientRequest::ThreadArchive { params, .. }
if params.thread_id == thread_id.to_string())
));
let reply = if succeeded {
Ok(serde_json::json!({}))
} else {
Err(JSONRPCErrorError {
code: -32000,
message: "Archive rejected".into(),
data: None,
})
};
// Reconnect replaces the UI event channel without losing archive results.
let (tx, mut events) = tokio::sync::mpsc::unbounded_channel();
app.app_event_tx = AppEventSender::new(tx);
drop(old_events);
command.response.send(Ok(reply)).expect("archive pending");
let event = app
.saved_openings
.next_event(&mut events)
.await
.expect("archive completion");
assert_matches!(&event, AppEvent::ArchiveFinished { .. });
Box::pin(app.handle_event(&mut tui, &mut server, event)).await?;
if succeeded {
assert_eq!(app.agents_overview.visible_thread_ids, [other_id]);
assert!(!app.agents_overview.input_states.contains_key(&thread_id));
assert!(!app.dynamic_tool_tasks.contains_key(&tool_id));
} else {
let (_, task) = app
.dynamic_tool_tasks
.remove(&tool_id)
.expect("tool still running");
assert!(!task.is_finished());
task.abort();
let frame = render_bottom_popup(&app.chat_widget, /*width*/ 120);
let error = &frame[frame
.find(" Unable to complete action")
.expect("expected archive error dialog")..];
insta::assert_snapshot!(error, @"
Unable to complete action
Failed to archive thread 11111111-1111-4111-8111-111111111111: failed to archive session
› 1. Return to command center
enter select · esc back
");
assert!(app.agents_overview.visible_thread_ids.contains(&thread_id));
assert_eq!(
app.agents_overview.input_states.get(&thread_id),
Some(&input)
);
}
}
Ok(())
}
#[tokio::test]
async fn archive_shows_progress_and_keeps_the_session_when_side_chat_cleanup_fails() -> Result<()> {
use codex_app_server_client::AppServerClient;
use codex_app_server_client::CloudClient;
use codex_app_server_client::CloudOperation;
let (mut app, _events, _ops) = make_test_app_with_channels().await;
let (client, mut commands, _server_events) = CloudClient::channel(/*capacity*/ 1);
let mut server = AppServerSession::new(
crate::backend_id::BackendId::new(),
AppServerClient::Cloud(client),
crate::ThreadParamsMode::Remote,
);
app.app_server_target = AppServerTarget::Remote {
endpoint: crate::resolve_remote_addr("ws://127.0.0.1:4500")?,
};
let thread_id = ThreadId::new();
let session = test_thread_session(thread_id, app.config.cwd.to_path_buf());
app.enqueue_primary_thread_session(session.clone(), Vec::new())
.await?;
app.chat_widget.handle_thread_session(session);
app.chat_widget.insert_str("Unsent draft");
let side_id = ThreadId::new();
app.side_threads
.insert(side_id, SideThreadState::new(thread_id));
let mut tui = crate::tui::test_support::make_test_tui()?;
let mut archive =
Box::pin(app.handle_event(&mut tui, &mut server, AppEvent::ArchiveCurrentThread));
assert!(futures::poll!(archive.as_mut()).is_pending());
let interrupt = commands.try_recv().expect("side chat interrupt");
assert!(matches!(
interrupt.operation,
CloudOperation::Request(request)
if matches!(request.as_ref(), ClientRequest::TurnInterrupt { params, .. }
if params.thread_id == side_id.to_string())
));
interrupt
.response
.send(Ok(Ok(serde_json::json!({}))))
.expect("pending interrupt");
assert!(futures::poll!(archive.as_mut()).is_pending());
let unsubscribe = commands.try_recv().expect("side chat unsubscribe");
assert!(matches!(
unsubscribe.operation,
CloudOperation::Request(request)
if matches!(request.as_ref(), ClientRequest::ThreadUnsubscribe { params, .. }
if params.thread_id == side_id.to_string())
));
unsubscribe
.response
.send(Ok(Err(JSONRPCErrorError {
code: -32000,
message: "Unsubscribe rejected".into(),
data: None,
})))
.expect("pending unsubscribe");
assert_matches!(archive.await?, AppRunControl::Continue);
assert!(commands.try_recv().is_err(), "archive must not be sent");
// The handler drew this frame before it waited for either cleanup reply.
let rendered = buffer_text(tui.terminal.previous_buffer());
insta::assert_snapshot!(
rendered
.lines()
.find(|line| line.contains("Archiving"))
.expect("archive progress hint")
.trim(),
@"Archiving…"
);
assert_eq!(app.current_displayed_thread_id(), Some(thread_id));
assert!(app.side_threads.contains_key(&side_id));
assert_eq!(
app.chat_widget.composer_draft_snapshot().text,
"Unsent draft"
);
assert!(!render_bottom_popup(&app.chat_widget, /*width*/ 80).contains("Archiving"));
Ok(())
}
@@ -2459,12 +2654,16 @@ async fn archive_current_thread_returns_to_agents() -> Result<()> {
let (mut app, _codex_home) = make_history_test_app().await?;
let thread_id =
create_history_rollout(&app.config, ThreadHistoryMode::Legacy, "archive me")?;
let (mut server, requests, proxy) = start_recording_app_server(
&app.config,
/*blocked_thread_list*/ None,
/*failed_thread_name*/ None,
)
.await?;
let (mut server, requests, proxy) = if matches!(&target, AppServerTarget::Remote { .. }) {
start_recording_remote_app_server(&app.config).await?
} else {
start_recording_app_server(
&app.config,
/*blocked_thread_list*/ None,
/*failed_thread_name*/ None,
)
.await?
};
let resumed = server
.resume_thread(
&app.local_settings,
@@ -2510,15 +2709,24 @@ async fn archive_current_thread_returns_to_agents() -> Result<()> {
.await?,
AppRunControl::Continue
);
loop {
let event = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), events.recv())
.await?
.expect("expected command center refresh");
let refreshed = matches!(&event, AppEvent::AgentsOverviewThreadsLoaded { .. });
Box::pin(app.handle_event(&mut tui, &mut server, event)).await?;
if refreshed {
break;
let mut archived = false;
let mut refreshed = false;
while !archived || !refreshed {
let event = tokio::time::timeout(
Duration::from_secs(/*secs*/ 5),
app.saved_openings.next_event(&mut events),
)
.await?
.expect("expected archive completion and command center refresh");
match &event {
AppEvent::ArchiveFinished { result, .. } => {
assert_eq!(*result, Ok(()));
archived = true;
}
AppEvent::AgentsOverviewThreadsLoaded { .. } => refreshed = true,
_ => {}
}
Box::pin(app.handle_event(&mut tui, &mut server, event)).await?;
}
assert!(
app.agents_overview
@@ -3187,6 +3395,7 @@ async fn check_dynamic_tool_requests(
let AppEvent::DynamicToolCallCompleted {
request_id,
response,
reply,
} = event
else {
panic!("expected a dynamic tool completion event")
@@ -3206,6 +3415,7 @@ async fn check_dynamic_tool_requests(
AppEvent::DynamicToolCallCompleted {
request_id,
response,
reply,
},
))
.await?;
@@ -2,6 +2,8 @@
source: tui/src/app/tests/background_exit_tests.rs
expression: output
---
Archive of thread PENDING_ID was not confirmed.
Failed to archive thread THREAD_ID: permission denied
Disconnected from this task. Any running work continues.
To reconnect, run:
codex resume THREAD_ID
+3 -2
View File
@@ -165,13 +165,14 @@ impl App {
}
}
pub(super) fn retain_subscriptions_for_fork(&mut self) {
// Tasks can start while the fork RPC is pending.
pub(super) fn retain_thread_subscriptions(&mut self) {
// Keep approvals routable while leaving the current task.
for id in self
.thread_event_channels
.keys()
.copied()
.chain(self.agent_navigation.tracked_thread_ids())
.chain(self.current_displayed_thread_id())
.filter(|id| {
!self.side_threads.contains_key(id)
&& !self
+6
View File
@@ -736,6 +736,7 @@ pub(crate) enum AppEvent {
DynamicToolCallCompleted {
request_id: AppServerRequestId,
response: DynamicToolCallResponse,
reply: Option<codex_app_server_client::AppServerReplyHandle>,
},
/// Register task tools inherited by a dynamically created thread.
@@ -801,6 +802,11 @@ pub(crate) enum AppEvent {
/// Archive the current active main thread and return to the command center.
ArchiveCurrentThread,
ArchiveFinished {
backend_id: crate::backend_id::BackendId,
thread_id: ThreadId,
result: Result<(), String>,
},
/// Permanently delete the current active main thread and return to the command center.
DeleteCurrentThread,
+7
View File
@@ -1217,6 +1217,7 @@ pub async fn run_main(
token_usage: TokenUsage::default(),
thread_id: None,
resume_hint: None,
archive_warnings: Vec::new(),
disconnect_info: None,
update_action: None,
exit_reason: ExitReason::UserRequested,
@@ -1306,6 +1307,7 @@ async fn run_ratatui_app(
token_usage: crate::token_usage::TokenUsage::default(),
thread_id: None,
resume_hint: None,
archive_warnings: Vec::new(),
disconnect_info: None,
update_action: Some(action),
exit_reason: ExitReason::UserRequested,
@@ -1494,6 +1496,7 @@ async fn run_ratatui_app(
token_usage: crate::token_usage::TokenUsage::default(),
thread_id: None,
resume_hint: None,
archive_warnings: Vec::new(),
disconnect_info: None,
update_action: None,
exit_reason: ExitReason::UserRequested,
@@ -1627,6 +1630,7 @@ async fn run_ratatui_app(
token_usage: crate::token_usage::TokenUsage::default(),
thread_id: None,
resume_hint: None,
archive_warnings: Vec::new(),
disconnect_info: None,
update_action: None,
exit_reason: ExitReason::Fatal(format!(
@@ -1744,6 +1748,7 @@ async fn run_ratatui_app(
token_usage: crate::token_usage::TokenUsage::default(),
thread_id: None,
resume_hint: None,
archive_warnings: Vec::new(),
disconnect_info: None,
update_action: None,
exit_reason: ExitReason::UserRequested,
@@ -1848,6 +1853,7 @@ async fn run_ratatui_app(
token_usage: crate::token_usage::TokenUsage::default(),
thread_id: None,
resume_hint: None,
archive_warnings: Vec::new(),
disconnect_info: None,
update_action: None,
exit_reason: ExitReason::UserRequested,
@@ -1899,6 +1905,7 @@ async fn run_ratatui_app(
token_usage: crate::token_usage::TokenUsage::default(),
thread_id: None,
resume_hint: None,
archive_warnings: Vec::new(),
disconnect_info: None,
update_action: None,
exit_reason: ExitReason::UserRequested,
+1
View File
@@ -128,6 +128,7 @@ pub(crate) async fn cancel_session_start(app_server: AppServerSession) -> AppExi
token_usage: Default::default(),
thread_id: None,
resume_hint: None,
archive_warnings: Vec::new(),
disconnect_info: None,
update_action: None,
exit_reason: ExitReason::UserRequested,