Show recent sessions in the agent command center (#42104)

## Why

The agent command center only listed sessions currently loaded by the app server, so completed or otherwise unloaded tasks could not be revisited from the overview.

## What changed

- Seed the overview with up to 20 recent root sessions in addition to loaded sessions, retain discovered sessions for the lifetime of the TUI, and update rows from thread lifecycle notifications.
- Allow unloaded sessions to be resumed from the overview using the normal working-directory selection and configuration rebuild flow. Explicit runtime permission choices carry across a cold resume, while settings inherited from the previously selected task do not.
- Fall back from `recency_at` to `updated_at` when connected to an older server, and continue showing loaded sessions when recent-history listing is unavailable.

## Testing

Added coverage for recent-session discovery and retention, notification races, legacy and failed listing fallbacks, cold-resume working-directory and permission handling, reconnect behavior, and unloaded-session rendering and selection.

GitOrigin-RevId: 668068b1594eb24b2ea7faccd0327804b8cd22ef
This commit is contained in:
Eric Traut authored and copyberry committed 2026-09-01 17:28:35 +00:00
1 parent 9969043b95
commit f40e08478c
21 files changed
+1352 -316

No files matched your search

@@ -21,7 +21,9 @@ async fn reconnect_restores_history_permissions_and_keeps_old_input_paused() ->
app.config
.permissions
.set_permission_profile(PermissionProfile::read_only())?;
app.runtime_approval_policy_override = Some(AskForApproval::OnRequest);
app.runtime_approval_policy_override = Some(RuntimeApprovalPolicyOverride::Explicit(
AskForApproval::OnRequest,
));
app.runtime_permission_profile_override =
Some(RuntimePermissionProfileOverride::from_config(&app.config));
app.active_thread_id = Some(id);
@@ -5,7 +5,9 @@ use super::disconnect::serve_reconnect_requests;
use super::*;
use crate::app::reconnect::ReconnectPresentation;
use crate::app::reconnect::reconnect;
use crate::app_event::AgentsOverviewThreadRefresh;
use crate::app_server_session::ThreadParamsMode;
use codex_app_server_client::AppServerEvent;
use pretty_assertions::assert_eq;
use serde_json::json;
@@ -18,10 +20,11 @@ async fn reconnect_daemon_command_center_after_socket_replacement_without_a_conv
use tokio::net::UnixListener;
// Losing an optional, previously opened thread must not strand the command center either.
for (previous_thread, changed_child_permissions) in [
(None, false),
(Some(ThreadId::new()), false),
(Some(ThreadId::new()), true),
for (previous_thread, changed_child_permissions, overview_initialized) in [
(None, false, false),
(None, false, true),
(Some(ThreadId::new()), false, true),
(Some(ThreadId::new()), true, true),
] {
let (mut app, mut events, _) = make_test_app_with_channels().await;
app.keymap.app.open_agents = vec![crate::key_hint::alt(KeyCode::Char('a'))];
@@ -37,7 +40,9 @@ async fn reconnect_daemon_command_center_after_socket_replacement_without_a_conv
app.config
.permissions
.set_permission_profile(PermissionProfile::read_only())?;
app.runtime_approval_policy_override = Some(AskForApproval::OnRequest);
app.runtime_approval_policy_override = Some(RuntimeApprovalPolicyOverride::Explicit(
AskForApproval::OnRequest,
));
app.runtime_permission_profile_override =
Some(RuntimePermissionProfileOverride::from_config(&app.config));
let mut session = test_thread_session(id, app.config.cwd.to_path_buf());
@@ -118,7 +123,12 @@ async fn reconnect_daemon_command_center_after_socket_replacement_without_a_conv
},
)?,
];
app.agents_overview.threads = stale.clone();
let stale_threads = stale
.iter()
.map(|thread| Ok((ThreadId::from_string(&thread.id)?, Some(thread.clone()))))
.collect::<Result<HashMap<_, _>>>()?;
app.agents_overview.threads = stale_threads.clone();
app.agents_overview.initialized = overview_initialized;
let view = app.agents_overview_view(
stale.clone(),
Some(if previous_thread.is_some() {
@@ -135,7 +145,7 @@ async fn reconnect_daemon_command_center_after_socket_replacement_without_a_conv
app.agents_overview.request_id = Some(stale_request);
app.agents_overview.refresh_pending = true;
let refresh = tokio::spawn(std::future::pending::<()>());
app.agents_overview.view_state.lock().unwrap().refresh_task = Some(refresh.abort_handle());
app.agents_overview.refresh_task = Some(refresh.abort_handle());
let directory = tempfile::tempdir()?;
let socket_path = directory.path().join("daemon.sock");
let listener = UnixListener::bind(&socket_path)?;
@@ -187,6 +197,7 @@ async fn reconnect_daemon_command_center_after_socket_replacement_without_a_conv
Some(json!({"result": {"turn": {"id": "fresh", "items": [], "status": "inProgress"}}}))
}
"thread/loaded/list" => Some(json!({"result": {"data": [selected, added], "nextCursor": null}})),
"thread/list" => Some(json!({"result": {"data": [], "nextCursor": null}})),
"thread/turns/list" => Some(json!({"result": {"data": [], "nextCursor": null}})),
"thread/goal/get" => Some(json!({"result": {"goal": null}})),
"thread/read" if request.params.as_ref().unwrap()["threadId"] == child.to_string() => Some(json!({"result": {"thread": child_thread}})),
@@ -196,6 +207,7 @@ async fn reconnect_daemon_command_center_after_socket_replacement_without_a_conv
thread.turns = vec![test_turn("saved", status, Vec::new())];
json!({"result": {"thread": thread}})
} else if server_available.load(std::sync::atomic::Ordering::SeqCst) { json!({"result": {"thread": restored_previous}}) } else { json!({"error": {"code": -32600, "message": "thread no longer exists"}}) }),
"thread/read" if request.params.as_ref().unwrap()["threadId"] == vanished.to_string() => Some(json!({"error": {"code": -32600, "message": "thread no longer exists"}})),
"thread/read" => Some(json!({"result": {"thread": fresh.iter().find(|thread| request.params.as_ref().unwrap()["threadId"] == thread.id).unwrap()}})),
method => panic!("unexpected daemon reconnect request: {method}"),
}
@@ -232,7 +244,14 @@ async fn reconnect_daemon_command_center_after_socket_replacement_without_a_conv
),
(None, false)
);
app.apply_agents_overview_thread_refresh(&session, stale_request, Ok(Vec::new()));
app.apply_agents_overview_thread_refresh(
&session,
stale_request,
Ok(AgentsOverviewThreadRefresh {
threads: HashMap::new(),
recent_seed_complete: false,
}),
);
assert_eq!(app.agents_overview.visible_thread_ids.len(), 2);
let mut tui = crate::tui::test_support::make_test_tui()?;
app.handle_tui_event(
@@ -293,6 +312,18 @@ async fn reconnect_daemon_command_center_after_socket_replacement_without_a_conv
Ok::<_, color_eyre::Report>(())
})
.await??;
assert!(app.agents_overview.visible_thread_ids.contains(&vanished));
// Missing metadata alone does not evict a retained row; an archive notification does.
app.handle_app_server_event(
&session,
AppServerEvent::ServerNotification(Box::new(ServerNotification::ThreadArchived(
ThreadArchivedNotification {
thread_id: vanished.to_string(),
},
))),
)
.await;
let index = app
.chat_widget
.selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID)
@@ -336,7 +367,14 @@ async fn reconnect_daemon_command_center_after_socket_replacement_without_a_conv
.connection_notice
.is_none()
);
app.apply_agents_overview_thread_refresh(&session, stale_request, Ok(stale));
app.apply_agents_overview_thread_refresh(
&session,
stale_request,
Ok(AgentsOverviewThreadRefresh {
threads: stale_threads,
recent_seed_complete: true,
}),
);
assert!(!app.agents_overview.visible_thread_ids.contains(&vanished));
if let Some(id) = previous_thread {
@@ -407,7 +445,9 @@ async fn reconnect_daemon_command_center_after_socket_replacement_without_a_conv
&PermissionProfile::Disabled
);
if changed_child_permissions {
app.runtime_approval_policy_override = Some(AskForApproval::Never);
app.runtime_approval_policy_override = Some(
RuntimeApprovalPolicyOverride::Explicit(AskForApproval::Never),
);
app.runtime_permission_profile_override = Some(
RuntimePermissionProfileOverride::from_config(app.chat_widget.config_ref()),
);
@@ -4,6 +4,7 @@ use app_test_support::create_fake_paginated_rollout;
use app_test_support::create_fake_parented_rollout_with_source;
use app_test_support::create_fake_rollout;
use app_test_support::rollout_path;
use codex_app_server_client::AppServerEvent;
use codex_app_server_protocol::ClientNotification;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::JSONRPCError;
@@ -47,6 +48,7 @@ enum HistoryCapabilities {
LegacyOnlyUnsupportedVariant,
LegacyDynamicToolsAndHistory,
ForkHydrationFails,
ThreadListFails,
}
/// Returns and resets `(thread/loaded/list, thread/read)` request counts.
@@ -127,6 +129,7 @@ async fn start_recording_app_server_with_history(
let mut websocket = accept_async(stream).await?;
let mut inventories = usize::from(failed_thread_name == Some("background"));
let mut reject_detach = false;
let mut reject_thread_list = history_capabilities == HistoryCapabilities::ThreadListFails;
while let Some(frame) = websocket.next().await {
let Message::Text(text) = frame? else {
continue;
@@ -182,7 +185,30 @@ async fn start_recording_app_server_with_history(
.is_some_and(|tools| {
tools.iter().any(|tool| tool["type"] == "namespace")
});
let response = if reject_dynamic_tools {
let response = if request.method == "thread/list"
&& std::mem::take(&mut reject_thread_list)
{
JSONRPCMessage::Error(JSONRPCError {
id: request_id,
error: JSONRPCErrorError {
code: -32603,
data: None,
message: "thread listing unavailable".to_string(),
},
})
} else if history_capabilities == HistoryCapabilities::LegacyOnly
&& request.method == "thread/list"
&& params.is_some_and(|params| params["sortKey"] == "recency_at")
{
JSONRPCMessage::Error(JSONRPCError {
id: request_id,
error: JSONRPCErrorError {
code: -32602,
data: None,
message: "unknown variant `recency_at`".to_string(),
},
})
} else if reject_dynamic_tools {
JSONRPCMessage::Error(JSONRPCError {
id: request_id,
error: JSONRPCErrorError {
@@ -2367,6 +2393,88 @@ async fn agents_overview_stop_uses_history_mode_for_turn_lookup() -> Result<()>
Ok(())
}
#[tokio::test]
async fn agents_overview_seeds_loaded_threads_when_recent_listing_is_unavailable() -> Result<()> {
for (capabilities, expected_sort_keys) in [
(
HistoryCapabilities::LegacyOnly,
vec!["recency_at", "recency_at", "updated_at", "updated_at"],
),
(
HistoryCapabilities::ThreadListFails,
vec!["recency_at", "recency_at", "recency_at", "recency_at"],
),
] {
let (mut app, _codex_home) = make_history_test_app().await?;
let (mut app_server, requests, proxy) = start_recording_app_server_with_history(
&app.config,
capabilities,
/*blocked_thread_list*/ None,
/*failed_thread_name*/ None,
crate::app_server_session::ThreadParamsMode::Embedded,
)
.await?;
let started = app_server.start_thread(&app.config).await?;
app.app_server_target = AppServerTarget::LocalDaemon {
endpoint: crate::RemoteAppServerEndpoint::UnixSocket {
socket_path: test_path_buf("/tmp/unused.sock").abs(),
},
};
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
app.app_event_tx = AppEventSender::new(tx);
for attempt in 0..2 {
if attempt == 0 {
app.refresh_agents_overview_threads(&app_server);
} else {
app.open_agents_overview(&app_server);
}
let Some(AppEvent::AgentsOverviewThreadsLoaded { request_id, result }) =
tokio::time::timeout(Duration::from_secs(10), rx.recv()).await?
else {
panic!("expected overview result")
};
app.apply_agents_overview_thread_refresh(&app_server, request_id, result);
assert_eq!(
app.agents_overview
.threads
.keys()
.copied()
.collect::<Vec<_>>(),
vec![started.session.thread_id]
);
assert_eq!(
app.agents_overview.initialized,
capabilities != HistoryCapabilities::ThreadListFails || attempt > 0
);
if attempt == 0 {
app.handle_app_server_event(
&app_server,
AppServerEvent::ServerNotification(Box::new(
ServerNotification::ThreadStatusChanged(
codex_app_server_protocol::ThreadStatusChangedNotification {
thread_id: started.session.thread_id.to_string(),
status: codex_app_server_protocol::ThreadStatus::Idle,
},
),
)),
)
.await;
assert!(app.agents_overview.request_id.is_none());
}
}
let list_requests = recorded_params(&requests, "thread/list");
let mut sort_keys = list_requests
.iter()
.map(|params| params["sortKey"].as_str().unwrap())
.collect::<Vec<_>>();
sort_keys.sort_unstable();
assert_eq!(sort_keys, expected_sort_keys);
app_server.shutdown().await?;
proxy.await??;
}
Ok(())
}
#[tokio::test]
async fn agents_overview_stop_uses_full_history_after_legacy_negotiation() -> Result<()> {
let (mut app, _codex_home) = make_history_test_app().await?;
@@ -2698,8 +2806,9 @@ async fn changing_directory_preserves_project_trust_permissions_history_and_hook
matches!(kind, "approval" | "profile" | "reviewer").then_some(requirements.clone());
app.harness_overrides.permission_profile =
(kind != "named").then_some(PermissionProfile::workspace_write());
app.runtime_approval_policy_override =
(kind == "approval").then_some(AskForApproval::OnRequest);
app.runtime_approval_policy_override = (kind == "approval").then_some(
RuntimeApprovalPolicyOverride::Explicit(AskForApproval::OnRequest),
);
let mut profile = RuntimePermissionProfileOverride::from_config(&app.config);
profile.active_permission_profile =
(kind == "named").then(|| ActivePermissionProfile::new("dev"));
@@ -6,6 +6,7 @@ Cached previous conversation
• This conversation is unavailable. Its cached transcript and draft remain here; input is paused. Open the agent picker or return to the parent to continue.
• Reconnected. No input was resent. Review uncertain submissions before retrying; recovered queues remain paused.
• The rename target disappeared. Unsubmitted title: Keep this task draft!
› latest draft
gpt-test default · /tmp/project