From 9b2d2c12db7a6d658203f2911dc7c83165967bb4 Mon Sep 17 00:00:00 2001 From: Benjamin Carlsson Date: Tue, 17 Nov 2026 01:20:23 +0000 Subject: [PATCH] Add saved environment listing to the Cloud client (#61940) ## What changed Add `Client::list_saved_environments` and export `SavedEnvironment` with each environment's ID, name, and workspace-sharing status. - Fetch personal and workspace environments from the authenticated `/v1/environment-configs` picker API, following pagination independently for each scope. - Request non-draft configurations and filter out the default environment, empty IDs, and blank names. - Bound the catalog request to 10 seconds and each response page to 1 MiB. Return `EnvironmentCatalogUnavailable` for request, parsing, or limit failures and repeated cursors. ## Testing Add a client test covering pagination, cursor encoding, scope ordering, default-environment filtering, workspace-sharing status, and authenticated request headers. GitOrigin-RevId: ca7793a53eade36ba510a53b4a827f945a109072 --- codex-rs/cloud-client/Cargo.toml | 2 +- codex-rs/cloud-client/src/client_tests.rs | 48 ++++++++++++ codex-rs/cloud-client/src/environments.rs | 94 +++++++++++++++++++++++ codex-rs/cloud-client/src/lib.rs | 2 + codex-rs/cloud-client/src/prewarm.rs | 4 +- codex-rs/cloud-client/src/types.rs | 2 + 6 files changed, 150 insertions(+), 2 deletions(-) create mode 100644 codex-rs/cloud-client/src/environments.rs diff --git a/codex-rs/cloud-client/Cargo.toml b/codex-rs/cloud-client/Cargo.toml index 53ce327483..f8c7ba134e 100644 --- a/codex-rs/cloud-client/Cargo.toml +++ b/codex-rs/cloud-client/Cargo.toml @@ -13,6 +13,7 @@ workspace = true [dependencies] serde = { workspace = true } +serde_json = { workspace = true } async-stream = { workspace = true } bytes = { workspace = true } codex-http-client = { workspace = true } @@ -28,7 +29,6 @@ tokio = { workspace = true, features = ["time"] } url = { workspace = true } [dev-dependencies] -serde_json = { workspace = true } anyhow = { workspace = true } pretty_assertions = { workspace = true } tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } diff --git a/codex-rs/cloud-client/src/client_tests.rs b/codex-rs/cloud-client/src/client_tests.rs index 2fa361c02f..7fdd6c2449 100644 --- a/codex-rs/cloud-client/src/client_tests.rs +++ b/codex-rs/cloud-client/src/client_tests.rs @@ -367,6 +367,54 @@ async fn prewarm_defers_readiness_only_for_selected_projects() { assert_request(&mut fixture, "Prewarm", &expected).await; } +#[tokio::test] +async fn saved_environment_catalog_follows_each_scope_cursor() { + let mut fixture = fixture_responses( + [ + br#"{"data":[{"id":"asenvcfg_base","name":"Default"}],"next_cursor":"a+b"}"#.as_slice(), + br#"{"data":[{"id":"asenvcfg_personal","name":"Personal Rust"}],"next_cursor":null}"#, + br#"{"data":[{"id":"ws~asenvcfg_saved","name":"Team Rust"}],"next_cursor":null}"#, + ] + .into_iter() + .map(|body| { + http::Response::new(Body::new(http_body_util::Full::new(Bytes::from_static( + body, + )))) + }) + .collect(), + ) + .await; + assert_eq!( + fixture.client.list_saved_environments().await.unwrap(), + vec![ + SavedEnvironment { + id: "asenvcfg_personal".into(), + name: "Personal Rust".into(), + workspace_shared: false, + }, + SavedEnvironment { + id: "ws~asenvcfg_saved".into(), + name: "Team Rust".into(), + workspace_shared: true, + }, + ] + ); + + for query in [ + "scope=user&limit=100&omitDraft=true&view=picker", + "scope=user&limit=100&omitDraft=true&view=picker&cursor=a%2Bb", + "scope=workspace&limit=100&omitDraft=true&view=picker", + ] { + let (parts, body) = fixture.requests.recv().await.unwrap(); + assert_eq!(parts.method, http::Method::GET); + assert_eq!(parts.uri.path(), "/v1/environment-configs"); + assert_eq!(parts.uri.query(), Some(query)); + assert_eq!(parts.headers["chatgpt-account-id"], "synthetic-account"); + assert_eq!(parts.headers["x-openai-product-sku"], "codex"); + assert!(body.is_empty()); + } +} + #[tokio::test] async fn prewarm_uses_managed_defaults_and_preserves_resolved_settings() { // PrewarmThread uses Thread field numbers but omits turns entirely. diff --git a/codex-rs/cloud-client/src/environments.rs b/codex-rs/cloud-client/src/environments.rs new file mode 100644 index 0000000000..881a3b2b30 --- /dev/null +++ b/codex-rs/cloud-client/src/environments.rs @@ -0,0 +1,94 @@ +//! Reads the desktop Cloud picker's runnable configurations for the bound account. + +use crate::Client; +use crate::Error; +use crate::prewarm::DEFAULT_ENVIRONMENT_CONFIG_ID; +use codex_http_client::bounded_response_bytes; +use serde::Deserialize; +use std::collections::HashSet; +use std::time::Duration; + +const CATALOG_TIMEOUT: Duration = Duration::from_secs(10); +const MAX_PAGE_BYTES: usize = 1024 * 1024; + +/// A saved environment available to the current Cloud account. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +pub struct SavedEnvironment { + pub id: String, + pub name: String, + #[serde(skip)] + pub workspace_shared: bool, +} + +#[derive(Deserialize)] +struct Page { + data: Vec, + next_cursor: Option, +} + +impl Client { + /// Fetch both personal and workspace environments through the authenticated picker API. + pub async fn list_saved_environments(&self) -> Result, Error> { + tokio::time::timeout(CATALOG_TIMEOUT, async { + let mut environments = self.list_saved_environment_scope("user").await?; + environments.extend(self.list_saved_environment_scope("workspace").await?); + Ok(environments) + }) + .await + .map_err(|_| Error::EnvironmentCatalogUnavailable)? + } + + async fn list_saved_environment_scope( + &self, + scope: &str, + ) -> Result, Error> { + let mut url = self.model_catalog_url.clone(); + url.set_path("/v1/environment-configs"); + let mut configs = Vec::new(); + let mut seen_cursors = HashSet::new(); + let mut cursor: Option = None; + loop { + url.set_query(None); + { + let mut query = url.query_pairs_mut(); + query.extend_pairs([ + ("scope", scope), + ("limit", "100"), + ("omitDraft", "true"), + ("view", "picker"), + ]); + if let Some(cursor) = cursor.as_deref() { + query.append_pair("cursor", cursor); + } + } + let response = self + .http + .get(url.clone()) + .headers(self.credentials.headers.clone()) + .header("x-openai-product-sku", "codex") + .send() + .await + .and_then(codex_http_client::HttpResponse::error_for_status) + .map_err(|_| Error::EnvironmentCatalogUnavailable)?; + let body = bounded_response_bytes(response, MAX_PAGE_BYTES) + .await + .map_err(|_| Error::EnvironmentCatalogUnavailable)?; + let page: Page = + serde_json::from_slice(&body).map_err(|_| Error::EnvironmentCatalogUnavailable)?; + configs.extend(page.data.into_iter().filter_map(|mut config| { + config.workspace_shared = scope == "workspace"; + (!config.id.is_empty() + && config.id != DEFAULT_ENVIRONMENT_CONFIG_ID + && !config.name.trim().is_empty()) + .then_some(config) + })); + let Some(next_cursor) = page.next_cursor else { + return Ok(configs); + }; + if !seen_cursors.insert(next_cursor.clone()) { + return Err(Error::EnvironmentCatalogUnavailable); + } + cursor = Some(next_cursor); + } + } +} diff --git a/codex-rs/cloud-client/src/lib.rs b/codex-rs/cloud-client/src/lib.rs index 304c26c102..6d16142d0b 100644 --- a/codex-rs/cloud-client/src/lib.rs +++ b/codex-rs/cloud-client/src/lib.rs @@ -7,6 +7,7 @@ mod activation; mod activation_wire; mod discovery; +mod environments; mod history; mod history_wire; mod item_wire; @@ -41,6 +42,7 @@ pub use discovery::ThreadReadState; pub use discovery::ThreadSortDirection; pub use discovery::ThreadSortKey; pub use discovery::ThreadUnreadPosition; +pub use environments::SavedEnvironment; pub use history::HistoryAccess; pub use history::HistoryItem; pub use history::HistoryOrder; diff --git a/codex-rs/cloud-client/src/prewarm.rs b/codex-rs/cloud-client/src/prewarm.rs index c97ab6b8e5..627864a8d9 100644 --- a/codex-rs/cloud-client/src/prewarm.rs +++ b/codex-rs/cloud-client/src/prewarm.rs @@ -16,6 +16,8 @@ pub struct ProjectEnvironment { pub cwd: Option, } +pub(super) const DEFAULT_ENVIRONMENT_CONFIG_ID: &str = "asenvcfg_base"; + impl std::fmt::Debug for ProjectEnvironment { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("ProjectEnvironment([redacted])") @@ -51,7 +53,7 @@ impl Client { origin_urls, cwd, }) => wire::ManagedEnvironment { - environment_config_id: Some("asenvcfg_base".to_owned()), + environment_config_id: Some(DEFAULT_ENVIRONMENT_CONFIG_ID.to_owned()), cwd, overrides: Some(wire::EnvironmentOverrides { repositories: Some(wire::RepositoryOverrides { diff --git a/codex-rs/cloud-client/src/types.rs b/codex-rs/cloud-client/src/types.rs index 76c5e1328b..952ee10b17 100644 --- a/codex-rs/cloud-client/src/types.rs +++ b/codex-rs/cloud-client/src/types.rs @@ -105,6 +105,8 @@ pub enum Error { ModelCatalogUnavailable, #[error("Cloud model catalog exceeds the response limit")] ModelCatalogTooLarge, + #[error("Cloud environment catalog is unavailable")] + EnvironmentCatalogUnavailable, #[error("invalid gRPC event envelope")] InvalidResponse, #[error("cloud response contains an unsupported {0}")]