Lightweight coding agent that runs in your terminal
Rust
Keep archived threads with empty previews visible in listings (#48199)
acrognale-oai7596ab19a661
diff --git a/codex-rs/app-server/tests/suite/v2/thread_list.rs b/codex-rs/app-server/tests/suite/v2/thread_list.rsindex 036dd056a8..6a9696bb86 100644--- a/codex-rs/app-server/tests/suite/v2/thread_list.rs+++ b/codex-rs/app-server/tests/suite/v2/thread_list.rs@@ -2610,6 +2610,68 @@ async fn thread_list_archived_filter() -> Result<()> {Ok(())}+#[tokio::test]+async fn thread_list_keeps_archived_threads_without_previews() -> Result<()> {+ let codex_home = TempDir::new()?;+ create_minimal_config(codex_home.path())?;+ let mut archived_ids = Vec::new();+ for (timestamp, metadata_timestamp) in [+ ("2025-03-01T09-00-00", "2025-03-01T09:00:00Z"),+ ("2025-03-01T10-00-00", "2025-03-01T10:00:00Z"),+ ] {+ archived_ids.push(create_fake_rollout(+ codex_home.path(),+ timestamp,+ metadata_timestamp,+ "",+ Some("mock_provider"),+ /*git_info*/ None,+ )?);+ }+ let mut mcp = init_mcp(codex_home.path()).await?;+ for thread_id in &archived_ids {+ let _: codex_app_server_protocol::ThreadArchiveResponse = mcp+ .request(|request_id| ClientRequest::ThreadArchive {+ request_id,+ params: codex_app_server_protocol::ThreadArchiveParams {+ thread_id: thread_id.clone(),+ },+ })+ .await?;+ }+ archived_ids.reverse();+ for use_state_db_only in [true, false] {+ let mut cursor = None;+ let mut found_ids = Vec::new();+ loop {+ let page: ThreadListResponse = mcp+ .request(|request_id| ClientRequest::ThreadList {+ request_id,+ params: serde_json::from_value(json!({+ "archived": true,+ "modelProviders": [],+ "limit": 1,+ "cursor": cursor,+ "useStateDbOnly": use_state_db_only,+ }))+ .expect("valid list params"),+ })+ .await?;+ for thread in page.data {+ assert_eq!(thread.preview, "");+ found_ids.push(thread.id);+ }+ cursor = page.next_cursor;+ if cursor.is_none() {+ break;+ }+ assert!(found_ids.len() <= archived_ids.len());+ }+ assert_eq!(found_ids, archived_ids);+ }+ Ok(())+}+#[tokio::test]async fn thread_list_rejects_originator_filter_but_accepts_empty_allowlist() -> Result<()> {let codex_home = TempDir::new()?;diff --git a/codex-rs/rollout/src/list.rs b/codex-rs/rollout/src/list.rsindex 219b243153..13c94617a1 100644--- a/codex-rs/rollout/src/list.rs+++ b/codex-rs/rollout/src/list.rs@@ -280,6 +280,7 @@ impl<'a> RolloutFileVisitor for FilesByCreatedAtVisitor<'a> {self.provider_matcher,self.cwd_filters,updated_at,+ PreviewFilter::RequirePreview,).await{@@ -597,6 +598,7 @@ async fn traverse_directories_for_paths_updated(provider_matcher,cwd_filters,updated_at_fallback,+ PreviewFilter::RequirePreview,).await{@@ -654,6 +656,7 @@ async fn traverse_flat_paths_created(provider_matcher,cwd_filters,updated_at,+ PreviewFilter::IncludeEmpty,).await{@@ -715,6 +718,7 @@ async fn traverse_flat_paths_updated(provider_matcher,cwd_filters,updated_at_fallback,+ PreviewFilter::IncludeEmpty,).await{@@ -784,12 +788,18 @@ fn build_next_cursor(items: &[ThreadItem], sort_key: ThreadSortKey) -> Option<Cu}}+enum PreviewFilter {+ RequirePreview,+ IncludeEmpty,+}+async fn build_thread_item(path: PathBuf,allowed_sources: &[SessionSource],provider_matcher: Option<&ProviderMatcher<'_>>,cwd_filters: Option<&[PathBuf]>,updated_at: Option<String>,+ preview_filter: PreviewFilter,) -> Option<ThreadItem> {// Read head and detect preview-bearing events; goal previews can appear before// the first normal user message.@@ -818,8 +828,9 @@ async fn build_thread_item({return None;}- // Apply filters: must have session meta and a discoverable preview.- if summary.saw_session_meta && summary.preview.is_some() {+ if summary.saw_session_meta+ && (matches!(preview_filter, PreviewFilter::IncludeEmpty) || summary.preview.is_some())+ {let HeadTailSummary {originator,thread_id,@@ -885,6 +896,7 @@ pub async fn read_thread_item_from_rollout(path: PathBuf) -> Option<ThreadItem>/*provider_matcher*/ None,/*cwd_filters*/ None,/*updated_at*/ None,+ PreviewFilter::RequirePreview,).await}diff --git a/codex-rs/rollout/src/recorder_tests.rs b/codex-rs/rollout/src/recorder_tests.rsindex c36321a988..af55bf6ddf 100644--- a/codex-rs/rollout/src/recorder_tests.rs+++ b/codex-rs/rollout/src/recorder_tests.rs@@ -1236,6 +1236,52 @@ async fn list_threads_db_disabled_does_not_skip_paginated_items() -> std::io::ReOk(())}+#[tokio::test]+async fn list_archived_threads_without_db_keeps_threads_without_previews() -> std::io::Result<()> {+ let home = TempDir::new().expect("temp dir");+ let config = test_config(home.path());+ let archive_dir = home.path().join(crate::ARCHIVED_SESSIONS_SUBDIR);+ fs::create_dir_all(&archive_dir)?;+ let older = ThreadId::new();+ let newer = ThreadId::new();+ for (timestamp, thread_id) in [+ ("2026-07-09T00-00-00", older),+ ("2026-07-09T00-01-00", newer),+ ] {+ let path = archive_dir.join(format!("rollout-{timestamp}-{thread_id}.jsonl"));+ write_paginated_rollout(&path, thread_id, &[])?;+ }++ let mut cursor = None;+ let mut found = Vec::new();+ for expected_more in [true, false] {+ let page = RolloutRecorder::list_archived_threads(+ /*state_db_ctx*/ None,+ &config,+ /*page_size*/ 1,+ cursor.as_ref(),+ ThreadSortKey::CreatedAt,+ SortDirection::Desc,+ &[],+ /*model_providers*/ None,+ /*cwd_filters*/ None,+ config.model_provider_id.as_str(),+ /*search_term*/ None,+ )+ .await?;+ assert_eq!(page.items.len(), 1);+ found.extend(+ page.items+ .into_iter()+ .map(|item| (item.thread_id, item.preview)),+ );+ cursor = page.next_cursor;+ assert_eq!(cursor.is_some(), expected_more);+ }+ assert_eq!(found, vec![(Some(newer), None), (Some(older), None)]);+ Ok(())+}+#[tokio::test]async fn list_threads_db_enabled_preserves_metadata_for_missing_rollout_paths()-> std::io::Result<()> {diff --git a/codex-rs/state/migrations/0058_threads_archive_sort_indexes.sql b/codex-rs/state/migrations/0058_threads_archive_sort_indexes.sqlnew file mode 100644index 0000000000..2d04515064--- /dev/null+++ b/codex-rs/state/migrations/0058_threads_archive_sort_indexes.sql@@ -0,0 +1,12 @@+-- Archived listings include empty previews and cannot use the visible-only indexes.+CREATE INDEX idx_threads_archive_created_at_ms+ ON threads(archived, created_at_ms DESC, id DESC)+ WHERE archived = 1;++CREATE INDEX idx_threads_archive_updated_at_ms+ ON threads(archived, updated_at_ms DESC, id DESC)+ WHERE archived = 1;++CREATE INDEX idx_threads_archive_recency_at_ms+ ON threads(archived, recency_at_ms DESC, id DESC)+ WHERE archived = 1;diff --git a/codex-rs/state/src/runtime/threads.rs b/codex-rs/state/src/runtime/threads.rsindex 18225f020c..fe64fb6050 100644--- a/codex-rs/state/src/runtime/threads.rs+++ b/codex-rs/state/src/runtime/threads.rs@@ -1433,7 +1433,7 @@ fn push_thread_filters_with_preview<'a>(} else {builder.push(" AND threads.archived = 0");}- if !include_empty_preview && !matches!(section, Some(Some(_))) {+ if !archived_only && !include_empty_preview && !matches!(section, Some(Some(_))) {builder.push(" AND threads.preview <> ''");}match section {@@ -1693,6 +1693,62 @@ mod tests {);}+ #[tokio::test]+ async fn archived_threads_without_previews_remain_listed() {+ let codex_home = unique_temp_dir();+ let runtime = StateRuntime::init(+ crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),+ "test-provider".to_string(),+ )+ .await+ .unwrap();+ let thread_id = ThreadId::from_string("00000000-0000-0000-0000-000000000045").unwrap();+ let mut metadata = test_thread_metadata(&codex_home, thread_id, codex_home.clone());+ metadata.preview = Some(String::new());+ metadata.first_user_message = None;+ runtime.upsert_thread(&metadata).await.unwrap();+ let filters = |archived_only| ThreadFilterOptions {+ archived_only,+ allowed_sources: &[],+ model_providers: None,+ cwd_filters: None,+ section: None,+ project_id: None,+ anchor: None,+ sort_key: SortKey::CreatedAt,+ sort_direction: SortDirection::Desc,+ search_term: None,+ };+ let active = runtime+ .list_threads(/*page_size*/ 10, filters(/*archived_only*/ false))+ .await+ .unwrap();+ assert!(active.items.is_empty());++ runtime+ .mark_archived(thread_id, &metadata.rollout_path, Utc::now())+ .await+ .unwrap();+ let archived = runtime+ .list_threads(/*page_size*/ 10, filters(/*archived_only*/ true))+ .await+ .unwrap();+ assert_eq!(+ archived+ .items+ .iter()+ .map(|thread| thread.id)+ .collect::<Vec<_>>(),+ vec![thread_id]+ );+ assert_eq!(archived.next_anchor, None);+ let active = runtime+ .list_threads(/*page_size*/ 10, filters(/*archived_only*/ false))+ .await+ .unwrap();+ assert!(active.items.is_empty());+ }+#[tokio::test]async fn list_threads_filters_sections_before_recency_pagination_and_uses_index() {let codex_home = unique_temp_dir();@@ -2377,6 +2433,65 @@ mod tests {}}+ #[tokio::test]+ async fn archived_thread_pages_use_ordered_indexes_without_sorting() {+ let codex_home = unique_temp_dir();+ let runtime = StateRuntime::init(+ crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),+ "test-provider".to_string(),+ )+ .await+ .expect("state db should initialize");+ let anchor = Anchor {+ ts: DateTime::<Utc>::from_timestamp(1_700_000_000, 0).expect("valid timestamp"),+ id: Some(ThreadId::new()),+ };+ for (sort_key, expected_index) in [+ (SortKey::CreatedAt, "idx_threads_archive_created_at_ms"),+ (SortKey::UpdatedAt, "idx_threads_archive_updated_at_ms"),+ (SortKey::RecencyAt, "idx_threads_archive_recency_at_ms"),+ ] {+ for sort_direction in [SortDirection::Asc, SortDirection::Desc] {+ for anchor in [None, Some(&anchor)] {+ let mut builder = QueryBuilder::<Sqlite>::new("EXPLAIN QUERY PLAN ");+ push_list_threads_query(+ &mut builder,+ ThreadFilterOptions {+ archived_only: true,+ allowed_sources: &[],+ model_providers: None,+ cwd_filters: None,+ section: None,+ project_id: None,+ anchor,+ sort_key,+ sort_direction,+ search_term: None,+ },+ /*relation_filter*/ None,+ /*limit*/ 2,+ );+ let details = builder+ .build()+ .fetch_all(runtime.pool.as_ref())+ .await+ .expect("load archive query plan")+ .into_iter()+ .map(|row| row.get::<String, _>("detail"))+ .collect::<Vec<_>>();+ assert!(+ details.iter().any(|detail| detail.contains(expected_index)),+ "archive page did not use {expected_index}: {details:?}"+ );+ assert!(+ !details.iter().any(|detail| detail.contains("TEMP B-TREE")),+ "archive page needed a temporary sort: {details:?}"+ );+ }+ }+ }+ }+#[tokio::test]async fn list_threads_by_relation_filters_spawn_graph_with_keyset_pagination() {let codex_home = unique_temp_dir();diff --git a/codex-rs/thread-store/src/local/mod.rs b/codex-rs/thread-store/src/local/mod.rsindex c30dc74c23..24f1e54990 100644--- a/codex-rs/thread-store/src/local/mod.rs+++ b/codex-rs/thread-store/src/local/mod.rs@@ -34,6 +34,9 @@ mod daybreak_metadata_tests;#[path = "pending_thread_metadata_tests.rs"]mod pending_thread_metadata_tests;#[cfg(test)]+#[path = "read_thread_tests.rs"]+mod read_thread_tests;+#[cfg(test)]mod test_support;use codex_protocol::ThreadId;diff --git a/codex-rs/thread-store/src/local/read_thread_tests.rs b/codex-rs/thread-store/src/local/read_thread_tests.rsnew file mode 100644index 0000000000..065c47d63a--- /dev/null+++ b/codex-rs/thread-store/src/local/read_thread_tests.rs@@ -0,0 +1,89 @@+//! Regression coverage for metadata reads without SQLite.++use std::fs;+use std::fs::FileTimes;++use chrono::DateTime;+use chrono::Utc;+use codex_protocol::ThreadId;+use codex_protocol::protocol::SessionMeta;+use codex_protocol::protocol::SessionMetaLine;+use codex_protocol::protocol::ThreadSource;+use codex_rollout::RolloutItem;+use codex_rollout::RolloutLine;+use pretty_assertions::assert_eq;+use tempfile::TempDir;++use super::LocalThreadStore;+use super::test_support::test_config;+use crate::ReadThreadParams;+use crate::ThreadStore;++#[tokio::test]+async fn empty_archived_reads_without_sqlite_preserve_source_and_file_time()+-> Result<(), Box<dyn std::error::Error>> {+ let home = TempDir::new()?;+ let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);+ let thread_id = ThreadId::new();+ let timestamp = "2026-07-09T00:00:00Z";+ let created_at = DateTime::parse_from_rfc3339(timestamp)?.with_timezone(&Utc);+ let updated_at = DateTime::parse_from_rfc3339("2026-07-10T00:00:00Z")?.with_timezone(&Utc);+ let directory = home.path().join(codex_rollout::ARCHIVED_SESSIONS_SUBDIR);+ fs::create_dir_all(&directory)?;+ let path = directory.join(format!("rollout-2026-07-09T00-00-00-{thread_id}.jsonl"));+ let line = RolloutLine {+ timestamp: timestamp.to_string(),+ ordinal: None,+ item: RolloutItem::SessionMeta(SessionMetaLine {+ meta: SessionMeta {+ id: thread_id,+ session_id: thread_id.into(),+ timestamp: timestamp.to_string(),+ thread_source: Some(ThreadSource::User),+ ..SessionMeta::default()+ },+ git: None,+ }),+ };+ fs::write(&path, format!("{}\n", serde_json::to_string(&line)?))?;+ fs::OpenOptions::new()+ .write(true)+ .open(&path)?+ .set_times(FileTimes::new().set_modified(updated_at.into()))?;++ let by_id = store+ .read_thread(ReadThreadParams {+ thread_id,+ include_archived: true,+ include_history: false,+ })+ .await?;+ let by_path = store+ .read_thread_by_rollout_path(+ path, /*include_archived*/ true, /*include_history*/ false,+ )+ .await?;+ for thread in [by_id, by_path] {+ assert_eq!(+ (+ thread.thread_id,+ thread.thread_source,+ thread.preview,+ thread.created_at,+ thread.updated_at,+ thread.recency_at,+ thread.archived_at+ ),+ (+ thread_id,+ Some(ThreadSource::User),+ String::new(),+ created_at,+ updated_at,+ updated_at,+ Some(updated_at)+ ),+ );+ }+ Ok(())+}