From ed33bb35af89338536c7bbb385da6fdf9eb031c8 Mon Sep 17 00:00:00 2001 From: Benjamin Carlsson Date: Mon, 30 Nov 2026 16:52:20 +0000 Subject: [PATCH] Enable `/archive` in TUI side chats (#64767) ## Why Side chats disabled `/archive`, so users couldn't archive the current side chat from the composer while the sidebar was hidden. ## What changed Show a confirmation in the composer even when the sidebar is hidden. Warn about stopping a running turn, discarding unsent input, or losing temporary chat history when applicable. On confirmation, return focus to the parent chat's composer. Archive saved side chats and remove them from Side chats. Close temporary side chats and discard their history after cleanup succeeds. ## Testing Cover saved side-chat archiving, including retry after a failed archive, and verify that a temporary side chat stays accessible with its queued input when cleanup fails. GitOrigin-RevId: 1bbe25a241719cdc2722bc8db915dea9111b6fc9 --- codex-rs/tui/src/app/event_dispatch.rs | 8 ++ codex-rs/tui/src/app/sidebar_close.rs | 61 ++++++++++--- codex-rs/tui/src/app/tests.rs | 21 ++++- .../src/app/tests/side_chat_policy_tests.rs | 90 +++++++++++++++++++ codex-rs/tui/src/app_event.rs | 4 + .../bottom_pane/chat_composer/slash_input.rs | 8 +- codex-rs/tui/src/bottom_pane/command_popup.rs | 6 +- .../tui/src/bottom_pane/slash_commands.rs | 1 + ...side_conversation_unavailable_command.snap | 8 +- codex-rs/tui/src/chatwidget/slash_dispatch.rs | 77 +++++++++------- codex-rs/tui/src/slash_command.rs | 1 + 11 files changed, 224 insertions(+), 61 deletions(-) diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 4e65d55925..73b3fe9bfb 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -792,6 +792,14 @@ impl App { AppEvent::ArchiveCurrentThread => { return self.archive_current_thread(tui, app_server).await; } + AppEvent::RequestSideArchive(target) => { + sidebar_close::confirm_archive(self, target).await; + } + AppEvent::ArchiveSideThread(target) => { + if self.current_displayed_thread_id() == Some(target) { + crate::boxed_future!(sidebar_close::execute(self, tui, app_server, target, sidebar_close::Action::Archive)).await?; + } + } AppEvent::ArchiveFinished { backend_id, thread_id, result } => { if self.agents_overview.pending_archives.remove(&thread_id).is_some() { match result { diff --git a/codex-rs/tui/src/app/sidebar_close.rs b/codex-rs/tui/src/app/sidebar_close.rs index d8c9047354..1b8210fda3 100644 --- a/codex-rs/tui/src/app/sidebar_close.rs +++ b/codex-rs/tui/src/app/sidebar_close.rs @@ -68,19 +68,12 @@ impl Confirmation { } } -pub(super) async fn request( - app: &mut App, - tui: &mut tui::Tui, - server: &mut AppServerSession, +async fn removal_losses( + app: &App, target: ThreadId, + side: &SideThreadState, action: Action, -) -> Result<()> { - let Some(side) = app.side_threads.get(&target) else { - return Ok(()); - }; - if side.close_request.is_some() { - return Ok(()); - } +) -> Vec<&'static str> { let displayed = app.current_displayed_thread_id() == Some(target); let mut losses = Vec::new(); if app.active_turn_id_for_thread(target).await.is_some() @@ -107,10 +100,43 @@ pub(super) async fn request( } if side.storage == SideChatStorage::Temporary { losses.push("lose this temporary chat’s history"); - } - if action == Action::Archive { + } else if action == Action::Archive { losses.push("remove it from Side chats"); } + losses +} + +/// The slash command uses the composer popup even when the sidebar is hidden. +pub(super) async fn confirm_archive(app: &mut App, target: ThreadId) { + if app.current_displayed_thread_id() != Some(target) { + return; + } + let Some(side) = app + .side_threads + .get(&target) + .filter(|s| s.close_request.is_none()) + else { + return; + }; + let losses = removal_losses(app, target, side, Action::Archive).await; + app.chat_widget + .show_archive_confirmation(Some(target), format!("This will {}.", losses.join(" and "))); +} + +pub(super) async fn request( + app: &mut App, + tui: &mut tui::Tui, + server: &mut AppServerSession, + target: ThreadId, + action: Action, +) -> Result<()> { + let Some(side) = app.side_threads.get(&target) else { + return Ok(()); + }; + if side.close_request.is_some() { + return Ok(()); + } + let losses = removal_losses(app, target, side, action).await; if losses.is_empty() { return execute(app, tui, server, target, action).await; } @@ -215,7 +241,7 @@ pub(super) async fn handle( true } -async fn execute( +pub(super) async fn execute( app: &mut App, tui: &mut tui::Tui, server: &mut AppServerSession, @@ -256,6 +282,13 @@ async fn execute( if side.close_request.is_some() { return Ok(()); } + // Both storage types return to the parent on /archive. Only saved chats + // have a rollout to archive. Keep temporary state until cleanup succeeds. + let action = if side.storage == SideChatStorage::Temporary { + Action::CloseTab + } else { + action + }; let request = uuid::Uuid::new_v4(); side.close_request = Some(request); let turn = app.active_turn_id_for_thread(target).await; diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index a41db99eb5..49602337aa 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -3896,7 +3896,10 @@ async fn reopen_saved_side_chat(during: DuringOpen) -> Result<()> { .unwrap_or_else(|| panic!("expected the archive confirmation in {frame}")); insta::assert_snapshot!(prompt, @"This will remove it from Side chats. Archive “New name”?"); let enter = TuiEvent::Key(KeyCode::Enter.into()); - boxed_future!(app.handle_tui_event(&mut tui, &mut server, enter)).await?; + boxed_future!(app.handle_tui_event(&mut tui, &mut server, enter.clone())).await?; + let mut release = KeyEvent::from(KeyCode::Enter); + release.kind = KeyEventKind::Release; + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(release))).await?; assert_eq!(app.current_displayed_thread_id(), Some(child)); let rollout = server .thread_read(child, /*include_turns*/ false) @@ -3910,9 +3913,19 @@ async fn reopen_saved_side_chat(during: DuringOpen) -> Result<()> { .join(rollout.file_name().unwrap()); std::fs::create_dir_all(&destination)?; for blocked in [true, false] { - boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(archive))).await?; - side_frame(&mut app, &mut tui, size)?; - for key in [KeyCode::Right.into(), KeyCode::Enter.into()] { + app.chat_widget.insert_str("/archive"); + boxed_future!(app.handle_tui_event(&mut tui, &mut server, enter.clone())).await?; + drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; + let frame = side_frame(&mut app, &mut tui, size)?; + let warning = frame + .lines() + .find_map(|line| line.split_once("This will ").map(|(_, rest)| rest)) + .expect("archive warning"); + let warning = warning.split(" ").next().unwrap().trim(); + if blocked { + insta::assert_snapshot!(warning, @"remove it from Side chats."); + } + for key in [KeyCode::Down, KeyCode::F(5), KeyCode::Char('g')].map(Into::into) { boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key))).await?; } loop { diff --git a/codex-rs/tui/src/app/tests/side_chat_policy_tests.rs b/codex-rs/tui/src/app/tests/side_chat_policy_tests.rs index 7468ee6bf7..44bcd959f5 100644 --- a/codex-rs/tui/src/app/tests/side_chat_policy_tests.rs +++ b/codex-rs/tui/src/app/tests/side_chat_policy_tests.rs @@ -111,6 +111,96 @@ async fn temporary_side_chat_sends_policy_on_its_first_request() -> Result<()> { Ok(()) } +#[tokio::test] +async fn temporary_side_archive_warns_about_queued_input_and_keeps_chat_on_failure() -> Result<()> { + let (mut app, mut events, _ops) = make_test_app_with_channels().await; + let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?; + let primary = server.start_thread(&app.config).await?; + let parent = primary.session.thread_id; + app.enqueue_primary_thread_session(primary.session, primary.turns) + .await?; + // The client still has the tab, but the server cannot interrupt this thread. + let child = ThreadId::new(); + let channel = ThreadEventChannel::new(/*capacity*/ 1); + channel.store.lock().await.set_session( + test_thread_session(child, app.config.cwd.to_path_buf()), + Vec::new(), + ); + app.thread_event_channels.insert(child, channel); + app.side_threads.insert(child, SideThreadState::new(parent)); + let mut tui = crate::tui::test_support::make_test_tui()?; + app.select_agent_thread(&mut tui, &mut server, child) + .await?; + drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; + app.chat_widget + .set_queue_autosend_suppressed(/*suppressed*/ true); + assert!(app.chat_widget.queue_user_message_with_options( + "queued follow-up".into(), + crate::bottom_pane::QueuedInputAction::Plain, + Vec::new(), + )); + app.chat_widget.insert_str("/archive"); + boxed_future!(app.handle_tui_event( + &mut tui, + &mut server, + TuiEvent::Key(KeyCode::Enter.into()) + )) + .await?; + drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; + // Isolate the wrapped warning from the queued message behind the dialog. + let dialog = app.chat_widget.centered_dialog().expect("archive dialog"); + let area = Rect::new( + /*x*/ 0, + /*y*/ 0, + /*width*/ 80, + dialog.desired_height(/*width*/ 80), + ); + let mut buffer = Buffer::empty(area); + dialog.render(area, &mut buffer); + let warning = buffer_text(&buffer) + .lines() + .map(str::trim) + .skip_while(|line| !line.starts_with("This will ")) + .take(2) + .collect::>() + .join(" "); + insta::assert_snapshot!(warning, @"This will discard unsent input and lose this temporary chat’s history."); + app.chat_widget.handle_key_event(KeyCode::Down.into()); + app.chat_widget.handle_key_event(KeyCode::Enter.into()); + loop { + let event = time::timeout(Duration::from_secs(/*secs*/ 5), events.recv()) + .await? + .expect("cleanup result"); + let finished = + matches!(&event, AppEvent::SideChatRemovalFinished { target, .. } if *target == child); + if let AppEvent::SideChatRemovalFinished { result, .. } = &event { + assert!(result.as_ref().unwrap_err().contains("Failed to interrupt")); + } + boxed_future!(app.handle_event(&mut tui, &mut server, event)).await?; + if finished { + break; + } + } + assert_eq!(app.current_displayed_thread_id(), Some(parent)); + assert!(app.side_threads[&child].close_request.is_none()); + assert!(!app.abandoned_side_threads.contains(&child)); + assert!( + app.thread_event_channels[&child] + .store + .lock() + .await + .input_state + .as_ref() + .unwrap() + .has_unsent_input() + ); + app.select_agent_thread(&mut tui, &mut server, child) + .await?; + assert_eq!(app.current_displayed_thread_id(), Some(child)); + server.shutdown().await?; + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn saved_side_chat_title_uses_only_its_first_direct_input() -> Result<()> { let question = "Why is CI failing on Windows?"; diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 81db59d536..be5f92b0e2 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -873,6 +873,10 @@ pub(crate) enum AppEvent { /// Archive the current active main thread and return to the command center. ArchiveCurrentThread, + /// Show the loss warning for the displayed side chat before archiving. + RequestSideArchive(ThreadId), + /// Archive the confirmed side chat, provided it is still displayed. + ArchiveSideThread(ThreadId), ArchiveFinished { backend_id: crate::backend_id::BackendId, thread_id: ThreadId, diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs b/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs index 5140fa6d12..c4f0eedaa0 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs @@ -635,7 +635,7 @@ mod tests { fn unavailable_side_conversation_command_still_opens_popup() { let mut composer = test_composer(); composer.set_side_conversation_active(/*active*/ true); - composer.draft.textarea.set_text_clearing_elements("/arch"); + composer.draft.textarea.set_text_clearing_elements("/comp"); composer.draft.textarea.set_cursor(/*pos*/ 5); composer.sync_popups(); @@ -651,7 +651,7 @@ mod tests { composer.sync_popups(); assert_eq!(press(&mut composer, KeyCode::Tab), InputResult::None); - assert_eq!(composer.draft.textarea.text(), "/agents "); + assert_eq!(composer.draft.textarea.text(), "/archive "); } #[test] @@ -659,12 +659,12 @@ mod tests { let mut composer = test_composer(); composer.set_side_conversation_active(/*active*/ true); composer.set_task_running(/*running*/ true); - composer.draft.textarea.set_text_clearing_elements("/arch"); + composer.draft.textarea.set_text_clearing_elements("/comp"); composer.draft.textarea.set_cursor(/*pos*/ 5); composer.sync_popups(); assert_eq!(press(&mut composer, KeyCode::Tab), InputResult::None); - assert_eq!(composer.draft.textarea.text(), "/arch"); + assert_eq!(composer.draft.textarea.text(), "/comp"); } #[test] diff --git a/codex-rs/tui/src/bottom_pane/command_popup.rs b/codex-rs/tui/src/bottom_pane/command_popup.rs index 4a5bda6aa2..a2a7f36386 100644 --- a/codex-rs/tui/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui/src/bottom_pane/command_popup.rs @@ -337,13 +337,13 @@ mod tests { assert!( !popup .filtered_items() - .contains(&CommandItem::Builtin(SlashCommand::Archive)) + .contains(&CommandItem::Builtin(SlashCommand::Resume)) ); - popup.on_composer_text_change("/arch".to_string()); + popup.on_composer_text_change("/resu".to_string()); assert_eq!( popup.filtered_items(), - vec![CommandItem::Builtin(SlashCommand::Archive)] + vec![CommandItem::Builtin(SlashCommand::Resume)] ); assert_eq!(popup.selected_item(), None); diff --git a/codex-rs/tui/src/bottom_pane/slash_commands.rs b/codex-rs/tui/src/bottom_pane/slash_commands.rs index c492007822..e32be3314f 100644 --- a/codex-rs/tui/src/bottom_pane/slash_commands.rs +++ b/codex-rs/tui/src/bottom_pane/slash_commands.rs @@ -344,6 +344,7 @@ mod tests { vec![ SlashCommand::Ide, SlashCommand::Rename, + SlashCommand::Archive, SlashCommand::Agents, SlashCommand::Copy, SlashCommand::Export, diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__command_popup__tests__side_conversation_unavailable_command.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__command_popup__tests__side_conversation_unavailable_command.snap index 3419c66744..e3db26ef3d 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__command_popup__tests__side_conversation_unavailable_command.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__command_popup__tests__side_conversation_unavailable_command.snap @@ -5,15 +5,13 @@ expression: "format!(\"{buf:?}\")" Buffer { area: Rect { x: 0, y: 0, width: 76, height: 2 }, content: [ - " /archive (disabled) archive this session (disabled: not available in a ", - " side conversation) ", + " /resume (disabled) resume a saved chat (disabled: not available in a side", + " conversation) ", ], styles: [ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM, x: 3, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | DIM, x: 7, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM, - x: 73, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, - x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM, - x: 41, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + x: 35, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, ] } diff --git a/codex-rs/tui/src/chatwidget/slash_dispatch.rs b/codex-rs/tui/src/chatwidget/slash_dispatch.rs index afa4345333..b631bdcfcb 100644 --- a/codex-rs/tui/src/chatwidget/slash_dispatch.rs +++ b/codex-rs/tui/src/chatwidget/slash_dispatch.rs @@ -42,6 +42,40 @@ const RAW_USAGE: &str = "Usage: /raw [on|off]"; const USAGE_CHATGPT_LOGIN_REQUIRED: &str = "Sign in with ChatGPT to use /usage."; impl ChatWidget { + pub(crate) fn show_archive_confirmation( + &mut self, + side_thread_id: Option, + warning: String, + ) { + self.bottom_pane.show_selection_view(SelectionViewParams { + title: Some("Archive this session?".to_string()), + subtitle: Some(warning), + footer_hint: Some(standard_popup_hint_line()), + items: vec![ + SelectionItem { + name: "No, don't archive".to_string(), + description: Some("Return to the current session".to_string()), + dismiss_on_select: true, + ..Default::default() + }, + SelectionItem { + name: "Yes, archive".to_string(), + description: Some("Archive this session now".to_string()), + actions: vec![Box::new(move |tx| { + tx.send(match side_thread_id { + Some(thread_id) => AppEvent::ArchiveSideThread(thread_id), + None => AppEvent::ArchiveCurrentThread, + }); + })], + dismiss_on_select: true, + ..Default::default() + }, + ], + ..SelectionViewParams::confirmation() + }); + self.request_redraw(); + } + /// Dispatch a bare slash command and record its staged local-history entry. /// /// The composer stages history before returning `InputResult::Command`; this wrapper commits @@ -289,37 +323,18 @@ impl ChatWidget { self.show_session_checkout_picker(ManagedWorktreeMode::New, /*name*/ None); } SlashCommand::Archive => { - self.bottom_pane.show_selection_view(SelectionViewParams { - title: Some("Archive this session?".to_string()), - subtitle: Some( - if self.bottom_pane.is_task_running() { - "This will stop the current turn and archive the session." - } else { - "Are you sure? This will archive the current session" - } - .to_string(), - ), - footer_hint: Some(standard_popup_hint_line()), - items: vec![ - SelectionItem { - name: "No, don't archive".to_string(), - description: Some("Return to the current session".to_string()), - dismiss_on_select: true, - ..Default::default() - }, - SelectionItem { - name: "Yes, archive".to_string(), - description: Some("Archive this session now".to_string()), - actions: vec![Box::new(|tx| { - tx.send(AppEvent::ArchiveCurrentThread); - })], - dismiss_on_select: true, - ..Default::default() - }, - ], - ..SelectionViewParams::confirmation() - }); - self.request_redraw(); + if self.active_side_conversation { + if let Some(target) = self.thread_id { + self.app_event_tx.send(AppEvent::RequestSideArchive(target)); + } + return; + } + let warning = if self.bottom_pane.is_task_running() { + "This will stop the current turn and archive the session." + } else { + "Are you sure? This will archive the current session" + }; + self.show_archive_confirmation(/*side_thread_id*/ None, warning.to_string()); } SlashCommand::Delete => { self.bottom_pane.show_selection_view(SelectionViewParams { diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 87036b0300..239a121e35 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -208,6 +208,7 @@ impl SlashCommand { matches!( self, SlashCommand::Copy + | SlashCommand::Archive | SlashCommand::Agents | SlashCommand::Export | SlashCommand::Raw