diff --git a/codex-rs/app-server-client/src/cloud.rs b/codex-rs/app-server-client/src/cloud.rs index d846532e76..9e7e2e1c5f 100644 --- a/codex-rs/app-server-client/src/cloud.rs +++ b/codex-rs/app-server-client/src/cloud.rs @@ -122,12 +122,18 @@ pub(super) enum IdleReconnect { CaughtUp(Arc), } +/// The scoped worker retired while a direct history read was outstanding. +#[derive(Debug, thiserror::Error)] +#[error("Prepared Cloud resume ended.")] +pub struct PreparedResumeEnded; + #[derive(Clone)] pub struct CloudRequestHandle { pub(super) reconnect: tokio::sync::watch::Sender, pub(super) attached: Arc, commands: mpsc::Sender, native: Option>, + prepared_turns: Option<(Arc, Arc)>, title_client: Option>, } @@ -216,6 +222,7 @@ impl CloudClient { reconnect: Default::default(), attached: Default::default(), native: native.map(Arc::new), + prepared_turns: None, title_client: title_client.map(Arc::new), }, events: event_receiver, @@ -467,6 +474,10 @@ impl CloudRequestHandle { request_id: RequestId, params: codex_app_server_protocol::ThreadResumeParams, ) -> Result<(codex_app_server_protocol::ThreadResumeResponse, Self), TypedRequestError> { + let prepared_turns = self + .native + .as_ref() + .map(|client| (Arc::from(params.thread_id.as_str()), Arc::clone(client))); let (commands, history) = mpsc::channel(/*capacity*/ 1); let response = self .send(CloudOperation::PrepareThreadResume { @@ -483,6 +494,7 @@ impl CloudRequestHandle { reconnect: self.reconnect.clone(), attached: self.attached.clone(), native: None, + prepared_turns, title_client: None, }, )) @@ -519,6 +531,19 @@ impl CloudRequestHandle { } pub(crate) async fn request(&self, request: ClientRequest) -> io::Result { + // Prepared turn metadata is stateless. Read it alongside the worker's item + // page, which owns partial-history warnings. Retiring the scope cancels the read. + if let (Some((id, client)), ClientRequest::ThreadTurnsList { params, .. }) = + (&self.prepared_turns, &request) + && params.thread_id == id.as_ref() + { + return tokio::select! { + biased; + () = self.commands.closed() => Err(io::Error::other(PreparedResumeEnded)), + page = Box::pin(crate::cloud_backend::list_turns(client, params.clone())) => + Ok(crate::cloud_backend::request_result(page)), + }; + } // Catalog reads must not occupy the serialized send and attachment lane. if let (Some(catalog), ClientRequest::ModelList { params, .. }) = (&self.native, &request) { // Keep the catalog HTTP state out of the shared request future. diff --git a/codex-rs/app-server-client/src/cloud_backend/mod.rs b/codex-rs/app-server-client/src/cloud_backend/mod.rs index 3b972ccc92..c0581de6b5 100644 --- a/codex-rs/app-server-client/src/cloud_backend/mod.rs +++ b/codex-rs/app-server-client/src/cloud_backend/mod.rs @@ -6,6 +6,7 @@ mod auth; mod events; mod idle; mod requests; +pub(crate) use requests::list_turns; mod thread_title; use crate::AppServerClient; @@ -664,7 +665,7 @@ async fn run_worker_with_prepared( } } -fn request_result(result: Result) -> crate::RequestResult { +pub(crate) fn request_result(result: Result) -> crate::RequestResult { result.map_err(|error| protocol::JSONRPCErrorError { code: if error .downcast_ref::() diff --git a/codex-rs/app-server-client/src/cloud_backend/requests.rs b/codex-rs/app-server-client/src/cloud_backend/requests.rs index 30a97c5304..172b193dac 100644 --- a/codex-rs/app-server-client/src/cloud_backend/requests.rs +++ b/codex-rs/app-server-client/src/cloud_backend/requests.rs @@ -32,6 +32,39 @@ pub(super) enum Response { Archived(String), } +pub(crate) async fn list_turns( + client: &cloud::Client, + params: protocol::ThreadTurnsListParams, +) -> Result { + if params.items_view != Some(protocol::TurnItemsView::NotLoaded) { + bail!("Read cloud turn items separately with thread/items/list."); + } + let page = client + .list_turns(&cloud::ListTurnsRequest { + thread_id: params.thread_id, + page: cloud::HistoryQuery { + cursor: params.cursor, + limit: params.limit, + order: history_order( + params + .sort_direction + .unwrap_or(protocol::SortDirection::Desc), + ), + ..Default::default() + }, + }) + .await?; + Ok(serde_json::to_value(protocol::ThreadTurnsListResponse { + data: page + .data + .into_iter() + .map(|entry| events::turn(entry.summary)) + .collect::>()?, + next_cursor: page.next_cursor, + backwards_cursor: page.backwards_cursor, + })?) +} + impl Requests { pub(super) fn thread_name_saved( &mut self, @@ -150,36 +183,7 @@ impl Requests { let settings = self.client.activate(¶ms.thread_id).await?; return attach_response(settings); } - Request::ThreadTurnsList { params, .. } => { - if params.items_view != Some(protocol::TurnItemsView::NotLoaded) { - bail!("Read cloud turn items separately with thread/items/list."); - } - let page = self - .client - .list_turns(&cloud::ListTurnsRequest { - thread_id: params.thread_id, - page: cloud::HistoryQuery { - cursor: params.cursor, - limit: params.limit, - order: history_order( - params - .sort_direction - .unwrap_or(protocol::SortDirection::Desc), - ), - ..Default::default() - }, - }) - .await?; - serde_json::to_value(protocol::ThreadTurnsListResponse { - data: page - .data - .into_iter() - .map(|entry| events::turn(entry.summary)) - .collect::>()?, - next_cursor: page.next_cursor, - backwards_cursor: page.backwards_cursor, - })? - } + Request::ThreadTurnsList { params, .. } => list_turns(&self.client, params).await?, Request::ThreadItemsList { params, .. } => { let cursor = match params.cursor { Some(protocol::ThreadItemsListCursor::Opaque(cursor)) => Some(cursor), diff --git a/codex-rs/app-server-client/src/cloud_tests.rs b/codex-rs/app-server-client/src/cloud_tests.rs index f5ab8cb50f..15f3106e4d 100644 --- a/codex-rs/app-server-client/src/cloud_tests.rs +++ b/codex-rs/app-server-client/src/cloud_tests.rs @@ -4,6 +4,65 @@ use crate::AppServerEvent; use codex_app_server_protocol::ThreadReadParams; use pretty_assertions::assert_eq; +#[tokio::test] +async fn prepared_turns_load_while_the_item_worker_is_busy() -> color_eyre::Result<()> { + let server = wiremock::MockServer::start().await; + wiremock::Mock::given(wiremock::matchers::path( + "/oaiproto.codex_app_server_backend.ThreadService/ListTurns", + )) + .respond_with( + wiremock::ResponseTemplate::new(200) + .insert_header("grpc-status", "0") + .set_body_raw(vec![0, 0, 0, 0, 2, 0x0a, 0], "application/grpc"), + ) + .expect(1) + .mount(&server) + .await; + let native = codex_cloud_client::Client::new( + &codex_http_client::HttpClientFactory::new( + codex_http_client::OutboundProxyPolicy::ReqwestDefault, + ), + &server.uri(), + codex_cloud_client::Credentials::new("synthetic-bearer", "synthetic-account")?, + )?; + let (client, mut history, _events) = CloudClient::channel(/*capacity*/ 1); + let mut handle = client.request_handle(); + handle.prepared_turns = Some((Arc::from("t"), Arc::new(native))); + let mut items = Box::pin(handle.request(ClientRequest::ThreadItemsList { + request_id: RequestId::Integer(1), + params: serde_json::from_value(serde_json::json!({"threadId": "t"}))?, + })); + assert!(futures::poll!(&mut items).is_pending()); + let held = history.try_recv()?; + let turns = || { + handle.request(ClientRequest::ThreadTurnsList { + request_id: RequestId::Integer(2), + params: serde_json::from_value( + serde_json::json!({"threadId": "t", "itemsView": "notLoaded"}), + ) + .unwrap(), + }) + }; + let page = tokio::time::timeout(crate::SHUTDOWN_TIMEOUT, turns()) + .await?? + .unwrap(); + assert_eq!(page["data"], serde_json::json!([])); + held.response + .send(Ok(Ok(serde_json::json!({"data": []})))) + .unwrap(); + assert!(items.await?.is_ok()); + drop(history); + assert!( + turns() + .await + .unwrap_err() + .get_ref() + .unwrap() + .is::() + ); + Ok(()) +} + #[tokio::test] async fn retained_request_and_reply_stay_with_their_cloud_backend() { let (first, mut first_commands, first_events) = CloudClient::channel(/*capacity*/ 1); diff --git a/codex-rs/app-server-client/src/lib.rs b/codex-rs/app-server-client/src/lib.rs index 3f8a5ff080..e9905291d5 100644 --- a/codex-rs/app-server-client/src/lib.rs +++ b/codex-rs/app-server-client/src/lib.rs @@ -35,6 +35,7 @@ pub use cloud::CloudOperation; pub use cloud::CloudRecoveryRelease; pub use cloud::CloudRequestHandle; pub use cloud::CloudUserMessageReceipt; +pub use cloud::PreparedResumeEnded; pub use cloud_backend::CloudRecoverySignInChanged; mod server_request; pub use server_request::AppServerReplyHandle; diff --git a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs index 9436d40c65..c40d816e74 100644 --- a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs +++ b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs @@ -1688,11 +1688,14 @@ async fn cloud_resume_picker_reconciles_admitted_steers() -> Result<()> { }; command.response.send(Ok(reply)).unwrap(); if let Some(mut scoped_history) = scoped_history { - let commit = scoped_history.recv().await.unwrap(); if history_fails { - assert!(matches!(commit.operation, CloudOperation::Request(request) + let items = scoped_history.recv().await.unwrap(); + assert!(matches!(items.operation, CloudOperation::Request(request) + if matches!(request.as_ref(), ClientRequest::ThreadItemsList { params, .. } if params.thread_id == failed.to_string()))); + let turns = scoped_history.recv().await.unwrap(); + assert!(matches!(turns.operation, CloudOperation::Request(request) if matches!(request.as_ref(), ClientRequest::ThreadTurnsList { params, .. } if params.thread_id == failed.to_string()))); - commit + turns .response .send(Ok(Err(JSONRPCErrorError { code: -32000, @@ -1704,8 +1707,10 @@ async fn cloud_resume_picker_reconciles_admitted_steers() -> Result<()> { scoped_history.recv().await.is_none(), "failed B must not commit" ); + assert!(items.response.is_closed()); continue; } + let commit = scoped_history.recv().await.unwrap(); assert!(matches!( commit.operation, CloudOperation::CommitPreparedResume diff --git a/codex-rs/tui/src/app_server_session/history.rs b/codex-rs/tui/src/app_server_session/history.rs index 89d8307eb3..9a8c736e96 100644 --- a/codex-rs/tui/src/app_server_session/history.rs +++ b/codex-rs/tui/src/app_server_session/history.rs @@ -37,6 +37,8 @@ pub(crate) const HISTORY_ITEM_SCAN_LIMIT: usize = 4 * HISTORY_ITEM_PAGE_LIMIT as #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum HistoryHydrationScope<'a> { Initial, + /// Initial history on the scoped handle returned by prepare_thread_resume. + PreparedCloud, CloudRecovery(Option<&'a str>), Complete, /// Include older turns that have no items. @@ -57,10 +59,12 @@ impl HistoryLoadBudget { terminal_height: u16, ) -> Self { use HistoryHydrationScope::CloudRecovery; + use HistoryHydrationScope::Initial; + use HistoryHydrationScope::PreparedCloud; let transcript_mode = local_settings.map(|settings| settings.transcript_mode); if matches!(scope, CloudRecovery(_)) - || (scope == HistoryHydrationScope::Initial + || (matches!(scope, Initial | PreparedCloud) && transcript_mode.is_some_and(crate::transcript_mode::TranscriptMode::is_owned)) { // A few screenfuls cover the first viewport and nearby reading without coupling @@ -75,11 +79,11 @@ impl HistoryLoadBudget { let items = match (scope, local_settings, rows) { (HistoryHydrationScope::Complete | HistoryHydrationScope::FullTranscript, _, _) | (HistoryHydrationScope::ThroughTurn(_) | CloudRecovery(_), _, _) - | (HistoryHydrationScope::Initial, Some(_), None) => None, - (HistoryHydrationScope::Initial, Some(_), Some(max_rows)) => { + | (Initial | PreparedCloud, Some(_), None) => None, + (Initial | PreparedCloud, Some(_), Some(max_rows)) => { Some(max_rows.saturating_add(HISTORY_ITEM_SCAN_LIMIT)) } - (HistoryHydrationScope::Initial, None, _) => Some(HISTORY_ITEM_PAGE_LIMIT as usize), + (Initial | PreparedCloud, None, _) => Some(HISTORY_ITEM_PAGE_LIMIT as usize), }; Self { rows, items } } @@ -391,26 +395,29 @@ impl AppServerSession { .wrap_err("failed to load a bounded thread item page") } - pub(crate) async fn thread_turns_page( + pub(crate) fn thread_turns_page( &mut self, thread_id: ThreadId, cursor: Option, limit: u32, - ) -> Result { + ) -> impl Future> + use<> { let request_id = self.next_request_id(); - self.request_handle - .request_typed(ClientRequest::ThreadTurnsList { - request_id, - params: ThreadTurnsListParams { - thread_id: thread_id.to_string(), - cursor, - limit: Some(limit), - sort_direction: Some(SortDirection::Desc), - items_view: Some(TurnItemsView::NotLoaded), - }, - }) - .await - .wrap_err("failed to load a bounded thread history page") + let handle = self.request_handle(); + async move { + handle + .request_typed(ClientRequest::ThreadTurnsList { + request_id, + params: ThreadTurnsListParams { + thread_id: thread_id.to_string(), + cursor, + limit: Some(limit), + sort_direction: Some(SortDirection::Desc), + items_view: Some(TurnItemsView::NotLoaded), + }, + }) + .await + .wrap_err("failed to load a bounded thread history page") + } } async fn merge_thread_item_page( @@ -507,21 +514,6 @@ impl AppServerSession { // A missing cursor in a paginated saved-chat resume means this stream was // empty when subscribed. An unanchored page would also contain later live events. let anchored = self.attachment_subscribed == Some(true); - let next_turn_cursor = if !anchored || turn_cursor.is_some() { - let page = self - .thread_turns_page(thread_id, turn_cursor, INITIAL_HISTORY_TURN_LIMIT) - .await?; - thread.turns = page.data.into_iter().rev().collect(); - page.next_cursor - } else { - None - }; - let mut state = ThreadHistoryPagination { - history_mode: ThreadHistoryMode::Paginated, - next_turn_cursor, - next_item_cursor: item_cursor, - ..ThreadHistoryPagination::default() - }; let (width, height) = crossterm::terminal::size().unwrap_or(/*default*/ (80, 24)); let width = width.max(/*other*/ 1); let budget = HistoryLoadBudget::new(scope, local_settings, height); @@ -533,19 +525,54 @@ impl AppServerSession { }; let mut scanned_items = 0; let mut rendered_rows = 0; + let mut first_items = None; + let next_turn_cursor = if !anchored || turn_cursor.is_some() { + let turns = self.thread_turns_page(thread_id, turn_cursor, INITIAL_HISTORY_TURN_LIMIT); + let page = if scope == HistoryHydrationScope::PreparedCloud + && (!anchored || item_cursor.is_some()) + && let Some(limit) = budget.next_page_size(rendered_rows, scanned_items) + { + let items = self.thread_items_page( + thread_id, + /*turn_id*/ None, + item_cursor.clone(), + limit, + ); + // Keep the two request futures out of the picker's bounded stack. + let (items, turns) = Box::pin(join_initial_pages(items, turns)).await?; + first_items = Some(items); + turns + } else { + turns.await? + }; + thread.turns = page.data.into_iter().rev().collect(); + page.next_cursor + } else { + None + }; + let mut state = ThreadHistoryPagination { + history_mode: ThreadHistoryMode::Paginated, + next_turn_cursor, + next_item_cursor: item_cursor, + ..ThreadHistoryPagination::default() + }; while let Some(limit) = budget.next_page_size(rendered_rows, scanned_items) { if anchored && state.next_item_cursor.is_none() { break; } - let page = self - .thread_items_page( - thread_id, - /*turn_id*/ None, - state.next_item_cursor.clone(), - limit, - ) - .await?; + let page = match first_items.take() { + Some(page) => page, + None => { + self.thread_items_page( + thread_id, + /*turn_id*/ None, + state.next_item_cursor.clone(), + limit, + ) + .await? + } + }; if page.data.is_empty() { state.next_item_cursor = recovery_cursor( state.next_item_cursor.as_deref(), @@ -629,6 +656,30 @@ impl AppServerSession { } } +async fn join_initial_pages( + items: impl Future>, + turns: impl Future>, +) -> Result<(ThreadItemsListResponse, ThreadTurnsListResponse)> { + use codex_app_server_client::PreparedResumeEnded; + use codex_app_server_client::TypedRequestError; + + let turns = async { + let page = turns.await; + if let Err(error) = &page + && let Some(TypedRequestError::Transport { source, .. }) = error.downcast_ref() + && let Some(cause) = source.get_ref() + && cause.is::() + { + // The worker can send an item error and retire between polls. + // Receive its reply before reporting the resulting cancellation. + return Ok(page); + } + page.map(Ok) + }; + let (items, turns) = tokio::try_join!(items, turns)?; + Ok((items, turns?)) +} + fn rendered_history_rows( thread_id: ThreadId, thread: &Thread, diff --git a/codex-rs/tui/src/app_server_session/history_tests.rs b/codex-rs/tui/src/app_server_session/history_tests.rs index f8117d8eba..bc65f96dc8 100644 --- a/codex-rs/tui/src/app_server_session/history_tests.rs +++ b/codex-rs/tui/src/app_server_session/history_tests.rs @@ -6,6 +6,95 @@ use crate::transcript_mode::TranscriptMode; use pretty_assertions::assert_eq; use std::collections::HashSet; +#[tokio::test] +async fn cloud_history_overlaps_initial_pages_only_during_prepared_navigation() +-> color_eyre::Result<()> { + use codex_app_server_client::AppServerClient; + use codex_app_server_client::CloudClient; + use codex_app_server_client::CloudOperation; + use codex_app_server_protocol::ClientRequest; + use serde_json::json; + + let (client, mut commands, _events) = CloudClient::channel(/*capacity*/ 2); + let mut session = super::AppServerSession::new( + crate::backend_id::BackendId::new(), + AppServerClient::Cloud(client), + crate::app_server_session::ThreadParamsMode::Cloud, + ); + let id = codex_protocol::ThreadId::new().to_string(); + let mut thread = serde_json::from_value(json!({ + "id": id, "sessionId": id, "historyMode": "paginated", "turns": [], + "preview": "", "ephemeral": false, "modelProvider": "openai", + "createdAt": 1, "updatedAt": 1, "status": {"type": "idle"}, + "cwd": std::env::current_dir()?, "cliVersion": "test", "source": "cli" + }))?; + let mut startup = Box::pin(session.hydrate_initial_thread_history( + &mut thread, + Some("turns".into()), + Some("items".into()), + /*config*/ None, + /*local_settings*/ None, + HistoryHydrationScope::Initial, + )); + assert!(futures::poll!(&mut startup).is_pending()); + let turns = commands.try_recv()?; + assert!(matches!(turns.operation, CloudOperation::Request(request) + if matches!(*request, ClientRequest::ThreadTurnsList { .. }))); + assert!(commands.try_recv().is_err()); + turns + .response + .send(Err(std::io::Error::other("turn failed"))) + .unwrap(); + assert!(startup.await.is_err()); + assert!(commands.try_recv().is_err()); + + let mut load = Box::pin(session.hydrate_initial_thread_history( + &mut thread, + Some("turns".into()), + Some("items".into()), + /*config*/ None, + /*local_settings*/ None, + HistoryHydrationScope::PreparedCloud, + )); + assert!(futures::poll!(&mut load).is_pending()); + let items = commands.try_recv()?; + let turns = commands.try_recv()?; + assert!(matches!(turns.operation, CloudOperation::Request(request) + if matches!(*request, ClientRequest::ThreadTurnsList { .. }))); + assert!(matches!(items.operation, CloudOperation::Request(request) + if matches!(*request, ClientRequest::ThreadItemsList { .. }))); + let item = json!({"type": "agentMessage", "id": "reply", "text": "Hello"}); + let items_page = json!({"data": [{"turnId": "turn", "item": item}]}); + items.response.send(Ok(Ok(items_page))).unwrap(); + assert!(futures::poll!(&mut load).is_pending()); + let turns_page = json!({"data": [{"id": "turn", "status": "completed", "items": []}]}); + turns.response.send(Ok(Ok(turns_page))).unwrap(); + load.await?; + assert_eq!(thread.turns[0].items[0].id(), "reply"); + Ok(()) +} + +#[tokio::test] +async fn cloud_history_surfaces_item_error_when_scope_closes_between_polls() { + use codex_app_server_client::PreparedResumeEnded; + use codex_app_server_client::TypedRequestError; + + let (reply, pending) = tokio::sync::oneshot::channel(); + let items = async { pending.await.unwrap() }; + let turns = async { + reply + .send(Err(color_eyre::eyre::eyre!("item failed"))) + .unwrap(); + Err(color_eyre::Report::new(TypedRequestError::Transport { + method: "thread/turns/list".into(), + source: std::io::Error::other(PreparedResumeEnded), + }) + .wrap_err("turn page failed")) + }; + let error = super::join_initial_pages(items, turns).await.unwrap_err(); + assert_eq!(error.to_string(), "item failed"); +} + #[test] fn advancing_cursor_rejects_repeated_cursors() { let mut seen_cursors = HashSet::new(); diff --git a/codex-rs/tui/src/app_server_session/rollout_history.rs b/codex-rs/tui/src/app_server_session/rollout_history.rs index 042d6eabd6..4857598e54 100644 --- a/codex-rs/tui/src/app_server_session/rollout_history.rs +++ b/codex-rs/tui/src/app_server_session/rollout_history.rs @@ -205,7 +205,7 @@ impl AppServerSession { response.items_backwards_cursor.clone(), Some(&config), Some(local_settings), - HistoryHydrationScope::Initial, + HistoryHydrationScope::PreparedCloud, ) .await?; let mut started = started_thread_from_resume_response(