Load initial Cloud history concurrently when switching threads (#65364)

## Why

When switching to a Cloud thread in the TUI, the initial item page
waited for the turn metadata page even though the two reads can start
independently.

## What changed

During a prepared Cloud resume, fetch the first turn metadata and item
pages concurrently when both are needed. The turn metadata request
bypasses the worker handling the item page and is canceled if the
prepared resume ends. If the item read fails as the worker closes,
surface the item error ahead of the resulting cancellation.

## Testing

Add coverage for overlapping the two reads during thread switching,
loading turns while the item worker is busy, and preserving the item
error when the prepared resume closes.

GitOrigin-RevId: 1b4aee89b10f318de2732c30c6d31e255a492c38
This commit is contained in:
Benjamin Carlsson
2026-12-03 00:27:06 +00:00
committed by copyberry
parent e6a7862259
commit 53052950cb
9 changed files with 312 additions and 77 deletions
+25
View File
@@ -122,12 +122,18 @@ pub(super) enum IdleReconnect {
CaughtUp(Arc<str>),
}
/// 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<IdleReconnect>,
pub(super) attached: Arc<AtomicBool>,
commands: mpsc::Sender<CloudCommand>,
native: Option<Arc<codex_cloud_client::Client>>,
prepared_turns: Option<(Arc<str>, Arc<codex_cloud_client::Client>)>,
title_client: Option<Arc<CloudTitleClient>>,
}
@@ -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<RequestResult> {
// 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.
@@ -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<Value>) -> crate::RequestResult {
pub(crate) fn request_result(result: Result<Value>) -> crate::RequestResult {
result.map_err(|error| protocol::JSONRPCErrorError {
code: if error
.downcast_ref::<requests::UnsupportedOperation>()
@@ -32,6 +32,39 @@ pub(super) enum Response {
Archived(String),
}
pub(crate) async fn list_turns(
client: &cloud::Client,
params: protocol::ThreadTurnsListParams,
) -> Result<Value> {
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::<Result<_>>()?,
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(&params.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::<Result<_>>()?,
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),
@@ -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::<PreparedResumeEnded>()
);
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);
+1
View File
@@ -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;