Add session archiving to the resume picker (#37369)

## What changed

- Add a `Ctrl+A` action and footer hint for archiving the selected session in the resume picker.
- Send archive requests through the app server, remove successfully archived sessions from the picker, and surface failures inline.
- Prevent duplicate actions while an archive is pending, preserve configured keybindings, and direct users to `/archive` when they select the current session.
- Ignore archive notifications for untracked side threads so they do not appear in agent navigation.

## Testing

- Cover successful, repeated, rejected, and failed archive requests, shortcut conflicts, footer rendering, and untracked-thread notifications.

GitOrigin-RevId: 20ea21c804a9685e46484d67df967859f9be4651
This commit is contained in:
joshyin-oai authored and copyberry committed 2026-08-07 03:48:15 +00:00
1 parent 6622546169
commit 1efd8fcb26
6 files changed
+403 -7

No files matched your search

+134
View File
@@ -0,0 +1,134 @@
use codex_protocol::ThreadId;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use super::LoadTrigger;
use super::PickerLoadRequest;
use super::PickerState;
use super::Row;
use super::SearchState;
use super::SessionPickerAction;
use super::SessionPickerLaunchContext;
use crate::keymap::KeymapContext;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(super) enum ArchiveState {
#[default]
Idle,
Pending {
thread_id: ThreadId,
},
}
impl PickerState {
pub(super) fn archive_shortcut_available(&self) -> bool {
if !matches!(self.action, SessionPickerAction::Resume) {
return false;
}
let archive_key = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::CONTROL);
self.list_keymap.action_for(archive_key).is_none()
&& !self.chord_keymap.bindings.iter().any(|binding| {
binding.action.context == KeymapContext::List
&& binding.chord.prefix.is_press(archive_key)
})
}
pub(super) fn request_archive_for_selected_session(&mut self) {
if !matches!(self.archive_state, ArchiveState::Idle) {
return;
}
let Some(row) = self.filtered_rows.get(self.selected) else {
return;
};
let Some(thread_id) = row.thread_id else {
self.inline_error = Some(String::from("Selected session does not have a thread ID."));
self.request_frame();
return;
};
if matches!(
self.launch_context,
SessionPickerLaunchContext::ExistingSession {
current_thread_id: Some(current_thread_id)
} if current_thread_id == thread_id
) {
self.inline_error = Some(String::from(
"Use /archive to archive the current session and exit.",
));
self.request_frame();
return;
}
self.archive_state = ArchiveState::Pending { thread_id };
self.request_frame();
(self.picker_loader)(PickerLoadRequest::Archive { thread_id });
}
pub(super) fn handle_archive_result(
&mut self,
thread_id: ThreadId,
result: std::io::Result<()>,
) {
if self.archive_state != (ArchiveState::Pending { thread_id }) {
return;
}
self.archive_state = ArchiveState::Idle;
if let Err(error) = result {
self.inline_error = Some(format!("Failed to archive session: {error}"));
self.request_frame();
return;
}
let selected_key = self
.filtered_rows
.get(self.selected)
.filter(|row| row.thread_id != Some(thread_id))
.and_then(Row::seen_key);
self.all_rows.retain(|row| row.thread_id != Some(thread_id));
// Keep the seen-row key as a tombstone so an older page that is already
// in flight cannot put the archived session back into the picker.
self.transcript_previews.remove(&thread_id);
self.transcript_cells.remove(&thread_id);
if self.expanded_thread_id == Some(thread_id) {
self.expanded_thread_id = None;
}
if self.pending_transcript_open == Some(thread_id) {
self.pending_transcript_open = None;
if let Some(cancellation) = self.pending_transcript_cancellation.take() {
let _ = cancellation.send(());
}
self.transcript_loading_frame_shown = false;
}
self.inline_error = None;
self.apply_filter();
if let Some(selected_key) = selected_key
&& let Some(selected) = self
.filtered_rows
.iter()
.position(|row| row.seen_key().as_ref() == Some(&selected_key))
{
self.selected = selected;
self.ensure_selected_visible();
}
if self.filtered_rows.is_empty()
&& !self.query.is_empty()
&& self.pagination.next_cursor.is_some()
&& !self.pagination.reached_scan_cap
&& !self.search_state.is_active()
{
let token = self.allocate_search_token();
self.search_state = SearchState::Active { token };
self.load_more_if_needed(LoadTrigger::Search { token });
}
}
}
#[cfg(test)]
#[path = "archive_tests.rs"]
mod tests;
@@ -0,0 +1,157 @@
use super::super::PickerLoadRequest;
use super::super::PickerLoader;
use super::super::PickerState;
use super::super::ProviderFilter;
use super::super::Row;
use super::super::SessionPickerAction;
use super::super::SessionPickerLaunchContext;
use super::ArchiveState;
use crate::key_hint::KeyBinding;
use crate::tui::FrameRequester;
use codex_app_server_client::TypedRequestError;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_protocol::ThreadId;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
use std::sync::Arc;
use std::sync::Mutex;
fn archive_picker_state() -> (PickerState, Arc<Mutex<Vec<ThreadId>>>) {
let requests = Arc::new(Mutex::new(Vec::new()));
let request_sink = Arc::clone(&requests);
let picker_loader: PickerLoader = Arc::new(move |request| {
if let PickerLoadRequest::Archive { thread_id } = request {
request_sink
.lock()
.expect("archive request sink")
.push(thread_id);
}
});
let state = PickerState::new(
FrameRequester::test_dummy(),
picker_loader,
ProviderFilter::Any,
/*show_all*/ true,
/*filter_cwd*/ None,
SessionPickerAction::Resume,
);
(state, requests)
}
fn set_selected_session(state: &mut PickerState, thread_id: ThreadId) {
state.all_rows = vec![Row {
path: None,
preview: String::from("Selected session"),
thread_id: Some(thread_id),
thread_name: None,
created_at: None,
updated_at: None,
cwd: None,
git_branch: None,
}];
state.apply_filter();
}
#[tokio::test]
async fn archive_shortcut_archives_selected_session_once() {
let (mut state, requests) = archive_picker_state();
let thread_id = ThreadId::new();
set_selected_session(&mut state, thread_id);
let shortcut = KeyEvent::new(KeyCode::Char('\u{0001}'), KeyModifiers::NONE);
assert!(state.handle_key(shortcut).await.unwrap().is_none());
assert!(state.handle_key(shortcut).await.unwrap().is_none());
assert_eq!(state.archive_state, ArchiveState::Pending { thread_id });
assert_eq!(*requests.lock().unwrap(), vec![thread_id]);
assert!(
state
.handle_key(KeyEvent::from(KeyCode::Enter))
.await
.unwrap()
.is_none()
);
state.handle_archive_result(thread_id, Ok(()));
assert_eq!(state.archive_state, ArchiveState::Idle);
assert!(state.filtered_rows.is_empty());
}
#[test]
fn archive_request_rejects_current_session() {
let (mut state, requests) = archive_picker_state();
let thread_id = ThreadId::new();
state.launch_context = SessionPickerLaunchContext::ExistingSession {
current_thread_id: Some(thread_id),
};
set_selected_session(&mut state, thread_id);
state.request_archive_for_selected_session();
assert_eq!(state.archive_state, ArchiveState::Idle);
assert_eq!(
state.inline_error.as_deref(),
Some("Use /archive to archive the current session and exit.")
);
assert!(requests.lock().unwrap().is_empty());
}
#[test]
fn archive_failure_preserves_session_and_reports_server_error() {
let (mut state, requests) = archive_picker_state();
let thread_id = ThreadId::new();
set_selected_session(&mut state, thread_id);
state.request_archive_for_selected_session();
let error = TypedRequestError::Server {
method: String::from("thread/archive"),
source: JSONRPCErrorError {
code: -32600,
message: String::from("thread already has an active writer"),
data: None,
},
};
state.handle_archive_result(thread_id, Err(std::io::Error::other(error)));
assert_eq!(state.archive_state, ArchiveState::Idle);
assert_eq!(
state.inline_error.as_deref(),
Some(
"Failed to archive session: thread/archive failed: thread already has an active writer (code -32600)"
)
);
assert_eq!(state.filtered_rows.len(), 1);
state.request_archive_for_selected_session();
assert_eq!(*requests.lock().unwrap(), vec![thread_id, thread_id]);
}
#[test]
fn archive_shortcut_preserves_configured_list_binding() {
let (mut state, _requests) = archive_picker_state();
state.list_keymap.move_up.push(KeyBinding::new(
KeyCode::Char('\u{0001}'),
KeyModifiers::NONE,
));
assert!(!state.archive_shortcut_available());
}
#[test]
fn archive_footer_shows_shortcut_for_resume_sessions() {
let (mut state, _requests) = archive_picker_state();
set_selected_session(&mut state, ThreadId::new());
let footer = super::super::footer_hint_lines(&state, /*width*/ 220)
.into_iter()
.map(|line| line.to_string())
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(footer, @r"
enter resume ctrl+a archive esc start new ctrl+c quit tab focus sort/filter ←/→ change option
ctrl+o dense view ctrl+t transcript ctrl+e expand ↑/↓ browse
");
}