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
This commit is contained in:
Benjamin Carlsson
2026-11-17 02:01:18 +00:00
committed by copyberry
parent cc356fd384
commit 9b2d2c12db
6 changed files with 150 additions and 2 deletions
+48
View File
@@ -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.
+94
View File
@@ -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<SavedEnvironment>,
next_cursor: Option<String>,
}
impl Client {
/// Fetch both personal and workspace environments through the authenticated picker API.
pub async fn list_saved_environments(&self) -> Result<Vec<SavedEnvironment>, 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<Vec<SavedEnvironment>, 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<String> = 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);
}
}
}
+2
View File
@@ -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;
+3 -1
View File
@@ -16,6 +16,8 @@ pub struct ProjectEnvironment {
pub cwd: Option<String>,
}
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 {
+2
View File
@@ -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}")]