From 4ae20b9f28f72d46fcea7431381b88fb4c70514a Mon Sep 17 00:00:00 2001 From: Benjamin Carlsson Date: Sun, 22 Nov 2026 22:48:31 +0000 Subject: [PATCH] Add creation-time sorting to Command Center search (#63208) ## Why Sorting by last update can put older tasks ahead of recently created ones, making it harder to find the newest tasks that match a search. ## What changed Press `Tab` while editing a search to toggle between `Updated` and `Created` when the key is unbound. The footer shows the active sort, and the date column shows the corresponding timestamp. Restart history pagination in the selected order while keeping existing matches visible. Ignore late pages from the previous sort. ## Testing Cover the sort hint and date column, configured `Tab` bindings, and a sort switch that keeps the selected task visible while fetching newer matches by creation time. GitOrigin-RevId: b17006c546f8f121a790f3fffc27c27035c85771 --- codex-rs/tui/src/app/agent_center/hints.rs | 10 +++ codex-rs/tui/src/app/agent_center/input.rs | 31 +++++++++ codex-rs/tui/src/app/agent_center/rows.rs | 11 ++- codex-rs/tui/src/app/agent_center_tests.rs | 36 ++++++++++ .../tui/src/app/agents_overview_discovery.rs | 67 ++++++++++++++++--- .../app/agents_overview_discovery_tests.rs | 53 ++++++++++++++- .../tui/src/app/agents_overview_grouping.rs | 37 +++++----- codex-rs/tui/src/app/agents_overview_view.rs | 21 ++++-- ...and_center__live_center_search_active.snap | 2 +- 9 files changed, 227 insertions(+), 41 deletions(-) diff --git a/codex-rs/tui/src/app/agent_center/hints.rs b/codex-rs/tui/src/app/agent_center/hints.rs index 9c155ad1ae..f22fbc059f 100644 --- a/codex-rs/tui/src/app/agent_center/hints.rs +++ b/codex-rs/tui/src/app/agent_center/hints.rs @@ -178,6 +178,16 @@ impl AgentsOverviewView { { hints.push(("?".into(), "help".into())); } + if state.searching + && state.rename_target.is_none() + && state.connection_notice.is_none() + && self.search_sort_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)) + { + hints.push(( + "Tab".into(), + format!("sort ({})", state.search_sort.label()), + )); + } let cancel = if state.help { self.keymap.primary_hint(ListAction::Cancel) } else if state.editing_metadata() || self.can_return_to_chat { diff --git a/codex-rs/tui/src/app/agent_center/input.rs b/codex-rs/tui/src/app/agent_center/input.rs index 0abc72f7a0..0def0476be 100644 --- a/codex-rs/tui/src/app/agent_center/input.rs +++ b/codex-rs/tui/src/app/agent_center/input.rs @@ -50,11 +50,42 @@ impl AgentsOverviewView { false } + pub(super) fn search_sort_key(&self, key: KeyEvent) -> bool { + key.code == KeyCode::Tab + && key.modifiers.is_empty() + && self.keymap.action_for(key).is_none() + && !self.center_shortcut_keys.is_pressed(key) + } + pub(in crate::app::agents_overview_view) fn command_center_key( &mut self, key: KeyEvent, ) -> bool { if self.state().editing_metadata() { + if self.search_sort_key(key) && key.kind == KeyEventKind::Press { + let mut state = self.state(); + if state.searching + && state.rename_target.is_none() + && state.connection_notice.is_none() + { + state.search_sort = match state.search_sort { + HistorySort::Updated => HistorySort::Created, + HistorySort::Created => HistorySort::Updated, + }; + if let Some(search) = &mut state.history { + *search = HistorySearch { + id: search.id, + scan_id: uuid::Uuid::new_v4(), + retained: self.rows.iter().map(|row| row.thread_id).collect(), + ..Default::default() + }; + } + state.scroll = 0; + drop(state); + self.load_search_matches(/*additional*/ 10); + return true; + } + } if self.keymap.action_for(key) == Some(ListAction::Cancel) { self.on_ctrl_c(); return true; diff --git a/codex-rs/tui/src/app/agent_center/rows.rs b/codex-rs/tui/src/app/agent_center/rows.rs index 9f15891f83..3d632db138 100644 --- a/codex-rs/tui/src/app/agent_center/rows.rs +++ b/codex-rs/tui/src/app/agent_center/rows.rs @@ -98,15 +98,20 @@ impl AgentsOverviewView { }; let entries = self.center_rows(&indices, &state); let reference = chrono::Utc::now(); + let sort = if state.searching { + state.search_sort + } else { + HistorySort::Updated + }; let age = |task: &AgentsOverviewRow| { format_relative_time( reference, - chrono::DateTime::from_timestamp(task.thread.updated_at, /*nsecs*/ 0), + chrono::DateTime::from_timestamp(sort.timestamp(&task.thread), /*nsecs*/ 0), ) }; let widths = (state.list_width >= STATUS_COLUMNS_MIN_WIDTH).then(|| { let mut status_width = "Status".width(); - let mut updated_width = "Updated".width(); + let mut updated_width = sort.label().width(); for task in indices.iter().filter_map(|&index| self.rows.get(index)) { status_width = status_width.max(status_for(task).0.width()); updated_width = updated_width.max(age(task).width()); @@ -117,7 +122,7 @@ impl AgentsOverviewView { let (title, status, updated) = columns(row(area, /*offset*/ 0, /*height*/ 1), widths); line("Tasks".dim(), title, buf); line("Status".dim(), status, buf); - Line::from("Updated".dim()) + Line::from(sort.label().dim()) .right_aligned() .render(updated, buf); } diff --git a/codex-rs/tui/src/app/agent_center_tests.rs b/codex-rs/tui/src/app/agent_center_tests.rs index f33860dc8f..e7512e34ec 100644 --- a/codex-rs/tui/src/app/agent_center_tests.rs +++ b/codex-rs/tui/src/app/agent_center_tests.rs @@ -979,6 +979,11 @@ async fn live_center_search_row_appears_only_while_editing() { "live_center_search_active", screen(&view, area.width, area.height) ); + view.handle_key_event(KeyCode::Tab.into()); + let created = screen(&view, area.width, area.height); + assert!(created.contains("Status Created"), "{created}"); + assert!(created.contains("Tab sort (Created)"), "{created}"); + view.handle_key_event(KeyCode::Tab.into()); view.handle_key_event(KeyCode::Esc.into()); assert_eq!(screen(&view, area.width, area.height), idle); } @@ -1448,3 +1453,34 @@ async fn workspace_navigation_preserves_the_draft_and_reading_position() -> Resu server.shutdown().await?; Ok(()) } + +#[tokio::test] +async fn search_sort_tab_respects_configured_list_bindings_and_rename() { + use crate::app::agents_overview_discovery::HistorySort; + + let mut app = make_test_app().await; + let id = ThreadId::from_u128(/*value*/ 101); + let thread = overview_thread( + id, + /*parent_thread_id*/ None, + "Task", + ThreadStatus::Idle, + ); + let config: TuiKeymap = toml::from_str("[list]\nmove_down = 'tab'").unwrap(); + app.keymap = RuntimeKeymap::from_config(&config).unwrap(); + let mut view = app.agents_overview_view(vec![thread], Some(id)); + view.handle_key_event(KeyCode::Char('/').into()); + view.handle_key_event(KeyCode::Tab.into()); + assert_eq!( + app.agents_overview.view_state.lock().unwrap().search_sort, + HistorySort::Updated + ); + assert!(!screen(&view, /*width*/ 88, /*height*/ 16).contains("Tab sort")); + view.handle_key_event(KeyCode::Esc.into()); + view.handle_key_event(KeyCode::Char('r').into()); + view.handle_key_event(KeyCode::Tab.into()); + assert_eq!( + app.agents_overview.view_state.lock().unwrap().search_sort, + HistorySort::Updated + ); +} diff --git a/codex-rs/tui/src/app/agents_overview_discovery.rs b/codex-rs/tui/src/app/agents_overview_discovery.rs index 33be1ac1b7..b267173f5a 100644 --- a/codex-rs/tui/src/app/agents_overview_discovery.rs +++ b/codex-rs/tui/src/app/agents_overview_discovery.rs @@ -19,6 +19,7 @@ use codex_app_server_protocol::ThreadSourceKind; use codex_protocol::ThreadId; use codex_protocol::protocol::SubAgentSource; use codex_state::PINNED_THREAD_SECTION_ID; +use std::collections::HashSet; use std::collections::VecDeque; use std::sync::PoisonError; use tokio_util::task::AbortOnDropHandle; @@ -159,7 +160,12 @@ impl AgentsOverviewDiscovery { &mut self, handle: &AppServerRequestHandle, limit: usize, + search_sort: Option, ) -> (Vec<(Thread, bool)>, bool) { + let timestamp = |thread: &Thread| match search_sort { + Some(sort) => sort.timestamp(thread), + None => thread.recency_at.unwrap_or(thread.updated_at), + }; let [interactive, other] = &mut self.sources; // Cloud does not support filtering its task list to Exec and AppServer threads. if matches!(handle, AppServerRequestHandle::Cloud(_)) { @@ -182,9 +188,8 @@ impl AgentsOverviewDiscovery { source.rows.front().map(|(thread, _)| (index, thread)) }) .max_by(|(_, left), (_, right)| { - left.recency_at - .unwrap_or(left.updated_at) - .cmp(&right.recency_at.unwrap_or(right.updated_at)) + timestamp(left) + .cmp(×tamp(right)) .then_with(|| left.id.cmp(&right.id)) }) .map(|(index, _)| index); @@ -211,7 +216,7 @@ impl AgentsOverviewDiscovery { refresh_recent: bool, ) -> (Vec<(Thread, bool)>, bool) { if !matches!(handle, AppServerRequestHandle::Cloud(_)) { - return self.next_batch(handle, limit).await; + return self.next_batch(handle, limit, /*search_sort*/ None).await; } // Cloud has one source. Fetch only what we can show, even for a partial refill. self.sources[1].exhausted = true; @@ -334,9 +339,44 @@ impl SourcePage { } } +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(super) enum HistorySort { + Created, + #[default] + Updated, +} + +impl HistorySort { + pub(super) fn label(self) -> &'static str { + match self { + Self::Created => "Created", + Self::Updated => "Updated", + } + } + + fn sort_key(self) -> ThreadSortKey { + match self { + Self::Created => ThreadSortKey::CreatedAt, + Self::Updated => ThreadSortKey::UpdatedAt, + } + } + + pub(super) fn timestamp(self, thread: &Thread) -> i64 { + match self { + Self::Created => thread.created_at, + Self::Updated => thread.updated_at, + } + } +} + #[derive(Default)] pub(super) struct HistorySearch { + /// Identifies matches for this query across sort changes. pub(super) id: Uuid, + /// Changes on every restart so a late page cannot advance a different scan. + pub(super) scan_id: Uuid, + /// Visible before the sort changed, but not yet encountered in the new order. + pub(super) retained: HashSet, pub(super) cursor: AgentsOverviewDiscovery, /// Requested number of matches visible under the active status filter. pub(super) target: usize, @@ -371,17 +411,19 @@ impl App { let shared = &self.agents_overview.view_state; let mut state = shared.lock().unwrap_or_else(PoisonError::into_inner); let query = state.search.to_lowercase(); - let Some(search) = state.history.as_mut().filter(|search| search.id == id) else { + let sort = state.search_sort; + let Some(search) = state.history.as_mut().filter(|search| search.scan_id == id) else { return; }; - let first = self.agents_overview.search_id != id; + let first = self.agents_overview.search_id != search.id; let mut cursor = std::mem::take(&mut search.cursor); if first { self.agents_overview.search_matches.clear(); - self.agents_overview.search_id = id; + self.agents_overview.search_id = search.id; } for source in &mut cursor.sources { source.page_size = 100; + source.sort_key = sort.sort_key(); } if matches!(handle, AppServerRequestHandle::Cloud(_)) { cursor.sources[1].exhausted = true; @@ -392,7 +434,7 @@ impl App { tokio::time::sleep(std::time::Duration::from_millis(180)).await; } loop { - let (mut rows, ok) = cursor.next_batch(&handle, limit).await; + let (mut rows, ok) = cursor.next_batch(&handle, limit, Some(sort)).await; rows.retain(|(thread, _)| matches_query(thread, &query)); if rows.is_empty() && ok && cursor.has_more() { continue; @@ -422,12 +464,15 @@ impl App { .view_state .lock() .unwrap_or_else(PoisonError::into_inner); - let Some(search) = state.history.as_mut().filter(|s| s.id == id) else { + let Some(search) = state.history.as_mut().filter(|s| s.scan_id == id) else { return; }; for (thread, unread) in rows { - if let Ok(id) = codex_protocol::ThreadId::from_string(&thread.id) - && !overview.threads.get(&id).is_some_and(Option::is_some) + let Ok(id) = ThreadId::from_string(&thread.id) else { + continue; + }; + search.retained.remove(&id); + if !overview.threads.get(&id).is_some_and(Option::is_some) && !overview.removed_threads.contains(&id) && !overview.hidden_threads.contains(&id) && let std::collections::hash_map::Entry::Vacant(entry) = diff --git a/codex-rs/tui/src/app/agents_overview_discovery_tests.rs b/codex-rs/tui/src/app/agents_overview_discovery_tests.rs index 55d5a39647..8d9d5ecbc2 100644 --- a/codex-rs/tui/src/app/agents_overview_discovery_tests.rs +++ b/codex-rs/tui/src/app/agents_overview_discovery_tests.rs @@ -731,6 +731,7 @@ async fn check_discovery(mixed_sources: bool) -> Result<()> { thread.name = None; thread.history_mode = ThreadHistoryMode::Paginated; } + thread.created_at -= 24 - index; thread.updated_at += 24 - index; thread.recency_at = Some(thread.updated_at); thread @@ -769,6 +770,7 @@ async fn check_discovery(mixed_sources: bool) -> Result<()> { let (stream, _) = listener.accept().await?; let mut socket = tokio_tungstenite::accept_async(stream).await?; let mut cursors = Vec::new(); + let mut created_first_pages = 0; while let Some(Ok(Message::Text(text))) = socket.next().await { let JSONRPCMessage::Request(request) = serde_json::from_str(&text)? else { continue; @@ -806,8 +808,15 @@ async fn check_discovery(mixed_sources: bool) -> Result<()> { .await?; continue; } - assert_eq!(params["sortKey"], "recency_at"); let limit = params["limit"].as_u64().unwrap() as usize; + if limit == 100 { + assert!(matches!( + params["sortKey"].as_str(), + Some("updated_at" | "created_at") + )); + } else { + assert_eq!(params["sortKey"], "recency_at"); + } assert!(params["searchTerm"].is_null()); { let interactive = params["sourceKinds"] == json!([]); @@ -815,6 +824,12 @@ async fn check_discovery(mixed_sources: bool) -> Result<()> { .iter() .filter(|row| matches!(row.source, SessionSource::Exec) != interactive) .collect(); + if params["sortKey"] == "created_at" { + if interactive && params["cursor"].is_null() { + created_first_pages += 1; + } + source_rows.sort_by_key(|row| std::cmp::Reverse(row.created_at)); + } if interactive && server_show_reopened_pin.load(Ordering::SeqCst) { source_rows.insert(0, &reopened_pin); } @@ -858,6 +873,8 @@ async fn check_discovery(mixed_sources: bool) -> Result<()> { )) .await?; } + // One switch to Created, then one search typed in several edits. + assert_eq!(created_first_pages, 2); Ok::<_, color_eyre::Report>(cursors) }); let mut session = AppServerSession::new( @@ -916,6 +933,36 @@ async fn check_discovery(mixed_sources: bool) -> Result<()> { assert!(rendered.contains("1 of 10"), "{rendered}"); // The pinned task has its own group. view.handle_key_event(KeyCode::Esc.into()); + // The newest-created task is outside the first screen in updated order. + // Retain that screen and its selection while fetching the new first page. + view.handle_key_event(KeyCode::Char('/').into()); + view.handle_paste("Task".into()); + finish_history_search(&mut app, &mut tui, &mut session, &mut rx).await?; + view = app.agents_overview_view(browse_rows(), Some(ids[12])); + assert_eq!(view.thread_ids()[view.selected_index().unwrap()], ids[12]); + assert!(!view.thread_ids().contains(&ids[23])); + let old_id = app.agents_overview.search_id; + view.handle_key_event(KeyCode::Tab.into()); + app.apply_agents_overview_search_page( + old_id, + owner, + Vec::new(), + Default::default(), + /*ok*/ false, + ); + assert_eq!(view.thread_ids()[view.selected_index().unwrap()], ids[12]); + finish_history_search(&mut app, &mut tui, &mut session, &mut rx).await?; + view = app.agents_overview_view(browse_rows(), Some(ids[12])); + let order: Vec<_> = view + .visible_indices() + .into_iter() + .map(|index| view.rows[index].thread_id) + .collect(); + assert_eq!(&order[..3], &[ids[1], ids[23], ids[22]]); + assert_eq!(view.thread_ids()[view.selected_index().unwrap()], ids[12]); + view.handle_key_event(KeyCode::Esc.into()); + assert_eq!(app.agents_overview.threads, browse); + if mixed_sources { // Queue Show more behind a metadata refresh before the archive creates a vacancy. app.refresh_agents_overview_threads(&session); @@ -1051,7 +1098,9 @@ async fn check_discovery(mixed_sources: bool) -> Result<()> { // Another CLI inserts a matching session ahead of the exhausted browse cursor. show_reopened_pin.store(true, Ordering::SeqCst); view.handle_key_event(KeyCode::Char('/').into()); - view.handle_paste("DA7ABA5E-0000-4000".into()); + for c in "DA7ABA5E-0000-4000".chars() { + view.handle_key_event(KeyCode::Char(c).into()); + } finish_history_search(&mut app, &mut tui, &mut session, &mut rx).await?; assert_eq!( app.agents_overview diff --git a/codex-rs/tui/src/app/agents_overview_grouping.rs b/codex-rs/tui/src/app/agents_overview_grouping.rs index 5d093f402d..9f2b59c664 100644 --- a/codex-rs/tui/src/app/agents_overview_grouping.rs +++ b/codex-rs/tui/src/app/agents_overview_grouping.rs @@ -73,31 +73,32 @@ impl AgentsOverviewView { if let Some(ranks) = &self.pinned_thread_ranks { pinned.sort_by_key(|index| ranks.get(&self.rows[*index].thread_id).copied()); } + let date_key = |index: usize| { + let thread = &self.rows[index].thread; + std::cmp::Reverse(if state.searching { + state.search_sort.timestamp(thread) + } else { + thread.updated_at + }) + }; match state.grouping { - AgentsOverviewGrouping::Project => visible.sort_by_key(|index| { - ( - &self.project_groups[*index].key, - std::cmp::Reverse(self.rows[*index].thread.updated_at), - ) - }), - AgentsOverviewGrouping::Directory => visible.sort_by_key(|index| { - ( - &self.directory_group_keys[*index], - std::cmp::Reverse(self.rows[*index].thread.updated_at), - ) - }), + AgentsOverviewGrouping::Project => { + visible.sort_by_key(|index| (&self.project_groups[*index].key, date_key(*index))) + } + AgentsOverviewGrouping::Directory => { + visible.sort_by_key(|index| (&self.directory_group_keys[*index], date_key(*index))) + } AgentsOverviewGrouping::Status => { + if state.searching { + visible.sort_by_key(|index| date_key(*index)); + } pinned.extend(visible); // Stable grouping preserves pin order, then the supplied newest-first order. pinned.sort_by_key(|index| self.rows[*index].group); return pinned; } - AgentsOverviewGrouping::Model => visible.sort_by_key(|index| { - ( - model_name(&self.rows[*index].thread), - std::cmp::Reverse(self.rows[*index].thread.updated_at), - ) - }), + AgentsOverviewGrouping::Model => visible + .sort_by_key(|index| (model_name(&self.rows[*index].thread), date_key(*index))), } pinned.extend(visible); pinned diff --git a/codex-rs/tui/src/app/agents_overview_view.rs b/codex-rs/tui/src/app/agents_overview_view.rs index 1854571d43..78506e01f0 100644 --- a/codex-rs/tui/src/app/agents_overview_view.rs +++ b/codex-rs/tui/src/app/agents_overview_view.rs @@ -14,6 +14,7 @@ use grouping::model_name; use super::agents_overview::AGENTS_OVERVIEW_VIEW_ID; use super::agents_overview_details::AgentsOverviewDetails; use super::agents_overview_discovery::HistorySearch; +use super::agents_overview_discovery::HistorySort; use super::agents_overview_discovery::supports_shared_pinning; use crate::app_event::AgentsOverviewAction; use crate::app_event::AppEvent; @@ -196,6 +197,7 @@ pub(super) struct AgentsOverviewViewState { pub(super) removal: Option, pub(super) server_version_notice: Option, pub(super) search: String, + pub(super) search_sort: HistorySort, pub(super) history: Option, browse_selection: Option, searching: bool, @@ -222,12 +224,15 @@ impl AgentsOverviewViewState { } pub(super) fn restart_history_search(&mut self) { - self.history = - (!self.search.is_empty() && self.connection_notice.is_none()).then(|| HistorySearch { - id: uuid::Uuid::new_v4(), + self.history = (!self.search.is_empty() && self.connection_notice.is_none()).then(|| { + let id = uuid::Uuid::new_v4(); + HistorySearch { + id, + scan_id: id, target: self.history.as_ref().map_or(10, |search| search.target), ..Default::default() - }); + } + }); } fn includes_row(&self, row: &AgentsOverviewRow) -> bool { @@ -449,12 +454,16 @@ impl AgentsOverviewView { if self.state().history.is_none() { return; } - let visible = self.visible_indices().len(); + let indices = self.visible_indices(); let mut state = self.state(); if state.more_available() && let Some(search) = &mut state.history && !search.loading { + let visible = indices + .iter() + .filter(|&&i| !search.retained.contains(&self.rows[i].thread_id)) + .count(); if additional > 0 { search.target = visible + additional; search.failed = false; @@ -464,7 +473,7 @@ impl AgentsOverviewView { } search.loading = true; self.app_event_tx.send(AppEvent::SearchAgentsOverview( - search.id, + search.scan_id, search.target - visible, )); } diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__agents_overview__tests__command_center__live_center_search_active.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__agents_overview__tests__command_center__live_center_search_active.snap index e9cad8fefc..d8e0eef598 100644 --- a/codex-rs/tui/src/app/snapshots/codex_tui__app__agents_overview__tests__command_center__live_center_search_active.snap +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__agents_overview__tests__command_center__live_center_search_active.snap @@ -17,4 +17,4 @@ expression: "screen(&view, area.width, area.height)" - esc back enter open + Tab sort (Updated) esc back enter open