Prefer the most recent session when queueing by name (#39385)

## What changed

- Resolve duplicate exact-name matches to the most recent session instead of rejecting the queue request as ambiguous.
- Include non-interactive and custom-source sessions in name-based queue lookups.
- Prefer state database matches before falling back to rollout scanning.

## Testing

- Cover queueing to non-interactive and custom-source sessions, including duplicate names and a state database match that avoids importing a legacy rollout.

GitOrigin-RevId: 5b019da0a950c9381d324a09a21c78a9d0ac2252
This commit is contained in:
Eric Traut authored and copyberry committed 2026-08-19 02:45:45 +00:00
1 parent 8843960ba0
commit 14a8ac89af
3 files changed
+62 -38

No files matched your search

+24 -20
View File
@@ -59,7 +59,7 @@ pub struct SessionArchiveCommandOptions {
#[derive(Clone, Copy, PartialEq, Eq)] #[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum SessionNameMatch { pub(super) enum SessionNameMatch {
First, First,
Unique, FirstIncludingNonInteractive,
} }
fn success_message( fn success_message(
@@ -201,7 +201,7 @@ pub(super) async fn lookup_session_by_exact_name(
SessionNameLookupMode::ScanAndRepair, SessionNameLookupMode::ScanAndRepair,
][..] ][..]
}; };
let source_kind_filters = if match_policy == SessionNameMatch::Unique { let source_kind_filters = if match_policy == SessionNameMatch::FirstIncludingNonInteractive {
// An empty filter includes Atlas/ChatGPT sessions; explicit kinds additionally include exec. // An empty filter includes Atlas/ChatGPT sessions; explicit kinds additionally include exec.
vec![ vec![
super::resume_source_kinds(/*include_non_interactive*/ true), super::resume_source_kinds(/*include_non_interactive*/ true),
@@ -212,11 +212,13 @@ pub(super) async fn lookup_session_by_exact_name(
/*include_non_interactive*/ false, /*include_non_interactive*/ false,
)] )]
}; };
let mut unique_match: Option<AppServerThread> = None; for &lookup_mode in lookup_modes {
for source_kinds in source_kind_filters { let sort_by_recency = lookup_mode == SessionNameLookupMode::StateDbOnly
for &lookup_mode in lookup_modes { && app_server.uses_embedded_app_server();
// Search is the fast path, but legacy stores attach renamed titles after filtering. // Search is the fast path, but legacy stores attach renamed titles after filtering.
for search_term in [Some(name), None] { for search_term in [Some(name), None] {
let mut first_match: Option<AppServerThread> = None;
for source_kinds in &source_kind_filters {
let mut candidates = NamedSessionCandidates::new( let mut candidates = NamedSessionCandidates::new(
name, name,
codex_home, codex_home,
@@ -234,7 +236,7 @@ pub(super) async fn lookup_session_by_exact_name(
.await .await
.wrap_err("failed to list sessions while resolving session name")? .wrap_err("failed to list sessions while resolving session name")?
{ {
let thread = if match_policy == SessionNameMatch::Unique let thread = if match_policy == SessionNameMatch::FirstIncludingNonInteractive
&& lookup_mode == SessionNameLookupMode::ScanAndRepair && lookup_mode == SessionNameLookupMode::ScanAndRepair
&& !app_server.uses_remote_workspace() && !app_server.uses_remote_workspace()
{ {
@@ -251,23 +253,25 @@ pub(super) async fn lookup_session_by_exact_name(
} else { } else {
candidate.thread candidate.thread
}; };
if match_policy == SessionNameMatch::First { if first_match.as_ref().is_none_or(|existing| {
return Ok(Some(thread)); if sort_by_recency {
thread.recency_at.unwrap_or(thread.updated_at)
> existing.recency_at.unwrap_or(existing.updated_at)
} else {
thread.updated_at > existing.updated_at
}
}) {
first_match = Some(thread);
} }
if unique_match break;
.as_ref()
.is_some_and(|existing| existing.id != thread.id)
{
return Err(eyre!(
"More than one active session is named '{name}'; use a session UUID instead."
));
}
unique_match = Some(thread);
} }
} }
if first_match.is_some() {
return Ok(first_match);
}
} }
} }
Ok(unique_match) Ok(None)
} }
fn session_target_from_app_server_thread(thread: AppServerThread) -> Result<ResolvedSessionTarget> { fn session_target_from_app_server_thread(thread: AppServerThread) -> Result<ResolvedSessionTarget> {
@@ -393,7 +393,7 @@ async fn trusts_sqlite_name_over_legacy_index_for_delete() -> color_eyre::Result
} }
#[tokio::test] #[tokio::test]
async fn queues_non_interactive_and_custom_sessions_and_rejects_ambiguous_name() async fn queues_non_interactive_and_custom_sessions_without_scanning_rollouts()
-> color_eyre::Result<()> { -> color_eyre::Result<()> {
let temp_dir = TempDir::new()?; let temp_dir = TempDir::new()?;
let config = build_config(&temp_dir).await?; let config = build_config(&temp_dir).await?;
@@ -460,20 +460,12 @@ async fn queues_non_interactive_and_custom_sessions_and_rejects_ambiguous_name()
/*archived*/ false, /*archived*/ false,
); );
custom_metadata.source = serde_json::to_string(&custom_source)?; custom_metadata.source = serde_json::to_string(&custom_source)?;
custom_metadata.recency_at += chrono::Duration::hours(/*hours*/ 1);
custom_metadata.updated_at += chrono::Duration::hours(/*hours*/ 1);
runtime runtime
.upsert_thread(&custom_metadata) .upsert_thread(&custom_metadata)
.await .await
.map_err(std::io::Error::other)?; .map_err(std::io::Error::other)?;
let (resolved_custom_thread_id, _) = run_session_queue_action_with_app_server(
&mut app_server,
config.codex_home.as_path(),
"atlas-session",
"do the thing",
"custom-client-message-id",
)
.await?;
assert_eq!(resolved_custom_thread_id, custom_thread_id);
let legacy_thread_id = ThreadId::new(); let legacy_thread_id = ThreadId::new();
write_rollout( write_rollout(
&config, &config,
@@ -489,20 +481,48 @@ async fn queues_non_interactive_and_custom_sessions_and_rejects_ambiguous_name()
"saved-session", "saved-session",
) )
.await?; .await?;
let error = run_session_queue_action_with_app_server( let (resolved_custom_thread_id, _) = run_session_queue_action_with_app_server(
&mut app_server,
config.codex_home.as_path(),
"atlas-session",
"do the thing",
"custom-client-message-id",
)
.await?;
assert_eq!(
(
resolved_custom_thread_id,
runtime
.get_thread(legacy_thread_id)
.await
.map_err(std::io::Error::other)?,
),
(custom_thread_id, None),
);
runtime
.update_thread_title(custom_thread_id, "saved-session")
.await
.map_err(std::io::Error::other)?;
let (resolved_duplicate_id, _) = run_session_queue_action_with_app_server(
&mut app_server, &mut app_server,
config.codex_home.as_path(), config.codex_home.as_path(),
"saved-session", "saved-session",
"do the thing", "do the thing",
"stable-client-message-id", "duplicate-client-message-id",
) )
.await .await?;
.expect_err("ambiguous session names should be rejected");
app_server.shutdown().await?; app_server.shutdown().await?;
assert_eq!( assert_eq!(
error.to_string(), (
"More than one active session is named 'saved-session'; use a session UUID instead." resolved_duplicate_id,
runtime
.get_thread(legacy_thread_id)
.await
.map_err(std::io::Error::other)?,
),
(custom_thread_id, None),
); );
Ok(()) Ok(())
} }
+1 -1
View File
@@ -92,7 +92,7 @@ pub(super) async fn run_session_queue_action_with_app_server(
codex_home, codex_home,
target, target,
/*archived*/ false, /*archived*/ false,
SessionNameMatch::Unique, SessionNameMatch::FirstIncludingNonInteractive,
) )
.await? .await?
.ok_or_else(|| eyre!("No active session found matching '{target}'."))?; .ok_or_else(|| eyre!("No active session found matching '{target}'."))?;