From 21e643d32e5da0639724a24a0a8c9f5fedc67b7a Mon Sep 17 00:00:00 2001 From: yansenzhou-oai Date: Wed, 2 Dec 2026 02:14:12 +0000 Subject: [PATCH] Remove the `codex cloud` and `codex apply` commands (#65173) ## Why Once the commands are removed, invocations such as `codex cloud exec work` could be interpreted as interactive prompts. Rejecting retired command names in the root prompt position prevents old invocations from starting a session by mistake. ## What changed - Remove `codex cloud` and `codex apply`, which provided CLI workflows for running and browsing cloud tasks and applying their diffs locally. Delete the cloud task crates, related backend client code, and the TUI composer widget used by the cloud task interface. - Reject `cloud`, `cloud-tasks`, `apply`, and `a` as retired root commands. To use one of those names as a prompt, pass it after `--`, as in `codex -- apply`. ## Testing Add parser coverage for retired names used alone, with trailing arguments, and after root options, as well as for explicit prompts after `--`. GitOrigin-RevId: 8469e936eacde3428862c6bf1b7e33084b8ead68 --- .../scripts/windows_bazel_test_durations.tsv | 6 - codex-rs/Cargo.lock | 72 - codex-rs/Cargo.toml | 5 - codex-rs/backend-client/BUILD.bazel | 1 - codex-rs/backend-client/src/client.rs | 129 - .../src/client_request_tests.rs | 123 - codex-rs/backend-client/src/lib.rs | 5 - codex-rs/backend-client/src/types.rs | 358 --- .../fixtures/task_details_with_diff.json | 38 - .../fixtures/task_details_with_error.json | 22 - codex-rs/chatgpt/Cargo.toml | 6 +- codex-rs/chatgpt/src/apply_command.rs | 77 - codex-rs/chatgpt/src/chatgpt_client.rs | 52 - .../src/chatgpt_client_runtime_auth_tests.rs | 66 +- codex-rs/chatgpt/src/get_task.rs | 40 - codex-rs/chatgpt/src/lib.rs | 2 - codex-rs/chatgpt/tests/all.rs | 3 - .../chatgpt/tests/suite/apply_command_e2e.rs | 188 -- codex-rs/chatgpt/tests/suite/mod.rs | 2 - codex-rs/chatgpt/tests/task_turn_fixture.json | 65 - codex-rs/cli/Cargo.toml | 2 - codex-rs/cli/src/config_override_args.rs | 21 + .../cli/src/config_override_args_tests.rs | 20 + codex-rs/cli/src/main.rs | 38 - codex-rs/cli/tests/cloud_auth.rs | 113 - codex-rs/cli/tests/daemon_startup.rs | 1 - codex-rs/cli/tests/features.rs | 15 - codex-rs/cloud-tasks-client/BUILD.bazel | 6 - codex-rs/cloud-tasks-client/Cargo.toml | 25 - codex-rs/cloud-tasks-client/src/api.rs | 176 -- codex-rs/cloud-tasks-client/src/http.rs | 929 ------- codex-rs/cloud-tasks-client/src/lib.rs | 20 - codex-rs/cloud-tasks-mock-client/BUILD.bazel | 6 - codex-rs/cloud-tasks-mock-client/Cargo.toml | 20 - codex-rs/cloud-tasks-mock-client/src/lib.rs | 3 - codex-rs/cloud-tasks-mock-client/src/mock.rs | 267 -- codex-rs/cloud-tasks/BUILD.bazel | 7 - codex-rs/cloud-tasks/Cargo.toml | 54 - codex-rs/cloud-tasks/src/app.rs | 534 ---- .../cloud-tasks/src/backend_auth_tests.rs | 277 -- codex-rs/cloud-tasks/src/cli.rs | 120 - codex-rs/cloud-tasks/src/env_detect.rs | 446 --- .../src/env_detect_runtime_auth_tests.rs | 130 - codex-rs/cloud-tasks/src/env_detect_tests.rs | 362 --- codex-rs/cloud-tasks/src/lib.rs | 2467 ----------------- codex-rs/cloud-tasks/src/new_task.rs | 35 - codex-rs/cloud-tasks/src/scrollable_diff.rs | 208 -- .../cloud-tasks/src/scrollable_diff_tests.rs | 48 - codex-rs/cloud-tasks/src/ui.rs | 1046 ------- codex-rs/cloud-tasks/src/util.rs | 200 -- codex-rs/cloud-tasks/tests/env_filter.rs | 39 - codex-rs/tui/src/bottom_pane/chat_composer.rs | 36 +- .../bottom_pane/chat_composer/test_support.rs | 40 + codex-rs/tui/src/lib.rs | 3 - .../tui/src/public_widgets/composer_input.rs | 149 - codex-rs/tui/src/public_widgets/mod.rs | 1 - 56 files changed, 87 insertions(+), 9037 deletions(-) delete mode 100644 codex-rs/backend-client/tests/fixtures/task_details_with_diff.json delete mode 100644 codex-rs/backend-client/tests/fixtures/task_details_with_error.json delete mode 100644 codex-rs/chatgpt/src/apply_command.rs delete mode 100644 codex-rs/chatgpt/src/get_task.rs delete mode 100644 codex-rs/chatgpt/tests/all.rs delete mode 100644 codex-rs/chatgpt/tests/suite/apply_command_e2e.rs delete mode 100644 codex-rs/chatgpt/tests/suite/mod.rs delete mode 100644 codex-rs/chatgpt/tests/task_turn_fixture.json delete mode 100644 codex-rs/cli/tests/cloud_auth.rs delete mode 100644 codex-rs/cloud-tasks-client/BUILD.bazel delete mode 100644 codex-rs/cloud-tasks-client/Cargo.toml delete mode 100644 codex-rs/cloud-tasks-client/src/api.rs delete mode 100644 codex-rs/cloud-tasks-client/src/http.rs delete mode 100644 codex-rs/cloud-tasks-client/src/lib.rs delete mode 100644 codex-rs/cloud-tasks-mock-client/BUILD.bazel delete mode 100644 codex-rs/cloud-tasks-mock-client/Cargo.toml delete mode 100644 codex-rs/cloud-tasks-mock-client/src/lib.rs delete mode 100644 codex-rs/cloud-tasks-mock-client/src/mock.rs delete mode 100644 codex-rs/cloud-tasks/BUILD.bazel delete mode 100644 codex-rs/cloud-tasks/Cargo.toml delete mode 100644 codex-rs/cloud-tasks/src/app.rs delete mode 100644 codex-rs/cloud-tasks/src/backend_auth_tests.rs delete mode 100644 codex-rs/cloud-tasks/src/cli.rs delete mode 100644 codex-rs/cloud-tasks/src/env_detect.rs delete mode 100644 codex-rs/cloud-tasks/src/env_detect_runtime_auth_tests.rs delete mode 100644 codex-rs/cloud-tasks/src/env_detect_tests.rs delete mode 100644 codex-rs/cloud-tasks/src/lib.rs delete mode 100644 codex-rs/cloud-tasks/src/new_task.rs delete mode 100644 codex-rs/cloud-tasks/src/scrollable_diff.rs delete mode 100644 codex-rs/cloud-tasks/src/scrollable_diff_tests.rs delete mode 100644 codex-rs/cloud-tasks/src/ui.rs delete mode 100644 codex-rs/cloud-tasks/src/util.rs delete mode 100644 codex-rs/cloud-tasks/tests/env_filter.rs create mode 100644 codex-rs/tui/src/bottom_pane/chat_composer/test_support.rs delete mode 100644 codex-rs/tui/src/public_widgets/composer_input.rs delete mode 100644 codex-rs/tui/src/public_widgets/mod.rs diff --git a/.github/scripts/windows_bazel_test_durations.tsv b/.github/scripts/windows_bazel_test_durations.tsv index b328c667cc..bc78838847 100644 --- a/.github/scripts/windows_bazel_test_durations.tsv +++ b/.github/scripts/windows_bazel_test_durations.tsv @@ -28,11 +28,9 @@ //codex-rs/apply-patch:apply_patch-bin-unit-tests 24 //codex-rs/arg0:arg0-unit-tests 24 //codex-rs/backend-client:backend-client-unit-tests 41 -//codex-rs/chatgpt:chatgpt-all-test-windows-cross 26 //codex-rs/chatgpt:chatgpt-unit-tests 27 //codex-rs/cli:cli-app_server-test-windows-cross 3 //codex-rs/cli:cli-app_server_daemon-test-windows-cross 1 -//codex-rs/cli:cli-cloud_auth-test-windows-cross 47 //codex-rs/cli:cli-cloud_config-test-windows-cross 3 //codex-rs/cli:cli-daemon_startup-test-windows-cross 4 //codex-rs/cli:cli-daemon_telemetry-test-windows-cross 1 @@ -63,10 +61,6 @@ //codex-rs/cli:codex-bin-unit-tests 60 //codex-rs/cli:logs_client-bin-unit-tests 1 //codex-rs/cloud-config:cloud-config-unit-tests 47 -//codex-rs/cloud-tasks-client:cloud-tasks-client-unit-tests 35 -//codex-rs/cloud-tasks-mock-client:cloud-tasks-mock-client-unit-tests 59 -//codex-rs/cloud-tasks:cloud-tasks-env_filter-test-windows-cross 1 -//codex-rs/cloud-tasks:cloud-tasks-unit-tests 1 //codex-rs/code-mode-host:code-mode-host-grpc-test-windows-cross 28 //codex-rs/code-mode-host:code-mode-host-grpc_notifications-test-windows-cross 25 //codex-rs/code-mode-host:code-mode-host-grpc_tcp-test-windows-cross 1 diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 6ce7252369..a618889979 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2611,19 +2611,15 @@ version = "0.0.0" dependencies = [ "anyhow", "base64 0.22.1", - "clap", "codex-connectors", "codex-core", "codex-features", - "codex-git-utils", "codex-http-client", "codex-login", "codex-model-provider", "codex-plugin", "codex-protocol", "codex-runtime-agent-instance", - "codex-utils-cargo-bin", - "codex-utils-cli", "pretty_assertions", "serde", "serde_json", @@ -2653,9 +2649,7 @@ dependencies = [ "codex-app-server-test-client", "codex-arg0", "codex-build-info", - "codex-chatgpt", "codex-cloud-config", - "codex-cloud-tasks", "codex-config", "codex-core", "codex-core-plugins", @@ -2808,72 +2802,6 @@ dependencies = [ "wiremock", ] -[[package]] -name = "codex-cloud-tasks" -version = "0.0.0" -dependencies = [ - "anyhow", - "base64 0.22.1", - "chrono", - "clap", - "codex-agent-identity", - "codex-backend-client", - "codex-cloud-tasks-client", - "codex-cloud-tasks-mock-client", - "codex-core", - "codex-features", - "codex-git-utils", - "codex-http-client", - "codex-login", - "codex-model-provider", - "codex-runtime-agent-instance", - "codex-tui", - "codex-utils-cli", - "core_test_support", - "crossterm", - "http 1.4.0", - "insta", - "owo-colors", - "pretty_assertions", - "ratatui", - "serde", - "serde_json", - "supports-color 3.0.2", - "tempfile", - "tokio", - "tokio-stream", - "tracing", - "tracing-subscriber", - "unicode-segmentation", - "unicode-width 0.2.1", - "uuid", - "wiremock", -] - -[[package]] -name = "codex-cloud-tasks-client" -version = "0.0.0" -dependencies = [ - "anyhow", - "chrono", - "codex-api", - "codex-backend-client", - "codex-git-utils", - "codex-http-client", - "serde", - "serde_json", - "thiserror 2.0.18", -] - -[[package]] -name = "codex-cloud-tasks-mock-client" -version = "0.0.0" -dependencies = [ - "chrono", - "codex-cloud-tasks-client", - "diffy", -] - [[package]] name = "codex-code-mode" version = "0.0.0" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 73603e553f..991bf639c2 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -35,9 +35,6 @@ members = [ "plugin-host", "codex-home", "cloud-config", - "cloud-tasks", - "cloud-tasks-client", - "cloud-tasks-mock-client", "cli", "collaboration-mode-templates", "connectors", @@ -219,8 +216,6 @@ codex-chatgpt = { path = "chatgpt" } codex-client = { path = "codex-client" } codex-collaboration-mode-templates = { path = "collaboration-mode-templates" } codex-cloud-config = { path = "cloud-config" } -codex-cloud-tasks-client = { path = "cloud-tasks-client" } -codex-cloud-tasks-mock-client = { path = "cloud-tasks-mock-client" } codex-code-mode = { path = "code-mode" } codex-code-mode-protocol = { path = "code-mode-protocol" } codex-code-mode-runtime = { path = "code-mode-runtime" } diff --git a/codex-rs/backend-client/BUILD.bazel b/codex-rs/backend-client/BUILD.bazel index 5a990abd20..2deaae5674 100644 --- a/codex-rs/backend-client/BUILD.bazel +++ b/codex-rs/backend-client/BUILD.bazel @@ -2,6 +2,5 @@ load("//:defs.bzl", "codex_rust_crate") codex_rust_crate( name = "backend-client", - compile_data = glob(["tests/fixtures/**"]), crate_name = "codex_backend_client", ) diff --git a/codex-rs/backend-client/src/client.rs b/codex-rs/backend-client/src/client.rs index a61d2da948..4b32cc1fa6 100644 --- a/codex-rs/backend-client/src/client.rs +++ b/codex-rs/backend-client/src/client.rs @@ -1,13 +1,10 @@ use crate::types::AccountsCheckResponse; -use crate::types::CodeTaskDetailsResponse; use crate::types::CodexUserSettingsResponse; use crate::types::CodexWorkspaceMessagesResponse; use crate::types::ConfigBundleResponse; -use crate::types::PaginatedListTaskListItem; use crate::types::RateLimitReachedKind as BackendRateLimitReachedKind; use crate::types::RateLimitStatusPayload; use crate::types::TokenUsageProfile; -use crate::types::TurnAttemptsSiblingTurnsResponse; use anyhow::Result; use codex_api::AuthError; use codex_api::SharedAuthProvider; @@ -638,98 +635,6 @@ impl Client { Ok(()) } - pub async fn list_tasks( - &self, - limit: Option, - task_filter: Option<&str>, - environment_id: Option<&str>, - cursor: Option<&str>, - ) -> Result { - let url = self.list_tasks_url(limit, task_filter, environment_id, cursor)?; - let req = self - .request(Method::GET, &url) - .headers(self.headers().await?); - let (body, ct) = self.exec_request(req, "GET", &url).await?; - self.decode_json::(&url, &ct, &body) - } - - fn list_tasks_url( - &self, - limit: Option, - task_filter: Option<&str>, - environment_id: Option<&str>, - cursor: Option<&str>, - ) -> Result { - let url = match self.path_style { - PathStyle::CodexApi => format!("{}/api/codex/tasks/list", self.base_url), - PathStyle::ChatGptApi => format!("{}/wham/tasks/list", self.base_url), - }; - if limit.is_none() && task_filter.is_none() && environment_id.is_none() && cursor.is_none() - { - return Ok(url); - } - let mut url = url::Url::parse(&url)?; - { - let mut query = url.query_pairs_mut(); - if let Some(limit) = limit { - query.append_pair("limit", &limit.to_string()); - } - if let Some(task_filter) = task_filter { - query.append_pair("task_filter", task_filter); - } - if let Some(cursor) = cursor { - query.append_pair("cursor", cursor); - } - if let Some(environment_id) = environment_id { - query.append_pair("environment_id", environment_id); - } - } - Ok(url.to_string()) - } - - pub async fn get_task_details(&self, task_id: &str) -> Result { - let (parsed, _body, _ct) = self.get_task_details_with_body(task_id).await?; - Ok(parsed) - } - - pub async fn get_task_details_with_body( - &self, - task_id: &str, - ) -> Result<(CodeTaskDetailsResponse, String, String)> { - let url = match self.path_style { - PathStyle::CodexApi => format!("{}/api/codex/tasks/{}", self.base_url, task_id), - PathStyle::ChatGptApi => format!("{}/wham/tasks/{}", self.base_url, task_id), - }; - let req = self - .request(Method::GET, &url) - .headers(self.headers().await?); - let (body, ct) = self.exec_request(req, "GET", &url).await?; - let parsed: CodeTaskDetailsResponse = self.decode_json(&url, &ct, &body)?; - Ok((parsed, body, ct)) - } - - pub async fn list_sibling_turns( - &self, - task_id: &str, - turn_id: &str, - ) -> Result { - let url = match self.path_style { - PathStyle::CodexApi => format!( - "{}/api/codex/tasks/{}/turns/{}/sibling_turns", - self.base_url, task_id, turn_id - ), - PathStyle::ChatGptApi => format!( - "{}/wham/tasks/{}/turns/{}/sibling_turns", - self.base_url, task_id, turn_id - ), - }; - let req = self - .request(Method::GET, &url) - .headers(self.headers().await?); - let (body, ct) = self.exec_request(req, "GET", &url).await?; - self.decode_json::(&url, &ct, &body) - } - /// `GET /api/codex/config/bundle` (Codex API style) or /// `GET /wham/config/bundle` (ChatGPT backend-api style), or /// `GET /codex/config/bundle` beneath a custom config server's base URL. @@ -787,40 +692,6 @@ impl Client { .map_err(RequestError::from) } - /// Create a new task (user turn) by POSTing to the appropriate backend path - /// based on `path_style`. Returns the created task id. - pub async fn create_task(&self, request_body: serde_json::Value) -> Result { - let url = match self.path_style { - PathStyle::CodexApi => format!("{}/api/codex/tasks", self.base_url), - PathStyle::ChatGptApi => format!("{}/wham/tasks", self.base_url), - }; - let req = self - .request(Method::POST, &url) - .headers(self.headers().await?) - .header(CONTENT_TYPE, HeaderValue::from_static("application/json")) - .json(&request_body); - let (body, ct) = self.exec_request(req, "POST", &url).await?; - // Extract id from JSON: prefer `task.id`; fallback to top-level `id` when present. - match serde_json::from_str::(&body) { - Ok(v) => { - if let Some(id) = v - .get("task") - .and_then(|t| t.get("id")) - .and_then(|s| s.as_str()) - { - Ok(id.to_string()) - } else if let Some(id) = v.get("id").and_then(|s| s.as_str()) { - Ok(id.to_string()) - } else { - anyhow::bail!( - "POST {url} succeeded but no task id found; content-type={ct}; body={body}" - ); - } - } - Err(e) => anyhow::bail!("Decode error for {url}: {e}; content-type={ct}; body={body}"), - } - } - // rate limit helpers fn rate_limit_snapshots_from_payload( payload: RateLimitStatusPayload, diff --git a/codex-rs/backend-client/src/client_request_tests.rs b/codex-rs/backend-client/src/client_request_tests.rs index 0d89fb1bf8..a175cdff67 100644 --- a/codex-rs/backend-client/src/client_request_tests.rs +++ b/codex-rs/backend-client/src/client_request_tests.rs @@ -1,5 +1,4 @@ use std::io::BufRead; -use std::io::Read; use std::io::Write; use std::net::TcpListener; use std::process::Command; @@ -123,128 +122,6 @@ async fn client_preserves_supplied_factory_and_typed_policy_denial() { assert!(matches!(denied, Err(RequestError::Policy(_)))); } -#[test] -fn list_tasks_url_omits_empty_query_and_encodes_all_parameters() { - let client = Client::new( - "https://example.test", - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - ); - - assert_eq!( - client - .list_tasks_url( - /*limit*/ None, /*task_filter*/ None, /*environment_id*/ None, - /*cursor*/ None, - ) - .unwrap(), - "https://example.test/api/codex/tasks/list" - ); - assert_eq!( - client - .list_tasks_url( - /*limit*/ Some(10), - /*task_filter*/ Some("mine / shared"), - /*environment_id*/ Some("env&one"), - /*cursor*/ Some("next=page"), - ) - .unwrap(), - "https://example.test/api/codex/tasks/list?limit=10&task_filter=mine+%2F+shared&cursor=next%3Dpage&environment_id=env%26one" - ); -} - -#[tokio::test] -async fn migrated_requests_preserve_query_auth_and_json_body() { - let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("HTTP listener should bind"); - let address = listener - .local_addr() - .expect("HTTP listener should have an address"); - let server = std::thread::spawn(move || { - let mut requests = Vec::new(); - for body in [r#"{"items":[]}"#, r#"{"task":{"id":"task-created"}}"#] { - let (mut stream, _) = listener.accept().expect("HTTP listener should accept"); - stream - .set_read_timeout(Some(Duration::from_secs(2))) - .expect("HTTP stream should get a read timeout"); - let mut request = Vec::new(); - let mut buffer = [0_u8; 4096]; - loop { - let size = stream.read(&mut buffer).expect("HTTP request should read"); - if size == 0 { - break; - } - request.extend_from_slice(&buffer[..size]); - let Some(headers_end) = request.windows(4).position(|part| part == b"\r\n\r\n") - else { - continue; - }; - let headers = String::from_utf8_lossy(&request[..headers_end]); - let content_length = headers - .lines() - .find_map(|line| { - let (name, value) = line.split_once(':')?; - name.eq_ignore_ascii_case("content-length") - .then(|| value.trim().parse::().ok()) - .flatten() - }) - .unwrap_or(0); - if request.len() >= headers_end + 4 + content_length { - break; - } - } - requests.push(String::from_utf8(request).expect("request should be UTF-8")); - write!( - stream, - "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - ) - .expect("HTTP response should write"); - } - requests - }); - let client = Client::new( - format!("http://{address}"), - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - ) - .with_auth_provider(Arc::new(codex_model_provider::BearerAuthProvider::new( - "request-token".to_string(), - ))) - .unwrap(); - - let tasks = client - .list_tasks( - Some(10), - Some("mine / shared"), - Some("env&one"), - Some("next=page"), - ) - .await - .expect("list request should succeed"); - let task_id = client - .create_task(serde_json::json!({ "prompt": "hello" })) - .await - .expect("create request should succeed"); - let requests = server.join().expect("HTTP server should finish"); - - assert_eq!(tasks, PaginatedListTaskListItem::new(Vec::new())); - assert_eq!(task_id, "task-created"); - assert_eq!(requests.len(), 2); - assert!(requests[0].starts_with( - "GET /api/codex/tasks/list?limit=10&task_filter=mine+%2F+shared&cursor=next%3Dpage&environment_id=env%26one HTTP/1.1\r\n" - )); - assert!( - requests[0] - .to_ascii_lowercase() - .contains("authorization: bearer request-token\r\n") - ); - assert!(requests[1].starts_with("POST /api/codex/tasks HTTP/1.1\r\n")); - assert!( - requests[1] - .to_ascii_lowercase() - .contains("authorization: bearer request-token\r\n") - ); - assert!(requests[1].ends_with(r#"{"prompt":"hello"}"#)); -} - const BLOCKED_ORIGIN: &str = "http://127.0.0.1:0"; fn run_without_environment_proxies(test_name: &str) -> bool { diff --git a/codex-rs/backend-client/src/lib.rs b/codex-rs/backend-client/src/lib.rs index b0b5c4d136..f7cd1638f5 100644 --- a/codex-rs/backend-client/src/lib.rs +++ b/codex-rs/backend-client/src/lib.rs @@ -25,8 +25,6 @@ pub use client::turn_usage::ApiKeyTurnCost; pub use client::turn_usage::ApiKeyTurnCostStatus; pub use types::AccountEntry; pub use types::AccountsCheckResponse; -pub use types::CodeTaskDetailsResponse; -pub use types::CodeTaskDetailsResponseExt; pub use types::CodexUserSettingsResponse; pub use types::CodexWorkspaceMessage; pub use types::CodexWorkspaceMessageType; @@ -38,16 +36,13 @@ pub use types::DeliveredConfigToml; pub use types::DeliveredManagedLayers; pub use types::DeliveredRequirementsToml; pub use types::DeliveredTomlFragment; -pub use types::PaginatedListTaskListItem; pub use types::RateLimitResetCreditDetails; pub use types::RateLimitResetCreditsDetails; pub use types::RateLimitResetCreditsSummary; pub use types::RateLimitsWithResetCredits; -pub use types::TaskListItem; pub use types::TokenUsageProfile; pub use types::TokenUsageProfileDailyBucket; pub use types::TokenUsageProfileStats; -pub use types::TurnAttemptsSiblingTurnsResponse; pub use types::VoiceOption; pub use types::VoiceSettings; diff --git a/codex-rs/backend-client/src/types.rs b/codex-rs/backend-client/src/types.rs index 17d041ea63..4b81c5961e 100644 --- a/codex-rs/backend-client/src/types.rs +++ b/codex-rs/backend-client/src/types.rs @@ -4,14 +4,12 @@ pub use codex_backend_openapi_models::models::DeliveredConfigToml; pub use codex_backend_openapi_models::models::DeliveredManagedLayers; pub use codex_backend_openapi_models::models::DeliveredRequirementsToml; pub use codex_backend_openapi_models::models::DeliveredTomlFragment; -pub use codex_backend_openapi_models::models::PaginatedListTaskListItem; pub use codex_backend_openapi_models::models::PlanType; pub use codex_backend_openapi_models::models::RateLimitReachedKind; pub use codex_backend_openapi_models::models::RateLimitStatusDetails; pub use codex_backend_openapi_models::models::RateLimitStatusPayload; pub use codex_backend_openapi_models::models::RateLimitWindowSnapshot; pub use codex_backend_openapi_models::models::SpendControlLimitDetails; -pub use codex_backend_openapi_models::models::TaskListItem; use codex_protocol::protocol::RateLimitSnapshot; use serde::Deserialize; @@ -252,311 +250,6 @@ impl<'de> Deserialize<'de> for AccountsCheckResponse { } } -/// Hand-rolled models for the Cloud Tasks task-details response. -/// The generated OpenAPI models are pretty bad. This is a half-step -/// towards hand-rolling them. -#[derive(Clone, Debug, Deserialize)] -pub struct CodeTaskDetailsResponse { - #[serde(default)] - pub current_user_turn: Option, - #[serde(default)] - pub current_assistant_turn: Option, - #[serde(default)] - pub current_diff_task_turn: Option, -} - -#[derive(Clone, Debug, Default, Deserialize)] -pub struct Turn { - #[serde(default)] - pub id: Option, - #[serde(default)] - pub attempt_placement: Option, - #[serde(default, rename = "turn_status")] - pub turn_status: Option, - #[serde(default, deserialize_with = "deserialize_vec")] - pub sibling_turn_ids: Vec, - #[serde(default, deserialize_with = "deserialize_vec")] - pub input_items: Vec, - #[serde(default, deserialize_with = "deserialize_vec")] - pub output_items: Vec, - #[serde(default)] - pub worklog: Option, - #[serde(default)] - pub error: Option, -} - -#[derive(Clone, Debug, Default, Deserialize)] -pub struct TurnItem { - #[serde(rename = "type", default)] - pub kind: String, - #[serde(default)] - pub role: Option, - #[serde(default, deserialize_with = "deserialize_vec")] - pub content: Vec, - #[serde(default)] - pub diff: Option, - #[serde(default)] - pub output_diff: Option, -} - -#[derive(Clone, Debug, Deserialize)] -#[serde(untagged)] -pub enum ContentFragment { - Structured(StructuredContent), - Text(String), -} - -#[derive(Clone, Debug, Default, Deserialize)] -pub struct StructuredContent { - #[serde(rename = "content_type", default)] - pub content_type: Option, - #[serde(default)] - pub text: Option, -} - -#[derive(Clone, Debug, Default, Deserialize)] -pub struct DiffPayload { - #[serde(default)] - pub diff: Option, -} - -#[derive(Clone, Debug, Default, Deserialize)] -pub struct Worklog { - #[serde(default, deserialize_with = "deserialize_vec")] - pub messages: Vec, -} - -#[derive(Clone, Debug, Default, Deserialize)] -pub struct WorklogMessage { - #[serde(default)] - pub author: Option, - #[serde(default)] - pub content: Option, -} - -#[derive(Clone, Debug, Default, Deserialize)] -pub struct Author { - #[serde(default)] - pub role: Option, -} - -#[derive(Clone, Debug, Default, Deserialize)] -pub struct WorklogContent { - #[serde(default)] - pub parts: Vec, -} - -#[derive(Clone, Debug, Default, Deserialize)] -pub struct TurnError { - #[serde(default)] - pub code: Option, - #[serde(default)] - pub message: Option, -} - -impl ContentFragment { - fn text(&self) -> Option<&str> { - match self { - ContentFragment::Structured(inner) => { - if inner - .content_type - .as_deref() - .map(|ct| ct.eq_ignore_ascii_case("text")) - .unwrap_or(false) - { - inner.text.as_deref().filter(|s| !s.is_empty()) - } else { - None - } - } - ContentFragment::Text(raw) => { - if raw.trim().is_empty() { - None - } else { - Some(raw.as_str()) - } - } - } - } -} - -impl TurnItem { - fn text_values(&self) -> Vec { - self.content - .iter() - .filter_map(|fragment| fragment.text().map(str::to_string)) - .collect() - } - - fn diff_text(&self) -> Option { - if self.kind == "output_diff" { - if let Some(diff) = &self.diff - && !diff.is_empty() - { - return Some(diff.clone()); - } - } else if self.kind == "pr" - && let Some(payload) = &self.output_diff - && let Some(diff) = &payload.diff - && !diff.is_empty() - { - return Some(diff.clone()); - } - None - } -} - -impl Turn { - fn unified_diff(&self) -> Option { - self.output_items.iter().find_map(TurnItem::diff_text) - } - - fn message_texts(&self) -> Vec { - let mut out: Vec = self - .output_items - .iter() - .filter(|item| item.kind == "message") - .flat_map(TurnItem::text_values) - .collect(); - - if let Some(log) = &self.worklog { - for message in &log.messages { - if message.is_assistant() { - out.extend(message.text_values()); - } - } - } - - out - } - - fn user_prompt(&self) -> Option { - let parts: Vec = self - .input_items - .iter() - .filter(|item| item.kind == "message") - .filter(|item| { - item.role - .as_deref() - .map(|r| r.eq_ignore_ascii_case("user")) - .unwrap_or(true) - }) - .flat_map(TurnItem::text_values) - .collect(); - - if parts.is_empty() { - None - } else { - Some(parts.join( - " - -", - )) - } - } - - fn error_summary(&self) -> Option { - self.error.as_ref().and_then(TurnError::summary) - } -} - -impl WorklogMessage { - fn is_assistant(&self) -> bool { - self.author - .as_ref() - .and_then(|a| a.role.as_deref()) - .map(|role| role.eq_ignore_ascii_case("assistant")) - .unwrap_or(false) - } - - fn text_values(&self) -> Vec { - self.content - .as_ref() - .map(|content| { - content - .parts - .iter() - .filter_map(|fragment| fragment.text().map(str::to_string)) - .collect() - }) - .unwrap_or_default() - } -} - -impl TurnError { - fn summary(&self) -> Option { - let code = self.code.as_deref().unwrap_or(""); - let message = self.message.as_deref().unwrap_or(""); - match (code.is_empty(), message.is_empty()) { - (true, true) => None, - (false, true) => Some(code.to_string()), - (true, false) => Some(message.to_string()), - (false, false) => Some(format!("{code}: {message}")), - } - } -} - -pub trait CodeTaskDetailsResponseExt { - /// Attempt to extract a unified diff string from the assistant or diff turn. - fn unified_diff(&self) -> Option; - /// Extract assistant text output messages (no diff) from current turns. - fn assistant_text_messages(&self) -> Vec; - /// Extract the user's prompt text from the current user turn, when present. - fn user_text_prompt(&self) -> Option; - /// Extract an assistant error message (if the turn failed and provided one). - fn assistant_error_message(&self) -> Option; -} - -impl CodeTaskDetailsResponseExt for CodeTaskDetailsResponse { - fn unified_diff(&self) -> Option { - [ - self.current_diff_task_turn.as_ref(), - self.current_assistant_turn.as_ref(), - ] - .into_iter() - .flatten() - .find_map(Turn::unified_diff) - } - - fn assistant_text_messages(&self) -> Vec { - let mut out = Vec::new(); - for turn in [ - self.current_diff_task_turn.as_ref(), - self.current_assistant_turn.as_ref(), - ] - .into_iter() - .flatten() - { - out.extend(turn.message_texts()); - } - out - } - - fn user_text_prompt(&self) -> Option { - self.current_user_turn.as_ref().and_then(Turn::user_prompt) - } - - fn assistant_error_message(&self) -> Option { - self.current_assistant_turn - .as_ref() - .and_then(Turn::error_summary) - } -} - -fn deserialize_vec<'de, D, T>(deserializer: D) -> Result, D::Error> -where - D: Deserializer<'de>, - T: Deserialize<'de>, -{ - Option::>::deserialize(deserializer).map(Option::unwrap_or_default) -} - -#[derive(Clone, Debug, Deserialize)] -pub struct TurnAttemptsSiblingTurnsResponse { - #[serde(default)] - pub sibling_turns: Vec>, -} - #[derive(Clone, Debug, Deserialize, PartialEq, Eq)] pub struct TokenUsageProfile { pub stats: TokenUsageProfileStats, @@ -583,57 +276,6 @@ mod tests { use super::*; use pretty_assertions::assert_eq; - fn fixture(name: &str) -> CodeTaskDetailsResponse { - let json = match name { - "diff" => include_str!("../tests/fixtures/task_details_with_diff.json"), - "error" => include_str!("../tests/fixtures/task_details_with_error.json"), - other => panic!("unknown fixture {other}"), - }; - serde_json::from_str(json).expect("fixture should deserialize") - } - - #[test] - fn unified_diff_prefers_current_diff_task_turn() { - let details = fixture("diff"); - let diff = details.unified_diff().expect("diff present"); - assert!(diff.contains("diff --git")); - } - - #[test] - fn unified_diff_falls_back_to_pr_output_diff() { - let details = fixture("error"); - let diff = details.unified_diff().expect("diff from pr output"); - assert!(diff.contains("lib.rs")); - } - - #[test] - fn assistant_text_messages_extracts_text_content() { - let details = fixture("diff"); - let messages = details.assistant_text_messages(); - assert_eq!(messages, vec!["Assistant response".to_string()]); - } - - #[test] - fn user_text_prompt_joins_parts_with_spacing() { - let details = fixture("diff"); - let prompt = details.user_text_prompt().expect("prompt present"); - assert_eq!( - prompt, - "First line - -Second line" - ); - } - - #[test] - fn assistant_error_message_combines_code_and_message() { - let details = fixture("error"); - let msg = details - .assistant_error_message() - .expect("error should be present"); - assert_eq!(msg, "APPLY_FAILED: Patch could not be applied"); - } - #[test] fn workspace_messages_response_deserializes_messages() { let response: CodexWorkspaceMessagesResponse = serde_json::from_value(serde_json::json!({ diff --git a/codex-rs/backend-client/tests/fixtures/task_details_with_diff.json b/codex-rs/backend-client/tests/fixtures/task_details_with_diff.json deleted file mode 100644 index 3a06b04c1c..0000000000 --- a/codex-rs/backend-client/tests/fixtures/task_details_with_diff.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "task": { - "id": "task_123", - "title": "Refactor cloud task client", - "archived": false, - "external_pull_requests": [] - }, - "current_user_turn": { - "input_items": [ - { - "type": "message", - "role": "user", - "content": [ - { "content_type": "text", "text": "First line" }, - { "content_type": "text", "text": "Second line" } - ] - } - ] - }, - "current_assistant_turn": { - "output_items": [ - { - "type": "message", - "content": [ - { "content_type": "text", "text": "Assistant response" } - ] - } - ] - }, - "current_diff_task_turn": { - "output_items": [ - { - "type": "output_diff", - "diff": "diff --git a/src/main.rs b/src/main.rs\n+fn main() { println!(\"hi\"); }\n" - } - ] - } -} diff --git a/codex-rs/backend-client/tests/fixtures/task_details_with_error.json b/codex-rs/backend-client/tests/fixtures/task_details_with_error.json deleted file mode 100644 index 6f6b66a72c..0000000000 --- a/codex-rs/backend-client/tests/fixtures/task_details_with_error.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "task": { - "id": "task_456", - "title": "Investigate failure", - "archived": false, - "external_pull_requests": [] - }, - "current_assistant_turn": { - "output_items": [ - { - "type": "pr", - "output_diff": { - "diff": "diff --git a/lib.rs b/lib.rs\n+pub fn hello() {}\n" - } - } - ], - "error": { - "code": "APPLY_FAILED", - "message": "Patch could not be applied" - } - } -} diff --git a/codex-rs/chatgpt/Cargo.toml b/codex-rs/chatgpt/Cargo.toml index 158dda0311..4ac4b8450a 100644 --- a/codex-rs/chatgpt/Cargo.toml +++ b/codex-rs/chatgpt/Cargo.toml @@ -9,17 +9,14 @@ workspace = true [dependencies] anyhow = { workspace = true } -clap = { workspace = true, features = ["derive"] } codex-connectors = { workspace = true } codex-core = { workspace = true } codex-features = { workspace = true } codex-runtime-agent-instance = { workspace = true } -codex-git-utils = { workspace = true } codex-http-client = { workspace = true } codex-login = { workspace = true } codex-model-provider = { workspace = true } codex-plugin = { workspace = true } -codex-utils-cli = { workspace = true } serde = { workspace = true, features = ["derive"] } [dev-dependencies] @@ -27,11 +24,10 @@ codex-protocol = { workspace = true } base64 = { workspace = true } uuid = { workspace = true } wiremock = { workspace = true } -codex-utils-cargo-bin = { workspace = true } pretty_assertions = { workspace = true } serde_json = { workspace = true } tempfile = { workspace = true } -tokio = { workspace = true, features = ["fs", "macros", "process", "rt"] } +tokio = { workspace = true, features = ["macros", "rt"] } [lib] doctest = false diff --git a/codex-rs/chatgpt/src/apply_command.rs b/codex-rs/chatgpt/src/apply_command.rs deleted file mode 100644 index 70fe4481db..0000000000 --- a/codex-rs/chatgpt/src/apply_command.rs +++ /dev/null @@ -1,77 +0,0 @@ -use std::path::PathBuf; - -use clap::Parser; -use codex_core::config::Config; -use codex_git_utils::ApplyGitRequest; -use codex_git_utils::apply_git_patch; -use codex_utils_cli::CliConfigOverrides; - -use crate::get_task::GetTaskResponse; -use crate::get_task::OutputItem; -use crate::get_task::PrOutputItem; -use crate::get_task::get_task; - -/// Applies the latest diff from a Codex agent task. -#[derive(Debug, Parser)] -pub struct ApplyCommand { - pub task_id: String, - - #[clap(flatten)] - pub config_overrides: CliConfigOverrides, -} -pub async fn run_apply_command( - apply_cli: ApplyCommand, - cwd: Option, -) -> anyhow::Result<()> { - let config = Config::load_with_cli_overrides( - apply_cli - .config_overrides - .parse_overrides() - .map_err(anyhow::Error::msg)?, - ) - .await?; - - let task_response = get_task(&config, apply_cli.task_id).await?; - apply_diff_from_task(task_response, cwd).await -} - -pub async fn apply_diff_from_task( - task_response: GetTaskResponse, - cwd: Option, -) -> anyhow::Result<()> { - let diff_turn = match task_response.current_diff_task_turn { - Some(turn) => turn, - None => anyhow::bail!("No diff turn found"), - }; - let output_diff = diff_turn.output_items.iter().find_map(|item| match item { - OutputItem::Pr(PrOutputItem { output_diff }) => Some(output_diff), - _ => None, - }); - match output_diff { - Some(output_diff) => apply_diff(&output_diff.diff, cwd).await, - None => anyhow::bail!("No PR output item found"), - } -} - -async fn apply_diff(diff: &str, cwd: Option) -> anyhow::Result<()> { - let cwd = cwd.unwrap_or(std::env::current_dir().unwrap_or_else(|_| std::env::temp_dir())); - let req = ApplyGitRequest { - cwd, - diff: diff.to_string(), - revert: false, - preflight: false, - }; - let res = apply_git_patch(&req)?; - if res.exit_code != 0 { - anyhow::bail!( - "Git apply failed (applied={}, skipped={}, conflicts={})\nstdout:\n{}\nstderr:\n{}", - res.applied_paths.len(), - res.skipped_paths.len(), - res.conflicted_paths.len(), - res.stdout, - res.stderr - ); - } - println!("Successfully applied diff"); - Ok(()) -} diff --git a/codex-rs/chatgpt/src/chatgpt_client.rs b/codex-rs/chatgpt/src/chatgpt_client.rs index 1b0cfd3d66..0128917547 100644 --- a/codex-rs/chatgpt/src/chatgpt_client.rs +++ b/codex-rs/chatgpt/src/chatgpt_client.rs @@ -1,9 +1,7 @@ use codex_core::config::Config; -use codex_features::Feature; use codex_features::RuntimeAuthMode; use codex_http_client::HttpClient; use codex_http_client::HttpClientFactory; -use codex_login::AuthManager; use codex_login::CodexAuth; use codex_login::default_client::RESIDENCY_HEADER_NAME; use codex_login::default_client::create_client_with_chatgpt_cookies; @@ -54,56 +52,6 @@ fn chatgpt_client(factory: HttpClientFactory) -> HttpClient { client } -/// Make a GET request to the ChatGPT backend API. -pub(crate) async fn chatgpt_get_request( - config: &Config, - path: String, -) -> anyhow::Result { - let mut config = config.clone(); - let (auth, runtime) = standalone_auth(&mut config).await?; - chatgpt_get_request_with_timeout( - &config, - &auth, - runtime.as_ref(), - path, - /*timeout*/ None, - ) - .await -} - -pub(crate) async fn standalone_auth( - config: &mut Config, -) -> anyhow::Result<( - CodexAuth, - Option<(Arc, RuntimeAuthMode)>, -)> { - // Standalone commands create one owner. Freeze the caller's account policy before loading - // credentials; this temporary manager does not own later account changes. - config.application_network_policy = config - .application_network_policy - .clone() - .for_current_account(); - if config.features.enabled(Feature::RuntimeAgentInstances) { - codex_model_provider::validate_runtime_destination(Some(&config.chatgpt_base_url))?; - } - let auth_manager = - AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await?; - let runtime = if config.features.enabled(Feature::RuntimeAgentInstances) - && codex_runtime_agent_instance::is_openai_api_url(&config.chatgpt_base_url) - { - let installation_id = codex_core::resolve_installation_id(&config.codex_home).await?; - codex_core::build_runtime_auth_manager(config, auth_manager.clone(), &installation_id) - .map(|runtime| (runtime, config.runtime_auth_mode)) - } else { - None - }; - let auth = auth_manager - .auth() - .await - .ok_or_else(|| anyhow::anyhow!("ChatGPT auth not available"))?; - Ok((auth, runtime)) -} - pub(crate) async fn chatgpt_get_request_with_timeout( config: &Config, auth: &CodexAuth, diff --git a/codex-rs/chatgpt/src/chatgpt_client_runtime_auth_tests.rs b/codex-rs/chatgpt/src/chatgpt_client_runtime_auth_tests.rs index 65cfb3c5af..21155a9d46 100644 --- a/codex-rs/chatgpt/src/chatgpt_client_runtime_auth_tests.rs +++ b/codex-rs/chatgpt/src/chatgpt_client_runtime_auth_tests.rs @@ -2,7 +2,9 @@ use super::*; use base64::Engine; +use codex_features::Feature; use codex_features::RuntimeAuthMode; +use codex_login::AuthManager; use codex_runtime_agent_instance::AgentHostAuthorization; use codex_runtime_agent_instance::RuntimeAuthManager; use codex_runtime_agent_instance::RuntimeRegistrationMetadata; @@ -177,45 +179,6 @@ fn actor_token() -> String { format!("header.{claims}.signature") } -#[tokio::test] -async fn standalone_apply_keeps_custom_backend_auth_when_runtime_feature_is_enabled() { - let server = MockServer::start().await; - let token = actor_token(); - Mock::given(path("/task")) - .and(wiremock::matchers::header( - "authorization", - format!("Bearer {token}"), - )) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true}))) - .expect(1) - .mount(&server) - .await; - let home = tempfile::TempDir::new().unwrap(); - codex_login::auth::login_with_chatgpt_auth_tokens( - home.path(), - &token, - "workspace-a", - /*chatgpt_plan_type*/ None, - ) - .unwrap(); - let mut config = codex_core::config::ConfigBuilder::default() - .codex_home(home.path().to_path_buf()) - .build() - .await - .unwrap(); - config.chatgpt_base_url = server.uri(); - config - .features - .enable(Feature::RuntimeAgentInstances) - .unwrap(); - let response: serde_json::Value = chatgpt_get_request(&config, "task".into()).await.unwrap(); - assert_eq!(response, json!({"ok": true})); - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 1); - assert!(!requests[0].headers.contains_key("x-openai-agent-assertion")); - server.verify().await; -} - #[tokio::test] async fn connector_requests_reject_unsupported_openai_destinations() { for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { @@ -294,28 +257,3 @@ async fn connector_requests_reject_unsupported_openai_destinations() { } } } - -#[tokio::test] -async fn standalone_apply_rejects_unsupported_openai_destination() { - let home = tempfile::TempDir::new().unwrap(); - let mut config = codex_core::config::ConfigBuilder::default() - .codex_home(home.path().to_path_buf()) - .build() - .await - .unwrap(); - config.chatgpt_base_url = "https://future.openai.com/backend-api".into(); - config - .features - .enable(Feature::RuntimeAgentInstances) - .unwrap(); - - let error = chatgpt_get_request::(&config, "task".into()) - .await - .unwrap_err(); - assert!(matches!( - error - .downcast_ref::() - .map(codex_protocol::error::CodexErr::details), - Some(codex_protocol::error::CodexErrorDetails::UnsupportedOperation(_)) - )); -} diff --git a/codex-rs/chatgpt/src/get_task.rs b/codex-rs/chatgpt/src/get_task.rs deleted file mode 100644 index 9301ffc38d..0000000000 --- a/codex-rs/chatgpt/src/get_task.rs +++ /dev/null @@ -1,40 +0,0 @@ -use codex_core::config::Config; -use serde::Deserialize; - -use crate::chatgpt_client::chatgpt_get_request; - -#[derive(Debug, Deserialize)] -pub struct GetTaskResponse { - pub current_diff_task_turn: Option, -} - -// Only relevant fields for our extraction -#[derive(Debug, Deserialize)] -pub struct AssistantTurn { - pub output_items: Vec, -} - -#[derive(Debug, Deserialize)] -#[serde(tag = "type")] -pub enum OutputItem { - #[serde(rename = "pr")] - Pr(PrOutputItem), - - #[serde(other)] - Other, -} - -#[derive(Debug, Deserialize)] -pub struct PrOutputItem { - pub output_diff: OutputDiff, -} - -#[derive(Debug, Deserialize)] -pub struct OutputDiff { - pub diff: String, -} - -pub(crate) async fn get_task(config: &Config, task_id: String) -> anyhow::Result { - let path = format!("/wham/tasks/{task_id}"); - chatgpt_get_request(config, path).await -} diff --git a/codex-rs/chatgpt/src/lib.rs b/codex-rs/chatgpt/src/lib.rs index 5589621149..c849201169 100644 --- a/codex-rs/chatgpt/src/lib.rs +++ b/codex-rs/chatgpt/src/lib.rs @@ -1,6 +1,4 @@ #![recursion_limit = "256"] -pub mod apply_command; mod chatgpt_client; pub mod connectors; -pub mod get_task; diff --git a/codex-rs/chatgpt/tests/all.rs b/codex-rs/chatgpt/tests/all.rs deleted file mode 100644 index 7e136e4cce..0000000000 --- a/codex-rs/chatgpt/tests/all.rs +++ /dev/null @@ -1,3 +0,0 @@ -// Single integration test binary that aggregates all test modules. -// The submodules live in `tests/suite/`. -mod suite; diff --git a/codex-rs/chatgpt/tests/suite/apply_command_e2e.rs b/codex-rs/chatgpt/tests/suite/apply_command_e2e.rs deleted file mode 100644 index c2d570528c..0000000000 --- a/codex-rs/chatgpt/tests/suite/apply_command_e2e.rs +++ /dev/null @@ -1,188 +0,0 @@ -use codex_chatgpt::apply_command::apply_diff_from_task; -use codex_chatgpt::get_task::GetTaskResponse; -use codex_utils_cargo_bin::find_resource; -use tempfile::TempDir; -use tokio::process::Command; - -/// Creates a temporary git repository with initial commit -async fn create_temp_git_repo() -> anyhow::Result { - let temp_dir = TempDir::new()?; - let repo_path = temp_dir.path(); - let envs = vec![ - ("GIT_CONFIG_GLOBAL", "/dev/null"), - ("GIT_CONFIG_NOSYSTEM", "1"), - ]; - - let output = Command::new("git") - .envs(envs.clone()) - .args(["init"]) - .current_dir(repo_path) - .output() - .await?; - - if !output.status.success() { - anyhow::bail!( - "Failed to initialize git repo: {}", - String::from_utf8_lossy(&output.stderr) - ); - } - - Command::new("git") - .envs(envs.clone()) - .args(["config", "user.email", "test@example.com"]) - .current_dir(repo_path) - .output() - .await?; - - Command::new("git") - .envs(envs.clone()) - .args(["config", "user.name", "Test User"]) - .current_dir(repo_path) - .output() - .await?; - - std::fs::write(repo_path.join("README.md"), "# Test Repo\n")?; - - Command::new("git") - .envs(envs.clone()) - .args(["add", "README.md"]) - .current_dir(repo_path) - .output() - .await?; - - let output = Command::new("git") - .envs(envs.clone()) - .args(["commit", "-m", "Initial commit"]) - .current_dir(repo_path) - .output() - .await?; - - if !output.status.success() { - anyhow::bail!( - "Failed to create initial commit: {}", - String::from_utf8_lossy(&output.stderr) - ); - } - - Ok(temp_dir) -} - -async fn mock_get_task_with_fixture() -> anyhow::Result { - let fixture_path = find_resource!("tests/task_turn_fixture.json")?; - let fixture_content = tokio::fs::read_to_string(fixture_path).await?; - let response: GetTaskResponse = serde_json::from_str(&fixture_content)?; - Ok(response) -} - -#[tokio::test] -async fn test_apply_command_creates_fibonacci_file() { - let temp_repo = create_temp_git_repo() - .await - .expect("Failed to create temp git repo"); - let repo_path = temp_repo.path(); - - let task_response = mock_get_task_with_fixture() - .await - .expect("Failed to load fixture"); - - apply_diff_from_task(task_response, Some(repo_path.to_path_buf())) - .await - .expect("Failed to apply diff from task"); - - // Assert that fibonacci.js was created in scripts/ directory - let fibonacci_path = repo_path.join("scripts/fibonacci.js"); - assert!(fibonacci_path.exists(), "fibonacci.js was not created"); - - // Verify the file contents match expected - let contents = std::fs::read_to_string(&fibonacci_path).expect("Failed to read fibonacci.js"); - assert!( - contents.contains("function fibonacci(n)"), - "fibonacci.js doesn't contain expected function" - ); - assert!( - contents.contains("#!/usr/bin/env node"), - "fibonacci.js doesn't have shebang" - ); - assert!( - contents.contains("module.exports = fibonacci;"), - "fibonacci.js doesn't export function" - ); - - // Verify file has correct number of lines (31 as specified in fixture) - let line_count = contents.lines().count(); - assert_eq!( - line_count, 31, - "fibonacci.js should have 31 lines, got {line_count}", - ); -} - -#[tokio::test] -async fn test_apply_command_with_merge_conflicts() { - let temp_repo = create_temp_git_repo() - .await - .expect("Failed to create temp git repo"); - let repo_path = temp_repo.path(); - - // Create conflicting fibonacci.js file first - let scripts_dir = repo_path.join("scripts"); - std::fs::create_dir_all(&scripts_dir).expect("Failed to create scripts directory"); - - let conflicting_content = r#"#!/usr/bin/env node - -// This is a different fibonacci implementation -function fib(num) { - if (num <= 1) return num; - return fib(num - 1) + fib(num - 2); -} - -console.log("Running fibonacci..."); -console.log(fib(10)); -"#; - - let fibonacci_path = scripts_dir.join("fibonacci.js"); - std::fs::write(&fibonacci_path, conflicting_content).expect("Failed to write conflicting file"); - - Command::new("git") - .args(["add", "scripts/fibonacci.js"]) - .current_dir(repo_path) - .output() - .await - .expect("Failed to add fibonacci.js"); - - Command::new("git") - .args(["commit", "-m", "Add conflicting fibonacci implementation"]) - .current_dir(repo_path) - .output() - .await - .expect("Failed to commit conflicting file"); - - let original_dir = std::env::current_dir().expect("Failed to get current dir"); - std::env::set_current_dir(repo_path).expect("Failed to change directory"); - struct DirGuard(std::path::PathBuf); - impl Drop for DirGuard { - fn drop(&mut self) { - let _ = std::env::set_current_dir(&self.0); - } - } - let _guard = DirGuard(original_dir); - - let task_response = mock_get_task_with_fixture() - .await - .expect("Failed to load fixture"); - - let apply_result = apply_diff_from_task(task_response, Some(repo_path.to_path_buf())).await; - - assert!( - apply_result.is_err(), - "Expected apply to fail due to merge conflicts" - ); - - let contents = std::fs::read_to_string(&fibonacci_path).expect("Failed to read fibonacci.js"); - - assert!( - contents.contains("<<<<<<< HEAD") - || contents.contains("=======") - || contents.contains(">>>>>>> "), - "fibonacci.js should contain merge conflict markers, got: {contents}", - ); -} diff --git a/codex-rs/chatgpt/tests/suite/mod.rs b/codex-rs/chatgpt/tests/suite/mod.rs deleted file mode 100644 index 40b4a59a0d..0000000000 --- a/codex-rs/chatgpt/tests/suite/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -// Aggregates all former standalone integration tests as modules. -mod apply_command_e2e; diff --git a/codex-rs/chatgpt/tests/task_turn_fixture.json b/codex-rs/chatgpt/tests/task_turn_fixture.json deleted file mode 100644 index 3750f55039..0000000000 --- a/codex-rs/chatgpt/tests/task_turn_fixture.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "current_diff_task_turn": { - "output_items": [ - { - "type": "pr", - "pr_title": "Add fibonacci script", - "pr_message": "## Summary\n- add a basic Fibonacci script under `scripts/`\n\n## Testing\n- `node scripts/fibonacci.js 10`\n- `npm run lint` *(fails: next not found)*", - "output_diff": { - "type": "output_diff", - "repo_id": "/workspace/rddit-vercel", - "base_commit_sha": "1a2e9baf2ce2fdd0c126b47b1bcfd512de2a9f7b", - "diff": "diff --git a/scripts/fibonacci.js b/scripts/fibonacci.js\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..6c9fdfdbf8669b7968936411050525b995d0a9a6\n--- /dev/null\n+++ b/scripts/fibonacci.js\n@@ -0,0 +1,31 @@\n+#!/usr/bin/env node\n+\n+function fibonacci(n) {\n+ if (n < 0) {\n+ throw new Error(\"n must be non-negative\");\n+ }\n+ let a = 0;\n+ let b = 1;\n+ for (let i = 0; i < n; i++) {\n+ const next = a + b;\n+ a = b;\n+ b = next;\n+ }\n+ return a;\n+}\n+\n+function printUsage() {\n+ console.log(\"Usage: node scripts/fibonacci.js \");\n+}\n+\n+if (require.main === module) {\n+ const arg = process.argv[2];\n+ if (arg === undefined || isNaN(Number(arg))) {\n+ printUsage();\n+ process.exit(1);\n+ }\n+ const n = Number(arg);\n+ console.log(fibonacci(n));\n+}\n+\n+module.exports = fibonacci;\n", - "external_storage_diff": { - "file_id": "file_00000000114c61f786900f8c2130ace7", - "ttl": null - }, - "files_modified": 1, - "lines_added": 31, - "lines_removed": 0, - "commit_message": "Add fibonacci script" - } - }, - { - "type": "message", - "role": "assistant", - "content": [ - { - "content_type": "text", - "text": "**Summary**\n\n- Created a command-line Fibonacci script that validates input and prints the result when executed with Node" - }, - { - "content_type": "repo_file_citation", - "path": "scripts/fibonacci.js", - "line_range_start": 1, - "line_range_end": 31 - }, - { - "content_type": "text", - "text": "\n\n**Testing**\n\n- ❌ `npm run lint` (failed to run `next lint`)" - }, - { - "content_type": "terminal_chunk_citation", - "terminal_chunk_id": "7dd543", - "line_range_start": 1, - "line_range_end": 5 - }, - { - "content_type": "text", - "text": "\n- ✅ `node scripts/fibonacci.js 10` produced “55”" - }, - { - "content_type": "terminal_chunk_citation", - "terminal_chunk_id": "6ee559", - "line_range_start": 1, - "line_range_end": 3 - }, - { - "content_type": "text", - "text": "\n\nCodex couldn't run certain commands due to environment limitations. Consider configuring a setup script or internet access in your Codex environment to install dependencies." - } - ] - } - ] - } -} diff --git a/codex-rs/cli/Cargo.toml b/codex-rs/cli/Cargo.toml index 0a90b46866..d9e6453b8c 100644 --- a/codex-rs/cli/Cargo.toml +++ b/codex-rs/cli/Cargo.toml @@ -40,9 +40,7 @@ codex-app-server-test-client = { workspace = true } codex-arg0 = { workspace = true } codex-build-info = { workspace = true } codex-api = { workspace = true } -codex-chatgpt = { workspace = true } codex-cloud-config = { workspace = true } -codex-cloud-tasks = { path = "../cloud-tasks" } codex-utils-cli = { workspace = true } codex-config = { workspace = true } codex-core = { workspace = true } diff --git a/codex-rs/cli/src/config_override_args.rs b/codex-rs/cli/src/config_override_args.rs index bf87a77bde..5f7e87e70d 100644 --- a/codex-rs/cli/src/config_override_args.rs +++ b/codex-rs/cli/src/config_override_args.rs @@ -12,6 +12,27 @@ pub(super) fn try_parse_from( ) -> Result { let args: Vec = args.into_iter().map(Into::into).collect(); let mut command = MultitoolCli::command(); + // A retired command can otherwise become a prompt, even in `cloud exec work`. + // Let clap distinguish root prompts from option values and subcommand arguments. + for (index, arg) in args + .iter() + .enumerate() + .skip(1) + .take_while(|(_, arg)| *arg != "--") + { + if let Some(name @ ("cloud" | "cloud-tasks" | "apply" | "a")) = arg.to_str() + && let Ok(prefix) = command.clone().try_get_matches_from(&args[..=index]) + && prefix.subcommand().is_none() + && prefix + .get_one::("prompt") + .is_some_and(|prompt| prompt == name) + { + return Err(command.error( + clap::error::ErrorKind::InvalidSubcommand, + format!("unrecognized subcommand '{name}'"), + )); + } + } let mut matches = command.try_get_matches_from_mut(&args)?; crate::queue_cmd::validate_options(&command, &matches)?; let mut cli = MultitoolCli::from_arg_matches_mut(&mut matches) diff --git a/codex-rs/cli/src/config_override_args_tests.rs b/codex-rs/cli/src/config_override_args_tests.rs index 4818b128f3..f99f1a1b9c 100644 --- a/codex-rs/cli/src/config_override_args_tests.rs +++ b/codex-rs/cli/src/config_override_args_tests.rs @@ -5,6 +5,26 @@ use crate::Subcommand; use crate::mcp_cmd::McpSubcommand; use pretty_assertions::assert_eq; +#[test] +fn retired_command_names_require_an_explicit_root_prompt() { + for name in ["cloud", "cloud-tasks", "apply", "a"] { + for args in [ + vec!["codex", name], + vec!["codex", name, "--help"], + vec!["codex", name, "exec", "work"], + vec!["codex", "--remote", "cloud", name, "exec", "--help"], + ] { + assert_eq!( + try_parse_from(args).unwrap_err().kind(), + clap::error::ErrorKind::InvalidSubcommand, + ); + } + let cli = + try_parse_from(["codex", "--remote", "cloud", "--", name]).expect("explicit prompt"); + assert_eq!(cli.interactive.prompt.as_deref(), Some(name)); + } +} + #[test] fn preserves_scoped_overrides_and_forwarded_arguments() { let mut cli = try_parse_from([ diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index c10b225c52..d64c0a8181 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -8,8 +8,6 @@ use codex_app_server_daemon::LifecycleCommand as AppServerLifecycleCommand; use codex_app_server_daemon::RemoteControlMode as AppServerRemoteControlMode; use codex_arg0::Arg0DispatchPaths; use codex_arg0::arg0_dispatch_or_else; -use codex_chatgpt::apply_command::ApplyCommand; -use codex_chatgpt::apply_command::run_apply_command; use codex_cli::cloud_config; use codex_cli::read_access_token_from_stdin; use codex_cli::read_api_key_from_stdin; @@ -19,7 +17,6 @@ use codex_cli::run_login_with_api_key; use codex_cli::run_login_with_browser; use codex_cli::run_login_with_device_code; use codex_cli::run_logout; -use codex_cloud_tasks::Cli as CloudTasksCli; use codex_exec::Cli as ExecCli; use codex_exec::Command as ExecCommand; use codex_exec::ReviewArgs; @@ -203,10 +200,6 @@ enum Subcommand { #[clap(hide = true)] Execpolicy(ExecpolicyCommand), - /// Apply the latest diff produced by Codex agent as a `git apply` to your local working tree. - #[clap(visible_alias = "a")] - Apply(ApplyCommand), - /// Resume a previous interactive session (picker by default; use --last to continue the most recent). Resume(ResumeCommand), @@ -231,10 +224,6 @@ enum Subcommand { /// Fork a previous interactive session (picker by default; use --last to fork the most recent). Fork(ForkCommand), - /// [EXPERIMENTAL] Browse tasks from Codex Cloud and apply changes locally. - #[clap(name = "cloud", alias = "cloud-tasks")] - Cloud(CloudTasksCli), - /// Internal: run the responses API proxy. #[clap(hide = true)] ResponsesApiProxy(ResponsesApiProxyArgs), @@ -1809,19 +1798,6 @@ async fn dispatch_cli( ) .await?; } - Some(Subcommand::Cloud(mut cloud_cli)) => { - reject_remote_mode_for_subcommand( - root_remote.as_deref(), - root_remote_auth_token_env.as_deref(), - "cloud", - )?; - prepend_config_flags( - &mut cloud_cli.config_overrides, - root_config_overrides.clone(), - ); - codex_cloud_tasks::run_main(cloud_cli, arg0_paths.codex_linux_sandbox_exe.clone()) - .await?; - } Some(Subcommand::Sandbox(SandboxCommand { host: mut sandbox_cli, subcommand, @@ -1943,18 +1919,6 @@ async fn dispatch_cli( run_execpolicycheck(cmd)? } }, - Some(Subcommand::Apply(mut apply_cli)) => { - reject_remote_mode_for_subcommand( - root_remote.as_deref(), - root_remote_auth_token_env.as_deref(), - "apply", - )?; - prepend_config_flags( - &mut apply_cli.config_overrides, - root_config_overrides.clone(), - ); - run_apply_command(apply_cli, /*cwd*/ None).await?; - } Some(Subcommand::ResponsesApiProxy(args)) => { reject_remote_mode_for_subcommand( root_remote.as_deref(), @@ -2452,11 +2416,9 @@ fn unsupported_subcommand_name_for_strict_config( Some(Subcommand::Logout(_)) => Some("logout"), Some(Subcommand::Completion(_)) => Some("completion"), Some(Subcommand::Update) => Some("update"), - Some(Subcommand::Cloud(_)) => Some("cloud"), Some(Subcommand::Sandbox(_)) => Some("sandbox"), Some(Subcommand::Debug(_)) => Some("debug"), Some(Subcommand::Execpolicy(_)) => Some("execpolicy"), - Some(Subcommand::Apply(_)) => Some("apply"), Some(Subcommand::ResponsesApiProxy(_)) => Some("responses-api-proxy"), Some(Subcommand::Features(_)) => Some("features"), Some(Subcommand::TcpTunnel(_)) => Some("tcp-tunnel"), diff --git a/codex-rs/cli/tests/cloud_auth.rs b/codex-rs/cli/tests/cloud_auth.rs deleted file mode 100644 index a1c46efeea..0000000000 --- a/codex-rs/cli/tests/cloud_auth.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! Exercise Cloud credential isolation through the CLI using a synthetic login. - -use anyhow::Result; -use predicates::str::contains; -use serde_json::json; -use tempfile::TempDir; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::path; - -#[tokio::test] -async fn cloud_list_respects_the_credential_store_and_trusted_destinations() -> Result<()> { - let server = MockServer::start().await; - let codex_home = TempDir::new()?; - std::fs::write( - codex_home.path().join("config.toml"), - "cli_auth_credentials_store = 'file'\n", - )?; - std::fs::write( - codex_home.path().join("auth.json"), - serde_json::to_vec(&json!({ - "auth_mode": "chatgpt", - "tokens": { - "id_token": "eyJhbGciOiJub25lIn0.e30.c2ln", - "access_token": "synthetic-cloud-access-token", - "refresh_token": "synthetic-cloud-refresh-token", - "account_id": "synthetic-cloud-account", - }, - "last_refresh": chrono::Utc::now(), - }))?, - )?; - - let command = || -> Result { - let mut command = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?); - command - .current_dir(codex_home.path()) - .env("CODEX_HOME", codex_home.path()) - .env_remove("CODEX_ACCESS_TOKEN") - .env_remove("OPENAI_API_KEY") - .env_remove("CODEX_CLOUD_TASKS_MODE") - .env("NO_PROXY", "127.0.0.1,localhost") - .env("no_proxy", "127.0.0.1,localhost") - .timeout(std::time::Duration::from_secs(15)); - Ok(command) - }; - // Establish that the isolated profile has a usable ChatGPT login. - command()? - .args(["login", "status"]) - .assert() - .success() - .stderr(contains("Logged in using ChatGPT")); - - let output = command()? - .env( - "CODEX_CLOUD_TASKS_BASE_URL", - format!("{}/backend-api", server.uri()), - ) - .args(["cloud", "list", "--limit", "1", "--json"]) - .assert() - .failure() - .get_output() - .stderr - .clone(); - insta::assert_snapshot!(String::from_utf8(output)?, @"Error: CODEX_CLOUD_TASKS_BASE_URL must use a trusted HTTPS origin on port 443, without user information, a query, or a fragment; custom backends cannot use saved ChatGPT credentials"); - assert!(server.received_requests().await.unwrap().is_empty()); - - // An explicit ephemeral store must exclude the saved login for Cloud itself. - command()? - .env( - "CODEX_CLOUD_TASKS_BASE_URL", - "https://chatgpt-staging.com/backend-api", - ) - .env("HTTPS_PROXY", server.uri()) - .env("https_proxy", server.uri()) - .args([ - "-c", - "cli_auth_credentials_store='ephemeral'", - "cloud", - "list", - "--limit", - "1", - "--json", - ]) - .assert() - .failure() - .stderr(contains("Not signed in. Please run 'codex login'")); - assert!(server.received_requests().await.unwrap().is_empty()); - - // Staging must reach explicit PAT authentication. Reject the synthetic PAT locally so - // this test never sends a request to the real staging backend. - let auth_server = MockServer::start().await; - Mock::given(path("/v1/user-auth-credential/whoami")) - .and(header("authorization", "Bearer at-synthetic-cloud")) - .respond_with(ResponseTemplate::new(401)) - .expect(1) - .mount(&auth_server) - .await; - command()? - .env( - "CODEX_CLOUD_TASKS_BASE_URL", - "https://chatgpt-staging.com/backend-api", - ) - .env("CODEX_ACCESS_TOKEN", "at-synthetic-cloud") - .env("CODEX_AUTHAPI_BASE_URL", auth_server.uri()) - .args(["cloud", "list", "--limit", "1", "--json"]) - .assert() - .failure() - .stderr(contains("Not signed in. Please run 'codex login'")); - auth_server.verify().await; - Ok(()) -} diff --git a/codex-rs/cli/tests/daemon_startup.rs b/codex-rs/cli/tests/daemon_startup.rs index db178d0b23..1cbe968bec 100644 --- a/codex-rs/cli/tests/daemon_startup.rs +++ b/codex-rs/cli/tests/daemon_startup.rs @@ -274,7 +274,6 @@ model_providers.local = {{ name = "local", base_url = "{}/v1", wire_api = "respo "CODEX_EXEC_SERVER_URL", "CODEX_ACCESS_TOKEN", "CODEX_API_KEY", - "CODEX_CLOUD_TASKS_MODE", "OPENAI_API_KEY", "OPENAI_FEDERATION_RULE_ID", "OPENAI_IDENTITY_TOKEN_FILE", diff --git a/codex-rs/cli/tests/features.rs b/codex-rs/cli/tests/features.rs index 18b63355f9..5fd1c5fcb8 100644 --- a/codex-rs/cli/tests/features.rs +++ b/codex-rs/cli/tests/features.rs @@ -157,21 +157,6 @@ url = "ws://127.0.0.1:4512" Ok(()) } -#[test] -fn strict_config_is_not_supported_for_cloud_command() -> Result<()> { - let codex_home = TempDir::new()?; - - let mut cmd = codex_command(codex_home.path())?; - cmd.args(["--strict-config", "-c", "foo=bar", "cloud", "list"]) - .assert() - .failure() - .stderr(contains( - "`--strict-config` is not supported for `codex cloud`", - )); - - Ok(()) -} - #[tokio::test] async fn features_enable_writes_feature_flag_to_config() -> Result<()> { let codex_home = TempDir::new()?; diff --git a/codex-rs/cloud-tasks-client/BUILD.bazel b/codex-rs/cloud-tasks-client/BUILD.bazel deleted file mode 100644 index 83157266a5..0000000000 --- a/codex-rs/cloud-tasks-client/BUILD.bazel +++ /dev/null @@ -1,6 +0,0 @@ -load("//:defs.bzl", "codex_rust_crate") - -codex_rust_crate( - name = "cloud-tasks-client", - crate_name = "codex_cloud_tasks_client", -) diff --git a/codex-rs/cloud-tasks-client/Cargo.toml b/codex-rs/cloud-tasks-client/Cargo.toml deleted file mode 100644 index 8efd78cb22..0000000000 --- a/codex-rs/cloud-tasks-client/Cargo.toml +++ /dev/null @@ -1,25 +0,0 @@ -[package] -edition.workspace = true -license.workspace = true -name = "codex-cloud-tasks-client" -version.workspace = true - -[lib] -name = "codex_cloud_tasks_client" -path = "src/lib.rs" -test = false -doctest = false - -[lints] -workspace = true - -[dependencies] -anyhow = { workspace = true } -chrono = { workspace = true, features = ["serde"] } -codex-api = { workspace = true } -codex-backend-client = { workspace = true } -codex-git-utils = { workspace = true } -codex-http-client = { workspace = true } -serde = { version = "1", features = ["derive"] } -serde_json = { workspace = true } -thiserror = { workspace = true } diff --git a/codex-rs/cloud-tasks-client/src/api.rs b/codex-rs/cloud-tasks-client/src/api.rs deleted file mode 100644 index a9c75dedc6..0000000000 --- a/codex-rs/cloud-tasks-client/src/api.rs +++ /dev/null @@ -1,176 +0,0 @@ -use chrono::DateTime; -use chrono::Utc; -use serde::Deserialize; -use serde::Serialize; -use std::future::Future; -use std::pin::Pin; - -pub type Result = std::result::Result; -pub type CloudBackendFuture<'a, T> = Pin> + Send + 'a>>; - -#[derive(Debug, thiserror::Error)] -pub enum CloudTaskError { - #[error("unimplemented: {0}")] - Unimplemented(&'static str), - #[error("http error: {0}")] - Http(String), - #[error("io error: {0}")] - Io(String), - #[error("{0}")] - Msg(String), -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(transparent)] -pub struct TaskId(pub String); - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum TaskStatus { - Pending, - Ready, - Applied, - Error, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct TaskSummary { - pub id: TaskId, - pub title: String, - pub status: TaskStatus, - pub updated_at: DateTime, - /// Backend environment identifier (when available) - pub environment_id: Option, - /// Human-friendly environment label (when available) - pub environment_label: Option, - pub summary: DiffSummary, - /// True when the backend reports this task as a code review. - #[serde(default)] - pub is_review: bool, - /// Number of assistant attempts (best-of-N), when reported by the backend. - #[serde(default)] - pub attempt_total: Option, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -pub enum AttemptStatus { - Pending, - InProgress, - Completed, - Failed, - Cancelled, - #[default] - Unknown, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct TurnAttempt { - pub turn_id: String, - pub attempt_placement: Option, - pub created_at: Option>, - pub status: AttemptStatus, - pub diff: Option, - pub messages: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum ApplyStatus { - Success, - Partial, - Error, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct ApplyOutcome { - pub applied: bool, - pub status: ApplyStatus, - pub message: String, - #[serde(default)] - pub skipped_paths: Vec, - #[serde(default)] - pub conflict_paths: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct CreatedTask { - pub id: TaskId, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct TaskListPage { - pub tasks: Vec, - pub cursor: Option, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub struct DiffSummary { - pub files_changed: usize, - pub lines_added: usize, - pub lines_removed: usize, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct TaskText { - pub prompt: Option, - pub messages: Vec, - pub turn_id: Option, - pub sibling_turn_ids: Vec, - pub attempt_placement: Option, - pub attempt_status: AttemptStatus, -} - -impl Default for TaskText { - fn default() -> Self { - Self { - prompt: None, - messages: Vec::new(), - turn_id: None, - sibling_turn_ids: Vec::new(), - attempt_placement: None, - attempt_status: AttemptStatus::Unknown, - } - } -} - -pub trait CloudBackend: Send + Sync { - fn list_tasks<'a>( - &'a self, - env: Option<&'a str>, - limit: Option, - cursor: Option<&'a str>, - ) -> CloudBackendFuture<'a, TaskListPage>; - fn get_task_summary(&self, id: TaskId) -> CloudBackendFuture<'_, TaskSummary>; - fn get_task_diff(&self, id: TaskId) -> CloudBackendFuture<'_, Option>; - /// Return assistant output messages (no diff) when available. - fn get_task_messages(&self, id: TaskId) -> CloudBackendFuture<'_, Vec>; - /// Return the creating prompt and assistant messages (when available). - fn get_task_text(&self, id: TaskId) -> CloudBackendFuture<'_, TaskText>; - /// Return any sibling attempts (best-of-N) for the given assistant turn. - fn list_sibling_attempts( - &self, - task: TaskId, - turn_id: String, - ) -> CloudBackendFuture<'_, Vec>; - /// Dry-run apply (preflight) that validates whether the patch would apply cleanly. - /// Never modifies the working tree. When `diff_override` is supplied, the provided diff is - /// used instead of re-fetching the task details so callers can apply alternate attempts. - fn apply_task_preflight( - &self, - id: TaskId, - diff_override: Option, - ) -> CloudBackendFuture<'_, ApplyOutcome>; - fn apply_task( - &self, - id: TaskId, - diff_override: Option, - ) -> CloudBackendFuture<'_, ApplyOutcome>; - fn create_task<'a>( - &'a self, - env_id: &'a str, - prompt: &'a str, - git_ref: &'a str, - qa_mode: bool, - best_of_n: usize, - ) -> CloudBackendFuture<'a, CreatedTask>; -} diff --git a/codex-rs/cloud-tasks-client/src/http.rs b/codex-rs/cloud-tasks-client/src/http.rs deleted file mode 100644 index b6ea46bbf9..0000000000 --- a/codex-rs/cloud-tasks-client/src/http.rs +++ /dev/null @@ -1,929 +0,0 @@ -use crate::ApplyOutcome; -use crate::ApplyStatus; -use crate::AttemptStatus; -use crate::CloudBackend; -use crate::CloudBackendFuture; -use crate::CloudTaskError; -use crate::DiffSummary; -use crate::Result; -use crate::TaskId; -use crate::TaskListPage; -use crate::TaskStatus; -use crate::TaskSummary; -use crate::TurnAttempt; -use crate::api::TaskText; -use chrono::DateTime; -use chrono::Utc; - -use codex_api::SharedAuthProvider; -use codex_backend_client as backend; -use codex_backend_client::CodeTaskDetailsResponseExt; -use codex_git_utils::ApplyGitRequest; -use codex_git_utils::apply_git_patch; - -#[derive(Clone)] -pub struct HttpClient { - pub base_url: String, - backend: backend::Client, -} - -impl HttpClient { - pub fn new( - base_url: impl Into, - http_client_factory: codex_http_client::HttpClientFactory, - ) -> Self { - let base_url = base_url.into(); - let backend = backend::Client::new_without_redirects(base_url.clone(), http_client_factory); - Self { base_url, backend } - } - - pub fn from_backend(base_url: String, backend: backend::Client) -> Self { - Self { base_url, backend } - } - - pub fn with_user_agent(mut self, ua: impl Into) -> Self { - self.backend = self.backend.clone().with_user_agent(ua); - self - } - - pub fn with_auth_provider(mut self, auth: SharedAuthProvider) -> Result { - self.backend = self - .backend - .clone() - .with_auth_provider(auth) - .map_err(|error| CloudTaskError::Msg(error.to_string()))?; - Ok(self) - } - - pub fn with_chatgpt_account_id(mut self, account_id: impl Into) -> Self { - self.backend = self.backend.clone().with_chatgpt_account_id(account_id); - self - } - - fn tasks_api(&self) -> api::Tasks<'_> { - api::Tasks::new(self) - } - - fn attempts_api(&self) -> api::Attempts<'_> { - api::Attempts::new(self) - } - - fn apply_api(&self) -> api::Apply<'_> { - api::Apply::new(self) - } -} - -impl CloudBackend for HttpClient { - fn list_tasks<'a>( - &'a self, - env: Option<&'a str>, - limit: Option, - cursor: Option<&'a str>, - ) -> CloudBackendFuture<'a, TaskListPage> { - Box::pin(async move { self.tasks_api().list(env, limit, cursor).await }) - } - - fn get_task_summary(&self, id: TaskId) -> CloudBackendFuture<'_, TaskSummary> { - Box::pin(async move { self.tasks_api().summary(id).await }) - } - - fn get_task_diff(&self, id: TaskId) -> CloudBackendFuture<'_, Option> { - Box::pin(async move { self.tasks_api().diff(id).await }) - } - - fn get_task_messages(&self, id: TaskId) -> CloudBackendFuture<'_, Vec> { - Box::pin(async move { self.tasks_api().messages(id).await }) - } - - fn get_task_text(&self, id: TaskId) -> CloudBackendFuture<'_, TaskText> { - Box::pin(async move { self.tasks_api().task_text(id).await }) - } - - fn list_sibling_attempts( - &self, - task: TaskId, - turn_id: String, - ) -> CloudBackendFuture<'_, Vec> { - Box::pin(async move { self.attempts_api().list(task, turn_id).await }) - } - - fn apply_task( - &self, - id: TaskId, - diff_override: Option, - ) -> CloudBackendFuture<'_, ApplyOutcome> { - Box::pin(async move { - self.apply_api() - .run(id, diff_override, /*preflight*/ false) - .await - }) - } - - fn apply_task_preflight( - &self, - id: TaskId, - diff_override: Option, - ) -> CloudBackendFuture<'_, ApplyOutcome> { - Box::pin(async move { - self.apply_api() - .run(id, diff_override, /*preflight*/ true) - .await - }) - } - - fn create_task<'a>( - &'a self, - env_id: &'a str, - prompt: &'a str, - git_ref: &'a str, - qa_mode: bool, - best_of_n: usize, - ) -> CloudBackendFuture<'a, crate::CreatedTask> { - Box::pin(async move { - self.tasks_api() - .create(env_id, prompt, git_ref, qa_mode, best_of_n) - .await - }) - } -} - -mod api { - use super::*; - use serde_json::Value; - use std::cmp::Ordering; - use std::collections::HashMap; - - pub(crate) struct Tasks<'a> { - base_url: &'a str, - backend: &'a backend::Client, - } - - impl<'a> Tasks<'a> { - pub(crate) fn new(client: &'a HttpClient) -> Self { - Self { - base_url: &client.base_url, - backend: &client.backend, - } - } - - pub(crate) async fn list( - &self, - env: Option<&str>, - limit: Option, - cursor: Option<&str>, - ) -> Result { - let limit_i32 = limit.and_then(|lim| i32::try_from(lim).ok()); - let resp = self - .backend - .list_tasks(limit_i32, Some("current"), env, cursor) - .await - .map_err(|e| CloudTaskError::Http(format!("list_tasks failed: {e}")))?; - - let tasks: Vec = resp - .items - .into_iter() - .map(map_task_list_item_to_summary) - .collect(); - - append_error_log(&format!( - "http.list_tasks: env={} limit={} cursor_in={} cursor_out={} items={}", - env.unwrap_or(""), - limit_i32 - .map(|v| v.to_string()) - .unwrap_or_else(|| "".to_string()), - cursor.unwrap_or(""), - resp.cursor.as_deref().unwrap_or(""), - tasks.len() - )); - Ok(TaskListPage { - tasks, - cursor: resp.cursor, - }) - } - - pub(crate) async fn summary(&self, id: TaskId) -> Result { - let id_str = id.0.clone(); - let (details, body, ct) = self - .details_with_body(&id.0) - .await - .map_err(|e| CloudTaskError::Http(format!("get_task_details failed: {e}")))?; - let parsed: Value = serde_json::from_str(&body).map_err(|e| { - CloudTaskError::Http(format!( - "Decode error for {}: {e}; content-type={ct}; body={body}", - id.0 - )) - })?; - let task_obj = parsed - .get("task") - .and_then(Value::as_object) - .ok_or_else(|| { - CloudTaskError::Http(format!("Task metadata missing from details for {id_str}")) - })?; - let status_display = parsed - .get("task_status_display") - .or_else(|| task_obj.get("task_status_display")) - .and_then(Value::as_object) - .map(|m| { - m.iter() - .map(|(k, v)| (k.clone(), v.clone())) - .collect::>() - }); - let status = map_status(status_display.as_ref()); - let mut summary = diff_summary_from_status_display(status_display.as_ref()); - if summary.files_changed == 0 - && summary.lines_added == 0 - && summary.lines_removed == 0 - && let Some(diff) = details.unified_diff() - { - summary = diff_summary_from_diff(&diff); - } - let updated_at_raw = task_obj - .get("updated_at") - .and_then(Value::as_f64) - .or_else(|| task_obj.get("created_at").and_then(Value::as_f64)) - .or_else(|| latest_turn_timestamp(status_display.as_ref())); - let environment_id = task_obj - .get("environment_id") - .and_then(Value::as_str) - .map(str::to_string); - let environment_label = env_label_from_status_display(status_display.as_ref()); - let attempt_total = attempt_total_from_status_display(status_display.as_ref()); - let title = task_obj - .get("title") - .and_then(Value::as_str) - .unwrap_or("") - .to_string(); - let is_review = task_obj - .get("is_review") - .and_then(Value::as_bool) - .unwrap_or(false); - Ok(TaskSummary { - id, - title, - status, - updated_at: parse_updated_at(updated_at_raw.as_ref()), - environment_id, - environment_label, - summary, - is_review, - attempt_total, - }) - } - - pub(crate) async fn diff(&self, id: TaskId) -> Result> { - let (details, body, ct) = self - .details_with_body(&id.0) - .await - .map_err(|e| CloudTaskError::Http(format!("get_task_details failed: {e}")))?; - if let Some(diff) = details.unified_diff() { - return Ok(Some(diff)); - } - let _ = (body, ct); - Ok(None) - } - - pub(crate) async fn messages(&self, id: TaskId) -> Result> { - let (details, body, ct) = self - .details_with_body(&id.0) - .await - .map_err(|e| CloudTaskError::Http(format!("get_task_details failed: {e}")))?; - - let mut msgs = details.assistant_text_messages(); - if msgs.is_empty() { - msgs.extend(extract_assistant_messages_from_body(&body)); - } - if !msgs.is_empty() { - return Ok(msgs); - } - if let Some(err) = details.assistant_error_message() { - return Ok(vec![format!("Task failed: {err}")]); - } - - let url = match details_path(self.base_url, &id.0) { - Some(url) => url, - None => format!("{}/api/codex/tasks/{}", self.base_url, id.0), - }; - Err(CloudTaskError::Http(format!( - "No assistant text messages in response. GET {url}; content-type={ct}; body={body}" - ))) - } - - pub(crate) async fn task_text(&self, id: TaskId) -> Result { - let (details, body, _ct) = self - .details_with_body(&id.0) - .await - .map_err(|e| CloudTaskError::Http(format!("get_task_details failed: {e}")))?; - let prompt = details.user_text_prompt(); - let mut messages = details.assistant_text_messages(); - if messages.is_empty() { - messages.extend(extract_assistant_messages_from_body(&body)); - } - let assistant_turn = details.current_assistant_turn.as_ref(); - let turn_id = assistant_turn.and_then(|turn| turn.id.clone()); - let sibling_turn_ids = assistant_turn - .map(|turn| turn.sibling_turn_ids.clone()) - .unwrap_or_default(); - let attempt_placement = assistant_turn.and_then(|turn| turn.attempt_placement); - let attempt_status = attempt_status_from_str( - assistant_turn.and_then(|turn| turn.turn_status.as_deref()), - ); - Ok(TaskText { - prompt, - messages, - turn_id, - sibling_turn_ids, - attempt_placement, - attempt_status, - }) - } - - pub(crate) async fn create( - &self, - env_id: &str, - prompt: &str, - git_ref: &str, - qa_mode: bool, - best_of_n: usize, - ) -> Result { - let mut input_items: Vec = Vec::new(); - input_items.push(serde_json::json!({ - "type": "message", - "role": "user", - "content": [{ "content_type": "text", "text": prompt }] - })); - - if let Ok(diff) = std::env::var("CODEX_STARTING_DIFF") - && !diff.is_empty() - { - input_items.push(serde_json::json!({ - "type": "pre_apply_patch", - "output_diff": { "diff": diff } - })); - } - - let mut request_body = serde_json::json!({ - "new_task": { - "environment_id": env_id, - "branch": git_ref, - "run_environment_in_qa_mode": qa_mode, - }, - "input_items": input_items, - }); - - if best_of_n > 1 - && let Some(obj) = request_body.as_object_mut() - { - obj.insert( - "metadata".to_string(), - serde_json::json!({ "best_of_n": best_of_n }), - ); - } - - match self.backend.create_task(request_body).await { - Ok(id) => { - append_error_log(&format!( - "new_task: created id={id} env={} prompt_chars={}", - env_id, - prompt.chars().count() - )); - Ok(crate::CreatedTask { id: TaskId(id) }) - } - Err(e) => { - append_error_log(&format!( - "new_task: create failed env={} prompt_chars={}: {}", - env_id, - prompt.chars().count(), - e - )); - Err(CloudTaskError::Http(format!("create_task failed: {e}"))) - } - } - } - - async fn details_with_body( - &self, - id: &str, - ) -> anyhow::Result<(backend::CodeTaskDetailsResponse, String, String)> { - let (parsed, body, ct) = self.backend.get_task_details_with_body(id).await?; - Ok((parsed, body, ct)) - } - } - - pub(crate) struct Attempts<'a> { - backend: &'a backend::Client, - } - - impl<'a> Attempts<'a> { - pub(crate) fn new(client: &'a HttpClient) -> Self { - Self { - backend: &client.backend, - } - } - - pub(crate) async fn list(&self, task: TaskId, turn_id: String) -> Result> { - let resp = self - .backend - .list_sibling_turns(&task.0, &turn_id) - .await - .map_err(|e| CloudTaskError::Http(format!("list_sibling_turns failed: {e}")))?; - - let mut attempts: Vec = resp - .sibling_turns - .iter() - .filter_map(turn_attempt_from_map) - .collect(); - attempts.sort_by(compare_attempts); - Ok(attempts) - } - } - - pub(crate) struct Apply<'a> { - backend: &'a backend::Client, - } - - impl<'a> Apply<'a> { - pub(crate) fn new(client: &'a HttpClient) -> Self { - Self { - backend: &client.backend, - } - } - - pub(crate) async fn run( - &self, - task_id: TaskId, - diff_override: Option, - preflight: bool, - ) -> Result { - let id = task_id.0.clone(); - let diff = match diff_override { - Some(diff) => diff, - None => { - let details = self.backend.get_task_details(&id).await.map_err(|e| { - CloudTaskError::Http(format!("get_task_details failed: {e}")) - })?; - details.unified_diff().ok_or_else(|| { - CloudTaskError::Msg(format!("No diff available for task {id}")) - })? - } - }; - - if !is_unified_diff(&diff) { - let summary = summarize_patch_for_logging(&diff); - let mode = if preflight { "preflight" } else { "apply" }; - append_error_log(&format!( - "apply_error: id={id} mode={mode} format=non-unified; {summary}" - )); - return Ok(ApplyOutcome { - applied: false, - status: ApplyStatus::Error, - message: "Expected unified git diff; backend returned an incompatible format." - .to_string(), - skipped_paths: Vec::new(), - conflict_paths: Vec::new(), - }); - } - - let req = ApplyGitRequest { - cwd: std::env::current_dir().unwrap_or_else(|_| std::env::temp_dir()), - diff: diff.clone(), - revert: false, - preflight, - }; - let r = apply_git_patch(&req) - .map_err(|e| CloudTaskError::Io(format!("git apply failed to run: {e}")))?; - - let status = if r.exit_code == 0 { - ApplyStatus::Success - } else if !r.applied_paths.is_empty() || !r.conflicted_paths.is_empty() { - ApplyStatus::Partial - } else { - ApplyStatus::Error - }; - let applied = matches!(status, ApplyStatus::Success) && !preflight; - - let message = if preflight { - match status { - ApplyStatus::Success => { - format!("Preflight passed for task {id} (applies cleanly)") - } - ApplyStatus::Partial => format!( - "Preflight: patch does not fully apply for task {id} (applied={}, skipped={}, conflicts={})", - r.applied_paths.len(), - r.skipped_paths.len(), - r.conflicted_paths.len() - ), - ApplyStatus::Error => format!( - "Preflight failed for task {id} (applied={}, skipped={}, conflicts={})", - r.applied_paths.len(), - r.skipped_paths.len(), - r.conflicted_paths.len() - ), - } - } else { - match status { - ApplyStatus::Success => format!( - "Applied task {id} locally ({} files)", - r.applied_paths.len() - ), - ApplyStatus::Partial => format!( - "Apply partially succeeded for task {id} (applied={}, skipped={}, conflicts={})", - r.applied_paths.len(), - r.skipped_paths.len(), - r.conflicted_paths.len() - ), - ApplyStatus::Error => format!( - "Apply failed for task {id} (applied={}, skipped={}, conflicts={})", - r.applied_paths.len(), - r.skipped_paths.len(), - r.conflicted_paths.len() - ), - } - }; - - if matches!(status, ApplyStatus::Partial | ApplyStatus::Error) - || (preflight && !matches!(status, ApplyStatus::Success)) - { - let mut log = String::new(); - let summary = summarize_patch_for_logging(&diff); - let mode = if preflight { "preflight" } else { "apply" }; - use std::fmt::Write as _; - let _ = writeln!( - &mut log, - "apply_result: mode={} id={} status={:?} applied={} skipped={} conflicts={} cmd={}", - mode, - id, - status, - r.applied_paths.len(), - r.skipped_paths.len(), - r.conflicted_paths.len(), - r.cmd_for_log - ); - let _ = writeln!( - &mut log, - "stdout_tail=\n{}\nstderr_tail=\n{}", - tail(&r.stdout, /*max*/ 2000), - tail(&r.stderr, /*max*/ 2000) - ); - let _ = writeln!(&mut log, "{summary}"); - let _ = writeln!( - &mut log, - "----- PATCH BEGIN -----\n{diff}\n----- PATCH END -----" - ); - append_error_log(&log); - } - - Ok(ApplyOutcome { - applied, - status, - message, - skipped_paths: r.skipped_paths, - conflict_paths: r.conflicted_paths, - }) - } - } - - fn details_path(base_url: &str, id: &str) -> Option { - if base_url.contains("/backend-api") { - Some(format!("{base_url}/wham/tasks/{id}")) - } else if base_url.contains("/api/codex") { - Some(format!("{base_url}/tasks/{id}")) - } else { - None - } - } - - fn extract_assistant_messages_from_body(body: &str) -> Vec { - let mut msgs = Vec::new(); - if let Ok(full) = serde_json::from_str::(body) - && let Some(arr) = full - .get("current_assistant_turn") - .and_then(|v| v.get("worklog")) - .and_then(|v| v.get("messages")) - .and_then(|v| v.as_array()) - { - for m in arr { - let is_assistant = m - .get("author") - .and_then(|a| a.get("role")) - .and_then(|r| r.as_str()) - == Some("assistant"); - if !is_assistant { - continue; - } - if let Some(parts) = m - .get("content") - .and_then(|c| c.get("parts")) - .and_then(|p| p.as_array()) - { - for p in parts { - if let Some(s) = p.as_str() { - if !s.is_empty() { - msgs.push(s.to_string()); - } - continue; - } - if let Some(obj) = p.as_object() - && obj.get("content_type").and_then(|t| t.as_str()) == Some("text") - && let Some(txt) = obj.get("text").and_then(|t| t.as_str()) - { - msgs.push(txt.to_string()); - } - } - } - } - } - msgs - } - - fn turn_attempt_from_map(turn: &HashMap) -> Option { - let turn_id = turn.get("id").and_then(Value::as_str)?.to_string(); - let attempt_placement = turn.get("attempt_placement").and_then(Value::as_i64); - let created_at = parse_timestamp_value(turn.get("created_at")); - let status = attempt_status_from_str(turn.get("turn_status").and_then(Value::as_str)); - let diff = extract_diff_from_turn(turn); - let messages = extract_assistant_messages_from_turn(turn); - Some(TurnAttempt { - turn_id, - attempt_placement, - created_at, - status, - diff, - messages, - }) - } - - fn compare_attempts(a: &TurnAttempt, b: &TurnAttempt) -> Ordering { - match (a.attempt_placement, b.attempt_placement) { - (Some(lhs), Some(rhs)) => lhs.cmp(&rhs), - (Some(_), None) => Ordering::Less, - (None, Some(_)) => Ordering::Greater, - (None, None) => match (a.created_at, b.created_at) { - (Some(lhs), Some(rhs)) => lhs.cmp(&rhs), - (Some(_), None) => Ordering::Less, - (None, Some(_)) => Ordering::Greater, - (None, None) => a.turn_id.cmp(&b.turn_id), - }, - } - } - - fn extract_diff_from_turn(turn: &HashMap) -> Option { - let items = turn.get("output_items").and_then(Value::as_array)?; - for item in items { - match item.get("type").and_then(Value::as_str) { - Some("output_diff") => { - if let Some(diff) = item.get("diff").and_then(Value::as_str) - && !diff.is_empty() - { - return Some(diff.to_string()); - } - } - Some("pr") => { - if let Some(diff) = item - .get("output_diff") - .and_then(Value::as_object) - .and_then(|od| od.get("diff")) - .and_then(Value::as_str) - && !diff.is_empty() - { - return Some(diff.to_string()); - } - } - _ => {} - } - } - None - } - - fn extract_assistant_messages_from_turn(turn: &HashMap) -> Vec { - let mut msgs = Vec::new(); - if let Some(items) = turn.get("output_items").and_then(Value::as_array) { - for item in items { - if item.get("type").and_then(Value::as_str) != Some("message") { - continue; - } - if let Some(content) = item.get("content").and_then(Value::as_array) { - for part in content { - if part.get("content_type").and_then(Value::as_str) == Some("text") - && let Some(txt) = part.get("text").and_then(Value::as_str) - && !txt.is_empty() - { - msgs.push(txt.to_string()); - } - } - } - } - } - msgs - } - - fn attempt_status_from_str(raw: Option<&str>) -> AttemptStatus { - match raw.unwrap_or_default() { - "failed" => AttemptStatus::Failed, - "completed" => AttemptStatus::Completed, - "in_progress" => AttemptStatus::InProgress, - "pending" => AttemptStatus::Pending, - _ => AttemptStatus::Pending, - } - } - - fn parse_timestamp_value(v: Option<&Value>) -> Option> { - let ts = v?.as_f64()?; - let secs = ts as i64; - let nanos = ((ts - secs as f64) * 1_000_000_000.0) as u32; - Some(DateTime::::from( - std::time::UNIX_EPOCH + std::time::Duration::new(secs.max(0) as u64, nanos), - )) - } - - fn map_task_list_item_to_summary(src: backend::TaskListItem) -> TaskSummary { - let status_display = src.task_status_display.as_ref(); - TaskSummary { - id: TaskId(src.id), - title: src.title, - status: map_status(status_display), - updated_at: parse_updated_at(src.updated_at.as_ref()), - environment_id: None, - environment_label: env_label_from_status_display(status_display), - summary: diff_summary_from_status_display(status_display), - is_review: src - .pull_requests - .as_ref() - .is_some_and(|prs| !prs.is_empty()), - attempt_total: attempt_total_from_status_display(status_display), - } - } - - fn map_status(v: Option<&HashMap>) -> TaskStatus { - if let Some(val) = v { - if let Some(turn) = val - .get("latest_turn_status_display") - .and_then(Value::as_object) - && let Some(s) = turn.get("turn_status").and_then(Value::as_str) - { - return match s { - "failed" => TaskStatus::Error, - "completed" => TaskStatus::Ready, - "in_progress" => TaskStatus::Pending, - "pending" => TaskStatus::Pending, - "cancelled" => TaskStatus::Error, - _ => TaskStatus::Pending, - }; - } - if let Some(state) = val.get("state").and_then(Value::as_str) { - return match state { - "pending" => TaskStatus::Pending, - "ready" => TaskStatus::Ready, - "applied" => TaskStatus::Applied, - "error" => TaskStatus::Error, - _ => TaskStatus::Pending, - }; - } - } - TaskStatus::Pending - } - - fn parse_updated_at(ts: Option<&f64>) -> DateTime { - if let Some(v) = ts { - let secs = *v as i64; - let nanos = ((*v - secs as f64) * 1_000_000_000.0) as u32; - return DateTime::::from( - std::time::UNIX_EPOCH + std::time::Duration::new(secs.max(0) as u64, nanos), - ); - } - Utc::now() - } - - fn env_label_from_status_display(v: Option<&HashMap>) -> Option { - let map = v?; - map.get("environment_label") - .and_then(Value::as_str) - .map(str::to_string) - } - - fn diff_summary_from_diff(diff: &str) -> DiffSummary { - let mut files_changed = 0usize; - let mut lines_added = 0usize; - let mut lines_removed = 0usize; - for line in diff.lines() { - if line.starts_with("diff --git ") { - files_changed += 1; - continue; - } - if line.starts_with("+++") || line.starts_with("---") || line.starts_with("@@") { - continue; - } - match line.as_bytes().first() { - Some(b'+') => lines_added += 1, - Some(b'-') => lines_removed += 1, - _ => {} - } - } - if files_changed == 0 && !diff.trim().is_empty() { - files_changed = 1; - } - DiffSummary { - files_changed, - lines_added, - lines_removed, - } - } - - fn diff_summary_from_status_display(v: Option<&HashMap>) -> DiffSummary { - let mut out = DiffSummary::default(); - let Some(map) = v else { return out }; - let latest = map - .get("latest_turn_status_display") - .and_then(Value::as_object); - let Some(latest) = latest else { return out }; - if let Some(ds) = latest.get("diff_stats").and_then(Value::as_object) { - if let Some(n) = ds.get("files_modified").and_then(Value::as_i64) { - out.files_changed = n.max(0) as usize; - } - if let Some(n) = ds.get("lines_added").and_then(Value::as_i64) { - out.lines_added = n.max(0) as usize; - } - if let Some(n) = ds.get("lines_removed").and_then(Value::as_i64) { - out.lines_removed = n.max(0) as usize; - } - } - out - } - - fn latest_turn_timestamp(v: Option<&HashMap>) -> Option { - let map = v?; - let latest = map - .get("latest_turn_status_display") - .and_then(Value::as_object)?; - latest - .get("updated_at") - .or_else(|| latest.get("created_at")) - .and_then(Value::as_f64) - } - - fn attempt_total_from_status_display(v: Option<&HashMap>) -> Option { - let map = v?; - let latest = map - .get("latest_turn_status_display") - .and_then(Value::as_object)?; - let siblings = latest.get("sibling_turn_ids").and_then(Value::as_array)?; - Some(siblings.len().saturating_add(1)) - } - - fn is_unified_diff(diff: &str) -> bool { - let t = diff.trim_start(); - if t.starts_with("diff --git ") { - return true; - } - let has_dash_headers = diff.contains("\n--- ") && diff.contains("\n+++ "); - let has_hunk = diff.contains("\n@@ ") || diff.starts_with("@@ "); - has_dash_headers && has_hunk - } - - fn tail(s: &str, max: usize) -> String { - if s.len() <= max { - s.to_string() - } else { - s[s.len() - max..].to_string() - } - } - - fn summarize_patch_for_logging(patch: &str) -> String { - let trimmed = patch.trim_start(); - let kind = if trimmed.starts_with("*** Begin Patch") { - "codex-patch" - } else if trimmed.starts_with("diff --git ") || trimmed.contains("\n*** End Patch\n") { - "git-diff" - } else if trimmed.starts_with("@@ ") || trimmed.contains("\n@@ ") { - "unified-diff" - } else { - "unknown" - }; - let lines = patch.lines().count(); - let chars = patch.len(); - let cwd = std::env::current_dir() - .ok() - .map(|p| p.display().to_string()) - .unwrap_or_else(|| "".to_string()); - let head: String = patch.lines().take(20).collect::>().join("\n"); - let head_trunc = if head.len() > 800 { - format!("{}…", &head[..800]) - } else { - head - }; - format!( - "patch_summary: kind={kind} lines={lines} chars={chars} cwd={cwd} ; head=\n{head_trunc}" - ) - } -} - -fn append_error_log(message: &str) { - let ts = Utc::now().to_rfc3339(); - if let Ok(mut f) = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open("error.log") - { - use std::io::Write as _; - let _ = writeln!(f, "[{ts}] {message}"); - } -} diff --git a/codex-rs/cloud-tasks-client/src/lib.rs b/codex-rs/cloud-tasks-client/src/lib.rs deleted file mode 100644 index a3f883403b..0000000000 --- a/codex-rs/cloud-tasks-client/src/lib.rs +++ /dev/null @@ -1,20 +0,0 @@ -mod api; - -pub use api::ApplyOutcome; -pub use api::ApplyStatus; -pub use api::AttemptStatus; -pub use api::CloudBackend; -pub use api::CloudBackendFuture; -pub use api::CloudTaskError; -pub use api::CreatedTask; -pub use api::DiffSummary; -pub use api::Result; -pub use api::TaskId; -pub use api::TaskListPage; -pub use api::TaskStatus; -pub use api::TaskSummary; -pub use api::TaskText; -pub use api::TurnAttempt; - -mod http; -pub use http::HttpClient; diff --git a/codex-rs/cloud-tasks-mock-client/BUILD.bazel b/codex-rs/cloud-tasks-mock-client/BUILD.bazel deleted file mode 100644 index 4d54dab57e..0000000000 --- a/codex-rs/cloud-tasks-mock-client/BUILD.bazel +++ /dev/null @@ -1,6 +0,0 @@ -load("//:defs.bzl", "codex_rust_crate") - -codex_rust_crate( - name = "cloud-tasks-mock-client", - crate_name = "codex_cloud_tasks_mock_client", -) diff --git a/codex-rs/cloud-tasks-mock-client/Cargo.toml b/codex-rs/cloud-tasks-mock-client/Cargo.toml deleted file mode 100644 index b249b654e0..0000000000 --- a/codex-rs/cloud-tasks-mock-client/Cargo.toml +++ /dev/null @@ -1,20 +0,0 @@ - -[package] -edition.workspace = true -license.workspace = true -name = "codex-cloud-tasks-mock-client" -version.workspace = true - -[lib] -name = "codex_cloud_tasks_mock_client" -path = "src/lib.rs" -test = false -doctest = false - -[lints] -workspace = true - -[dependencies] -chrono = { workspace = true } -codex-cloud-tasks-client = { workspace = true } -diffy = { workspace = true } diff --git a/codex-rs/cloud-tasks-mock-client/src/lib.rs b/codex-rs/cloud-tasks-mock-client/src/lib.rs deleted file mode 100644 index 833ea5e1f8..0000000000 --- a/codex-rs/cloud-tasks-mock-client/src/lib.rs +++ /dev/null @@ -1,3 +0,0 @@ -mod mock; - -pub use mock::MockClient; diff --git a/codex-rs/cloud-tasks-mock-client/src/mock.rs b/codex-rs/cloud-tasks-mock-client/src/mock.rs deleted file mode 100644 index 08fadee371..0000000000 --- a/codex-rs/cloud-tasks-mock-client/src/mock.rs +++ /dev/null @@ -1,267 +0,0 @@ -use chrono::Utc; -use codex_cloud_tasks_client::ApplyOutcome; -use codex_cloud_tasks_client::ApplyStatus; -use codex_cloud_tasks_client::AttemptStatus; -use codex_cloud_tasks_client::CloudBackend; -use codex_cloud_tasks_client::CloudBackendFuture; -use codex_cloud_tasks_client::CloudTaskError; -use codex_cloud_tasks_client::CreatedTask; -use codex_cloud_tasks_client::DiffSummary; -use codex_cloud_tasks_client::Result; -use codex_cloud_tasks_client::TaskId; -use codex_cloud_tasks_client::TaskListPage; -use codex_cloud_tasks_client::TaskStatus; -use codex_cloud_tasks_client::TaskSummary; -use codex_cloud_tasks_client::TaskText; -use codex_cloud_tasks_client::TurnAttempt; - -#[derive(Clone, Default)] -pub struct MockClient; - -impl MockClient { - async fn list_tasks( - &self, - _env: Option<&str>, - _limit: Option, - _cursor: Option<&str>, - ) -> Result { - // Slightly vary content by env to aid tests that rely on the mock - let rows = match _env { - Some("env-A") => vec![("T-2000", "A: First", TaskStatus::Ready)], - Some("env-B") => vec![ - ("T-3000", "B: One", TaskStatus::Ready), - ("T-3001", "B: Two", TaskStatus::Pending), - ], - _ => vec![ - ("T-1000", "Update README formatting", TaskStatus::Ready), - ("T-1001", "Fix clippy warnings in core", TaskStatus::Pending), - ("T-1002", "Add contributing guide", TaskStatus::Ready), - ], - }; - let environment_id = _env.map(str::to_string); - let environment_label = match _env { - Some("env-A") => Some("Env A".to_string()), - Some("env-B") => Some("Env B".to_string()), - Some(other) => Some(other.to_string()), - None => Some("Global".to_string()), - }; - let mut out = Vec::new(); - for (id_str, title, status) in rows { - let id = TaskId(id_str.to_string()); - let diff = mock_diff_for(&id); - let (a, d) = count_from_unified(&diff); - out.push(TaskSummary { - id, - title: title.to_string(), - status, - updated_at: Utc::now(), - environment_id: environment_id.clone(), - environment_label: environment_label.clone(), - summary: DiffSummary { - files_changed: 1, - lines_added: a, - lines_removed: d, - }, - is_review: false, - attempt_total: Some(if id_str == "T-1000" { 2 } else { 1 }), - }); - } - Ok(TaskListPage { - tasks: out, - cursor: None, - }) - } - - async fn get_task_summary(&self, id: TaskId) -> Result { - let tasks = self - .list_tasks(/*env*/ None, /*limit*/ None, /*cursor*/ None) - .await? - .tasks; - tasks - .into_iter() - .find(|t| t.id == id) - .ok_or_else(|| CloudTaskError::Msg(format!("Task {} not found (mock)", id.0))) - } - - async fn get_task_diff(&self, id: TaskId) -> Result> { - Ok(Some(mock_diff_for(&id))) - } - - async fn get_task_messages(&self, _id: TaskId) -> Result> { - Ok(vec![ - "Mock assistant output: this task contains no diff.".to_string(), - ]) - } - - async fn get_task_text(&self, _id: TaskId) -> Result { - Ok(TaskText { - prompt: Some("Why is there no diff?".to_string()), - messages: vec!["Mock assistant output: this task contains no diff.".to_string()], - turn_id: Some("mock-turn".to_string()), - sibling_turn_ids: Vec::new(), - attempt_placement: Some(0), - attempt_status: AttemptStatus::Completed, - }) - } - - async fn apply_task(&self, id: TaskId, _diff_override: Option) -> Result { - Ok(ApplyOutcome { - applied: true, - status: ApplyStatus::Success, - message: format!("Applied task {} locally (mock)", id.0), - skipped_paths: Vec::new(), - conflict_paths: Vec::new(), - }) - } - - async fn apply_task_preflight( - &self, - id: TaskId, - _diff_override: Option, - ) -> Result { - Ok(ApplyOutcome { - applied: false, - status: ApplyStatus::Success, - message: format!("Preflight passed for task {} (mock)", id.0), - skipped_paths: Vec::new(), - conflict_paths: Vec::new(), - }) - } - - async fn list_sibling_attempts( - &self, - task: TaskId, - _turn_id: String, - ) -> Result> { - if task.0 == "T-1000" { - return Ok(vec![TurnAttempt { - turn_id: "T-1000-attempt-2".to_string(), - attempt_placement: Some(1), - created_at: Some(Utc::now()), - status: AttemptStatus::Completed, - diff: Some(mock_diff_for(&task)), - messages: vec!["Mock alternate attempt".to_string()], - }]); - } - Ok(Vec::new()) - } - - async fn create_task( - &self, - env_id: &str, - prompt: &str, - git_ref: &str, - qa_mode: bool, - best_of_n: usize, - ) -> Result { - let _ = (env_id, prompt, git_ref, qa_mode, best_of_n); - let id = format!("task_local_{}", chrono::Utc::now().timestamp_millis()); - Ok(CreatedTask { id: TaskId(id) }) - } -} - -impl CloudBackend for MockClient { - fn list_tasks<'a>( - &'a self, - env: Option<&'a str>, - limit: Option, - cursor: Option<&'a str>, - ) -> CloudBackendFuture<'a, TaskListPage> { - Box::pin(MockClient::list_tasks(self, env, limit, cursor)) - } - - fn get_task_summary(&self, id: TaskId) -> CloudBackendFuture<'_, TaskSummary> { - Box::pin(MockClient::get_task_summary(self, id)) - } - - fn get_task_diff(&self, id: TaskId) -> CloudBackendFuture<'_, Option> { - Box::pin(MockClient::get_task_diff(self, id)) - } - - fn get_task_messages(&self, id: TaskId) -> CloudBackendFuture<'_, Vec> { - Box::pin(MockClient::get_task_messages(self, id)) - } - - fn get_task_text(&self, id: TaskId) -> CloudBackendFuture<'_, TaskText> { - Box::pin(MockClient::get_task_text(self, id)) - } - - fn apply_task( - &self, - id: TaskId, - diff_override: Option, - ) -> CloudBackendFuture<'_, ApplyOutcome> { - Box::pin(MockClient::apply_task(self, id, diff_override)) - } - - fn apply_task_preflight( - &self, - id: TaskId, - diff_override: Option, - ) -> CloudBackendFuture<'_, ApplyOutcome> { - Box::pin(MockClient::apply_task_preflight(self, id, diff_override)) - } - - fn list_sibling_attempts( - &self, - task: TaskId, - turn_id: String, - ) -> CloudBackendFuture<'_, Vec> { - Box::pin(MockClient::list_sibling_attempts(self, task, turn_id)) - } - - fn create_task<'a>( - &'a self, - env_id: &'a str, - prompt: &'a str, - git_ref: &'a str, - qa_mode: bool, - best_of_n: usize, - ) -> CloudBackendFuture<'a, CreatedTask> { - Box::pin(MockClient::create_task( - self, env_id, prompt, git_ref, qa_mode, best_of_n, - )) - } -} - -fn mock_diff_for(id: &TaskId) -> String { - match id.0.as_str() { - "T-1000" => { - "diff --git a/README.md b/README.md\nindex 000000..111111 100644\n--- a/README.md\n+++ b/README.md\n@@ -1,2 +1,3 @@\n Intro\n-Hello\n+Hello, world!\n+Task: T-1000\n".to_string() - } - "T-1001" => { - "diff --git a/core/src/lib.rs b/core/src/lib.rs\nindex 000000..111111 100644\n--- a/core/src/lib.rs\n+++ b/core/src/lib.rs\n@@ -1,2 +1,1 @@\n-use foo;\n use bar;\n".to_string() - } - _ => { - "diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md\nindex 000000..111111 100644\n--- /dev/null\n+++ b/CONTRIBUTING.md\n@@ -0,0 +1,3 @@\n+## Contributing\n+Please open PRs.\n+Thanks!\n".to_string() - } - } -} - -fn count_from_unified(diff: &str) -> (usize, usize) { - if let Ok(patch) = diffy::Patch::from_str(diff) { - patch - .hunks() - .iter() - .flat_map(diffy::Hunk::lines) - .fold((0, 0), |(a, d), l| match l { - diffy::Line::Insert(_) => (a + 1, d), - diffy::Line::Delete(_) => (a, d + 1), - _ => (a, d), - }) - } else { - let mut a = 0; - let mut d = 0; - for l in diff.lines() { - if l.starts_with("+++") || l.starts_with("---") || l.starts_with("@@") { - continue; - } - match l.as_bytes().first() { - Some(b'+') => a += 1, - Some(b'-') => d += 1, - _ => {} - } - } - (a, d) - } -} diff --git a/codex-rs/cloud-tasks/BUILD.bazel b/codex-rs/cloud-tasks/BUILD.bazel deleted file mode 100644 index 9beb5f87b0..0000000000 --- a/codex-rs/cloud-tasks/BUILD.bazel +++ /dev/null @@ -1,7 +0,0 @@ -load("//:defs.bzl", "MACOS_WEBRTC_RUSTC_LINK_FLAGS", "codex_rust_crate") - -codex_rust_crate( - name = "cloud-tasks", - crate_name = "codex_cloud_tasks", - rustc_flags_extra = MACOS_WEBRTC_RUSTC_LINK_FLAGS, -) diff --git a/codex-rs/cloud-tasks/Cargo.toml b/codex-rs/cloud-tasks/Cargo.toml deleted file mode 100644 index 26564894e8..0000000000 --- a/codex-rs/cloud-tasks/Cargo.toml +++ /dev/null @@ -1,54 +0,0 @@ -[package] -edition.workspace = true -license.workspace = true -name = "codex-cloud-tasks" -version.workspace = true - -[lib] -name = "codex_cloud_tasks" -path = "src/lib.rs" -doctest = false - -[lints] -workspace = true - -[dependencies] -codex-backend-client = { workspace = true } -anyhow = { workspace = true } -chrono = { workspace = true, features = ["serde"] } -clap = { workspace = true, features = ["derive"] } -codex-http-client = { workspace = true } -codex-cloud-tasks-client = { workspace = true } -# TODO: codex-cloud-tasks-mock-client should be in dev-dependencies. -codex-cloud-tasks-mock-client = { workspace = true } -codex-core = { workspace = true } -codex-features = { workspace = true } -codex-git-utils = { workspace = true } -codex-login = { path = "../login" } -codex-model-provider = { workspace = true } -codex-tui = { workspace = true } -codex-utils-cli = { workspace = true } -crossterm = { workspace = true, features = ["event-stream"] } -http = { workspace = true } -owo-colors = { workspace = true, features = ["supports-colors"] } -ratatui = { workspace = true } -serde = { workspace = true, features = ["derive"] } -serde_json = { workspace = true } -supports-color = { workspace = true } -tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } -tokio-stream = { workspace = true } -tracing = { workspace = true, features = ["log"] } -tracing-subscriber = { workspace = true, features = ["env-filter"] } -unicode-segmentation = { workspace = true } -unicode-width = { workspace = true } - -[dev-dependencies] -codex-agent-identity = { workspace = true } -core_test_support = { workspace = true } -base64 = { workspace = true } -tempfile = { workspace = true } -codex-runtime-agent-instance = { workspace = true } -uuid = { workspace = true } -wiremock = { workspace = true } -insta = { workspace = true } -pretty_assertions = { workspace = true } diff --git a/codex-rs/cloud-tasks/src/app.rs b/codex-rs/cloud-tasks/src/app.rs deleted file mode 100644 index 7b227f0746..0000000000 --- a/codex-rs/cloud-tasks/src/app.rs +++ /dev/null @@ -1,534 +0,0 @@ -use std::time::Duration; -use std::time::Instant; - -// Environment filter data models for the TUI -#[derive(Clone, Debug, Default)] -pub struct EnvironmentRow { - pub id: String, - pub label: Option, - pub is_pinned: bool, - pub repo_hints: Option, // e.g., "openai/codex" -} - -#[derive(Clone, Debug, Default)] -pub struct EnvModalState { - pub query: String, - pub selected: usize, -} - -#[derive(Clone, Debug, Default)] -pub struct BestOfModalState { - pub selected: usize, -} - -#[derive(Clone, Debug, Copy, PartialEq, Eq)] -pub enum ApplyResultLevel { - Success, - Partial, - Error, -} - -#[derive(Clone, Debug)] -pub struct ApplyModalState { - pub task_id: TaskId, - pub title: String, - pub result_message: Option, - pub result_level: Option, - pub skipped_paths: Vec, - pub conflict_paths: Vec, - pub diff_override: Option, -} - -use crate::scrollable_diff::ScrollableDiff; -use codex_cloud_tasks_client::CloudBackend; -use codex_cloud_tasks_client::TaskId; -use codex_cloud_tasks_client::TaskSummary; -#[derive(Default)] -pub struct App { - pub tasks: Vec, - pub selected: usize, - pub status: String, - pub diff_overlay: Option, - pub spinner_start: Option, - pub refresh_inflight: bool, - pub details_inflight: bool, - // Environment filter state - pub env_filter: Option, - pub env_modal: Option, - pub apply_modal: Option, - pub best_of_modal: Option, - pub environments: Vec, - pub env_last_loaded: Option, - pub env_loading: bool, - pub env_error: Option, - // New Task page - pub new_task: Option, - pub best_of_n: usize, - // Apply preflight spinner state - pub apply_preflight_inflight: bool, - // Apply action spinner state - pub apply_inflight: bool, - // Background enrichment coordination - pub list_generation: u64, - pub in_flight: std::collections::HashSet, - // Background enrichment caches were planned; currently unused. -} - -impl App { - pub fn new() -> Self { - Self { - tasks: Vec::new(), - selected: 0, - status: "Press r to refresh".to_string(), - diff_overlay: None, - spinner_start: None, - refresh_inflight: false, - details_inflight: false, - env_filter: None, - env_modal: None, - apply_modal: None, - best_of_modal: None, - environments: Vec::new(), - env_last_loaded: None, - env_loading: false, - env_error: None, - new_task: None, - best_of_n: 1, - apply_preflight_inflight: false, - apply_inflight: false, - list_generation: 0, - in_flight: std::collections::HashSet::new(), - } - } - - pub fn next(&mut self) { - if self.tasks.is_empty() { - return; - } - self.selected = (self.selected + 1).min(self.tasks.len().saturating_sub(1)); - } - - pub fn prev(&mut self) { - if self.tasks.is_empty() { - return; - } - if self.selected > 0 { - self.selected -= 1; - } - } -} - -pub async fn load_tasks( - backend: &dyn CloudBackend, - env: Option<&str>, -) -> anyhow::Result> { - // In later milestones, add a small debounce, spinner, and error display. - let tasks = tokio::time::timeout( - Duration::from_secs(5), - backend.list_tasks(env, Some(20), /*cursor*/ None), - ) - .await??; - // Hide review-only tasks from the main list. - let filtered: Vec = tasks.tasks.into_iter().filter(|t| !t.is_review).collect(); - Ok(filtered) -} - -pub struct DiffOverlay { - pub title: String, - pub task_id: TaskId, - pub sd: ScrollableDiff, - pub base_can_apply: bool, - pub diff_lines: Vec, - pub text_lines: Vec, - pub prompt: Option, - pub attempts: Vec, - pub selected_attempt: usize, - pub current_view: DetailView, - pub base_turn_id: Option, - pub sibling_turn_ids: Vec, - pub attempt_total_hint: Option, -} - -#[derive(Clone, Debug, Default)] -pub struct AttemptView { - pub turn_id: Option, - pub status: codex_cloud_tasks_client::AttemptStatus, - pub attempt_placement: Option, - pub diff_lines: Vec, - pub text_lines: Vec, - pub prompt: Option, - pub diff_raw: Option, -} - -impl AttemptView { - pub fn has_diff(&self) -> bool { - !self.diff_lines.is_empty() - } - - pub fn has_text(&self) -> bool { - !self.text_lines.is_empty() || self.prompt.is_some() - } -} - -impl DiffOverlay { - pub fn new(task_id: TaskId, title: String, attempt_total_hint: Option) -> Self { - let mut sd = ScrollableDiff::new(); - sd.set_content(Vec::new()); - Self { - title, - task_id, - sd, - base_can_apply: false, - diff_lines: Vec::new(), - text_lines: Vec::new(), - prompt: None, - attempts: vec![AttemptView::default()], - selected_attempt: 0, - current_view: DetailView::Prompt, - base_turn_id: None, - sibling_turn_ids: Vec::new(), - attempt_total_hint, - } - } - - pub fn current_attempt(&self) -> Option<&AttemptView> { - self.attempts.get(self.selected_attempt) - } - - pub fn base_attempt_mut(&mut self) -> &mut AttemptView { - if self.attempts.is_empty() { - self.attempts.push(AttemptView::default()); - } - &mut self.attempts[0] - } - - pub fn set_view(&mut self, view: DetailView) { - self.current_view = view; - self.apply_selection_to_fields(); - } - - pub fn expected_attempts(&self) -> Option { - self.attempt_total_hint.or({ - if self.attempts.is_empty() { - None - } else { - Some(self.attempts.len()) - } - }) - } - - pub fn attempt_count(&self) -> usize { - self.attempts.len() - } - - pub fn attempt_display_total(&self) -> usize { - self.expected_attempts() - .unwrap_or_else(|| self.attempts.len().max(1)) - } - - pub fn step_attempt(&mut self, delta: isize) -> bool { - let total = self.attempts.len(); - if total <= 1 { - return false; - } - let total_isize = total as isize; - let current = self.selected_attempt as isize; - let mut next = current + delta; - next = ((next % total_isize) + total_isize) % total_isize; - let next = next as usize; - self.selected_attempt = next; - self.apply_selection_to_fields(); - true - } - - pub fn current_can_apply(&self) -> bool { - matches!(self.current_view, DetailView::Diff) - && self - .current_attempt() - .and_then(|attempt| attempt.diff_raw.as_ref()) - .map(|diff| !diff.is_empty()) - .unwrap_or(false) - } - - pub fn apply_selection_to_fields(&mut self) { - let (diff_lines, text_lines, prompt) = if let Some(attempt) = self.current_attempt() { - ( - attempt.diff_lines.clone(), - attempt.text_lines.clone(), - attempt.prompt.clone(), - ) - } else { - self.diff_lines.clear(); - self.text_lines.clear(); - self.prompt = None; - self.sd.set_content(vec!["".to_string()]); - return; - }; - - self.diff_lines = diff_lines.clone(); - self.text_lines = text_lines.clone(); - self.prompt = prompt; - - match self.current_view { - DetailView::Diff => { - if diff_lines.is_empty() { - self.sd.set_content(vec!["".to_string()]); - } else { - self.sd.set_content(diff_lines); - } - } - DetailView::Prompt => { - if text_lines.is_empty() { - self.sd.set_content(vec!["".to_string()]); - } else { - self.sd.set_content(text_lines); - } - } - } - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum DetailView { - Diff, - Prompt, -} - -/// Internal app events delivered from background tasks. -/// These let the UI event loop remain responsive and keep the spinner animating. -#[derive(Debug)] -pub enum AppEvent { - TasksLoaded { - env: Option, - result: anyhow::Result>, - }, - // Background diff summary events were planned; removed for now to keep code minimal. - /// Autodetection of a likely environment id finished - EnvironmentAutodetected(anyhow::Result), - /// Background completion of environment list fetch - EnvironmentsLoaded(anyhow::Result>), - DetailsDiffLoaded { - id: TaskId, - title: String, - diff: String, - }, - DetailsMessagesLoaded { - id: TaskId, - title: String, - messages: Vec, - prompt: Option, - turn_id: Option, - sibling_turn_ids: Vec, - attempt_placement: Option, - attempt_status: codex_cloud_tasks_client::AttemptStatus, - }, - DetailsFailed { - id: TaskId, - title: String, - error: String, - }, - AttemptsLoaded { - id: TaskId, - attempts: Vec, - }, - /// Background completion of new task submission - NewTaskSubmitted(Result), - /// Background completion of apply preflight when opening modal or on demand - ApplyPreflightFinished { - id: TaskId, - title: String, - message: String, - level: ApplyResultLevel, - skipped: Vec, - conflicts: Vec, - }, - /// Background completion of apply action (actual patch application) - ApplyFinished { - id: TaskId, - result: std::result::Result, - }, -} - -// Convenience aliases; currently unused. -#[cfg(test)] -mod tests { - use super::*; - use chrono::Utc; - use codex_cloud_tasks_client::CloudBackendFuture; - use codex_cloud_tasks_client::CloudTaskError; - - struct FakeBackend { - // maps env key to titles - by_env: std::collections::HashMap, Vec<&'static str>>, - } - - impl FakeBackend { - async fn list_tasks( - &self, - env: Option<&str>, - limit: Option, - cursor: Option<&str>, - ) -> Result { - let key = env.map(str::to_string); - let titles = self - .by_env - .get(&key) - .cloned() - .unwrap_or_else(|| vec!["default-a", "default-b"]); - let mut out = Vec::new(); - for (i, t) in titles.into_iter().enumerate() { - out.push(TaskSummary { - id: TaskId(format!("T-{i}")), - title: t.to_string(), - status: codex_cloud_tasks_client::TaskStatus::Ready, - updated_at: Utc::now(), - environment_id: env.map(str::to_string), - environment_label: None, - summary: codex_cloud_tasks_client::DiffSummary::default(), - is_review: false, - attempt_total: Some(1), - }); - } - let max = limit.unwrap_or(i64::MAX); - let max = max.min(20); - let mut limited = Vec::new(); - for task in out { - if (limited.len() as i64) >= max { - break; - } - limited.push(task); - } - Ok(codex_cloud_tasks_client::TaskListPage { - tasks: limited, - cursor: cursor.map(str::to_string), - }) - } - - async fn get_task_summary(&self, id: TaskId) -> Result { - self.list_tasks(/*env*/ None, /*limit*/ None, /*cursor*/ None) - .await? - .tasks - .into_iter() - .find(|t| t.id == id) - .ok_or_else(|| CloudTaskError::Msg(format!("Task {} not found", id.0))) - } - - async fn get_task_text( - &self, - _id: TaskId, - ) -> Result { - Ok(codex_cloud_tasks_client::TaskText { - prompt: Some("Example prompt".to_string()), - messages: Vec::new(), - turn_id: Some("fake-turn".to_string()), - sibling_turn_ids: Vec::new(), - attempt_placement: Some(0), - attempt_status: codex_cloud_tasks_client::AttemptStatus::Completed, - }) - } - } - - impl codex_cloud_tasks_client::CloudBackend for FakeBackend { - fn list_tasks<'a>( - &'a self, - env: Option<&'a str>, - limit: Option, - cursor: Option<&'a str>, - ) -> CloudBackendFuture<'a, codex_cloud_tasks_client::TaskListPage> { - Box::pin(FakeBackend::list_tasks(self, env, limit, cursor)) - } - - fn get_task_summary(&self, id: TaskId) -> CloudBackendFuture<'_, TaskSummary> { - Box::pin(FakeBackend::get_task_summary(self, id)) - } - - fn get_task_diff(&self, _id: TaskId) -> CloudBackendFuture<'_, Option> { - Box::pin(async { - Err(codex_cloud_tasks_client::CloudTaskError::Unimplemented( - "not used in test", - )) - }) - } - - fn get_task_messages(&self, _id: TaskId) -> CloudBackendFuture<'_, Vec> { - Box::pin(async { Ok(vec![]) }) - } - - fn get_task_text( - &self, - id: TaskId, - ) -> CloudBackendFuture<'_, codex_cloud_tasks_client::TaskText> { - Box::pin(FakeBackend::get_task_text(self, id)) - } - - fn list_sibling_attempts( - &self, - _task: TaskId, - _turn_id: String, - ) -> CloudBackendFuture<'_, Vec> { - Box::pin(async { Ok(Vec::new()) }) - } - - fn apply_task( - &self, - _id: TaskId, - _diff_override: Option, - ) -> CloudBackendFuture<'_, codex_cloud_tasks_client::ApplyOutcome> { - Box::pin(async { - Err(codex_cloud_tasks_client::CloudTaskError::Unimplemented( - "not used in test", - )) - }) - } - - fn apply_task_preflight( - &self, - _id: TaskId, - _diff_override: Option, - ) -> CloudBackendFuture<'_, codex_cloud_tasks_client::ApplyOutcome> { - Box::pin(async { - Err(codex_cloud_tasks_client::CloudTaskError::Unimplemented( - "not used in test", - )) - }) - } - - fn create_task<'a>( - &'a self, - _env_id: &'a str, - _prompt: &'a str, - _git_ref: &'a str, - _qa_mode: bool, - _best_of_n: usize, - ) -> CloudBackendFuture<'a, codex_cloud_tasks_client::CreatedTask> { - Box::pin(async { - Err(codex_cloud_tasks_client::CloudTaskError::Unimplemented( - "not used in test", - )) - }) - } - } - - #[tokio::test] - async fn load_tasks_uses_env_parameter() { - // Arrange: env-specific task titles - let mut by_env = std::collections::HashMap::new(); - by_env.insert(None, vec!["root-1", "root-2"]); - by_env.insert(Some("env-A".to_string()), vec!["A-1"]); - by_env.insert(Some("env-B".to_string()), vec!["B-1", "B-2", "B-3"]); - let backend = FakeBackend { by_env }; - - // Act + Assert - let root = load_tasks(&backend, /*env*/ None).await.unwrap(); - assert_eq!(root.len(), 2); - assert_eq!(root[0].title, "root-1"); - - let a = load_tasks(&backend, Some("env-A")).await.unwrap(); - assert_eq!(a.len(), 1); - assert_eq!(a[0].title, "A-1"); - - let b = load_tasks(&backend, Some("env-B")).await.unwrap(); - assert_eq!(b.len(), 3); - assert_eq!(b[2].title, "B-3"); - } -} diff --git a/codex-rs/cloud-tasks/src/backend_auth_tests.rs b/codex-rs/cloud-tasks/src/backend_auth_tests.rs deleted file mode 100644 index 1350158782..0000000000 --- a/codex-rs/cloud-tasks/src/backend_auth_tests.rs +++ /dev/null @@ -1,277 +0,0 @@ -//! Cover credential refresh between Cloud startup and environment discovery. - -#![cfg(test)] - -use base64::Engine; -use chrono::Utc; -use codex_utils_cli::CliConfigOverrides; -use pretty_assertions::assert_eq; -use serde_json::json; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; - -fn access_token(expires_at: i64) -> String { - let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode( - json!({ - "exp": expires_at, - "iss": "https://auth.openai.com/", - "sub": "user-a", - "session_id": "session-a", - "https://api.openai.com/auth": { - "chatgpt_account_id": "account-a", - "chatgpt_user_id": "user-a", - "chatgpt_plan_type": "plus", - }, - }) - .to_string(), - ); - format!("header.{claims}.signature") -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn environment_discovery_refreshes_after_cloud_startup() { - const SERVER: &str = "CODEX_CLOUD_REFRESH_TEST_SERVER"; - if let Ok(server) = std::env::var(SERVER) { - let overrides = CliConfigOverrides { - raw_overrides: vec![ - "cli_auth_credentials_store=\"file\"".into(), - "features.runtime_agent_instances=false".into(), - "features.use_agent_identity=false".into(), - ], - }; - let context = super::init_backend("cloud-refresh-test", &overrides) - .await - .expect("Cloud startup"); - for _ in 0..2 { - let environments = crate::env_detect::list_environments( - &context.environment_http, - &server, - &crate::util::build_chatgpt_headers(), - ) - .await - .expect("environment discovery after token refresh"); - assert_eq!(environments.len(), 1); - assert_eq!(environments[0].id, "env-a"); - } - return; - } - - let server = MockServer::start().await; - let home = tempfile::tempdir().expect("isolated Cloud credentials"); - let expired = access_token(Utc::now().timestamp() - 60); - // The startup token is near expiry, so discovery must refresh it through AuthManager. - let startup = access_token(Utc::now().timestamp() + 240); - let current = access_token(Utc::now().timestamp() + 3_600); - std::fs::write( - home.path().join("auth.json"), - json!({ - "tokens": { - "id_token": expired, "access_token": expired, - "refresh_token": "refresh-initial", "account_id": "account-a", - }, - "last_refresh": Utc::now(), - }) - .to_string(), - ) - .expect("write initial credentials"); - let refreshed = current.clone(); - Mock::given(method("POST")) - .and(path("/token")) - .respond_with(move |request: &wiremock::Request| { - let body: serde_json::Value = request.body_json().unwrap(); - let token = match body["refresh_token"].as_str().unwrap() { - "refresh-initial" => &startup, - "refresh-startup" => &refreshed, - other => panic!("unexpected test refresh token: {other}"), - }; - ResponseTemplate::new(200).set_body_json(json!({ - "id_token": token, "access_token": token, - "refresh_token": "refresh-startup", - })) - }) - .expect(2) - .mount(&server) - .await; - Mock::given(path("/api/codex/environments")) - .respond_with(ResponseTemplate::new(401)) - .with_priority(10) - .expect(0) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/api/codex/environments")) - .and(header("authorization", format!("Bearer {current}"))) - .and(header("chatgpt-account-id", "account-a")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!([ - {"id": "env-a", "label": "Environment A"}, - ]))) - .expect(2) - .mount(&server) - .await; - - let mut command = std::process::Command::new(std::env::current_exe().unwrap()); - command - .args([ - "--exact", - "backend_auth_tests::environment_discovery_refreshes_after_cloud_startup", - "--nocapture", - ]) - .current_dir(home.path()) - .env(SERVER, server.uri()) - .env("CODEX_HOME", home.path()) - .env( - "CODEX_REFRESH_TOKEN_URL_OVERRIDE", - format!("{}/token", server.uri()), - ) - .env( - "CODEX_CLOUD_TASKS_BASE_URL", - "https://chatgpt.com/backend-api", - ) - .env_remove("CODEX_CLOUD_TASKS_MODE") - .env_remove("CODEX_ACCESS_TOKEN") - .env_remove("CODEX_API_KEY") - .env_remove("OPENAI_API_KEY"); - let output = tokio::task::spawn_blocking(move || command.output()) - .await - .expect("Cloud test child task") - .expect("Cloud test child process"); - assert!( - output.status.success(), - "Cloud startup regression failed:\n{}\n{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr), - ); - server.verify().await; -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn cloud_list_preserves_existing_agent_identity_during_runtime_rollout() -> anyhow::Result<()> -{ - use core_test_support::runtime_auth::PROBE_SERVER; - use core_test_support::runtime_auth::run_harness_through_proxy; - - const TEST: &str = - "backend_auth_tests::cloud_list_preserves_existing_agent_identity_during_runtime_rollout"; - const MODE: &str = "CODEX_CLOUD_PROGRAMMATIC_TEST_MODE"; - if let Ok(mode) = std::env::var(MODE) { - let enabled = mode != "off"; - let mode = if enabled { - mode.as_str() - } else { - "dual_header" - }; - let overrides = CliConfigOverrides { - raw_overrides: vec![ - "cli_auth_credentials_store=\"file\"".into(), - format!("features.runtime_agent_instances={{ enabled={enabled}, mode={mode:?} }}"), - "features.use_agent_identity=false".into(), - ], - }; - let context = super::init_backend("cloud-programmatic-test", &overrides).await?; - let page = codex_cloud_tasks_client::CloudBackend::list_tasks( - &*context.backend, - /*env*/ None, - /*limit*/ Some(10), - /*cursor*/ None, - ) - .await?; - assert!(page.tasks.is_empty()); - let environments = crate::env_detect::list_environments( - &context.environment_http, - "https://chatgpt.com", - &crate::util::build_chatgpt_headers(), - ) - .await?; - assert_eq!(environments.len(), 1); - assert_eq!(environments[0].id, "env-a"); - return Ok(()); - } - if std::env::var(PROBE_SERVER).is_ok() { - let home = tempfile::tempdir()?; - let key = codex_agent_identity::generate_agent_key_material()?; - std::fs::write( - home.path().join("auth.json"), - json!({ - "auth_mode": "agentIdentity", - "agent_identity": { - "agent_runtime_id": "existing-agent", - "agent_private_key": key.private_key_pkcs8_base64, - "account_id": "account-a", - "chatgpt_user_id": "user-a", - "plan_type": "plus", - "chatgpt_account_is_fedramp": false, - "task_id": "existing-task", - }, - }) - .to_string(), - )?; - // Keep each credential/configuration case in its own process, retaining the proxy - // from the outer fixture without mutating environment variables in a running test. - for mode in ["off", "dual_header", "assertion_only"] { - let mut command = std::process::Command::new(std::env::current_exe()?); - command - .args(["--exact", TEST, "--nocapture"]) - .current_dir(home.path()) - .env(MODE, mode) - .env("CODEX_HOME", home.path()) - .env( - "CODEX_CLOUD_TASKS_BASE_URL", - "https://chatgpt.com/backend-api", - ) - .env_remove("CODEX_CLOUD_TASKS_MODE") - .env_remove("CODEX_ACCESS_TOKEN") - .env_remove("CODEX_API_KEY") - .env_remove("OPENAI_API_KEY"); - let output = tokio::task::spawn_blocking(move || command.output()).await??; - assert!( - output.status.success(), - "{mode}: {}\n{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); - assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed")); - } - return Ok(()); - } - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/tasks/list")) - .and(header("chatgpt-account-id", "account-a")) - .respond_with( - ResponseTemplate::new(200).set_body_json(json!({"items": [], "cursor": null})), - ) - .expect(3) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/api/codex/environments")) - .and(header("chatgpt-account-id", "account-a")) - .respond_with( - ResponseTemplate::new(200) - .set_body_json(json!([{ "id": "env-a", "label": "Environment A" }])), - ) - .expect(3) - .mount(&server) - .await; - run_harness_through_proxy(&server, TEST, /*realtime_target*/ None).await?; - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 6); - for request in requests { - let assertion = request.headers["authorization"] - .to_str()? - .strip_prefix("AgentAssertion ") - .unwrap(); - let envelope: serde_json::Value = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(assertion)?, - )?; - assert_eq!(envelope["agent_runtime_id"], "existing-agent"); - assert_eq!(envelope["task_id"], "existing-task"); - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - } - server.verify().await; - Ok(()) -} diff --git a/codex-rs/cloud-tasks/src/cli.rs b/codex-rs/cloud-tasks/src/cli.rs deleted file mode 100644 index e2c3a24442..0000000000 --- a/codex-rs/cloud-tasks/src/cli.rs +++ /dev/null @@ -1,120 +0,0 @@ -use clap::Args; -use clap::Parser; -use codex_utils_cli::CliConfigOverrides; - -#[derive(Parser, Debug, Default)] -#[command(version)] -pub struct Cli { - #[clap(skip)] - pub config_overrides: CliConfigOverrides, - - #[command(subcommand)] - pub command: Option, -} - -#[derive(Debug, clap::Subcommand)] -pub enum Command { - /// Submit a new Codex Cloud task without launching the TUI. - Exec(ExecCommand), - /// Show the status of a Codex Cloud task. - Status(StatusCommand), - /// List Codex Cloud tasks. - List(ListCommand), - /// Apply the diff for a Codex Cloud task locally. - Apply(ApplyCommand), - /// Show the unified diff for a Codex Cloud task. - Diff(DiffCommand), -} - -#[derive(Debug, Args)] -pub struct ExecCommand { - /// Task prompt to run in Codex Cloud. - #[arg(value_name = "QUERY")] - pub query: Option, - - /// Target environment identifier (see `codex cloud` to browse). - #[arg(long = "env", value_name = "ENV_ID")] - pub environment: String, - - /// Number of assistant attempts (best-of-N). - #[arg( - long = "attempts", - default_value_t = 1usize, - value_parser = parse_attempts - )] - pub attempts: usize, - - /// Git branch to run in Codex Cloud (defaults to current branch). - #[arg(long = "branch", value_name = "BRANCH")] - pub branch: Option, -} - -fn parse_attempts(input: &str) -> Result { - let value: usize = input - .parse() - .map_err(|_| "attempts must be an integer between 1 and 4".to_string())?; - if (1..=4).contains(&value) { - Ok(value) - } else { - Err("attempts must be between 1 and 4".to_string()) - } -} - -fn parse_limit(input: &str) -> Result { - let value: i64 = input - .parse() - .map_err(|_| "limit must be an integer between 1 and 20".to_string())?; - if (1..=20).contains(&value) { - Ok(value) - } else { - Err("limit must be between 1 and 20".to_string()) - } -} - -#[derive(Debug, Args)] -pub struct StatusCommand { - /// Codex Cloud task identifier to inspect. - #[arg(value_name = "TASK_ID")] - pub task_id: String, -} - -#[derive(Debug, Args)] -pub struct ListCommand { - /// Filter tasks by environment identifier. - #[arg(long = "env", value_name = "ENV_ID")] - pub environment: Option, - - /// Maximum number of tasks to return (1-20). - #[arg(long = "limit", default_value_t = 20, value_parser = parse_limit, value_name = "N")] - pub limit: i64, - - /// Pagination cursor returned by a previous call. - #[arg(long = "cursor", value_name = "CURSOR")] - pub cursor: Option, - - /// Emit JSON instead of plain text. - #[arg(long = "json", default_value_t = false)] - pub json: bool, -} - -#[derive(Debug, Args)] -pub struct ApplyCommand { - /// Codex Cloud task identifier to apply. - #[arg(value_name = "TASK_ID")] - pub task_id: String, - - /// Attempt number to apply (1-based). - #[arg(long = "attempt", value_parser = parse_attempts, value_name = "N")] - pub attempt: Option, -} - -#[derive(Debug, Args)] -pub struct DiffCommand { - /// Codex Cloud task identifier to display. - #[arg(value_name = "TASK_ID")] - pub task_id: String, - - /// Attempt number to display (1-based). - #[arg(long = "attempt", value_parser = parse_attempts, value_name = "N")] - pub attempt: Option, -} diff --git a/codex-rs/cloud-tasks/src/env_detect.rs b/codex-rs/cloud-tasks/src/env_detect.rs deleted file mode 100644 index d2535e0a9f..0000000000 --- a/codex-rs/cloud-tasks/src/env_detect.rs +++ /dev/null @@ -1,446 +0,0 @@ -use codex_git_utils::SanitizedGitUrl; -use codex_http_client::RouteAwareClientPool; -use codex_model_provider::ClientAuth; -use http::StatusCode; -use http::header::CONTENT_TYPE; -use http::header::HeaderMap; -use std::collections::HashMap; -use tracing::info; -use tracing::warn; - -#[derive(Clone)] -pub(crate) struct EnvironmentClient { - pub(crate) http: RouteAwareClientPool, - pub(crate) auth: Option, -} - -#[derive(Debug, Clone, serde::Deserialize)] -struct CodeEnvironment { - id: String, - #[serde(default)] - label: Option, - #[serde(default)] - is_pinned: Option, - #[serde(default)] - task_count: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct AutodetectSelection { - pub id: String, - pub label: Option, -} - -pub(crate) async fn autodetect_environment_id( - http: &EnvironmentClient, - base_url: &str, - headers: &HeaderMap, - desired_label: Option, -) -> anyhow::Result { - autodetect_environment_id_with_origins( - http, - base_url, - headers, - desired_label, - &get_git_origins(), - ) - .await -} - -async fn autodetect_environment_id_with_origins( - http: &impl EnvironmentHttp, - base_url: &str, - headers: &HeaderMap, - desired_label: Option, - origins: &[SanitizedGitUrl], -) -> anyhow::Result { - // 1) Try repo-specific environments based on local git origins (GitHub only, like VSCode) - crate::append_error_log(format!("env: git origins: {origins:?}")); - let mut by_repo_envs: Vec = Vec::new(); - for origin in origins { - if let Some((owner, repo)) = parse_owner_repo(origin.as_str()) { - let url = if base_url.contains("/backend-api") { - format!( - "{}/wham/environments/by-repo/{}/{}/{}", - base_url, "github", owner, repo - ) - } else { - format!( - "{}/api/codex/environments/by-repo/{}/{}/{}", - base_url, "github", owner, repo - ) - }; - crate::append_error_log(format!("env: GET {url}")); - match get_json::>(http, &url, headers).await { - Ok(mut list) => { - crate::append_error_log(format!( - "env: by-repo returned {} env(s) for {owner}/{repo}", - list.len(), - )); - by_repo_envs.append(&mut list); - } - Err(e) => crate::append_error_log(format!( - "env: by-repo fetch failed for {owner}/{repo}: {e}" - )), - } - } - } - if let Some(env) = pick_environment_row(&by_repo_envs, desired_label.as_deref()) { - return Ok(AutodetectSelection { - id: env.id.clone(), - label: env.label.as_deref().map(str::to_owned), - }); - } - - // 2) Fallback to the full list - let list_url = if base_url.contains("/backend-api") { - format!("{base_url}/wham/environments") - } else { - format!("{base_url}/api/codex/environments") - }; - crate::append_error_log(format!("env: GET {list_url}")); - // Fetch and log the full environments JSON for debugging - let response = http.get(&list_url, headers).await?; - let status = response.status; - let ct = response.content_type; - let body = response.body; - crate::append_error_log(format!("env: status={status} content-type={ct}")); - match serde_json::from_str::(&body) { - Ok(v) => { - let pretty = serde_json::to_string_pretty(&v).unwrap_or(body.clone()); - crate::append_error_log(format!("env: /environments JSON (pretty):\n{pretty}")); - } - Err(_) => crate::append_error_log(format!("env: /environments (raw):\n{body}")), - } - if !status.is_success() { - anyhow::bail!("GET {list_url} failed: {status}; content-type={ct}; body={body}"); - } - let all_envs: Vec = serde_json::from_str(&body).map_err(|e| { - anyhow::anyhow!("Decode error for {list_url}: {e}; content-type={ct}; body={body}") - })?; - if let Some(env) = pick_environment_row(&all_envs, desired_label.as_deref()) { - return Ok(AutodetectSelection { - id: env.id.clone(), - label: env.label.as_deref().map(str::to_owned), - }); - } - anyhow::bail!("no environments available") -} - -fn pick_environment_row( - envs: &[CodeEnvironment], - desired_label: Option<&str>, -) -> Option { - if envs.is_empty() { - return None; - } - if let Some(label) = desired_label { - let lc = label.to_lowercase(); - if let Some(e) = envs - .iter() - .find(|e| e.label.as_deref().unwrap_or("").to_lowercase() == lc) - { - crate::append_error_log(format!("env: matched by label: {label} -> {}", e.id)); - return Some(e.clone()); - } - } - if envs.len() == 1 { - crate::append_error_log("env: single environment available; selecting it"); - return Some(envs[0].clone()); - } - if let Some(e) = envs.iter().find(|e| e.is_pinned.unwrap_or(false)) { - crate::append_error_log(format!("env: selecting pinned environment: {}", e.id)); - return Some(e.clone()); - } - // Highest task_count as heuristic - if let Some(e) = envs - .iter() - .max_by_key(|e| e.task_count.unwrap_or(0)) - .or_else(|| envs.first()) - { - crate::append_error_log(format!("env: selecting by task_count/first: {}", e.id)); - return Some(e.clone()); - } - None -} - -async fn get_json( - http: &impl EnvironmentHttp, - url: &str, - headers: &HeaderMap, -) -> anyhow::Result { - let response = http.get(url, headers).await?; - let status = response.status; - let ct = response.content_type; - let body = response.body; - crate::append_error_log(format!("env: status={status} content-type={ct}")); - if !status.is_success() { - anyhow::bail!("GET {url} failed: {status}; content-type={ct}; body={body}"); - } - let parsed = serde_json::from_str::(&body).map_err(|e| { - anyhow::anyhow!("Decode error for {url}: {e}; content-type={ct}; body={body}") - })?; - Ok(parsed) -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct EnvironmentResponse { - status: StatusCode, - content_type: String, - body: String, -} - -/// HTTP boundary used by environment discovery. -/// -/// Implementations must issue a GET for the complete `url`, forward all supplied headers, and -/// return the response status, content type, and body for the caller to validate and decode. -trait EnvironmentHttp: Send + Sync { - fn get<'a>( - &'a self, - url: &'a str, - headers: &'a HeaderMap, - ) -> impl std::future::Future> + Send + 'a; -} - -impl EnvironmentHttp for EnvironmentClient { - async fn get(&self, url: &str, headers: &HeaderMap) -> anyhow::Result { - let headers = match &self.auth { - Some(auth) => { - auth.resolve(headers) - .await? - .auth - .apply_auth_headers(headers.clone()) - .await? - } - None => headers.clone(), - }; - let response = self.http.get(url).headers(headers).send().await?; - Ok(EnvironmentResponse { - status: response.status(), - content_type: response - .headers() - .get(CONTENT_TYPE) - .and_then(|value| value.to_str().ok()) - .unwrap_or("") - .to_string(), - body: response.text().await.unwrap_or_default(), - }) - } -} - -fn get_git_origins() -> Vec { - // Prefer: git config --get-regexp remote\..*\.url - let out = std::process::Command::new("git") - .args(["-c", codex_git_utils::SAFE_BARE_REPOSITORY_CONFIG]) - .args(["config", "--get-regexp", "remote\\..*\\.url"]) - .output(); - if let Ok(ok) = out - && ok.status.success() - { - let s = String::from_utf8_lossy(&ok.stdout); - let mut urls = Vec::new(); - for line in s.lines() { - if let Some((_, url)) = line.split_once(' ') - && let Ok(url) = SanitizedGitUrl::try_from(url.trim()) - { - urls.push(url); - } - } - if !urls.is_empty() { - return uniq(urls); - } - } - // Fallback: git remote -v - let out = std::process::Command::new("git") - .args(["-c", codex_git_utils::SAFE_BARE_REPOSITORY_CONFIG]) - .args(["remote", "-v"]) - .output(); - if let Ok(ok) = out - && ok.status.success() - { - let s = String::from_utf8_lossy(&ok.stdout); - let mut urls = Vec::new(); - for line in s.lines() { - let parts: Vec<&str> = line.split_whitespace().collect(); - if parts.len() >= 2 - && let Ok(url) = SanitizedGitUrl::try_from(parts[1]) - { - urls.push(url); - } - } - if !urls.is_empty() { - return uniq(urls); - } - } - Vec::new() -} - -fn uniq(mut v: Vec) -> Vec { - v.sort(); - v.dedup(); - v -} - -fn parse_owner_repo(url: &str) -> Option<(String, String)> { - // Normalize common prefixes and handle multiple SSH/HTTPS variants. - let mut s = url.trim().to_string(); - // Drop protocol scheme for ssh URLs - if let Some(rest) = s.strip_prefix("ssh://") { - s = rest.to_string(); - } - // Accept any user before @github.com (e.g., git@, org-123@) - if let Some(idx) = s.find("@github.com:") { - let rest = &s[idx + "@github.com:".len()..]; - let rest = rest.trim_start_matches('/').trim_end_matches(".git"); - let mut parts = rest.splitn(2, '/'); - let owner = parts.next()?.to_string(); - let repo = parts.next()?.to_string(); - crate::append_error_log(format!("env: parsed SSH GitHub origin => {owner}/{repo}")); - return Some((owner, repo)); - } - // HTTPS or git protocol - for prefix in [ - "https://github.com/", - "http://github.com/", - "git://github.com/", - "github.com/", - "github.com:", - ] { - if let Some(rest) = s.strip_prefix(prefix) { - let rest = rest.trim_start_matches('/').trim_end_matches(".git"); - let mut parts = rest.splitn(2, '/'); - let owner = parts.next()?.to_string(); - let repo = parts.next()?.to_string(); - crate::append_error_log(format!("env: parsed HTTP GitHub origin => {owner}/{repo}")); - return Some((owner, repo)); - } - } - None -} - -/// List environments for the current repo(s) with a fallback to the global list. -/// Returns a de-duplicated, sorted set suitable for the TUI modal. -pub(crate) async fn list_environments( - http: &EnvironmentClient, - base_url: &str, - headers: &HeaderMap, -) -> anyhow::Result> { - list_environments_with_origins(http, base_url, headers, &get_git_origins()).await -} - -async fn list_environments_with_origins( - http: &impl EnvironmentHttp, - base_url: &str, - headers: &HeaderMap, - origins: &[SanitizedGitUrl], -) -> anyhow::Result> { - let mut map: HashMap = HashMap::new(); - - // 1) By-repo lookup for each parsed GitHub origin - for origin in origins { - if let Some((owner, repo)) = parse_owner_repo(origin.as_str()) { - let url = if base_url.contains("/backend-api") { - format!( - "{}/wham/environments/by-repo/{}/{}/{}", - base_url, "github", owner, repo - ) - } else { - format!( - "{}/api/codex/environments/by-repo/{}/{}/{}", - base_url, "github", owner, repo - ) - }; - match get_json::>(http, &url, headers).await { - Ok(list) => { - info!("env_tui: by-repo {}:{} -> {} envs", owner, repo, list.len()); - for e in list { - let entry = - map.entry(e.id.clone()) - .or_insert_with(|| crate::app::EnvironmentRow { - id: e.id.clone(), - label: e.label.clone(), - is_pinned: e.is_pinned.unwrap_or(false), - repo_hints: Some(format!("{owner}/{repo}")), - }); - // Merge: keep label if present, or use new; accumulate pinned flag - if entry.label.is_none() { - entry.label = e.label.clone(); - } - entry.is_pinned = entry.is_pinned || e.is_pinned.unwrap_or(false); - if entry.repo_hints.is_none() { - entry.repo_hints = Some(format!("{owner}/{repo}")); - } - } - } - Err(e) => { - warn!( - "env_tui: by-repo fetch failed for {}/{}: {}", - owner, repo, e - ); - } - } - } - } - - // 2) Fallback to the full list; on error return what we have if any. - let list_url = if base_url.contains("/backend-api") { - format!("{base_url}/wham/environments") - } else { - format!("{base_url}/api/codex/environments") - }; - match get_json::>(http, &list_url, headers).await { - Ok(list) => { - info!("env_tui: global list -> {} envs", list.len()); - for e in list { - let entry = map - .entry(e.id.clone()) - .or_insert_with(|| crate::app::EnvironmentRow { - id: e.id.clone(), - label: e.label.clone(), - is_pinned: e.is_pinned.unwrap_or(false), - repo_hints: None, - }); - if entry.label.is_none() { - entry.label = e.label.clone(); - } - entry.is_pinned = entry.is_pinned || e.is_pinned.unwrap_or(false); - } - } - Err(e) => { - if map.is_empty() { - return Err(e); - } else { - warn!( - "env_tui: global list failed; using by-repo results only: {}", - e - ); - } - } - } - - let mut rows: Vec = map.into_values().collect(); - rows.sort_by(|a, b| { - // pinned first - let p = b.is_pinned.cmp(&a.is_pinned); - if p != std::cmp::Ordering::Equal { - return p; - } - // then label (ci), then id - let al = a.label.as_deref().unwrap_or("").to_lowercase(); - let bl = b.label.as_deref().unwrap_or("").to_lowercase(); - let l = al.cmp(&bl); - if l != std::cmp::Ordering::Equal { - return l; - } - a.id.cmp(&b.id) - }); - Ok(rows) -} - -#[cfg(test)] -#[path = "env_detect_tests.rs"] -mod tests; - -#[cfg(test)] -#[path = "env_detect_runtime_auth_tests.rs"] -mod runtime_auth_tests; diff --git a/codex-rs/cloud-tasks/src/env_detect_runtime_auth_tests.rs b/codex-rs/cloud-tasks/src/env_detect_runtime_auth_tests.rs deleted file mode 100644 index 9cb8d92b2c..0000000000 --- a/codex-rs/cloud-tasks/src/env_detect_runtime_auth_tests.rs +++ /dev/null @@ -1,130 +0,0 @@ -//! Environment discovery must resolve runtime authentication for each HTTP request. - -use super::*; -use codex_features::RuntimeAuthMode; -use codex_http_client::ClientRouteClass; -use codex_http_client::HttpClientFactory; -use codex_http_client::OutboundProxyPolicy; -use codex_login::AuthManager; -use codex_login::CodexAuth; -use codex_runtime_agent_instance::AgentHostAuthorization; -use codex_runtime_agent_instance::RuntimeAuthManager; -use codex_runtime_agent_instance::RuntimeRegistrationMetadata; -use codex_runtime_agent_instance::RuntimeRole; -use pretty_assertions::assert_eq; -use std::collections::HashSet; -use std::sync::Arc; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::path; - -struct ChangingCredentials(std::sync::RwLock); - -impl codex_login::ExternalAuth for ChangingCredentials { - fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, CodexAuth> { - Box::pin(async { Ok(self.0.read().unwrap().clone()) }) - } - - fn refresh( - &self, - _: codex_login::ExternalAuthRefreshContext, - ) -> codex_login::ExternalAuthFuture<'_, CodexAuth> { - self.resolve() - } -} - -#[tokio::test] -async fn discovery_signs_each_get_and_rejects_a_changed_credential_source() { - for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { - let server = MockServer::start().await; - Mock::given(path("/agent/register")).respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "runtime_agent_instance_id": "runtime-cloud", "agent_host_id": "host-a", - "actor": {"kind": "platform", "user_id": "user-a", "organization_id": "org-a", "project_id": null}, - }))).mount(&server).await; - Mock::given(path("/api/codex/environments")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([]))) - .expect(2) - .mount(&server) - .await; - let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault); - let auth = CodexAuth::from_api_key("key-a"); - let credentials = AuthManager::from_auth_for_testing(auth.clone()); - let source = Arc::new(ChangingCredentials(std::sync::RwLock::new(auth.clone()))); - credentials.set_external_auth(source.clone()).await.unwrap(); - let runtime = ( - Arc::new(RuntimeAuthManager::new( - credentials, - AgentHostAuthorization::InstallationId { - installation_id: uuid::Uuid::nil(), - }, - RuntimeRegistrationMetadata { - harness: Some("codex".into()), - harness_version: None, - role: RuntimeRole::Orchestrator, - }, - format!("{}/agent/register", server.uri()).parse().unwrap(), - )), - mode, - ); - let (auth, factory) = ClientAuth::for_auth( - &auth, - Some(&runtime), - factory, - /*headers*/ &Default::default(), - ) - .await - .unwrap(); - let client = EnvironmentClient { - http: RouteAwareClientPool::new_without_redirects_or_request_logging( - factory, - ClientRouteClass::Api, - ), - auth: Some(auth), - }; - for _ in 0..2 { - assert!( - list_environments_with_origins(&client, &server.uri(), &HeaderMap::new(), &[]) - .await - .unwrap() - .is_empty() - ); - } - assert_eq!( - server - .received_requests() - .await - .unwrap() - .iter() - .filter(|request| request.url.path() == "/agent/register") - .count(), - 1, - ); - *source.0.write().unwrap() = CodexAuth::from_api_key("key-b"); - assert!( - list_environments_with_origins(&client, &server.uri(), &HeaderMap::new(), &[]) - .await - .is_err() - ); - let requests = server.received_requests().await.unwrap(); - let proofs: HashSet<_> = requests - .iter() - .filter(|r| r.url.path() != "/agent/register") - .map(|r| { - let authorization = r.headers["authorization"].to_str().unwrap(); - match mode { - RuntimeAuthMode::DualHeader => { - assert_eq!(authorization, "Bearer key-a"); - r.headers["x-openai-agent-assertion"].to_str().unwrap() - } - RuntimeAuthMode::AssertionOnly => { - assert!(!r.headers.contains_key("x-openai-agent-assertion")); - authorization.strip_prefix("AgentAssertion ").unwrap() - } - } - }) - .collect(); - assert_eq!(proofs.len(), 2); - server.verify().await; - } -} diff --git a/codex-rs/cloud-tasks/src/env_detect_tests.rs b/codex-rs/cloud-tasks/src/env_detect_tests.rs deleted file mode 100644 index 2b14833d19..0000000000 --- a/codex-rs/cloud-tasks/src/env_detect_tests.rs +++ /dev/null @@ -1,362 +0,0 @@ -use std::collections::HashMap; -use std::io; -use std::io::Read; -use std::io::Write; -use std::sync::Mutex; -use std::time::Duration; -use std::time::Instant; - -use codex_http_client::ClientRouteClass; -use codex_http_client::HttpClientFactory; -use codex_http_client::OutboundProxyPolicy; -use http::HeaderMap; -use http::HeaderValue; -use http::StatusCode; -use http::header::AUTHORIZATION; -use pretty_assertions::assert_eq; - -use super::*; - -const BASE_URL: &str = "https://chatgpt.com/backend-api"; -const BY_REPO_URL: &str = - "https://chatgpt.com/backend-api/wham/environments/by-repo/github/openai/codex"; -const GLOBAL_URL: &str = "https://chatgpt.com/backend-api/wham/environments"; - -#[tokio::test] -async fn production_http_forwards_headers_and_decodes_response() { - let listener = std::net::TcpListener::bind(("127.0.0.1", 0)) - .expect("environment HTTP listener should bind"); - let address = listener - .local_addr() - .expect("environment HTTP listener should have an address"); - listener - .set_nonblocking(true) - .expect("environment HTTP listener should become nonblocking"); - let server = std::thread::spawn(move || { - let deadline = Instant::now() + Duration::from_secs(10); - let (mut stream, _) = loop { - match listener.accept() { - Ok(connection) => break connection, - Err(error) if error.kind() == io::ErrorKind::WouldBlock => { - assert!( - Instant::now() < deadline, - "environment HTTP listener should receive a request" - ); - std::thread::sleep(Duration::from_millis(10)); - } - Err(error) => panic!("environment HTTP listener should accept: {error}"), - } - }; - stream - .set_nonblocking(false) - .expect("environment HTTP stream should become blocking"); - stream - .set_read_timeout(Some(Duration::from_secs(10))) - .expect("environment HTTP stream should get a read timeout"); - let mut request = Vec::new(); - let mut buffer = [0_u8; 1024]; - loop { - let bytes_read = stream - .read(&mut buffer) - .expect("environment HTTP request should read"); - if bytes_read == 0 { - break; - } - request.extend_from_slice(&buffer[..bytes_read]); - if request.windows(4).any(|window| window == b"\r\n\r\n") { - break; - } - } - - let body = r#"[{"id":"env-real","label":"Real"}]"#; - write!( - stream, - "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - ) - .expect("environment HTTP response should write"); - String::from_utf8(request).expect("environment HTTP request should be UTF-8") - }); - let http = EnvironmentClient { - http: RouteAwareClientPool::new_without_request_logging( - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - ClientRouteClass::Api, - ), - auth: None, - }; - let base_url = format!("http://{address}"); - let headers = - HeaderMap::from_iter([(AUTHORIZATION, HeaderValue::from_static("Bearer real-token"))]); - - let selection = tokio::time::timeout( - Duration::from_secs(10), - autodetect_environment_id_with_origins( - &http, - &base_url, - &headers, - /*desired_label*/ None, - &[], - ), - ) - .await - .expect("environment request should finish") - .expect("environment response should decode"); - let request = server - .join() - .expect("environment HTTP server should finish"); - - assert_eq!( - selection, - AutodetectSelection { - id: "env-real".to_string(), - label: Some("Real".to_string()), - } - ); - assert!(request.starts_with("GET /api/codex/environments HTTP/1.1\r\n")); - assert!( - request - .to_ascii_lowercase() - .contains("authorization: bearer real-token\r\n") - ); -} - -#[tokio::test] -async fn autodetect_requests_exact_repository_endpoint_and_decodes_selection() { - let http = FakeHttp::new(HashMap::from([( - BY_REPO_URL.to_string(), - json_response(r#"[{"id":"env-repo","label":"Repository","is_pinned":true}]"#), - )])); - - let headers = HeaderMap::from_iter([( - AUTHORIZATION, - HeaderValue::from_static("Bearer forwarded-token"), - )]); - let selection = autodetect_environment_id_with_origins( - &http, - BASE_URL, - &headers, - Some("Repository".to_string()), - &[SanitizedGitUrl::try_from("git@github.com:openai/codex.git").expect("valid Git remote")], - ) - .await - .expect("repository environment should be selected"); - - assert_eq!( - selection, - AutodetectSelection { - id: "env-repo".to_string(), - label: Some("Repository".to_string()), - } - ); - assert_eq!( - http.requests(), - vec![RecordedRequest { - url: BY_REPO_URL.to_string(), - headers, - }] - ); -} - -/// Repository discovery must accept credential-bearing origins without exposing credentials. -#[tokio::test] -async fn autodetect_sanitizes_credential_bearing_git_origins() { - let http = FakeHttp::new(HashMap::from([( - BY_REPO_URL.to_string(), - json_response(r#"[{"id":"env-repo","label":"Repository"}]"#), - )])); - - let selection = autodetect_environment_id_with_origins( - &http, - BASE_URL, - &HeaderMap::new(), - /*desired_label*/ None, - &[SanitizedGitUrl::try_from( - "https://alice:synthetic-git-secret@github.com/openai/codex.git", - ) - .expect("valid Git remote")], - ) - .await - .expect("repository environment should be selected"); - - assert_eq!( - selection, - AutodetectSelection { - id: "env-repo".to_string(), - label: Some("Repository".to_string()), - } - ); - assert_eq!(http.requested_urls(), vec![BY_REPO_URL.to_string()]); -} - -/// Removing an SCP remote username must not prevent repository-specific discovery. -#[tokio::test] -async fn autodetect_recognizes_sanitized_scp_git_origins() { - let http = FakeHttp::new(HashMap::from([( - BY_REPO_URL.to_string(), - json_response(r#"[{"id":"env-repo","label":"Repository"}]"#), - )])); - - let selection = autodetect_environment_id_with_origins( - &http, - BASE_URL, - &HeaderMap::new(), - /*desired_label*/ None, - &[ - SanitizedGitUrl::try_from("org-123@github.com:openai/codex.git") - .expect("valid Git remote"), - ], - ) - .await - .expect("repository environment should be selected"); - - assert_eq!( - selection, - AutodetectSelection { - id: "env-repo".to_string(), - label: Some("Repository".to_string()), - } - ); - assert_eq!(http.requested_urls(), vec![BY_REPO_URL.to_string()]); -} - -#[tokio::test] -async fn autodetect_falls_back_to_exact_global_endpoint_and_decodes_selection() { - let http = FakeHttp::new(HashMap::from([ - (BY_REPO_URL.to_string(), json_response("[]")), - ( - GLOBAL_URL.to_string(), - json_response(r#"[{"id":"env-global","label":"Global"}]"#), - ), - ])); - - let selection = autodetect_environment_id_with_origins( - &http, - BASE_URL, - &HeaderMap::new(), - /*desired_label*/ None, - &[SanitizedGitUrl::try_from("git@github.com:openai/codex.git").expect("valid Git remote")], - ) - .await - .expect("global environment should be selected"); - - assert_eq!( - selection, - AutodetectSelection { - id: "env-global".to_string(), - label: Some("Global".to_string()), - } - ); - assert_eq!( - http.requested_urls(), - vec![BY_REPO_URL.to_string(), GLOBAL_URL.to_string()] - ); -} - -#[tokio::test] -async fn list_requests_exact_repository_and_global_endpoints_and_merges_results() { - let http = FakeHttp::new(HashMap::from([ - ( - BY_REPO_URL.to_string(), - json_response(r#"[{"id":"env-repo","label":"Repository"}]"#), - ), - ( - GLOBAL_URL.to_string(), - json_response( - r#"[{"id":"env-repo","is_pinned":true},{"id":"env-global","label":"Global"}]"#, - ), - ), - ])); - - let rows = list_environments_with_origins( - &http, - BASE_URL, - &HeaderMap::new(), - &[ - SanitizedGitUrl::try_from("https://github.com/openai/codex.git") - .expect("valid Git remote"), - ], - ) - .await - .expect("environment list should decode"); - - assert_eq!( - rows.into_iter() - .map(|row| (row.id, row.label, row.is_pinned, row.repo_hints)) - .collect::>(), - vec![ - ( - "env-repo".to_string(), - Some("Repository".to_string()), - true, - Some("openai/codex".to_string()), - ), - ( - "env-global".to_string(), - Some("Global".to_string()), - false, - None, - ), - ] - ); - assert_eq!( - http.requested_urls(), - vec![BY_REPO_URL.to_string(), GLOBAL_URL.to_string()] - ); -} - -struct FakeHttp { - responses: HashMap, - requests: Mutex>, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct RecordedRequest { - url: String, - headers: HeaderMap, -} - -impl FakeHttp { - fn new(responses: HashMap) -> Self { - Self { - responses, - requests: Mutex::new(Vec::new()), - } - } - - fn requests(&self) -> Vec { - self.requests.lock().expect("request lock").clone() - } - - fn requested_urls(&self) -> Vec { - self.requests - .lock() - .expect("request lock") - .iter() - .map(|request| request.url.clone()) - .collect() - } -} - -impl EnvironmentHttp for FakeHttp { - async fn get(&self, url: &str, headers: &HeaderMap) -> anyhow::Result { - self.requests - .lock() - .expect("request lock") - .push(RecordedRequest { - url: url.to_string(), - headers: headers.clone(), - }); - self.responses - .get(url) - .cloned() - .ok_or_else(|| anyhow::anyhow!("unexpected URL: {url}")) - } -} - -fn json_response(body: &str) -> EnvironmentResponse { - EnvironmentResponse { - status: StatusCode::OK, - content_type: "application/json".to_string(), - body: body.to_string(), - } -} diff --git a/codex-rs/cloud-tasks/src/lib.rs b/codex-rs/cloud-tasks/src/lib.rs deleted file mode 100644 index 864e9e067c..0000000000 --- a/codex-rs/cloud-tasks/src/lib.rs +++ /dev/null @@ -1,2467 +0,0 @@ -mod app; -#[cfg(test)] -mod backend_auth_tests; -mod cli; -pub(crate) mod env_detect; -mod new_task; -pub(crate) mod scrollable_diff; -mod ui; -pub(crate) mod util; -pub use cli::Cli; - -use anyhow::anyhow; -use chrono::Utc; -use codex_cloud_tasks_client::TaskStatus; -use codex_git_utils::current_branch_name; -use codex_git_utils::default_branch_name; -use codex_http_client::ClientRouteClass; -use codex_http_client::RouteAwareClientPool; -use codex_login::CodexAuth; -use codex_login::default_client::get_codex_user_agent; -use codex_model_provider::ClientAuth; -use codex_model_provider::auth_provider_from_auth_manager; -use codex_utils_cli::CliConfigOverrides; -use owo_colors::OwoColorize; -use owo_colors::Stream; -use std::cmp::Ordering; -use std::io::IsTerminal; -use std::io::Read; -use std::path::PathBuf; -use std::sync::Arc; -use std::time::Duration; -use std::time::Instant; -use supports_color::Stream as SupportStream; -use tokio::sync::mpsc::UnboundedSender; -use tracing::info; -use tracing_subscriber::EnvFilter; -use util::append_error_log; -use util::format_relative_time; -use util::set_user_agent_suffix; - -struct ApplyJob { - task_id: codex_cloud_tasks_client::TaskId, - diff_override: Option, -} - -struct BackendContext { - backend: Arc, - base_url: String, - environment_http: env_detect::EnvironmentClient, -} - -async fn init_backend( - user_agent_suffix: &str, - config_overrides: &CliConfigOverrides, -) -> anyhow::Result { - #[cfg(debug_assertions)] - let use_mock = matches!( - std::env::var("CODEX_CLOUD_TASKS_MODE").ok().as_deref(), - Some("mock") | Some("MOCK") - ); - let base_url = std::env::var("CODEX_CLOUD_TASKS_BASE_URL") - .unwrap_or_else(|_| "https://chatgpt.com/backend-api".to_string()); - let base_url = util::validate_chatgpt_base_url(&base_url)?; - - set_user_agent_suffix(user_agent_suffix); - - let ua = get_codex_user_agent(); - let (auth_manager, http_client_factory, config) = - util::load_auth_manager(Some(base_url.clone()), config_overrides).await?; - let auth = match auth_manager.as_ref() { - Some(manager) => manager.auth().await, - None => None, - }; - // Existing agent assertions and supplied headers cannot register a new runtime. - let runtime = if let (Some(config), Some(auth_manager)) = (config, auth_manager.as_ref()) - && config - .features - .enabled(codex_features::Feature::RuntimeAgentInstances) - && matches!( - auth.as_ref(), - Some( - CodexAuth::Chatgpt(_) - | CodexAuth::ChatgptAuthTokens(_) - | CodexAuth::PersonalAccessToken(_) - ) - ) { - // Use the validated command destination for registration as well as actor refresh. - let mut config = config; - config.chatgpt_base_url = base_url.clone(); - let installation_id = codex_core::resolve_installation_id(&config.codex_home).await?; - codex_core::build_runtime_auth_manager(&config, Arc::clone(auth_manager), &installation_id) - .map(|runtime| (runtime, config.runtime_auth_mode)) - } else { - None - }; - let (environment_auth, http_client_factory) = - match auth.as_ref().filter(|auth| auth.uses_codex_backend()) { - Some(auth) => { - let (mut client_auth, factory) = ClientAuth::for_auth( - auth, - runtime.as_ref(), - http_client_factory, - /*headers*/ &Default::default(), - ) - .await?; - if runtime.is_none() - && let Some(auth_manager) = auth_manager.as_ref() - { - client_auth.set_provider(auth_provider_from_auth_manager( - Arc::clone(auth_manager), - auth, - ))?; - } - (Some(client_auth), factory) - } - None => (None, http_client_factory), - }; - let environment_http = env_detect::EnvironmentClient { - http: RouteAwareClientPool::new_without_redirects_or_request_logging( - http_client_factory.clone(), - ClientRouteClass::Api, - ), - auth: environment_auth, - }; - #[cfg(debug_assertions)] - if use_mock { - return Ok(BackendContext { - backend: Arc::new(codex_cloud_tasks_mock_client::MockClient), - base_url, - environment_http, - }); - } - - let style = if base_url.contains("/backend-api") { - "wham" - } else { - "codex-api" - }; - append_error_log(format!("startup: base_url={base_url} path_style={style}")); - - let auth = match auth { - Some(auth) => auth, - None => { - eprintln!( - "Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'." - ); - std::process::exit(1); - } - }; - - if let Some(acc) = auth.get_account_id() { - append_error_log(format!("auth: mode=ChatGPT account_id={acc}")); - } - - if !auth.uses_codex_backend() { - eprintln!( - "Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'." - ); - std::process::exit(1); - } - - let backend = codex_backend_client::Client::from_auth_with_runtime_without_redirects( - base_url.clone(), - &auth, - http_client_factory, - runtime.as_ref(), - /*headers*/ &Default::default(), - ) - .await?; - let http = codex_cloud_tasks_client::HttpClient::from_backend( - base_url.clone(), - backend.with_user_agent(ua), - ); - if let Some(acc) = auth.get_account_id() { - append_error_log(format!("auth: set ChatGPT-Account-Id header: {acc}")); - } - - Ok(BackendContext { - backend: Arc::new(http), - base_url, - environment_http, - }) -} - -trait GitInfoProvider { - fn default_branch_name( - &self, - path: &std::path::Path, - ) -> impl std::future::Future> + Send; - - fn current_branch_name( - &self, - path: &std::path::Path, - ) -> impl std::future::Future> + Send; -} - -struct RealGitInfo; - -impl GitInfoProvider for RealGitInfo { - async fn default_branch_name(&self, path: &std::path::Path) -> Option { - default_branch_name(path).await - } - - async fn current_branch_name(&self, path: &std::path::Path) -> Option { - current_branch_name(path).await - } -} - -async fn resolve_git_ref(branch_override: Option<&String>) -> String { - resolve_git_ref_with_git_info(branch_override, &RealGitInfo).await -} - -async fn resolve_git_ref_with_git_info( - branch_override: Option<&String>, - git_info: &impl GitInfoProvider, -) -> String { - if let Some(branch) = branch_override { - let branch = branch.trim(); - if !branch.is_empty() { - return branch.to_string(); - } - } - - if let Ok(cwd) = std::env::current_dir() { - if let Some(branch) = git_info.current_branch_name(&cwd).await { - branch - } else if let Some(branch) = git_info.default_branch_name(&cwd).await { - branch - } else { - "main".to_string() - } - } else { - "main".to_string() - } -} - -async fn run_exec_command( - args: crate::cli::ExecCommand, - ctx: BackendContext, -) -> anyhow::Result<()> { - let crate::cli::ExecCommand { - query, - environment, - branch, - attempts, - } = args; - let prompt = resolve_query_input(query)?; - let env_id = resolve_environment_id(&ctx, &environment).await?; - let git_ref = resolve_git_ref(branch.as_ref()).await; - let created = codex_cloud_tasks_client::CloudBackend::create_task( - &*ctx.backend, - &env_id, - &prompt, - &git_ref, - /*qa_mode*/ false, - attempts, - ) - .await?; - let url = util::task_url(&ctx.base_url, &created.id.0); - println!("{url}"); - Ok(()) -} - -async fn resolve_environment_id(ctx: &BackendContext, requested: &str) -> anyhow::Result { - let trimmed = requested.trim(); - if trimmed.is_empty() { - return Err(anyhow!("environment id must not be empty")); - } - let normalized = util::normalize_base_url(&ctx.base_url); - let headers = util::build_chatgpt_headers(); - let environments = - crate::env_detect::list_environments(&ctx.environment_http, &normalized, &headers).await?; - if environments.is_empty() { - return Err(anyhow!( - "no cloud environments are available for this workspace" - )); - } - - if let Some(row) = environments.iter().find(|row| row.id == trimmed) { - return Ok(row.id.clone()); - } - - let label_matches = environments - .iter() - .filter(|row| { - row.label - .as_deref() - .map(|label| label.eq_ignore_ascii_case(trimmed)) - .unwrap_or(false) - }) - .collect::>(); - match label_matches.as_slice() { - [] => Err(anyhow!( - "environment '{trimmed}' not found; run `codex cloud` to list available environments" - )), - [single] => Ok(single.id.clone()), - [first, rest @ ..] => { - let first_id = &first.id; - if rest.iter().all(|row| row.id == *first_id) { - Ok(first_id.clone()) - } else { - Err(anyhow!( - "environment label '{trimmed}' is ambiguous; run `codex cloud` to pick the desired environment id" - )) - } - } - } -} - -fn resolve_query_input(query_arg: Option) -> anyhow::Result { - match query_arg { - Some(q) if q != "-" => Ok(q), - maybe_dash => { - let force_stdin = matches!(maybe_dash.as_deref(), Some("-")); - if std::io::stdin().is_terminal() && !force_stdin { - return Err(anyhow!( - "no query provided. Pass one as an argument or pipe it via stdin." - )); - } - if !force_stdin { - eprintln!("Reading query from stdin..."); - } - let mut buffer = String::new(); - std::io::stdin() - .read_to_string(&mut buffer) - .map_err(|e| anyhow!("failed to read query from stdin: {e}"))?; - if buffer.trim().is_empty() { - return Err(anyhow!( - "no query provided via stdin (received empty input)." - )); - } - Ok(buffer) - } - } -} - -fn parse_task_id(raw: &str) -> anyhow::Result { - let trimmed = raw.trim(); - if trimmed.is_empty() { - anyhow::bail!("task id must not be empty"); - } - let without_fragment = trimmed.split('#').next().unwrap_or(trimmed); - let without_query = without_fragment - .split('?') - .next() - .unwrap_or(without_fragment); - let id = without_query - .rsplit('/') - .next() - .unwrap_or(without_query) - .trim(); - if id.is_empty() { - anyhow::bail!("task id must not be empty"); - } - Ok(codex_cloud_tasks_client::TaskId(id.to_string())) -} - -#[derive(Clone, Debug)] -struct AttemptDiffData { - placement: Option, - created_at: Option>, - diff: String, -} - -fn cmp_attempt(lhs: &AttemptDiffData, rhs: &AttemptDiffData) -> Ordering { - match (lhs.placement, rhs.placement) { - (Some(a), Some(b)) => a.cmp(&b), - (Some(_), None) => Ordering::Less, - (None, Some(_)) => Ordering::Greater, - (None, None) => match (lhs.created_at, rhs.created_at) { - (Some(a), Some(b)) => a.cmp(&b), - (Some(_), None) => Ordering::Less, - (None, Some(_)) => Ordering::Greater, - (None, None) => Ordering::Equal, - }, - } -} - -async fn collect_attempt_diffs( - backend: &dyn codex_cloud_tasks_client::CloudBackend, - task_id: &codex_cloud_tasks_client::TaskId, -) -> anyhow::Result> { - let text = - codex_cloud_tasks_client::CloudBackend::get_task_text(backend, task_id.clone()).await?; - let mut attempts = Vec::new(); - if let Some(diff) = - codex_cloud_tasks_client::CloudBackend::get_task_diff(backend, task_id.clone()).await? - { - attempts.push(AttemptDiffData { - placement: text.attempt_placement, - created_at: None, - diff, - }); - } - if let Some(turn_id) = text.turn_id { - let siblings = codex_cloud_tasks_client::CloudBackend::list_sibling_attempts( - backend, - task_id.clone(), - turn_id, - ) - .await?; - for sibling in siblings { - if let Some(diff) = sibling.diff { - attempts.push(AttemptDiffData { - placement: sibling.attempt_placement, - created_at: sibling.created_at, - diff, - }); - } - } - } - attempts.sort_by(cmp_attempt); - if attempts.is_empty() { - anyhow::bail!( - "No diff available for task {}; it may still be running.", - task_id.0 - ); - } - Ok(attempts) -} - -fn select_attempt( - attempts: &[AttemptDiffData], - attempt: Option, -) -> anyhow::Result<&AttemptDiffData> { - if attempts.is_empty() { - anyhow::bail!("No attempts available"); - } - let desired = attempt.unwrap_or(1); - let idx = desired - .checked_sub(1) - .ok_or_else(|| anyhow!("attempt must be at least 1"))?; - if idx >= attempts.len() { - anyhow::bail!( - "Attempt {desired} not available; only {} attempt(s) found", - attempts.len() - ); - } - Ok(&attempts[idx]) -} - -fn task_status_label(status: &TaskStatus) -> &'static str { - match status { - TaskStatus::Pending => "PENDING", - TaskStatus::Ready => "READY", - TaskStatus::Applied => "APPLIED", - TaskStatus::Error => "ERROR", - } -} - -fn summary_line(summary: &codex_cloud_tasks_client::DiffSummary, colorize: bool) -> String { - if summary.files_changed == 0 && summary.lines_added == 0 && summary.lines_removed == 0 { - let base = "no diff"; - return if colorize { - base.if_supports_color(Stream::Stdout, |t| t.dimmed()) - .to_string() - } else { - base.to_string() - }; - } - let adds = summary.lines_added; - let dels = summary.lines_removed; - let files = summary.files_changed; - if colorize { - let adds_raw = format!("+{adds}"); - let adds_str = adds_raw - .as_str() - .if_supports_color(Stream::Stdout, |t| t.green()) - .to_string(); - let dels_raw = format!("-{dels}"); - let dels_str = dels_raw - .as_str() - .if_supports_color(Stream::Stdout, |t| t.red()) - .to_string(); - let bullet = "•" - .if_supports_color(Stream::Stdout, |t| t.dimmed()) - .to_string(); - let file_label = format!("file{}", if files == 1 { "" } else { "s" }) - .if_supports_color(Stream::Stdout, |t| t.dimmed()) - .to_string(); - format!("{adds_str}/{dels_str} {bullet} {files} {file_label}") - } else { - format!( - "+{adds}/-{dels} • {files} file{}", - if files == 1 { "" } else { "s" } - ) - } -} - -fn format_task_status_lines( - task: &codex_cloud_tasks_client::TaskSummary, - now: chrono::DateTime, - colorize: bool, -) -> Vec { - let mut lines = Vec::new(); - let status = task_status_label(&task.status); - let status = if colorize { - match task.status { - TaskStatus::Ready => status - .if_supports_color(Stream::Stdout, |t| t.green()) - .to_string(), - TaskStatus::Pending => status - .if_supports_color(Stream::Stdout, |t| t.magenta()) - .to_string(), - TaskStatus::Applied => status - .if_supports_color(Stream::Stdout, |t| t.blue()) - .to_string(), - TaskStatus::Error => status - .if_supports_color(Stream::Stdout, |t| t.red()) - .to_string(), - } - } else { - status.to_string() - }; - lines.push(format!("[{status}] {}", task.title)); - let mut meta_parts = Vec::new(); - if let Some(label) = task.environment_label.as_deref().filter(|s| !s.is_empty()) { - if colorize { - meta_parts.push( - label - .if_supports_color(Stream::Stdout, |t| t.dimmed()) - .to_string(), - ); - } else { - meta_parts.push(label.to_string()); - } - } else if let Some(id) = task.environment_id.as_deref() { - if colorize { - meta_parts.push( - id.if_supports_color(Stream::Stdout, |t| t.dimmed()) - .to_string(), - ); - } else { - meta_parts.push(id.to_string()); - } - } - let when = format_relative_time(now, task.updated_at); - meta_parts.push(if colorize { - when.as_str() - .if_supports_color(Stream::Stdout, |t| t.dimmed()) - .to_string() - } else { - when - }); - let sep = if colorize { - " • " - .if_supports_color(Stream::Stdout, |t| t.dimmed()) - .to_string() - } else { - " • ".to_string() - }; - lines.push(meta_parts.join(&sep)); - lines.push(summary_line(&task.summary, colorize)); - lines -} - -fn format_task_list_lines( - tasks: &[codex_cloud_tasks_client::TaskSummary], - base_url: &str, - now: chrono::DateTime, - colorize: bool, -) -> Vec { - let mut lines = Vec::new(); - for (idx, task) in tasks.iter().enumerate() { - lines.push(util::task_url(base_url, &task.id.0)); - for line in format_task_status_lines(task, now, colorize) { - lines.push(format!(" {line}")); - } - if idx + 1 < tasks.len() { - lines.push(String::new()); - } - } - lines -} - -async fn run_status_command( - args: crate::cli::StatusCommand, - ctx: BackendContext, -) -> anyhow::Result<()> { - let task_id = parse_task_id(&args.task_id)?; - let summary = - codex_cloud_tasks_client::CloudBackend::get_task_summary(&*ctx.backend, task_id).await?; - let now = Utc::now(); - let colorize = supports_color::on(SupportStream::Stdout).is_some(); - for line in format_task_status_lines(&summary, now, colorize) { - println!("{line}"); - } - if !matches!(summary.status, TaskStatus::Ready) { - std::process::exit(1); - } - Ok(()) -} - -async fn run_list_command( - args: crate::cli::ListCommand, - ctx: BackendContext, -) -> anyhow::Result<()> { - let env_filter = if let Some(env) = args.environment { - Some(resolve_environment_id(&ctx, &env).await?) - } else { - None - }; - let page = codex_cloud_tasks_client::CloudBackend::list_tasks( - &*ctx.backend, - env_filter.as_deref(), - Some(args.limit), - args.cursor.as_deref(), - ) - .await?; - if args.json { - let tasks: Vec<_> = page - .tasks - .iter() - .map(|task| { - serde_json::json!({ - "id": task.id.0, - "url": util::task_url(&ctx.base_url, &task.id.0), - "title": task.title, - "status": task.status, - "updated_at": task.updated_at, - "environment_id": task.environment_id, - "environment_label": task.environment_label, - "summary": { - "files_changed": task.summary.files_changed, - "lines_added": task.summary.lines_added, - "lines_removed": task.summary.lines_removed, - }, - "is_review": task.is_review, - "attempt_total": task.attempt_total, - }) - }) - .collect(); - let payload = serde_json::json!({ - "tasks": tasks, - "cursor": page.cursor, - }); - println!("{}", serde_json::to_string_pretty(&payload)?); - return Ok(()); - } - if page.tasks.is_empty() { - println!("No tasks found."); - return Ok(()); - } - let now = Utc::now(); - let colorize = supports_color::on(SupportStream::Stdout).is_some(); - for line in format_task_list_lines(&page.tasks, &ctx.base_url, now, colorize) { - println!("{line}"); - } - if let Some(cursor) = page.cursor { - let command = format!("codex cloud list --cursor='{cursor}'"); - if colorize { - println!( - "\nTo fetch the next page, run {}", - command.if_supports_color(Stream::Stdout, |text| text.cyan()) - ); - } else { - println!("\nTo fetch the next page, run {command}"); - } - } - Ok(()) -} - -async fn run_diff_command( - args: crate::cli::DiffCommand, - ctx: BackendContext, -) -> anyhow::Result<()> { - let task_id = parse_task_id(&args.task_id)?; - let attempts = collect_attempt_diffs(&*ctx.backend, &task_id).await?; - let selected = select_attempt(&attempts, args.attempt)?; - print!("{}", selected.diff); - Ok(()) -} - -async fn run_apply_command( - args: crate::cli::ApplyCommand, - ctx: BackendContext, -) -> anyhow::Result<()> { - let task_id = parse_task_id(&args.task_id)?; - let attempts = collect_attempt_diffs(&*ctx.backend, &task_id).await?; - let selected = select_attempt(&attempts, args.attempt)?; - let outcome = codex_cloud_tasks_client::CloudBackend::apply_task( - &*ctx.backend, - task_id, - Some(selected.diff.clone()), - ) - .await?; - println!("{}", outcome.message); - if !matches!( - outcome.status, - codex_cloud_tasks_client::ApplyStatus::Success - ) { - std::process::exit(1); - } - Ok(()) -} - -fn level_from_status(status: codex_cloud_tasks_client::ApplyStatus) -> app::ApplyResultLevel { - match status { - codex_cloud_tasks_client::ApplyStatus::Success => app::ApplyResultLevel::Success, - codex_cloud_tasks_client::ApplyStatus::Partial => app::ApplyResultLevel::Partial, - codex_cloud_tasks_client::ApplyStatus::Error => app::ApplyResultLevel::Error, - } -} - -fn spawn_preflight( - app: &mut app::App, - backend: &Arc, - tx: &UnboundedSender, - frame_tx: &UnboundedSender, - title: String, - job: ApplyJob, -) -> bool { - if app.apply_inflight { - app.status = "An apply is already running; wait for it to finish first.".to_string(); - return false; - } - if app.apply_preflight_inflight { - app.status = "A preflight is already running; wait for it to finish first.".to_string(); - return false; - } - - app.apply_preflight_inflight = true; - let _ = frame_tx.send(Instant::now() + Duration::from_millis(100)); - - let backend = backend.clone(); - let tx = tx.clone(); - tokio::spawn(async move { - let ApplyJob { - task_id, - diff_override, - } = job; - let result = codex_cloud_tasks_client::CloudBackend::apply_task_preflight( - &*backend, - task_id.clone(), - diff_override, - ) - .await; - - let event = match result { - Ok(outcome) => { - let level = level_from_status(outcome.status); - app::AppEvent::ApplyPreflightFinished { - id: task_id, - title, - message: outcome.message, - level, - skipped: outcome.skipped_paths, - conflicts: outcome.conflict_paths, - } - } - Err(e) => app::AppEvent::ApplyPreflightFinished { - id: task_id, - title, - message: format!("Preflight failed: {e}"), - level: app::ApplyResultLevel::Error, - skipped: Vec::new(), - conflicts: Vec::new(), - }, - }; - - let _ = tx.send(event); - }); - - true -} - -fn spawn_apply( - app: &mut app::App, - backend: &Arc, - tx: &UnboundedSender, - frame_tx: &UnboundedSender, - job: ApplyJob, -) -> bool { - if app.apply_inflight { - app.status = "An apply is already running; wait for it to finish first.".to_string(); - return false; - } - if app.apply_preflight_inflight { - app.status = "Finish the current preflight before starting another apply.".to_string(); - return false; - } - - app.apply_inflight = true; - let _ = frame_tx.send(Instant::now() + Duration::from_millis(100)); - - let backend = backend.clone(); - let tx = tx.clone(); - tokio::spawn(async move { - let ApplyJob { - task_id, - diff_override, - } = job; - let result = codex_cloud_tasks_client::CloudBackend::apply_task( - &*backend, - task_id.clone(), - diff_override, - ) - .await; - - let event = match result { - Ok(outcome) => app::AppEvent::ApplyFinished { - id: task_id, - result: Ok(outcome), - }, - Err(e) => app::AppEvent::ApplyFinished { - id: task_id, - result: Err(format!("{e}")), - }, - }; - - let _ = tx.send(event); - }); - - true -} - -// logging helper lives in util module - -// (no standalone patch summarizer needed – UI displays raw diffs) - -/// Entry point for the `codex cloud` subcommand. -pub async fn run_main(cli: Cli, _codex_linux_sandbox_exe: Option) -> anyhow::Result<()> { - // Keep the Cloud future out of the CLI dispatcher frame while the TUI is running. - Box::pin(run_cloud(cli)).await -} - -async fn run_cloud(cli: Cli) -> anyhow::Result<()> { - let backend = |suffix| init_backend(suffix, &cli.config_overrides); - if let Some(command) = cli.command { - return match command { - crate::cli::Command::Exec(args) => { - run_exec_command(args, backend("codex_cloud_tasks_exec").await?).await - } - crate::cli::Command::Status(args) => { - run_status_command(args, backend("codex_cloud_tasks_status").await?).await - } - crate::cli::Command::List(args) => { - run_list_command(args, backend("codex_cloud_tasks_list").await?).await - } - crate::cli::Command::Apply(args) => { - run_apply_command(args, backend("codex_cloud_tasks_apply").await?).await - } - crate::cli::Command::Diff(args) => { - run_diff_command(args, backend("codex_cloud_tasks_diff").await?).await - } - }; - } - - // Very minimal logging setup; mirrors other crates' pattern. - let default_level = "error"; - let _ = tracing_subscriber::fmt() - .with_env_filter( - EnvFilter::try_from_default_env() - .or_else(|_| EnvFilter::try_new(default_level)) - .unwrap_or_else(|_| EnvFilter::new(default_level)), - ) - .with_ansi(std::io::stderr().is_terminal()) - .with_writer(std::io::stderr) - .try_init(); - - info!("Launching Cloud Tasks list UI"); - let BackendContext { - backend, - base_url, - environment_http, - } = backend("codex_cloud_tasks_tui").await?; - - // Terminal setup - use crossterm::ExecutableCommand; - use crossterm::event::DisableBracketedPaste; - use crossterm::event::EnableBracketedPaste; - use crossterm::event::KeyboardEnhancementFlags; - use crossterm::event::PopKeyboardEnhancementFlags; - use crossterm::event::PushKeyboardEnhancementFlags; - use crossterm::terminal::EnterAlternateScreen; - use crossterm::terminal::LeaveAlternateScreen; - use crossterm::terminal::disable_raw_mode; - use crossterm::terminal::enable_raw_mode; - use ratatui::Terminal; - use ratatui::backend::CrosstermBackend; - let mut stdout = std::io::stdout(); - enable_raw_mode()?; - stdout.execute(EnterAlternateScreen)?; - stdout.execute(EnableBracketedPaste)?; - // Enable enhanced key reporting so Shift+Enter is distinguishable from Enter. - // Some terminals may not support these flags; ignore errors if enabling fails. - let _ = crossterm::execute!( - std::io::stdout(), - PushKeyboardEnhancementFlags( - KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES - | KeyboardEnhancementFlags::REPORT_EVENT_TYPES - | KeyboardEnhancementFlags::REPORT_ALTERNATE_KEYS - ) - ); - let backend_ui = CrosstermBackend::new(stdout); - let mut terminal = Terminal::new(backend_ui)?; - terminal.clear()?; - - // App state - let mut app = app::App::new(); - // Initial load - let force_internal = matches!( - std::env::var("CODEX_CLOUD_TASKS_FORCE_INTERNAL") - .ok() - .as_deref(), - Some("1") | Some("true") | Some("TRUE") - ); - append_error_log(format!( - "startup: wham_force_internal={} ua={}", - force_internal, - get_codex_user_agent() - )); - // Non-blocking initial load so the in-box spinner can animate - app.status = "Loading tasks…".to_string(); - app.refresh_inflight = true; - // New list generation; reset background enrichment coordination - app.list_generation = app.list_generation.saturating_add(1); - app.in_flight.clear(); - // reset any in-flight enrichment state - - // Event stream - use crossterm::event::Event; - use crossterm::event::EventStream; - use crossterm::event::KeyCode; - use crossterm::event::KeyEventKind; - use crossterm::event::KeyModifiers; - use tokio_stream::StreamExt; - let mut events = EventStream::new(); - - // Channel for non-blocking background loads - use tokio::sync::mpsc::unbounded_channel; - let (tx, mut rx) = unbounded_channel::(); - // Kick off the initial load in background - { - let backend = Arc::clone(&backend); - let tx = tx.clone(); - tokio::spawn(async move { - let res = app::load_tasks(&*backend, /*env*/ None).await; - let _ = tx.send(app::AppEvent::TasksLoaded { - env: None, - result: res, - }); - }); - } - // Fetch environment list in parallel so the header can show friendly names quickly. - spawn_environment_load(tx.clone(), base_url.clone(), environment_http.clone()); - - // Try to auto-detect a likely environment id on startup and refresh if found. - // Do this concurrently so the initial list shows quickly; on success we refetch with filter. - { - let tx = tx.clone(); - let base_url = base_url.clone(); - let environment_http = environment_http.clone(); - tokio::spawn(async move { - let base_url = util::normalize_base_url(&base_url); - // Authentication is resolved by the environment client for each request. - let headers = util::build_chatgpt_headers(); - - // Run autodetect. If it fails, we keep using "All". - let res = crate::env_detect::autodetect_environment_id( - &environment_http, - &base_url, - &headers, - /*desired_label*/ None, - ) - .await; - let _ = tx.send(app::AppEvent::EnvironmentAutodetected(res)); - }); - } - - // Event-driven redraws with a tiny coalescing scheduler (snappy UI, no fixed 250ms tick). - let mut needs_redraw = true; - use std::time::Instant; - use tokio::time::Instant as TokioInstant; - use tokio::time::sleep_until; - let (frame_tx, mut frame_rx) = tokio::sync::mpsc::unbounded_channel::(); - let (redraw_tx, mut redraw_rx) = tokio::sync::mpsc::unbounded_channel::<()>(); - - // Coalesce frame requests to the earliest deadline; emit a single redraw signal. - tokio::spawn(async move { - let mut next_deadline: Option = None; - loop { - let target = - next_deadline.unwrap_or_else(|| Instant::now() + Duration::from_secs(24 * 60 * 60)); - let sleeper = sleep_until(TokioInstant::from_std(target)); - tokio::pin!(sleeper); - tokio::select! { - recv = frame_rx.recv() => { - match recv { - Some(at) => { - if next_deadline.is_none_or(|cur| at < cur) { - next_deadline = Some(at); - } - continue; // recompute sleep target - } - None => break, - } - } - _ = &mut sleeper => { - if next_deadline.take().is_some() { - let _ = redraw_tx.send(()); - } - } - } - } - }); - // Kick an initial draw so the UI appears immediately. - let _ = frame_tx.send(Instant::now()); - - // Render helper to centralize immediate redraws after handling events. - let render_if_needed = |terminal: &mut Terminal>, - app: &mut app::App, - needs_redraw: &mut bool| - -> anyhow::Result<()> { - if *needs_redraw { - if let Some(delay) = app - .new_task - .as_ref() - .and_then(|page| page.composer.footer_flash_delay()) - { - let _ = frame_tx.send(Instant::now() + delay); - } - terminal.draw(|f| ui::draw(f, app))?; - *needs_redraw = false; - } - Ok(()) - }; - - let exit_code = loop { - tokio::select! { - // Coalesced redraw requests: spinner animation and paste-burst micro‑flush. - Some(()) = redraw_rx.recv() => { - // Micro‑flush pending first key held by paste‑burst. - if let Some(page) = app.new_task.as_mut() { - needs_redraw = true; - page.composer.flush_paste_burst_if_due(); - if page.composer.is_in_paste_burst() { - let _ = frame_tx - .send(Instant::now() + codex_tui::ComposerInput::recommended_flush_delay()); - } - } - // Keep spinner pulsing only while loading. - if app.refresh_inflight - || app.details_inflight - || app.env_loading - || app.apply_preflight_inflight - || app.apply_inflight - { - if app.spinner_start.is_none() { - app.spinner_start = Some(Instant::now()); - } - needs_redraw = true; - let _ = frame_tx.send(Instant::now() + Duration::from_millis(600)); - } else { - app.spinner_start = None; - } - render_if_needed(&mut terminal, &mut app, &mut needs_redraw)?; - } - maybe_app_event = rx.recv() => { - if let Some(ev) = maybe_app_event { - match ev { - app::AppEvent::TasksLoaded { env, result } => { - // Only apply results for the current filter to avoid races. - if env.as_deref() != app.env_filter.as_deref() { - append_error_log(format!( - "refresh.drop: env={} current={}", - env.clone().unwrap_or_else(|| "".to_string()), - app.env_filter.clone().unwrap_or_else(|| "".to_string()) - )); - continue; - } - app.refresh_inflight = false; - match result { - Ok(tasks) => { - append_error_log(format!( - "refresh.apply: env={} count={}", - env.clone().unwrap_or_else(|| "".to_string()), - tasks.len() - )); - app.tasks = tasks; - if app.selected >= app.tasks.len() { app.selected = app.tasks.len().saturating_sub(1); } - app.status = "Loaded tasks".to_string(); - } - Err(e) => { - append_error_log(format!("refresh load_tasks failed: {e}")); - app.status = format!("Failed to load tasks: {e}"); - } - } - needs_redraw = true; - let _ = frame_tx.send(Instant::now()); - } - app::AppEvent::NewTaskSubmitted(result) => { - match result { - Ok(created) => { - append_error_log(format!("new-task: created id={}", created.id.0)); - app.status = format!("Submitted as {}", created.id.0); - app.new_task = None; - // Refresh tasks in background for current filter - app.status = format!("Submitted as {} — refreshing…", created.id.0); - app.refresh_inflight = true; - app.list_generation = app.list_generation.saturating_add(1); - needs_redraw = true; - let backend = Arc::clone(&backend); - let tx = tx.clone(); - let env_sel = app.env_filter.clone(); - tokio::spawn(async move { - let res = app::load_tasks(&*backend, env_sel.as_deref()).await; - let _ = tx.send(app::AppEvent::TasksLoaded { env: env_sel, result: res }); - }); - let _ = frame_tx.send(Instant::now()); - } - Err(msg) => { - append_error_log(format!("new-task: submit failed: {msg}")); - if let Some(page) = app.new_task.as_mut() { page.submitting = false; } - app.status = format!("Submit failed: {msg}. See error.log for details."); - needs_redraw = true; - let _ = frame_tx.send(Instant::now()); - } - } - } - // (removed TaskSummaryUpdated; unused in this prototype) - app::AppEvent::ApplyPreflightFinished { id, title, message, level, skipped, conflicts } => { - // Only update if modal is still open and ids match - if let Some(m) = app.apply_modal.as_mut() - && m.task_id == id - { - m.title = title; - m.result_message = Some(message); - m.result_level = Some(level); - m.skipped_paths = skipped; - m.conflict_paths = conflicts; - app.apply_preflight_inflight = false; - needs_redraw = true; - let _ = frame_tx.send(Instant::now()); - } - } - app::AppEvent::EnvironmentsLoaded(result) => { - app.env_loading = false; - match result { - Ok(list) => { - app.environments = list; - app.env_error = None; - app.env_last_loaded = Some(std::time::Instant::now()); - } - Err(e) => { - app.env_error = Some(e.to_string()); - } - } - needs_redraw = true; - let _ = frame_tx.send(Instant::now()); - } - app::AppEvent::EnvironmentAutodetected(result) => { - if let Ok(sel) = result { - // Only apply if user hasn't set a filter yet or it's different. - if app.env_filter.as_deref() != Some(sel.id.as_str()) { - append_error_log(format!( - "env.select: autodetected id={} label={}", - sel.id, - sel.label.clone().unwrap_or_else(|| "".to_string()) - )); - // Preseed environments with detected label so header can show it even before list arrives - if let Some(lbl) = sel.label.clone() { - let present = app.environments.iter().any(|r| r.id == sel.id); - if !present { - app.environments.push(app::EnvironmentRow { id: sel.id.clone(), label: Some(lbl), is_pinned: false, repo_hints: None }); - } - } - app.env_filter = Some(sel.id); - app.status = "Loading tasks…".to_string(); - app.refresh_inflight = true; - app.list_generation = app.list_generation.saturating_add(1); - app.in_flight.clear(); - // reset spinner state - needs_redraw = true; - { - let backend = Arc::clone(&backend); - let tx = tx.clone(); - let env_sel = app.env_filter.clone(); - tokio::spawn(async move { - let res = app::load_tasks(&*backend, env_sel.as_deref()).await; - let _ = tx.send(app::AppEvent::TasksLoaded { env: env_sel, result: res }); - }); - } - // Proactively fetch environments to resolve a friendly name for the header. - app.env_loading = true; - spawn_environment_load( - tx.clone(), - base_url.clone(), - environment_http.clone(), - ); - let _ = frame_tx.send(Instant::now()); - } - } - // on Err, silently continue with All - } - app::AppEvent::DetailsDiffLoaded { id, title, diff } => { - if let Some(ov) = &app.diff_overlay - && ov.task_id != id { - continue; - } - let diff_lines: Vec = diff.lines().map(str::to_string).collect(); - if let Some(ov) = app.diff_overlay.as_mut() { - ov.title = title; - { - let base = ov.base_attempt_mut(); - base.diff_lines = diff_lines.clone(); - base.diff_raw = Some(diff.clone()); - } - ov.base_can_apply = true; - ov.apply_selection_to_fields(); - } else { - let mut overlay = app::DiffOverlay::new(id.clone(), title, /*attempt_total_hint*/ None); - { - let base = overlay.base_attempt_mut(); - base.diff_lines = diff_lines.clone(); - base.diff_raw = Some(diff.clone()); - } - overlay.base_can_apply = true; - overlay.current_view = app::DetailView::Diff; - overlay.apply_selection_to_fields(); - app.diff_overlay = Some(overlay); - } - app.details_inflight = false; - app.status.clear(); - needs_redraw = true; - } - app::AppEvent::DetailsMessagesLoaded { - id, - title, - messages, - prompt, - turn_id, - sibling_turn_ids, - attempt_placement, - attempt_status, - } => { - if let Some(ov) = &app.diff_overlay - && ov.task_id != id { - continue; - } - let conv = conversation_lines(prompt.clone(), &messages); - if let Some(ov) = app.diff_overlay.as_mut() { - ov.title = title.clone(); - { - let base = ov.base_attempt_mut(); - base.text_lines = conv.clone(); - base.prompt = prompt.clone(); - base.turn_id = turn_id.clone(); - base.status = attempt_status; - base.attempt_placement = attempt_placement; - } - ov.base_turn_id = turn_id.clone(); - ov.sibling_turn_ids = sibling_turn_ids.clone(); - ov.attempt_total_hint = Some(sibling_turn_ids.len().saturating_add(1)); - if !ov.base_can_apply { - ov.current_view = app::DetailView::Prompt; - } - ov.apply_selection_to_fields(); - if let (Some(turn_id), true) = (turn_id.clone(), !sibling_turn_ids.is_empty()) - && ov.attempts.len() == 1 { - let backend = Arc::clone(&backend); - let tx = tx.clone(); - let task_id = id.clone(); - tokio::spawn(async move { - match codex_cloud_tasks_client::CloudBackend::list_sibling_attempts( - &*backend, - task_id.clone(), - turn_id, - ) - .await - { - Ok(attempts) => { - let _ = tx.send(app::AppEvent::AttemptsLoaded { id: task_id, attempts }); - } - Err(e) => { - crate::util::append_error_log(format!( - "attempts.load failed for {}: {e}", - task_id.0 - )); - } - } - }); - } - } else { - let mut overlay = app::DiffOverlay::new(id.clone(), title, /*attempt_total_hint*/ None); - { - let base = overlay.base_attempt_mut(); - base.text_lines = conv.clone(); - base.prompt = prompt.clone(); - base.turn_id = turn_id.clone(); - base.status = attempt_status; - base.attempt_placement = attempt_placement; - } - overlay.base_turn_id = turn_id.clone(); - overlay.sibling_turn_ids = sibling_turn_ids.clone(); - overlay.attempt_total_hint = Some(sibling_turn_ids.len().saturating_add(1)); - overlay.current_view = app::DetailView::Prompt; - overlay.apply_selection_to_fields(); - app.diff_overlay = Some(overlay); - } - app.details_inflight = false; - app.status.clear(); - needs_redraw = true; - } - app::AppEvent::AttemptsLoaded { id, attempts } => { - if let Some(ov) = app.diff_overlay.as_mut() { - if ov.task_id != id { - continue; - } - for attempt in attempts { - if ov - .attempts - .iter() - .any(|existing| existing.turn_id.as_deref() == Some(attempt.turn_id.as_str())) - { - continue; - } - let diff_lines = attempt - .diff - .as_ref() - .map(|d| d.lines().map(str::to_string).collect()) - .unwrap_or_default(); - let text_lines = conversation_lines(/*prompt*/ None, &attempt.messages); - ov.attempts.push(app::AttemptView { - turn_id: Some(attempt.turn_id.clone()), - status: attempt.status, - attempt_placement: attempt.attempt_placement, - diff_lines, - text_lines, - prompt: None, - diff_raw: attempt.diff.clone(), - }); - } - if ov.attempts.len() > 1 { - let (_, rest) = ov.attempts.split_at_mut(1); - rest.sort_by(|a, b| match (a.attempt_placement, b.attempt_placement) { - (Some(lhs), Some(rhs)) => lhs.cmp(&rhs), - (Some(_), None) => std::cmp::Ordering::Less, - (None, Some(_)) => std::cmp::Ordering::Greater, - (None, None) => a.turn_id.cmp(&b.turn_id), - }); - } - if ov.selected_attempt >= ov.attempts.len() { - ov.selected_attempt = ov.attempts.len().saturating_sub(1); - } - ov.attempt_total_hint = Some(ov.attempts.len()); - ov.apply_selection_to_fields(); - needs_redraw = true; - } - } - app::AppEvent::DetailsFailed { id, title, error } => { - if let Some(ov) = &app.diff_overlay - && ov.task_id != id { - continue; - } - append_error_log(format!("details failed for {}: {error}", id.0)); - let pretty = pretty_lines_from_error(&error); - if let Some(ov) = app.diff_overlay.as_mut() { - ov.title = title.clone(); - { - let base = ov.base_attempt_mut(); - base.diff_lines.clear(); - base.text_lines = pretty.clone(); - base.prompt = None; - } - ov.base_can_apply = false; - ov.current_view = app::DetailView::Prompt; - ov.apply_selection_to_fields(); - } else { - let mut overlay = app::DiffOverlay::new(id.clone(), title, /*attempt_total_hint*/ None); - { - let base = overlay.base_attempt_mut(); - base.text_lines = pretty; - } - overlay.base_can_apply = false; - overlay.current_view = app::DetailView::Prompt; - overlay.apply_selection_to_fields(); - app.diff_overlay = Some(overlay); - } - app.details_inflight = false; - needs_redraw = true; - } - app::AppEvent::ApplyFinished { id, result } => { - // Only update if the modal still corresponds to this id. - if let Some(m) = &app.apply_modal { - if m.task_id != id { continue; } - } else { - continue; - } - app.apply_inflight = false; - match result { - Ok(outcome) => { - app.status = outcome.message.clone(); - if matches!(outcome.status, codex_cloud_tasks_client::ApplyStatus::Success) { - app.apply_modal = None; - app.diff_overlay = None; - // Refresh tasks after successful apply - let backend = Arc::clone(&backend); - let tx = tx.clone(); - let env_sel = app.env_filter.clone(); - tokio::spawn(async move { - let res = app::load_tasks(&*backend, env_sel.as_deref()).await; - let _ = tx.send(app::AppEvent::TasksLoaded { env: env_sel, result: res }); - }); - } - } - Err(e) => { - append_error_log(format!("apply_task failed for {}: {e}", id.0)); - app.status = format!("Apply failed: {e}"); - } - } - needs_redraw = true; - } - } - } - // Render immediately after processing app events. - render_if_needed(&mut terminal, &mut app, &mut needs_redraw)?; - } - maybe_event = events.next() => { - match maybe_event { - Some(Ok(Event::Paste(pasted))) => { - if app.env_modal.is_some() { - if let Some(m) = app.env_modal.as_mut() { - for ch in pasted.chars() { - match ch { - '\r' | '\n' => continue, - '\t' => m.query.push(' '), - _ => m.query.push(ch), - } - } - } - needs_redraw = true; - } else if let Some(page) = app.new_task.as_mut() - && !page.submitting - { - if page.composer.handle_paste(pasted) { - needs_redraw = true; - } - let _ = frame_tx.send(Instant::now()); - } - } - Some(Ok(Event::Key(key))) if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) => { - // Treat Ctrl-C like pressing 'q' in the current context. - if key.modifiers.contains(KeyModifiers::CONTROL) - && matches!(key.code, KeyCode::Char('c') | KeyCode::Char('C')) - { - if app.env_modal.is_some() { - // Close environment selector if open (don’t quit composer). - app.env_modal = None; - needs_redraw = true; - } else if app.best_of_modal.is_some() { - app.best_of_modal = None; - needs_redraw = true; - } else if app.apply_modal.is_some() { - app.apply_modal = None; - app.status = "Apply canceled".to_string(); - needs_redraw = true; - } else if app.new_task.is_some() { - app.new_task = None; - app.status = "Canceled new task".to_string(); - needs_redraw = true; - } else if app.diff_overlay.is_some() { - app.diff_overlay = None; - needs_redraw = true; - } else { - break 0; - } - // Render updated state immediately before continuing to next loop iteration. - render_if_needed(&mut terminal, &mut app, &mut needs_redraw)?; - // Render after New Task branch to reflect input changes immediately. - render_if_needed(&mut terminal, &mut app, &mut needs_redraw)?; - continue; - } - let is_ctrl_n = key.modifiers.contains(KeyModifiers::CONTROL) - && matches!(key.code, KeyCode::Char('n') | KeyCode::Char('N')) - || matches!(key.code, KeyCode::Char('\u{000E}')); - if is_ctrl_n { - if app.new_task.is_none() { - continue; - } - if app.best_of_modal.is_some() { - app.best_of_modal = None; - needs_redraw = true; - } else { - let selected = app.best_of_n.saturating_sub(1).min(3); - app.best_of_modal = Some(app::BestOfModalState { selected }); - app.status = format!( - "Select best-of attempts (current: {} attempt{})", - app.best_of_n, - if app.best_of_n == 1 { "" } else { "s" } - ); - needs_redraw = true; - } - render_if_needed(&mut terminal, &mut app, &mut needs_redraw)?; - continue; - } - if app.best_of_modal.is_some() { - match key.code { - KeyCode::Esc => { - app.best_of_modal = None; - needs_redraw = true; - } - KeyCode::Down | KeyCode::Char('j') => { - if let Some(m) = app.best_of_modal.as_mut() { - m.selected = (m.selected + 1).min(3); - } - needs_redraw = true; - } - KeyCode::Up | KeyCode::Char('k') => { - if let Some(m) = app.best_of_modal.as_mut() { - m.selected = m.selected.saturating_sub(1); - } - needs_redraw = true; - } - KeyCode::Char('1') | KeyCode::Char('2') | KeyCode::Char('3') | KeyCode::Char('4') => { - if let Some(m) = app.best_of_modal.as_mut() { - let val = match key.code { - KeyCode::Char('1') => 0, - KeyCode::Char('2') => 1, - KeyCode::Char('3') => 2, - KeyCode::Char('4') => 3, - _ => m.selected, - }; - m.selected = val; - } - needs_redraw = true; - } - KeyCode::Enter => { - if let Some(state) = app.best_of_modal.take() { - let new_value = state.selected + 1; - app.best_of_n = new_value; - if let Some(page) = app.new_task.as_mut() { - page.best_of_n = new_value; - } - append_error_log(format!("best-of.select: attempts={new_value}")); - app.status = format!( - "Best-of updated to {new_value} attempt{}", - if new_value == 1 { "" } else { "s" } - ); - needs_redraw = true; - } - } - _ => {} - } - render_if_needed(&mut terminal, &mut app, &mut needs_redraw)?; - continue; - } - // New Task page: Ctrl+O opens environment switcher while composing. - let is_ctrl_o = key.modifiers.contains(KeyModifiers::CONTROL) - && matches!(key.code, KeyCode::Char('o') | KeyCode::Char('O')) - || matches!(key.code, KeyCode::Char('\u{000F}')); - if is_ctrl_o && app.new_task.is_some() { - // Close task modal/pending apply if present before opening env modal - app.diff_overlay = None; - app.env_modal = Some(app::EnvModalState { query: String::new(), selected: 0 }); - // Cache environments while the modal is open to avoid repeated fetches. - let should_fetch = app.environments.is_empty(); - if should_fetch { - app.env_loading = true; - app.env_error = None; - // Ensure spinner animates while loading environments. - let _ = frame_tx.send(Instant::now() + Duration::from_millis(100)); - } - needs_redraw = true; - if should_fetch { - spawn_environment_load( - tx.clone(), - base_url.clone(), - environment_http.clone(), - ); - } - // Render after opening env modal to show it instantly. - render_if_needed(&mut terminal, &mut app, &mut needs_redraw)?; - continue; - } - - // New Task page has priority when active, unless an env modal is open. - if let Some(page) = app.new_task.as_mut() { - if app.env_modal.is_some() { - // Defer handling to env-modal branch below. - } else { - match key.code { - KeyCode::Esc => { - app.new_task = None; - app.status = "Canceled new task".to_string(); - needs_redraw = true; - } - _ => { - if page.submitting { - // Ignore input while submitting - } else if let codex_tui::ComposerAction::Submitted(text) = - page.composer.input(key) - { - // Submit only if we have an env id - if let Some(env) = page.env_id.clone() { - append_error_log(format!( - "new-task: submit env={} size={}", - env, - text.chars().count() - )); - page.submitting = true; - app.status = "Submitting new task…".to_string(); - let tx = tx.clone(); - let backend = Arc::clone(&backend); - let best_of_n = page.best_of_n; - tokio::spawn(async move { - let git_ref = resolve_git_ref(/*branch_override*/ None).await; - - let result = codex_cloud_tasks_client::CloudBackend::create_task(&*backend, &env, &text, &git_ref, /*qa_mode*/ false, best_of_n).await; - let evt = match result { - Ok(ok) => app::AppEvent::NewTaskSubmitted(Ok(ok)), - Err(e) => app::AppEvent::NewTaskSubmitted(Err(format!("{e}"))), - }; - let _ = tx.send(evt); - }); - } else { - app.status = "No environment selected".to_string(); - } - } - needs_redraw = true; - // If paste‑burst is active, schedule a micro‑flush frame. - if page.composer.is_in_paste_burst() { - let _ = frame_tx.send( - Instant::now() - + codex_tui::ComposerInput::recommended_flush_delay(), - ); - } - // Always schedule an immediate redraw for key edits in the composer. - let _ = frame_tx.send(Instant::now()); - // Draw now so non-char edits (e.g., Option+Delete) reflect instantly. - render_if_needed(&mut terminal, &mut app, &mut needs_redraw)?; - } - } - continue; - } - } - // If a diff overlay is open, handle its keys first. - if app.apply_modal.is_some() { - // Simple apply confirmation modal: y apply, p preflight, n/Esc cancel - match key.code { - KeyCode::Char('y') => { - if let Some(m) = app.apply_modal.as_ref() { - let title = m.title.clone(); - let job = ApplyJob { - task_id: m.task_id.clone(), - diff_override: m.diff_override.clone(), - }; - if spawn_apply(&mut app, &backend, &tx, &frame_tx, job) { - app.status = format!("Applying '{title}'..."); - } - needs_redraw = true; - } - } - KeyCode::Char('p') => { - if let Some(m) = app.apply_modal.take() { - let title = m.title.clone(); - let job = ApplyJob { - task_id: m.task_id.clone(), - diff_override: m.diff_override.clone(), - }; - if spawn_preflight(&mut app, &backend, &tx, &frame_tx, title.clone(), job) { - app.apply_modal = Some(app::ApplyModalState { - task_id: m.task_id, - title: title.clone(), - result_message: None, - result_level: None, - skipped_paths: Vec::new(), - conflict_paths: Vec::new(), - diff_override: m.diff_override, - }); - app.status = format!("Preflighting '{title}'..."); - } else { - app.apply_modal = Some(m); - } - needs_redraw = true; - } - } - KeyCode::Esc - | KeyCode::Char('n') - | KeyCode::Char('q') - | KeyCode::Char('Q') => { app.apply_modal = None; app.status = "Apply canceled".to_string(); needs_redraw = true; } - _ => {} - } - } else if app.diff_overlay.is_some() { - let mut cycle_attempt = |delta: isize| { - if let Some(ov) = app.diff_overlay.as_mut() - && ov.attempt_count() > 1 { - ov.step_attempt(delta); - let total = ov.attempt_display_total(); - let current = ov.selected_attempt + 1; - app.status = format!("Viewing attempt {current} of {total}"); - ov.sd.scroll_to_top(); - needs_redraw = true; - } - }; - - match key.code { - KeyCode::Char('a') => { - if app.apply_inflight || app.apply_preflight_inflight { - app.status = "Finish the current apply/preflight before starting another.".to_string(); - needs_redraw = true; - continue; - } - let snapshot = app.diff_overlay.as_ref().map(|ov| { - ( - ov.task_id.clone(), - ov.title.clone(), - ov.current_can_apply(), - ov.current_attempt().and_then(|attempt| attempt.diff_raw.clone()), - ) - }); - if let Some((task_id, title, can_apply, diff_override)) = snapshot { - if can_apply { - let job = ApplyJob { - task_id: task_id.clone(), - diff_override: diff_override.clone(), - }; - if spawn_preflight(&mut app, &backend, &tx, &frame_tx, title.clone(), job) { - app.apply_modal = Some(app::ApplyModalState { - task_id, - title: title.clone(), - result_message: None, - result_level: None, - skipped_paths: Vec::new(), - conflict_paths: Vec::new(), - diff_override, - }); - app.status = format!("Preflighting '{title}'..."); - } - } else { - app.status = "No diff available to apply.".to_string(); - } - needs_redraw = true; - } - } - KeyCode::Tab => { - cycle_attempt(1); - } - KeyCode::BackTab => { - cycle_attempt(-1); - } - // From task modal, 'o' should close it and open the env selector - KeyCode::Char('o') | KeyCode::Char('O') => { - app.diff_overlay = None; - app.env_modal = Some(app::EnvModalState { query: String::new(), selected: 0 }); - // Use cached environments unless empty - if app.environments.is_empty() { app.env_loading = true; app.env_error = None; } - needs_redraw = true; - if app.environments.is_empty() { - spawn_environment_load( - tx.clone(), - base_url.clone(), - environment_http.clone(), - ); - } - } - KeyCode::Left => { - if let Some(ov) = &mut app.diff_overlay { - let has_text = ov.current_attempt().is_some_and(app::AttemptView::has_text); - let has_diff = ov.current_attempt().is_some_and(app::AttemptView::has_diff) || ov.base_can_apply; - if has_text && has_diff { - ov.set_view(app::DetailView::Prompt); - ov.sd.scroll_to_top(); - needs_redraw = true; - } - } - } - KeyCode::Right => { - if let Some(ov) = &mut app.diff_overlay { - let has_text = ov.current_attempt().is_some_and(app::AttemptView::has_text); - let has_diff = ov.current_attempt().is_some_and(app::AttemptView::has_diff) || ov.base_can_apply; - if has_text && has_diff { - ov.set_view(app::DetailView::Diff); - ov.sd.scroll_to_top(); - needs_redraw = true; - } - } - } - KeyCode::Char(']') | KeyCode::Char('}') => { - cycle_attempt(1); - } - KeyCode::Char('[') | KeyCode::Char('{') => { - cycle_attempt(-1); - } - KeyCode::Esc | KeyCode::Char('q') => { - app.diff_overlay = None; - needs_redraw = true; - } - KeyCode::Down | KeyCode::Char('j') => { - if let Some(ov) = &mut app.diff_overlay { ov.sd.scroll_by(/*delta*/ 1); } - needs_redraw = true; - } - KeyCode::Up | KeyCode::Char('k') => { - if let Some(ov) = &mut app.diff_overlay { ov.sd.scroll_by(/*delta*/ -1); } - needs_redraw = true; - } - KeyCode::PageDown | KeyCode::Char(' ') => { - if let Some(ov) = &mut app.diff_overlay { let step = ov.sd.state.viewport_h.saturating_sub(1) as i16; ov.sd.page_by(step); } - needs_redraw = true; - } - KeyCode::PageUp => { - if let Some(ov) = &mut app.diff_overlay { let step = ov.sd.state.viewport_h.saturating_sub(1) as i16; ov.sd.page_by(-step); } - needs_redraw = true; - } - KeyCode::Home => { if let Some(ov) = &mut app.diff_overlay { ov.sd.scroll_to_top(); } needs_redraw = true; } - KeyCode::End => { if let Some(ov) = &mut app.diff_overlay { ov.sd.scroll_to_bottom(); } needs_redraw = true; } - _ => {} - } - } else if app.env_modal.is_some() { - // Environment modal key handling - match key.code { - KeyCode::Esc => { app.env_modal = None; needs_redraw = true; } - KeyCode::Char(ch) if !key.modifiers.contains(KeyModifiers::CONTROL) && !key.modifiers.contains(KeyModifiers::ALT) => { - if let Some(m) = app.env_modal.as_mut() { m.query.push(ch); } - needs_redraw = true; - } - KeyCode::Backspace => { if let Some(m) = app.env_modal.as_mut() { m.query.pop(); } needs_redraw = true; } - KeyCode::Down | KeyCode::Char('j') => { if let Some(m) = app.env_modal.as_mut() { m.selected = m.selected.saturating_add(1); } needs_redraw = true; } - KeyCode::Up | KeyCode::Char('k') => { if let Some(m) = app.env_modal.as_mut() { m.selected = m.selected.saturating_sub(1); } needs_redraw = true; } - KeyCode::Home => { if let Some(m) = app.env_modal.as_mut() { m.selected = 0; } needs_redraw = true; } - KeyCode::End => { if let Some(m) = app.env_modal.as_mut() { m.selected = app.environments.len(); } needs_redraw = true; } - KeyCode::PageDown | KeyCode::Char(' ') => { if let Some(m) = app.env_modal.as_mut() { let step = 10usize; m.selected = m.selected.saturating_add(step); } needs_redraw = true; } - KeyCode::PageUp => { if let Some(m) = app.env_modal.as_mut() { let step = 10usize; m.selected = m.selected.saturating_sub(step); } needs_redraw = true; } - KeyCode::Char('n') => { - if app.env_filter.is_none() { - app.new_task = Some(crate::new_task::NewTaskPage::new(/*env_id*/ None, app.best_of_n)); - } else { - app.new_task = Some(crate::new_task::NewTaskPage::new(app.env_filter.clone(), app.best_of_n)); - } - app.status = "New Task: Enter to submit; Esc to cancel".to_string(); - needs_redraw = true; - } - KeyCode::Enter => { - // Resolve selection over filtered set - if let Some(state) = app.env_modal.take() { - let q = state.query.to_lowercase(); - let filtered: Vec<&app::EnvironmentRow> = app.environments.iter().filter(|r| { - if q.is_empty() { return true; } - let mut hay = String::new(); - if let Some(l) = &r.label { hay.push_str(&l.to_lowercase()); hay.push(' '); } - hay.push_str(&r.id.to_lowercase()); - if let Some(h) = &r.repo_hints { hay.push(' '); hay.push_str(&h.to_lowercase()); } - hay.contains(&q) - }).collect(); - // Keep original order (already sorted) — no need to re-sort - let idx = state.selected; - if idx == 0 { app.env_filter = None; append_error_log("env.select: All"); } - else { - let env_idx = idx.saturating_sub(1); - if let Some(row) = filtered.get(env_idx) { - append_error_log(format!( - "env.select: id={} label={}", - row.id, - row.label.clone().unwrap_or_else(|| "".to_string()) - )); - app.env_filter = Some(row.id.clone()); - } - } - // If New Task page is open, reflect the new selection in its header immediately. - if let Some(page) = app.new_task.as_mut() { - page.env_id = app.env_filter.clone(); - } - // Trigger tasks refresh with the selected filter - app.status = "Loading tasks…".to_string(); - app.refresh_inflight = true; - app.list_generation = app.list_generation.saturating_add(1); - app.in_flight.clear(); - // reset spinner state - needs_redraw = true; - let backend = Arc::clone(&backend); - let tx = tx.clone(); - let env_sel = app.env_filter.clone(); - tokio::spawn(async move { - let res = app::load_tasks(&*backend, env_sel.as_deref()).await; - let _ = tx.send(app::AppEvent::TasksLoaded { env: env_sel, result: res }); - }); - } - } - _ => {} - } - } else { - // Base list view keys - match key.code { - KeyCode::Char('q') | KeyCode::Esc => { - break 0; - } - KeyCode::Down | KeyCode::Char('j') => { - app.next(); - needs_redraw = true; - } - KeyCode::Up | KeyCode::Char('k') => { - app.prev(); - needs_redraw = true; - } - // Ensure 'r' does not refresh tasks when the env modal is open. - KeyCode::Char('r') | KeyCode::Char('R') => { - if app.env_modal.is_some() { break 0; } - append_error_log(format!( - "refresh.request: env={}", - app.env_filter.clone().unwrap_or_else(|| "".to_string()) - )); - app.status = "Refreshing…".to_string(); - app.refresh_inflight = true; - app.list_generation = app.list_generation.saturating_add(1); - app.in_flight.clear(); - // reset spinner state - needs_redraw = true; - // Spawn background refresh - let backend = Arc::clone(&backend); - let tx = tx.clone(); - let env_sel = app.env_filter.clone(); - tokio::spawn(async move { - let res = app::load_tasks(&*backend, env_sel.as_deref()).await; - let _ = tx.send(app::AppEvent::TasksLoaded { env: env_sel, result: res }); - }); - } - KeyCode::Char('o') | KeyCode::Char('O') => { - app.env_modal = Some(app::EnvModalState { query: String::new(), selected: 0 }); - // Cache environments while the modal is open to avoid repeated fetches. - let should_fetch = app.environments.is_empty(); - if should_fetch { app.env_loading = true; app.env_error = None; } - needs_redraw = true; - if should_fetch { - spawn_environment_load( - tx.clone(), - base_url.clone(), - environment_http.clone(), - ); - } - } - KeyCode::Char('n') => { - let env_opt = app.env_filter.clone(); - app.new_task = Some(crate::new_task::NewTaskPage::new(env_opt, app.best_of_n)); - app.status = "New Task: Enter to submit; Esc to cancel".to_string(); - needs_redraw = true; - } - KeyCode::Enter => { - if let Some(task) = app.tasks.get(app.selected).cloned() { - app.status = format!("Loading details for {title}…", title = task.title); - app.details_inflight = true; - // Open empty overlay immediately; content arrives via events - let overlay = app::DiffOverlay::new( - task.id.clone(), - task.title.clone(), - task.attempt_total, - ); - app.diff_overlay = Some(overlay); - needs_redraw = true; - // Spawn background details load (diff first, then messages fallback) - let id = task.id.clone(); - let title = task.title.clone(); - { - let backend = Arc::clone(&backend); - let tx = tx.clone(); - let diff_id = id.clone(); - let diff_title = title.clone(); - tokio::spawn(async move { - match codex_cloud_tasks_client::CloudBackend::get_task_diff(&*backend, diff_id.clone()).await { - Ok(Some(diff)) => { - let _ = tx.send(app::AppEvent::DetailsDiffLoaded { id: diff_id, title: diff_title, diff }); - } - Ok(None) => { - match codex_cloud_tasks_client::CloudBackend::get_task_text(&*backend, diff_id.clone()).await { - Ok(text) => { - let evt = app::AppEvent::DetailsMessagesLoaded { - id: diff_id, - title: diff_title, - messages: text.messages, - prompt: text.prompt, - turn_id: text.turn_id, - sibling_turn_ids: text.sibling_turn_ids, - attempt_placement: text.attempt_placement, - attempt_status: text.attempt_status, - }; - let _ = tx.send(evt); - } - Err(e2) => { - let _ = tx.send(app::AppEvent::DetailsFailed { id: diff_id, title: diff_title, error: format!("{e2}") }); - } - } - } - Err(e) => { - append_error_log(format!("get_task_diff failed for {}: {e}", diff_id.0)); - match codex_cloud_tasks_client::CloudBackend::get_task_text(&*backend, diff_id.clone()).await { - Ok(text) => { - let evt = app::AppEvent::DetailsMessagesLoaded { - id: diff_id, - title: diff_title, - messages: text.messages, - prompt: text.prompt, - turn_id: text.turn_id, - sibling_turn_ids: text.sibling_turn_ids, - attempt_placement: text.attempt_placement, - attempt_status: text.attempt_status, - }; - let _ = tx.send(evt); - } - Err(e2) => { - let _ = tx.send(app::AppEvent::DetailsFailed { id: diff_id, title: diff_title, error: format!("{e2}") }); - } - } - } - } - }); - } - // Also fetch conversation text even when diff exists - { - let backend = Arc::clone(&backend); - let tx = tx.clone(); - let msg_id = id; - let msg_title = title; - tokio::spawn(async move { - if let Ok(text) = codex_cloud_tasks_client::CloudBackend::get_task_text(&*backend, msg_id.clone()).await { - let evt = app::AppEvent::DetailsMessagesLoaded { - id: msg_id, - title: msg_title, - messages: text.messages, - prompt: text.prompt, - turn_id: text.turn_id, - sibling_turn_ids: text.sibling_turn_ids, - attempt_placement: text.attempt_placement, - attempt_status: text.attempt_status, - }; - let _ = tx.send(evt); - } - }); - } - // Animate spinner while details load. - let _ = frame_tx.send(Instant::now() + Duration::from_millis(100)); - } - } - KeyCode::Char('a') => { - if app.apply_inflight || app.apply_preflight_inflight { - app.status = "Finish the current apply/preflight before starting another.".to_string(); - needs_redraw = true; - continue; - } - - if let Some(task) = app.tasks.get(app.selected).cloned() { - match codex_cloud_tasks_client::CloudBackend::get_task_diff(&*backend, task.id.clone()).await { - Ok(Some(diff)) => { - let diff_override = Some(diff.clone()); - let task_id = task.id.clone(); - let title = task.title.clone(); - let job = ApplyJob { - task_id: task_id.clone(), - diff_override: diff_override.clone(), - }; - if spawn_preflight( - &mut app, - &backend, - &tx, - &frame_tx, - title.clone(), - job, - ) { - app.apply_modal = Some(app::ApplyModalState { - task_id, - title: title.clone(), - result_message: None, - result_level: None, - skipped_paths: Vec::new(), - conflict_paths: Vec::new(), - diff_override, - }); - app.status = format!("Preflighting '{title}'..."); - } - } - Ok(None) | Err(_) => { - app.status = "No diff available to apply".to_string(); - } - } - needs_redraw = true; - } - } - _ => {} - } - } - // Render after handling a key event (when not quitting). - render_if_needed(&mut terminal, &mut app, &mut needs_redraw)?; - } - Some(Ok(Event::Resize(_, _))) => { - needs_redraw = true; - // Redraw immediately on resize for snappier UX. - render_if_needed(&mut terminal, &mut app, &mut needs_redraw)?; - } - Some(Err(_)) | None => {} - _ => {} - } - // Fallback: if any other event path requested a redraw, render now. - render_if_needed(&mut terminal, &mut app, &mut needs_redraw)?; - } - } - }; - - // Restore terminal - disable_raw_mode().ok(); - terminal.show_cursor().ok(); - let _ = crossterm::execute!(std::io::stdout(), DisableBracketedPaste); - // Best-effort restore of keyboard enhancement flags before leaving alt screen. - let _ = crossterm::execute!(std::io::stdout(), PopKeyboardEnhancementFlags); - let _ = crossterm::execute!(std::io::stdout(), LeaveAlternateScreen); - - if exit_code != 0 { - std::process::exit(exit_code); - } - Ok(()) -} - -fn spawn_environment_load( - tx: UnboundedSender, - base_url: String, - http: env_detect::EnvironmentClient, -) { - tokio::spawn(async move { - let base_url = util::normalize_base_url(&base_url); - let headers = util::build_chatgpt_headers(); - let result = crate::env_detect::list_environments(&http, &base_url, &headers).await; - let _ = tx.send(app::AppEvent::EnvironmentsLoaded(result)); - }); -} - -// extract_chatgpt_account_id moved to util.rs - -/// Build plain-text conversation lines: a labeled user prompt followed by assistant messages. -fn conversation_lines(prompt: Option, messages: &[String]) -> Vec { - let mut out: Vec = Vec::new(); - if let Some(p) = prompt { - out.push("user:".to_string()); - for l in p.lines() { - out.push(l.to_string()); - } - out.push(String::new()); - } - if !messages.is_empty() { - out.push("assistant:".to_string()); - for (i, m) in messages.iter().enumerate() { - for l in m.lines() { - out.push(l.to_string()); - } - if i + 1 < messages.len() { - out.push(String::new()); - } - } - } - if out.is_empty() { - out.push("".to_string()); - } - out -} - -/// Convert a verbose HTTP error with embedded JSON body into concise, user-friendly lines -/// for the details overlay. Falls back to a short raw message when parsing fails. -fn pretty_lines_from_error(raw: &str) -> Vec { - let mut lines: Vec = Vec::new(); - let is_no_diff = raw.contains("No output_diff in response."); - let is_no_msgs = raw.contains("No assistant text messages in response."); - if is_no_diff { - lines.push("No diff available for this task.".to_string()); - } else if is_no_msgs { - lines.push("No assistant messages found for this task.".to_string()); - } else { - lines.push("Failed to load task details.".to_string()); - } - - // Try to parse the embedded JSON body: find the first '{' after " body=" and decode. - if let Some(body_idx) = raw.find(" body=") - && let Some(json_start_rel) = raw[body_idx..].find('{') - { - let json_start = body_idx + json_start_rel; - let json_str = raw[json_start..].trim(); - if let Ok(v) = serde_json::from_str::(json_str) { - // Prefer assistant turn context. - let turn = v - .get("current_assistant_turn") - .and_then(|x| x.as_object()) - .cloned() - .or_else(|| { - v.get("current_diff_task_turn") - .and_then(|x| x.as_object()) - .cloned() - }); - if let Some(t) = turn { - if let Some(err) = t.get("error").and_then(|e| e.as_object()) { - let code = err.get("code").and_then(|s| s.as_str()).unwrap_or(""); - let msg = err.get("message").and_then(|s| s.as_str()).unwrap_or(""); - if !code.is_empty() || !msg.is_empty() { - let summary = if code.is_empty() { - msg.to_string() - } else if msg.is_empty() { - code.to_string() - } else { - format!("{code}: {msg}") - }; - lines.push(format!("Assistant error: {summary}")); - } - } - if let Some(status) = t.get("turn_status").and_then(|s| s.as_str()) { - lines.push(format!("Status: {status}")); - } - if let Some(text) = t - .get("latest_event") - .and_then(|e| e.get("text")) - .and_then(|s| s.as_str()) - && !text.trim().is_empty() - { - lines.push(format!("Latest event: {}", text.trim())); - } - } - } - } - - if lines.len() == 1 { - // Parsing yielded nothing; include a trimmed, short raw message tail for context. - let tail = if raw.len() > 320 { - format!("{}…", &raw[..320]) - } else { - raw.to_string() - }; - lines.push(tail); - } else if lines.len() >= 2 { - // Add a hint to refresh when still in progress. - if lines.iter().any(|l| l.contains("in_progress")) { - lines.push("This task may still be running. Press 'r' to refresh.".to_string()); - } - // Avoid an empty overlay - lines.push(String::new()); - } - lines -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::resolve_git_ref_with_git_info; - use codex_cloud_tasks_client::DiffSummary; - use codex_cloud_tasks_client::TaskId; - use codex_cloud_tasks_client::TaskStatus; - use codex_cloud_tasks_client::TaskSummary; - use codex_cloud_tasks_mock_client::MockClient; - use pretty_assertions::assert_eq; - - struct StubGitInfo { - default_branch: Option, - current_branch: Option, - } - - impl StubGitInfo { - fn new(default_branch: Option, current_branch: Option) -> Self { - Self { - default_branch, - current_branch, - } - } - } - - impl super::GitInfoProvider for StubGitInfo { - async fn default_branch_name(&self, _path: &std::path::Path) -> Option { - self.default_branch.clone() - } - - async fn current_branch_name(&self, _path: &std::path::Path) -> Option { - self.current_branch.clone() - } - } - - #[tokio::test] - async fn branch_override_is_used_when_provided() { - let git_ref = resolve_git_ref_with_git_info( - Some(&"feature/override".to_string()), - &StubGitInfo::new(/*default_branch*/ None, /*current_branch*/ None), - ) - .await; - - assert_eq!(git_ref, "feature/override"); - } - - #[tokio::test] - async fn trims_override_whitespace() { - let git_ref = resolve_git_ref_with_git_info( - Some(&" feature/spaces ".to_string()), - &StubGitInfo::new(/*default_branch*/ None, /*current_branch*/ None), - ) - .await; - - assert_eq!(git_ref, "feature/spaces"); - } - - #[tokio::test] - async fn prefers_current_branch_when_available() { - let git_ref = resolve_git_ref_with_git_info( - /*branch_override*/ None, - &StubGitInfo::new( - Some("default-main".to_string()), - Some("feature/current".to_string()), - ), - ) - .await; - - assert_eq!(git_ref, "feature/current"); - } - - #[tokio::test] - async fn falls_back_to_current_branch_when_default_is_missing() { - let git_ref = resolve_git_ref_with_git_info( - /*branch_override*/ None, - &StubGitInfo::new(/*default_branch*/ None, Some("develop".to_string())), - ) - .await; - - assert_eq!(git_ref, "develop"); - } - - #[tokio::test] - async fn falls_back_to_main_when_no_git_info_is_available() { - let git_ref = resolve_git_ref_with_git_info( - /*branch_override*/ None, - &StubGitInfo::new(/*default_branch*/ None, /*current_branch*/ None), - ) - .await; - - assert_eq!(git_ref, "main"); - } - - #[test] - fn format_task_status_lines_with_diff_and_label() { - let now = Utc::now(); - let task = TaskSummary { - id: TaskId("task_1".to_string()), - title: "Example task".to_string(), - status: TaskStatus::Ready, - updated_at: now, - environment_id: Some("env-1".to_string()), - environment_label: Some("Env".to_string()), - summary: DiffSummary { - files_changed: 3, - lines_added: 5, - lines_removed: 2, - }, - is_review: false, - attempt_total: None, - }; - let lines = format_task_status_lines(&task, now, /*colorize*/ false); - assert_eq!( - lines, - vec![ - "[READY] Example task".to_string(), - "Env • 0s ago".to_string(), - "+5/-2 • 3 files".to_string(), - ] - ); - } - - #[test] - fn format_task_status_lines_without_diff_falls_back() { - let now = Utc::now(); - let task = TaskSummary { - id: TaskId("task_2".to_string()), - title: "No diff task".to_string(), - status: TaskStatus::Pending, - updated_at: now, - environment_id: Some("env-2".to_string()), - environment_label: None, - summary: DiffSummary::default(), - is_review: false, - attempt_total: Some(1), - }; - let lines = format_task_status_lines(&task, now, /*colorize*/ false); - assert_eq!( - lines, - vec![ - "[PENDING] No diff task".to_string(), - "env-2 • 0s ago".to_string(), - "no diff".to_string(), - ] - ); - } - - #[test] - fn format_task_list_lines_formats_urls() { - let now = Utc::now(); - let tasks = vec![ - TaskSummary { - id: TaskId("task_1".to_string()), - title: "Example task".to_string(), - status: TaskStatus::Ready, - updated_at: now, - environment_id: Some("env-1".to_string()), - environment_label: Some("Env".to_string()), - summary: DiffSummary { - files_changed: 3, - lines_added: 5, - lines_removed: 2, - }, - is_review: false, - attempt_total: None, - }, - TaskSummary { - id: TaskId("task_2".to_string()), - title: "No diff task".to_string(), - status: TaskStatus::Pending, - updated_at: now, - environment_id: Some("env-2".to_string()), - environment_label: None, - summary: DiffSummary::default(), - is_review: false, - attempt_total: Some(1), - }, - ]; - let lines = format_task_list_lines( - &tasks, - "https://chatgpt.com/backend-api", - now, - /*colorize*/ false, - ); - assert_eq!( - lines, - vec![ - "https://chatgpt.com/codex/tasks/task_1".to_string(), - " [READY] Example task".to_string(), - " Env • 0s ago".to_string(), - " +5/-2 • 3 files".to_string(), - String::new(), - "https://chatgpt.com/codex/tasks/task_2".to_string(), - " [PENDING] No diff task".to_string(), - " env-2 • 0s ago".to_string(), - " no diff".to_string(), - ] - ); - } - - #[tokio::test] - async fn collect_attempt_diffs_includes_sibling_attempts() { - let backend = MockClient; - let task_id = parse_task_id("https://chatgpt.com/codex/tasks/T-1000").expect("id"); - let attempts = collect_attempt_diffs(&backend, &task_id) - .await - .expect("attempts"); - assert_eq!(attempts.len(), 2); - assert_eq!(attempts[0].placement, Some(0)); - assert_eq!(attempts[1].placement, Some(1)); - assert!(!attempts[0].diff.is_empty()); - assert!(!attempts[1].diff.is_empty()); - } - - #[test] - fn select_attempt_validates_bounds() { - let attempts = vec![AttemptDiffData { - placement: Some(0), - created_at: None, - diff: "diff --git a/file b/file\n".to_string(), - }]; - let first = select_attempt(&attempts, Some(1)).expect("attempt 1"); - assert_eq!(first.diff, "diff --git a/file b/file\n"); - assert!(select_attempt(&attempts, Some(2)).is_err()); - } - - #[test] - fn parse_task_id_from_url_and_raw() { - let raw = parse_task_id("task_i_abc123").expect("raw id"); - assert_eq!(raw.0, "task_i_abc123"); - let url = - parse_task_id("https://chatgpt.com/codex/tasks/task_i_123456?foo=bar").expect("url id"); - assert_eq!(url.0, "task_i_123456"); - assert!(parse_task_id(" ").is_err()); - } -} diff --git a/codex-rs/cloud-tasks/src/new_task.rs b/codex-rs/cloud-tasks/src/new_task.rs deleted file mode 100644 index 8708bd62fb..0000000000 --- a/codex-rs/cloud-tasks/src/new_task.rs +++ /dev/null @@ -1,35 +0,0 @@ -use codex_tui::ComposerInput; - -pub struct NewTaskPage { - pub composer: ComposerInput, - pub submitting: bool, - pub env_id: Option, - pub best_of_n: usize, -} - -impl NewTaskPage { - pub fn new(env_id: Option, best_of_n: usize) -> Self { - let mut composer = ComposerInput::new(); - composer.set_hint_items(vec![ - ("⏎", "send"), - ("Shift+⏎", "newline"), - ("Ctrl+O", "env"), - ("Ctrl+N", "attempts"), - ("Ctrl+C", "quit"), - ]); - Self { - composer, - submitting: false, - env_id, - best_of_n, - } - } - - // Additional helpers can be added as usage evolves. -} - -impl Default for NewTaskPage { - fn default() -> Self { - Self::new(/*env_id*/ None, /*best_of_n*/ 1) - } -} diff --git a/codex-rs/cloud-tasks/src/scrollable_diff.rs b/codex-rs/cloud-tasks/src/scrollable_diff.rs deleted file mode 100644 index a88fe1bf6e..0000000000 --- a/codex-rs/cloud-tasks/src/scrollable_diff.rs +++ /dev/null @@ -1,208 +0,0 @@ -use unicode_segmentation::UnicodeSegmentation; -use unicode_width::UnicodeWidthStr; - -/// Scroll position and geometry for a vertical scroll view. -#[derive(Clone, Copy, Debug, Default)] -pub struct ScrollViewState { - pub scroll: u16, - pub viewport_h: u16, - pub content_h: u16, -} - -impl ScrollViewState { - pub fn clamp(&mut self) { - let max_scroll = self.content_h.saturating_sub(self.viewport_h); - if self.scroll > max_scroll { - self.scroll = max_scroll; - } - } -} - -/// A simple, local scrollable view for diffs or message text. -/// -/// Owns raw lines, caches wrapped lines for a given width, and maintains -/// a small scroll state that is clamped whenever geometry shrinks. -#[derive(Clone, Debug, Default)] -pub struct ScrollableDiff { - raw: Vec, - wrapped: Vec, - wrapped_src_idx: Vec, - wrap_cols: Option, - pub state: ScrollViewState, -} - -impl ScrollableDiff { - pub fn new() -> Self { - Self::default() - } - - /// Replace the raw content lines. Does not rewrap immediately; call `set_width` next. - pub fn set_content(&mut self, lines: Vec) { - self.raw = lines; - self.wrapped.clear(); - self.wrapped_src_idx.clear(); - self.state.content_h = 0; - // Force rewrap on next set_width even if width is unchanged - self.wrap_cols = None; - } - - /// Set the wrap width. If changed, rebuild wrapped lines and clamp scroll. - pub fn set_width(&mut self, width: u16) { - if self.wrap_cols == Some(width) { - return; - } - self.wrap_cols = Some(width); - self.rewrap(width); - self.state.clamp(); - } - - /// Update viewport height and clamp scroll if needed. - pub fn set_viewport(&mut self, height: u16) { - self.state.viewport_h = height; - self.state.clamp(); - } - - /// Return the cached wrapped lines. Call `set_width` first when area changes. - pub fn wrapped_lines(&self) -> &[String] { - &self.wrapped - } - - pub fn wrapped_src_indices(&self) -> &[usize] { - &self.wrapped_src_idx - } - - pub fn raw_line_at(&self, idx: usize) -> &str { - self.raw.get(idx).map(String::as_str).unwrap_or("") - } - - /// Scroll by a signed delta; clamps to content. - pub fn scroll_by(&mut self, delta: i16) { - let s = self.state.scroll as i32 + delta as i32; - self.state.scroll = s.clamp(0, self.max_scroll() as i32) as u16; - } - - /// Page by a signed delta; typically viewport_h - 1. - pub fn page_by(&mut self, delta: i16) { - self.scroll_by(delta); - } - - pub fn scroll_to_top(&mut self) { - self.state.scroll = 0; - } - - pub fn scroll_to_bottom(&mut self) { - self.state.scroll = self.max_scroll(); - } - - /// Optional percent scrolled; None when not enough geometry is known. - pub fn percent_scrolled(&self) -> Option { - if self.state.content_h == 0 || self.state.viewport_h == 0 { - return None; - } - if self.state.content_h <= self.state.viewport_h { - return None; - } - let visible_bottom = self.state.scroll.saturating_add(self.state.viewport_h) as f32; - let pct = (visible_bottom / self.state.content_h as f32 * 100.0).round(); - Some(pct.clamp(0.0, 100.0) as u8) - } - - fn max_scroll(&self) -> u16 { - self.state.content_h.saturating_sub(self.state.viewport_h) - } - - fn rewrap(&mut self, width: u16) { - if width == 0 { - self.wrapped = self.raw.clone(); - self.state.content_h = self.wrapped.len() as u16; - return; - } - let max_cols = width as usize; - let mut out: Vec = Vec::new(); - let mut out_idx: Vec = Vec::new(); - for (raw_idx, raw) in self.raw.iter().enumerate() { - // Normalize tabs for width accounting (MVP: 4 spaces). - let raw = raw.replace('\t', " "); - if raw.is_empty() { - out.push(String::new()); - out_idx.push(raw_idx); - continue; - } - let mut line = String::new(); - let mut line_cols = 0usize; - let mut last_soft_idx: Option = None; // last whitespace or punctuation break - for grapheme in raw - .graphemes(/*is_extended*/ true) - .flat_map(|grapheme| grapheme.split_inclusive(char::is_whitespace)) - { - if grapheme == "\n" { - out.push(std::mem::take(&mut line)); - out_idx.push(raw_idx); - line_cols = 0; - last_soft_idx = None; - continue; - } - let grapheme_width = display_width(grapheme); - if line_cols.saturating_add(grapheme_width) > max_cols { - if let Some(split) = last_soft_idx { - let (prefix, rest) = line.split_at(split); - let prefix = prefix.trim_end(); - if !prefix.is_empty() { - out.push(prefix.to_string()); - out_idx.push(raw_idx); - } - line = rest.trim_start().to_string(); - last_soft_idx = None; - // Retry adding the current grapheme now that the line may be shorter. - } else if !line.is_empty() { - out.push(std::mem::take(&mut line)); - out_idx.push(raw_idx); - } - } - if grapheme.chars().all(char::is_whitespace) - || grapheme.chars().any(|ch| { - matches!( - ch, - ',' | ';' - | '.' - | ':' - | ')' - | ']' - | '}' - | '|' - | '/' - | '?' - | '!' - | '-' - | '_' - ) - }) - { - last_soft_idx = Some(line.len()); - } - line.push_str(grapheme); - line_cols = display_width(&line); - } - if !line.is_empty() { - out.push(line); - out_idx.push(raw_idx); - } - } - self.wrapped = out; - self.wrapped_src_idx = out_idx; - self.state.content_h = self.wrapped.len() as u16; - } -} - -/// Counts terminal cells, including the halfwidth sound marks omitted by `unicode-width`. -fn display_width(text: &str) -> usize { - UnicodeWidthStr::width(text) - + text - .chars() - .filter(|ch| matches!(ch, '\u{FF9E}' | '\u{FF9F}')) - .count() -} - -#[cfg(test)] -#[path = "scrollable_diff_tests.rs"] -mod tests; diff --git a/codex-rs/cloud-tasks/src/scrollable_diff_tests.rs b/codex-rs/cloud-tasks/src/scrollable_diff_tests.rs deleted file mode 100644 index 4db0a4f33f..0000000000 --- a/codex-rs/cloud-tasks/src/scrollable_diff_tests.rs +++ /dev/null @@ -1,48 +0,0 @@ -use super::ScrollableDiff; -use pretty_assertions::assert_eq; - -#[test] -fn wraps_halfwidth_sound_marks_using_ratatui_width() { - let mut diff = ScrollableDiff::new(); - diff.set_content(vec![ - "aガbパc".to_string(), - "a ゙b".to_string(), - "a ゚b".to_string(), - ]); - diff.set_width(/*width*/ 2); - - insta::assert_snapshot!( - diff.wrapped_lines().join("\n"), - @r" - a - ガ - b - パ - c - a - ゙b - a - ゚b - " - ); - assert_eq!(diff.wrapped_src_indices(), [0, 0, 0, 0, 0, 1, 1, 2, 2]); -} - -#[test] -fn does_not_emit_empty_rows_after_full_width_sound_mark_graphemes() { - for grapheme in ["ガ", "パ"] { - let mut diff = ScrollableDiff::new(); - diff.set_content(vec![format!("a {grapheme} tail")]); - diff.set_width(/*width*/ 2); - - let expected = ["a", grapheme, "ta", "il"]; - let actual = diff - .wrapped_lines() - .iter() - .map(String::as_str) - .collect::>(); - assert_eq!(actual, expected); - assert_eq!(diff.wrapped_src_indices(), [0, 0, 0, 0]); - assert_eq!(diff.state.content_h, 4); - } -} diff --git a/codex-rs/cloud-tasks/src/ui.rs b/codex-rs/cloud-tasks/src/ui.rs deleted file mode 100644 index 38f75e41ab..0000000000 --- a/codex-rs/cloud-tasks/src/ui.rs +++ /dev/null @@ -1,1046 +0,0 @@ -use ratatui::layout::Constraint; -use ratatui::layout::Direction; -use ratatui::layout::Layout; -use ratatui::prelude::*; -use ratatui::style::Color; -use ratatui::style::Modifier; -use ratatui::style::Style; -use ratatui::style::Stylize; -use ratatui::widgets::Block; -use ratatui::widgets::BorderType; -use ratatui::widgets::Borders; -use ratatui::widgets::Clear; -use ratatui::widgets::List; -use ratatui::widgets::ListItem; -use ratatui::widgets::ListState; -use ratatui::widgets::Padding; -use ratatui::widgets::Paragraph; -use std::sync::OnceLock; -use std::time::Instant; - -use crate::app::App; -use crate::app::AttemptView; -use crate::util::format_relative_time_now; -use codex_cloud_tasks_client::AttemptStatus; -use codex_cloud_tasks_client::TaskStatus; -use codex_tui::render_markdown_text; - -pub fn draw(frame: &mut Frame, app: &mut App) { - let area = frame.area(); - let chunks = Layout::default() - .direction(Direction::Vertical) - .constraints([ - Constraint::Min(1), // list - Constraint::Length(2), // two-line footer (help + status) - ]) - .split(area); - if app.new_task.is_some() { - draw_new_task_page(frame, chunks[0], app); - draw_footer(frame, chunks[1], app); - } else { - draw_list(frame, chunks[0], app); - draw_footer(frame, chunks[1], app); - } - - if app.diff_overlay.is_some() { - draw_diff_overlay(frame, area, app); - } - if app.env_modal.is_some() { - draw_env_modal(frame, area, app); - } - if app.best_of_modal.is_some() { - draw_best_of_modal(frame, area, app); - } - if app.apply_modal.is_some() { - draw_apply_modal(frame, area, app); - } -} - -// ===== Overlay helpers (geometry + styling) ===== -static ROUNDED: OnceLock = OnceLock::new(); - -fn rounded_enabled() -> bool { - *ROUNDED.get_or_init(|| { - std::env::var("CODEX_TUI_ROUNDED") - .ok() - .map(|v| v == "1") - .unwrap_or(true) - }) -} - -fn overlay_outer(area: Rect) -> Rect { - let outer_v = Layout::default() - .direction(Direction::Vertical) - .constraints([ - Constraint::Percentage(10), - Constraint::Percentage(80), - Constraint::Percentage(10), - ]) - .split(area)[1]; - Layout::default() - .direction(Direction::Horizontal) - .constraints([ - Constraint::Percentage(10), - Constraint::Percentage(80), - Constraint::Percentage(10), - ]) - .split(outer_v)[1] -} - -fn overlay_block() -> Block<'static> { - let base = Block::default().borders(Borders::ALL); - let base = if rounded_enabled() { - base.border_type(BorderType::Rounded) - } else { - base - }; - base.padding(Padding::new(2, 2, 1, 1)) -} - -fn overlay_content(area: Rect) -> Rect { - overlay_block().inner(area) -} - -pub fn draw_new_task_page(frame: &mut Frame, area: Rect, app: &mut App) { - let title_spans = { - let mut spans: Vec = vec!["New Task".magenta().bold()]; - if let Some(id) = app - .new_task - .as_ref() - .and_then(|p| p.env_id.as_ref()) - .cloned() - { - spans.push(" • ".into()); - // Try to map id to label - let label = app - .environments - .iter() - .find(|r| r.id == id) - .and_then(|r| r.label.clone()) - .unwrap_or(id); - spans.push(label.dim()); - } else { - spans.push(" • ".into()); - spans.push("Env: none (press ctrl-o to choose)".red()); - } - if let Some(page) = app.new_task.as_ref() { - spans.push(" • ".into()); - let attempts = page.best_of_n; - let label = format!( - "{} attempt{}", - attempts, - if attempts == 1 { "" } else { "s" } - ); - spans.push(label.cyan()); - } - spans - }; - let block = Block::default() - .borders(Borders::ALL) - .title(Line::from(title_spans)); - - frame.render_widget(Clear, area); - frame.render_widget(block.clone(), area); - let content = block.inner(area); - - // Expand composer height up to (terminal height - 6), with a 3-line minimum. - let max_allowed = frame.area().height.saturating_sub(6).max(3); - let desired = app - .new_task - .as_ref() - .map(|p| p.composer.desired_height(content.width)) - .unwrap_or(3) - .clamp(3, max_allowed); - - // Anchor the composer to the bottom-left by allocating a flexible spacer - // above it and a fixed `desired`-height area for the composer. - let rows = Layout::default() - .direction(Direction::Vertical) - .constraints([Constraint::Min(1), Constraint::Length(desired)]) - .split(content); - let composer_area = rows[1]; - - if let Some(page) = app.new_task.as_ref() { - page.composer.render_ref(composer_area, frame.buffer_mut()); - // Composer renders its own footer hints; no extra row here. - } - - // Place cursor where composer wants it - if let Some(page) = app.new_task.as_ref() - && let Some((x, y)) = page.composer.cursor_pos(composer_area) - { - frame.set_cursor_position((x, y)); - } -} - -fn draw_list(frame: &mut Frame, area: Rect, app: &mut App) { - let items: Vec = app.tasks.iter().map(|t| render_task_item(app, t)).collect(); - - // Selection reflects the actual task index (no artificial spacer item). - let mut state = ListState::default().with_selected(Some(app.selected)); - // Dim task list when a modal/overlay is active to emphasize focus. - let dim_bg = app.env_modal.is_some() - || app.apply_modal.is_some() - || app.best_of_modal.is_some() - || app.diff_overlay.is_some(); - // Dynamic title includes current environment filter - let suffix_span = if let Some(ref id) = app.env_filter { - let label = app - .environments - .iter() - .find(|r| &r.id == id) - .and_then(|r| r.label.clone()) - .unwrap_or_else(|| "Selected".to_string()); - format!(" • {label}").dim() - } else { - " • All".dim() - }; - // Percent scrolled based on selection position in the list (0% at top, 100% at bottom). - let percent_span = if app.tasks.len() <= 1 { - " • 0%".dim() - } else { - let p = ((app.selected as f32) / ((app.tasks.len() - 1) as f32) * 100.0).round() as i32; - format!(" • {}%", p.clamp(0, 100)).dim() - }; - let title_line = { - let base = Line::from(vec!["Cloud Tasks".into(), suffix_span, percent_span]); - if dim_bg { - base.style(Style::default().add_modifier(Modifier::DIM)) - } else { - base - } - }; - let block = Block::default().borders(Borders::ALL).title(title_line); - // Render the outer block first - frame.render_widget(block.clone(), area); - // Draw list inside with a persistent top spacer row - let inner = block.inner(area); - let rows = Layout::default() - .direction(Direction::Vertical) - .constraints([Constraint::Length(1), Constraint::Min(1)]) - .split(inner); - let mut list = List::new(items) - .highlight_symbol("› ") - .highlight_style(Style::default().bold()); - if dim_bg { - list = list.style(Style::default().add_modifier(Modifier::DIM)); - } - frame.render_stateful_widget(list, rows[1], &mut state); - - // In-box spinner during initial/refresh loads - if app.refresh_inflight { - draw_centered_spinner(frame, inner, &mut app.spinner_start, "Loading tasks…"); - } -} - -fn draw_footer(frame: &mut Frame, area: Rect, app: &mut App) { - let mut help = vec![ - "↑/↓".dim(), - ": Move ".dim(), - "r".dim(), - ": Refresh ".dim(), - "Enter".dim(), - ": Open ".dim(), - ]; - // Apply hint; show disabled note when overlay is open without a diff. - if let Some(ov) = app.diff_overlay.as_ref() { - if !ov.current_can_apply() { - help.push("a".dim()); - help.push(": Apply (disabled) ".dim()); - } else { - help.push("a".dim()); - help.push(": Apply ".dim()); - } - if ov.attempt_count() > 1 { - help.push("Tab".dim()); - help.push(": Next attempt ".dim()); - help.push("[ ]".dim()); - help.push(": Cycle attempts ".dim()); - } - } else { - help.push("a".dim()); - help.push(": Apply ".dim()); - } - help.push("o : Set Env ".dim()); - if app.new_task.is_some() { - help.push("Ctrl+N".dim()); - help.push(format!(": Attempts {}x ", app.best_of_n).dim()); - help.push("(editing new task) ".dim()); - } else { - help.push("n : New Task ".dim()); - } - help.extend(vec!["q".dim(), ": Quit ".dim()]); - // Split footer area into two rows: help+spinner (top) and status (bottom) - let rows = Layout::default() - .direction(Direction::Vertical) - .constraints([Constraint::Length(1), Constraint::Length(1)]) - .split(area); - - // Top row: help text + spinner at right - let top = Layout::default() - .direction(Direction::Horizontal) - .constraints([Constraint::Fill(1), Constraint::Length(18)]) - .split(rows[0]); - let para = Paragraph::new(Line::from(help)); - // Draw help text; avoid clearing the whole footer area every frame. - frame.render_widget(para, top[0]); - // Right side: spinner or clear the spinner area if idle to prevent stale glyphs. - if app.refresh_inflight - || app.details_inflight - || app.env_loading - || app.apply_preflight_inflight - || app.apply_inflight - { - draw_inline_spinner(frame, top[1], &mut app.spinner_start, "Loading…"); - } else { - frame.render_widget(Clear, top[1]); - } - - // Bottom row: status/log text across full width (single-line; sanitize newlines) - let mut status_line = app.status.replace('\n', " "); - if status_line.len() > 2000 { - // hard cap to avoid TUI noise - status_line.truncate(2000); - status_line.push('…'); - } - // Clear the status row to avoid trailing characters when the message shrinks. - frame.render_widget(Clear, rows[1]); - let status = Paragraph::new(status_line); - frame.render_widget(status, rows[1]); -} - -fn draw_diff_overlay(frame: &mut Frame, area: Rect, app: &mut App) { - let inner = overlay_outer(area); - if app.diff_overlay.is_none() { - return; - } - let ov_can_apply = app - .diff_overlay - .as_ref() - .map(super::app::DiffOverlay::current_can_apply) - .unwrap_or(false); - let is_error = app - .diff_overlay - .as_ref() - .and_then(|o| o.sd.wrapped_lines().first().cloned()) - .map(|s| s.trim_start().starts_with("Task failed:")) - .unwrap_or(false) - && !ov_can_apply; - let title = app - .diff_overlay - .as_ref() - .map(|o| o.title.clone()) - .unwrap_or_default(); - - // Title block - let title_ref = title.as_str(); - let mut title_spans: Vec = if is_error { - vec![ - "Details ".magenta(), - "[FAILED]".red().bold(), - " ".into(), - title_ref.magenta(), - ] - } else if ov_can_apply { - vec!["Diff: ".magenta(), title_ref.magenta()] - } else { - vec!["Details: ".magenta(), title_ref.magenta()] - }; - if let Some(p) = app - .diff_overlay - .as_ref() - .and_then(|o| o.sd.percent_scrolled()) - { - title_spans.push(" • ".dim()); - title_spans.push(format!("{p}%").dim()); - } - frame.render_widget(Clear, inner); - frame.render_widget( - overlay_block().title(Line::from(title_spans)).clone(), - inner, - ); - - // Content area and optional status bar - let content_full = overlay_content(inner); - let mut content_area = content_full; - if let Some(ov) = app.diff_overlay.as_mut() { - let has_text = ov.current_attempt().is_some_and(AttemptView::has_text); - let has_diff = ov.current_attempt().is_some_and(AttemptView::has_diff) || ov.base_can_apply; - if has_diff || has_text { - let rows = Layout::default() - .direction(Direction::Vertical) - .constraints([Constraint::Length(1), Constraint::Min(1)]) - .split(content_full); - // Status bar label - let mut spans: Vec = Vec::new(); - if has_diff && has_text { - let prompt_lbl = if matches!(ov.current_view, crate::app::DetailView::Prompt) { - "[Prompt]".magenta().bold() - } else { - "Prompt".dim() - }; - let diff_lbl = if matches!(ov.current_view, crate::app::DetailView::Diff) { - "[Diff]".magenta().bold() - } else { - "Diff".dim() - }; - spans.extend(vec![ - prompt_lbl, - " ".into(), - diff_lbl, - " ".into(), - "(← → to switch view)".dim(), - ]); - } else if has_text { - spans.push("Conversation".magenta().bold()); - } else { - spans.push("Diff".magenta().bold()); - } - if let Some(total) = ov.expected_attempts().or({ - if ov.attempts.is_empty() { - None - } else { - Some(ov.attempts.len()) - } - }) && total > 1 - { - spans.extend(vec![ - " ".into(), - format!("Attempt {}/{}", ov.selected_attempt + 1, total) - .bold() - .dim(), - " ".into(), - "(Tab/Shift-Tab or [ ] to cycle attempts)".dim(), - ]); - } - frame.render_widget(Paragraph::new(Line::from(spans)), rows[0]); - ov.sd.set_width(rows[1].width); - ov.sd.set_viewport(rows[1].height); - content_area = rows[1]; - } else { - ov.sd.set_width(content_full.width); - ov.sd.set_viewport(content_full.height); - content_area = content_full; - } - } - - // Styled content render - // Choose styling by the active view, not just presence of a diff - let is_diff_view = app - .diff_overlay - .as_ref() - .map(|o| matches!(o.current_view, crate::app::DetailView::Diff)) - .unwrap_or(false); - let styled_lines: Vec> = if is_diff_view { - let raw = app.diff_overlay.as_ref().map(|o| o.sd.wrapped_lines()); - raw.unwrap_or(&[]) - .iter() - .map(|l| style_diff_line(l)) - .collect() - } else { - app.diff_overlay - .as_ref() - .map(|o| style_conversation_lines(&o.sd, o.current_attempt())) - .unwrap_or_default() - }; - let raw_empty = app - .diff_overlay - .as_ref() - .map(|o| o.sd.wrapped_lines().is_empty()) - .unwrap_or(true); - if app.details_inflight && raw_empty { - draw_centered_spinner( - frame, - content_area, - &mut app.spinner_start, - "Loading details…", - ); - } else { - let scroll = app - .diff_overlay - .as_ref() - .map(|o| o.sd.state.scroll) - .unwrap_or(0); - let content = Paragraph::new(Text::from(styled_lines)).scroll((scroll, 0)); - frame.render_widget(content, content_area); - } -} - -pub fn draw_apply_modal(frame: &mut Frame, area: Rect, app: &mut App) { - use ratatui::widgets::Wrap; - let inner = overlay_outer(area); - let title = Line::from("Apply Changes?".magenta().bold()); - let block = overlay_block().title(title); - frame.render_widget(Clear, inner); - frame.render_widget(block.clone(), inner); - let content = overlay_content(inner); - - if let Some(m) = &app.apply_modal { - // Header - let header = Paragraph::new(Line::from( - format!("Apply '{}' ?", m.title).magenta().bold(), - )) - .wrap(Wrap { trim: true }); - // Footer instructions - let footer = - Paragraph::new(Line::from("Press Y to apply, P to preflight, N to cancel.").dim()) - .wrap(Wrap { trim: true }); - - // Split into header/body/footer - let rows = Layout::default() - .direction(Direction::Vertical) - .constraints([ - Constraint::Length(1), - Constraint::Min(1), - Constraint::Length(1), - ]) - .split(content); - - frame.render_widget(header, rows[0]); - // Body: spinner while preflight/apply runs; otherwise show result message and path lists - if app.apply_preflight_inflight { - draw_centered_spinner(frame, rows[1], &mut app.spinner_start, "Checking…"); - } else if app.apply_inflight { - draw_centered_spinner(frame, rows[1], &mut app.spinner_start, "Applying…"); - } else if m.result_message.is_none() { - draw_centered_spinner(frame, rows[1], &mut app.spinner_start, "Loading…"); - } else if let Some(msg) = &m.result_message { - let mut body_lines: Vec = Vec::new(); - let first = match m.result_level { - Some(crate::app::ApplyResultLevel::Success) => msg.clone().green(), - Some(crate::app::ApplyResultLevel::Partial) => msg.clone().magenta(), - Some(crate::app::ApplyResultLevel::Error) => msg.clone().red(), - None => msg.clone().into(), - }; - body_lines.push(Line::from(first)); - - // On partial or error, show conflicts/skips if present - if !matches!(m.result_level, Some(crate::app::ApplyResultLevel::Success)) { - use ratatui::text::Span; - if !m.conflict_paths.is_empty() { - body_lines.push(Line::from("")); - body_lines.push( - Line::from(format!("Conflicts ({}):", m.conflict_paths.len())) - .red() - .bold(), - ); - for p in &m.conflict_paths { - body_lines - .push(Line::from(vec![" • ".into(), Span::raw(p.clone()).dim()])); - } - } - if !m.skipped_paths.is_empty() { - body_lines.push(Line::from("")); - body_lines.push( - Line::from(format!("Skipped ({}):", m.skipped_paths.len())) - .magenta() - .bold(), - ); - for p in &m.skipped_paths { - body_lines - .push(Line::from(vec![" • ".into(), Span::raw(p.clone()).dim()])); - } - } - } - let body = Paragraph::new(body_lines).wrap(Wrap { trim: true }); - frame.render_widget(body, rows[1]); - } - frame.render_widget(footer, rows[2]); - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum ConversationSpeaker { - User, - Assistant, -} - -fn style_conversation_lines( - sd: &crate::scrollable_diff::ScrollableDiff, - attempt: Option<&AttemptView>, -) -> Vec> { - use ratatui::text::Span; - - let wrapped = sd.wrapped_lines(); - if wrapped.is_empty() { - return Vec::new(); - } - - let indices = sd.wrapped_src_indices(); - let mut styled: Vec> = Vec::new(); - let mut speaker: Option = None; - let mut in_code = false; - let mut last_src: Option = None; - let mut bullet_indent: Option = None; - - for (display, &src_idx) in wrapped.iter().zip(indices.iter()) { - let raw = sd.raw_line_at(src_idx); - let trimmed = raw.trim(); - let is_new_raw = last_src.map(|prev| prev != src_idx).unwrap_or(true); - - if trimmed.eq_ignore_ascii_case("user:") { - speaker = Some(ConversationSpeaker::User); - in_code = false; - bullet_indent = None; - styled.push(conversation_header_line( - ConversationSpeaker::User, - /*attempt*/ None, - )); - last_src = Some(src_idx); - continue; - } - if trimmed.eq_ignore_ascii_case("assistant:") { - speaker = Some(ConversationSpeaker::Assistant); - in_code = false; - bullet_indent = None; - styled.push(conversation_header_line( - ConversationSpeaker::Assistant, - attempt, - )); - last_src = Some(src_idx); - continue; - } - if raw.is_empty() { - let mut spans: Vec = Vec::new(); - if let Some(role) = speaker { - spans.push(conversation_gutter_span(role)); - } else { - spans.push(Span::raw(String::new())); - } - styled.push(Line::from(spans)); - last_src = Some(src_idx); - bullet_indent = None; - continue; - } - - if is_new_raw { - let trimmed_start = raw.trim_start(); - if trimmed_start.starts_with("```") { - in_code = !in_code; - bullet_indent = None; - } else if !in_code - && (trimmed_start.starts_with("- ") || trimmed_start.starts_with("* ")) - { - let indent = raw.chars().take_while(|c| c.is_whitespace()).count(); - bullet_indent = Some(indent); - } else if !in_code { - bullet_indent = None; - } - } - - let mut spans: Vec = Vec::new(); - if let Some(role) = speaker { - spans.push(conversation_gutter_span(role)); - } - - spans.extend(conversation_text_spans( - display, - in_code, - is_new_raw, - bullet_indent, - )); - - styled.push(Line::from(spans)); - last_src = Some(src_idx); - } - - if styled.is_empty() { - wrapped.iter().map(|l| Line::from(l.to_string())).collect() - } else { - styled - } -} - -fn conversation_header_line( - speaker: ConversationSpeaker, - attempt: Option<&AttemptView>, -) -> Line<'static> { - use ratatui::text::Span; - - let mut spans: Vec = vec!["╭ ".dim()]; - match speaker { - ConversationSpeaker::User => { - spans.push("User".cyan().bold()); - spans.push(" prompt".dim()); - } - ConversationSpeaker::Assistant => { - spans.push("Assistant".magenta().bold()); - spans.push(" response".dim()); - if let Some(attempt) = attempt - && let Some(status_span) = attempt_status_span(attempt.status) - { - spans.push(" • ".dim()); - spans.push(status_span); - } - } - } - Line::from(spans) -} - -fn conversation_gutter_span(speaker: ConversationSpeaker) -> ratatui::text::Span<'static> { - match speaker { - ConversationSpeaker::User => "│ ".cyan().dim(), - ConversationSpeaker::Assistant => "│ ".magenta().dim(), - } -} - -fn conversation_text_spans( - display: &str, - in_code: bool, - is_new_raw: bool, - bullet_indent: Option, -) -> Vec> { - use ratatui::text::Span; - - if in_code { - return vec![Span::styled( - display.to_string(), - Style::default().fg(Color::Cyan), - )]; - } - - let trimmed = display.trim_start(); - - if let Some(indent) = bullet_indent { - if is_new_raw { - let rest = trimmed.get(2..).unwrap_or("").trim_start(); - let mut spans: Vec = Vec::new(); - if indent > 0 { - spans.push(Span::raw(" ".repeat(indent))); - } - spans.push("• ".into()); - spans.push(Span::raw(rest.to_string())); - return spans; - } - let mut continuation = String::new(); - continuation.push_str(&" ".repeat(indent + 2)); - continuation.push_str(trimmed); - return vec![Span::raw(continuation)]; - } - - if is_new_raw - && (trimmed.starts_with("### ") || trimmed.starts_with("## ") || trimmed.starts_with("# ")) - { - return vec![Span::styled( - display.to_string(), - Style::default() - .fg(Color::Magenta) - .add_modifier(Modifier::BOLD), - )]; - } - - let mut rendered = render_markdown_text(display); - if rendered.lines.is_empty() { - return vec![Span::raw(display.to_string())]; - } - // `render_markdown_text` can yield multiple lines when the input contains - // explicit breaks. We only expect a single line here; join the spans of the - // first rendered line for styling. - rendered.lines.remove(0).spans.into_iter().collect() -} - -fn attempt_status_span(status: AttemptStatus) -> Option> { - match status { - AttemptStatus::Completed => Some("Completed".green()), - AttemptStatus::Failed => Some("Failed".red().bold()), - AttemptStatus::InProgress => Some("In progress".magenta()), - AttemptStatus::Pending => Some("Pending".cyan()), - AttemptStatus::Cancelled => Some("Cancelled".dim()), - AttemptStatus::Unknown => None, - } -} - -fn style_diff_line(raw: &str) -> Line<'static> { - use ratatui::style::Color; - use ratatui::style::Modifier; - use ratatui::style::Style; - use ratatui::text::Span; - - if raw.starts_with("@@") { - return Line::from(vec![Span::styled( - raw.to_string(), - Style::default() - .fg(Color::Magenta) - .add_modifier(Modifier::BOLD), - )]); - } - if raw.starts_with("+++") || raw.starts_with("---") { - return Line::from(vec![Span::styled( - raw.to_string(), - Style::default().add_modifier(Modifier::DIM), - )]); - } - if raw.starts_with('+') { - return Line::from(vec![Span::styled( - raw.to_string(), - Style::default().fg(Color::Green), - )]); - } - if raw.starts_with('-') { - return Line::from(vec![Span::styled( - raw.to_string(), - Style::default().fg(Color::Red), - )]); - } - Line::from(vec![Span::raw(raw.to_string())]) -} - -fn render_task_item(_app: &App, t: &codex_cloud_tasks_client::TaskSummary) -> ListItem<'static> { - let status = match t.status { - TaskStatus::Ready => "READY".green(), - TaskStatus::Pending => "PENDING".magenta(), - TaskStatus::Applied => "APPLIED".blue(), - TaskStatus::Error => "ERROR".red(), - }; - - // Title line: [STATUS] Title - let title = Line::from(vec![ - "[".into(), - status, - "] ".into(), - t.title.clone().into(), - ]); - - // Meta line: environment label and relative time (dim) - let mut meta: Vec = Vec::new(); - if let Some(lbl) = t.environment_label.as_ref().filter(|s| !s.is_empty()) { - meta.push(lbl.clone().dim()); - } - let when = format_relative_time_now(t.updated_at).dim(); - if !meta.is_empty() { - meta.push(" ".into()); - meta.push("•".dim()); - meta.push(" ".into()); - } - meta.push(when); - let meta_line = Line::from(meta); - - // Subline: summary when present; otherwise show "no diff" - let sub = if t.summary.files_changed > 0 - || t.summary.lines_added > 0 - || t.summary.lines_removed > 0 - { - let adds = t.summary.lines_added; - let dels = t.summary.lines_removed; - let files = t.summary.files_changed; - Line::from(vec![ - format!("+{adds}").green(), - "/".into(), - format!("−{dels}").red(), - " ".into(), - "•".dim(), - " ".into(), - format!("{files}").into(), - " ".into(), - "files".dim(), - ]) - } else { - Line::from("no diff".to_string().dim()) - }; - - // Insert a blank spacer line after the summary to separate tasks - let spacer = Line::from(""); - ListItem::new(vec![title, meta_line, sub, spacer]) -} - -fn draw_inline_spinner( - frame: &mut Frame, - area: Rect, - spinner_start: &mut Option, - label: &str, -) { - use ratatui::widgets::Paragraph; - let start = spinner_start.get_or_insert_with(Instant::now); - let blink_on = (start.elapsed().as_millis() / 600).is_multiple_of(2); - let dot = if blink_on { - "• ".into() - } else { - "◦ ".dim() - }; - let label = label.cyan(); - let line = Line::from(vec![dot, label]); - frame.render_widget(Paragraph::new(line), area); -} - -fn draw_centered_spinner( - frame: &mut Frame, - area: Rect, - spinner_start: &mut Option, - label: &str, -) { - // Center a 1xN spinner within the given rect - let rows = Layout::default() - .direction(Direction::Vertical) - .constraints([ - Constraint::Percentage(50), - Constraint::Length(1), - Constraint::Percentage(49), - ]) - .split(area); - let cols = Layout::default() - .direction(Direction::Horizontal) - .constraints([ - Constraint::Percentage(50), - Constraint::Length(18), - Constraint::Percentage(50), - ]) - .split(rows[1]); - draw_inline_spinner(frame, cols[1], spinner_start, label); -} - -// Styling helpers for diff rendering live inline where used. - -pub fn draw_env_modal(frame: &mut Frame, area: Rect, app: &mut App) { - use ratatui::widgets::Wrap; - - // Use shared overlay geometry and padding. - let inner = overlay_outer(area); - - // Title: primary only; move long hints to a subheader inside content. - let title = Line::from(vec!["Select Environment".magenta().bold()]); - let block = overlay_block().title(title); - - frame.render_widget(Clear, inner); - frame.render_widget(block.clone(), inner); - let content = overlay_content(inner); - - if app.env_loading { - draw_centered_spinner( - frame, - content, - &mut app.spinner_start, - "Loading environments…", - ); - return; - } - - // Layout: subheader + search + results list - let rows = Layout::default() - .direction(Direction::Vertical) - .constraints([ - Constraint::Length(1), // subheader - Constraint::Length(1), // search - Constraint::Min(1), // list - ]) - .split(content); - - // Subheader with usage hints (dim cyan) - let subheader = Paragraph::new(Line::from( - "Type to search, Enter select, Esc cancel".cyan().dim(), - )) - .wrap(Wrap { trim: true }); - frame.render_widget(subheader, rows[0]); - - let query = app - .env_modal - .as_ref() - .map(|m| m.query.clone()) - .unwrap_or_default(); - let ql = query.to_lowercase(); - let search = Paragraph::new(format!("Search: {query}")).wrap(Wrap { trim: true }); - frame.render_widget(search, rows[1]); - - // Filter environments by query (case-insensitive substring over label/id/hints) - let envs: Vec<&crate::app::EnvironmentRow> = app - .environments - .iter() - .filter(|e| { - if ql.is_empty() { - return true; - } - let mut hay = String::new(); - if let Some(l) = &e.label { - hay.push_str(&l.to_lowercase()); - hay.push(' '); - } - hay.push_str(&e.id.to_lowercase()); - if let Some(h) = &e.repo_hints { - hay.push(' '); - hay.push_str(&h.to_lowercase()); - } - hay.contains(&ql) - }) - .collect(); - - let mut items: Vec = Vec::new(); - items.push(ListItem::new(Line::from("All Environments (Global)"))); - for env in envs.iter() { - let primary = env.label.clone().unwrap_or_else(|| "".to_string()); - let mut spans: Vec = vec![primary.into()]; - if env.is_pinned { - spans.push(" ".into()); - spans.push("PINNED".magenta().bold()); - } - spans.push(" ".into()); - spans.push(env.id.clone().dim()); - if let Some(hint) = &env.repo_hints { - spans.push(" ".into()); - spans.push(hint.clone().dim()); - } - items.push(ListItem::new(Line::from(spans))); - } - - let sel_desired = app.env_modal.as_ref().map(|m| m.selected).unwrap_or(0); - let sel = sel_desired.min(envs.len()); - let mut list_state = ListState::default().with_selected(Some(sel)); - let list = List::new(items) - .highlight_symbol("› ") - .highlight_style(Style::default().bold()) - .block(Block::default().borders(Borders::NONE)); - frame.render_stateful_widget(list, rows[2], &mut list_state); -} - -pub fn draw_best_of_modal(frame: &mut Frame, area: Rect, app: &mut App) { - use ratatui::widgets::Wrap; - - let inner = overlay_outer(area); - const MAX_WIDTH: u16 = 40; - const MIN_WIDTH: u16 = 20; - const MAX_HEIGHT: u16 = 12; - const MIN_HEIGHT: u16 = 6; - let modal_width = inner.width.min(MAX_WIDTH).max(inner.width.min(MIN_WIDTH)); - let modal_height = inner - .height - .min(MAX_HEIGHT) - .max(inner.height.min(MIN_HEIGHT)); - let modal_x = inner.x + (inner.width.saturating_sub(modal_width)) / 2; - let modal_y = inner.y + (inner.height.saturating_sub(modal_height)) / 2; - let modal_area = Rect::new(modal_x, modal_y, modal_width, modal_height); - let title = Line::from(vec!["Parallel Attempts".magenta().bold()]); - let block = overlay_block().title(title); - - frame.render_widget(Clear, modal_area); - frame.render_widget(block.clone(), modal_area); - let content = overlay_content(modal_area); - - let rows = Layout::default() - .direction(Direction::Vertical) - .constraints([Constraint::Length(2), Constraint::Min(1)]) - .split(content); - - let hint = Paragraph::new(Line::from("Use ↑/↓ to choose, 1-4 jump".cyan().dim())) - .wrap(Wrap { trim: true }); - frame.render_widget(hint, rows[0]); - - let selected = app.best_of_modal.as_ref().map(|m| m.selected).unwrap_or(0); - let options = [1usize, 2, 3, 4]; - let mut items: Vec = Vec::new(); - for &attempts in &options { - let noun = if attempts == 1 { "attempt" } else { "attempts" }; - let mut spans: Vec = vec![format!("{attempts} {noun:<8}").into()]; - spans.push(" ".into()); - spans.push(format!("{attempts}x parallel").dim()); - if attempts == app.best_of_n { - spans.push(" ".into()); - spans.push("Current".magenta().bold()); - } - items.push(ListItem::new(Line::from(spans))); - } - let sel = selected.min(options.len().saturating_sub(1)); - let mut list_state = ListState::default().with_selected(Some(sel)); - let list = List::new(items) - .highlight_symbol("› ") - .highlight_style(Style::default().bold()) - .block(Block::default().borders(Borders::NONE)); - frame.render_stateful_widget(list, rows[1], &mut list_state); -} diff --git a/codex-rs/cloud-tasks/src/util.rs b/codex-rs/cloud-tasks/src/util.rs deleted file mode 100644 index da1a4b64c5..0000000000 --- a/codex-rs/cloud-tasks/src/util.rs +++ /dev/null @@ -1,200 +0,0 @@ -use chrono::DateTime; -use chrono::Local; -use chrono::Utc; -use http::header::HeaderMap; - -use codex_core::config::Config; -use codex_http_client::HttpClientFactory; -use codex_http_client::OutboundProxyPolicy; -use codex_login::AuthManager; -use codex_utils_cli::CliConfigOverrides; -use std::sync::Arc; - -pub fn set_user_agent_suffix(suffix: &str) { - if let Ok(mut guard) = codex_login::default_client::USER_AGENT_SUFFIX.lock() { - guard.replace(suffix.to_string()); - } -} - -pub fn append_error_log(message: impl AsRef) { - let ts = Utc::now().to_rfc3339(); - if let Ok(mut f) = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open("error.log") - { - use std::io::Write as _; - let _ = writeln!(f, "[{ts}] {}", message.as_ref()); - } -} - -/// Normalize the configured base URL to a canonical form used by the backend client. -/// - trims trailing '/' -/// - appends '/backend-api' for ChatGPT hosts when missing -pub fn normalize_base_url(input: &str) -> String { - let mut base_url = input.trim_end_matches('/').to_string(); - if (base_url.starts_with("https://chatgpt.com") - || base_url.starts_with("https://chat.openai.com")) - && !base_url.contains("/backend-api") - { - base_url = format!("{base_url}/backend-api"); - } - base_url -} - -/// Validate the destination before loading saved ChatGPT credentials, including in mock mode: -/// environment discovery still makes authenticated HTTP requests when the task backend is mocked. -pub(crate) fn validate_chatgpt_base_url(input: &str) -> anyhow::Result { - let invalid_url = || { - anyhow::anyhow!( - "CODEX_CLOUD_TASKS_BASE_URL must use a trusted HTTPS origin on port 443, without user information, a query, or a fragment; custom backends cannot use saved ChatGPT credentials" - ) - }; - let uri = input.parse::().map_err(|_| invalid_url())?; - let authority = uri - .authority() - .ok_or_else(invalid_url)? - .as_str() - .to_ascii_lowercase(); - if uri.scheme_str() != Some("https") - || !matches!( - authority.as_str(), - "chatgpt.com" - | "chatgpt.com:443" - | "chat.openai.com" - | "chat.openai.com:443" - | "chatgpt-staging.com" - | "chatgpt-staging.com:443" - ) - || uri.query().is_some() - || input.contains('#') - { - return Err(invalid_url()); - } - Ok(normalize_base_url(&format!( - "https://{authority}{}", - uri.path() - ))) -} - -pub async fn load_auth_manager( - chatgpt_base_url: Option, - config_overrides: &CliConfigOverrides, -) -> anyhow::Result<(Option>, HttpClientFactory, Option)> { - let overrides = config_overrides - .parse_overrides() - .map_err(anyhow::Error::msg)?; - let config = match Config::load_with_cli_overrides(overrides).await { - Ok(config) => config, - Err(error) => { - append_error_log(format!( - "failed to load auth config; using transport-default proxy handling: {error}" - )); - let http_client_factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault); - return Ok((None, http_client_factory, None)); - } - }; - let http_client_factory = config.http_client_factory(); - let mut auth_config = config.auth_config(); - auth_config.chatgpt_base_url = chatgpt_base_url.or(Some(config.chatgpt_base_url.clone())); - let auth_manager = match AuthManager::shared_from_auth_config( - auth_config, - /*enable_codex_api_key_env*/ false, - ) - .await - { - Ok(auth_manager) => auth_manager, - Err(error) => { - append_error_log(format!("failed to load auth: {error}")); - return Ok((None, http_client_factory, None)); - } - }; - Ok((Some(auth_manager), http_client_factory, Some(config))) -} - -/// Non-authentication headers shared by environment requests. The client resolves auth per GET. -pub fn build_chatgpt_headers() -> HeaderMap { - use http::header::HeaderValue; - use http::header::USER_AGENT; - - set_user_agent_suffix("codex_cloud_tasks_tui"); - let ua = codex_login::default_client::get_codex_user_agent(); - let mut headers = HeaderMap::new(); - headers.insert( - USER_AGENT, - HeaderValue::from_str(&ua).unwrap_or(HeaderValue::from_static("codex-cli")), - ); - headers -} - -/// Construct a browser-friendly task URL for the given backend base URL. -pub fn task_url(base_url: &str, task_id: &str) -> String { - let normalized = normalize_base_url(base_url); - if let Some(root) = normalized.strip_suffix("/backend-api") { - return format!("{root}/codex/tasks/{task_id}"); - } - if let Some(root) = normalized.strip_suffix("/api/codex") { - return format!("{root}/codex/tasks/{task_id}"); - } - if normalized.ends_with("/codex") { - return format!("{normalized}/tasks/{task_id}"); - } - format!("{normalized}/codex/tasks/{task_id}") -} - -pub fn format_relative_time(reference: DateTime, ts: DateTime) -> String { - let mut secs = (reference - ts).num_seconds(); - if secs < 0 { - secs = 0; - } - if secs < 60 { - return format!("{secs}s ago"); - } - let mins = secs / 60; - if mins < 60 { - return format!("{mins}m ago"); - } - let hours = mins / 60; - if hours < 24 { - return format!("{hours}h ago"); - } - let local = ts.with_timezone(&Local); - local.format("%b %e %H:%M").to_string() -} - -pub fn format_relative_time_now(ts: DateTime) -> String { - format_relative_time(Utc::now(), ts) -} - -#[cfg(test)] -mod tests { - use pretty_assertions::assert_eq; - - use super::normalize_base_url; - - #[test] - fn normalize_base_url_normalizes_urls() { - for (input, expected) in [ - ("https://example.com/path", "https://example.com/path"), - ("https://example.com/path/", "https://example.com/path"), - ("https://example.com/path///", "https://example.com/path"), - ("", ""), - ("///", ""), - ("https://chatgpt.com///", "https://chatgpt.com/backend-api"), - ( - "https://chatgpt.com/backend-api///", - "https://chatgpt.com/backend-api", - ), - ( - "https://chat.openai.com///", - "https://chat.openai.com/backend-api", - ), - ( - "https://chat.openai.com/backend-api///", - "https://chat.openai.com/backend-api", - ), - ] { - assert_eq!(normalize_base_url(input), expected, "input: {input:?}"); - } - } -} diff --git a/codex-rs/cloud-tasks/tests/env_filter.rs b/codex-rs/cloud-tasks/tests/env_filter.rs deleted file mode 100644 index 716e4f05ed..0000000000 --- a/codex-rs/cloud-tasks/tests/env_filter.rs +++ /dev/null @@ -1,39 +0,0 @@ -use codex_cloud_tasks_client::CloudBackend; -use codex_cloud_tasks_mock_client::MockClient; - -#[tokio::test] -async fn mock_backend_varies_by_env() { - let client = MockClient; - - let root = CloudBackend::list_tasks( - &client, /*env*/ None, /*limit*/ None, /*cursor*/ None, - ) - .await - .unwrap() - .tasks; - assert!(root.iter().any(|t| t.title.contains("Update README"))); - - let a = CloudBackend::list_tasks( - &client, - Some("env-A"), - /*limit*/ None, - /*cursor*/ None, - ) - .await - .unwrap() - .tasks; - assert_eq!(a.len(), 1); - assert_eq!(a[0].title, "A: First"); - - let b = CloudBackend::list_tasks( - &client, - Some("env-B"), - /*limit*/ None, - /*cursor*/ None, - ) - .await - .unwrap() - .tasks; - assert_eq!(b.len(), 2); - assert!(b[0].title.starts_with("B: ")); -} diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 88c73dcf24..450e9576c2 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -445,6 +445,8 @@ mod slash_argument; mod slash_input; mod sparkle; mod status_surface; +#[cfg(test)] +mod test_support; mod vim_register; mod vim_search; mod warning_notice; @@ -770,23 +772,6 @@ impl ChatComposer { ) } - pub fn new( - has_input_focus: bool, - app_event_tx: AppEventSender, - enhanced_keys_supported: bool, - placeholder_text: String, - disable_paste_burst: bool, - ) -> Self { - Self::new_with_config( - has_input_focus, - app_event_tx, - enhanced_keys_supported, - placeholder_text, - disable_paste_burst, - ChatComposerConfig::default(), - ) - } - /// Construct a composer with explicit feature gating. /// /// This enables reuse in contexts like request-user-input where we want @@ -5165,6 +5150,7 @@ mod skill_completion_tests; #[cfg(test)] mod tests { + pub(super) use super::test_support::new_test_composer; use super::*; use crate::test_support::PathBufExt; use crate::test_support::test_path_buf; @@ -5182,24 +5168,8 @@ mod tests { use crate::bottom_pane::chat_composer::LARGE_PASTE_CHAR_THRESHOLD; use crate::bottom_pane::textarea::TextArea; use codex_protocol::models::local_image_label_text; - use tokio::sync::mpsc::UnboundedReceiver; use tokio::sync::mpsc::unbounded_channel; - pub(super) fn new_test_composer() -> (ChatComposer, UnboundedReceiver) { - let (tx, rx) = unbounded_channel::(); - let sender = AppEventSender::new(tx); - ( - ChatComposer::new( - /*has_input_focus*/ true, - sender, - /*enhanced_keys_supported*/ false, - "Ask Codex to do anything".to_string(), - /*disable_paste_burst*/ false, - ), - rx, - ) - } - #[test] fn parent_owned_thread_placeholder_snapshot() { snapshot_composer_state( diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/test_support.rs b/codex-rs/tui/src/bottom_pane/chat_composer/test_support.rs new file mode 100644 index 0000000000..537f76c3a6 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/chat_composer/test_support.rs @@ -0,0 +1,40 @@ +use super::ChatComposer; +use super::ChatComposerConfig; +use crate::app_event::AppEvent; +use crate::app_event_sender::AppEventSender; +use tokio::sync::mpsc::UnboundedReceiver; +use tokio::sync::mpsc::unbounded_channel; + +impl ChatComposer { + pub(crate) fn new( + has_input_focus: bool, + app_event_tx: AppEventSender, + enhanced_keys_supported: bool, + placeholder_text: String, + disable_paste_burst: bool, + ) -> Self { + Self::new_with_config( + has_input_focus, + app_event_tx, + enhanced_keys_supported, + placeholder_text, + disable_paste_burst, + ChatComposerConfig::default(), + ) + } +} + +pub(super) fn new_test_composer() -> (ChatComposer, UnboundedReceiver) { + let (tx, rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + ( + ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ false, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ), + rx, + ) +} diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index f7f6ba4b6b..39ad052ce4 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -206,7 +206,6 @@ mod open_in_codex; mod oss_selection; mod pager_overlay; mod projectless; -pub(crate) mod public_widgets; mod render; mod resume_permissions; mod resume_picker; @@ -305,8 +304,6 @@ pub use cli::Cli; pub use cli::ResumeApprovalPreset; use codex_arg0::Arg0DispatchPaths; pub use markdown_render::render_markdown_text; -pub use public_widgets::composer_input::ComposerAction; -pub use public_widgets::composer_input::ComposerInput; // (tests access modules directly within the crate) const TUI_LOG_FILE_NAME: &str = "codex-tui.log"; diff --git a/codex-rs/tui/src/public_widgets/composer_input.rs b/codex-rs/tui/src/public_widgets/composer_input.rs deleted file mode 100644 index dc443f260c..0000000000 --- a/codex-rs/tui/src/public_widgets/composer_input.rs +++ /dev/null @@ -1,149 +0,0 @@ -//! Public wrapper around the internal ChatComposer for simple, reusable text input. -//! -//! This exposes a minimal interface suitable for other crates (e.g., -//! codex-cloud-tasks) to reuse the mature composer behavior: multi-line input, -//! paste heuristics, Enter-to-submit, and Shift+Enter for newline. - -use crossterm::event::KeyEvent; -use ratatui::buffer::Buffer; -use ratatui::layout::Rect; -use std::time::Duration; - -use crate::app_event::AppEvent; -use crate::app_event_sender::AppEventSender; -use crate::bottom_pane::ChatComposer; -use crate::bottom_pane::InputResult; -use crate::bottom_pane::QueuedInputAction; -use crate::render::renderable::Renderable; - -/// Action returned from feeding a key event into the ComposerInput. -pub enum ComposerAction { - /// The user submitted the current text (typically via Enter). Contains the submitted text. - Submitted(String), - /// No submission occurred; UI may need to redraw if `needs_redraw()` returned true. - None, -} - -/// A minimal, public wrapper for the internal `ChatComposer` that behaves as a -/// reusable text input field with submit semantics. -pub struct ComposerInput { - inner: ChatComposer, - _tx: tokio::sync::mpsc::UnboundedSender, - rx: tokio::sync::mpsc::UnboundedReceiver, -} - -impl ComposerInput { - /// Create a new composer input with a neutral placeholder. - pub fn new() -> Self { - let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); - let sender = AppEventSender::new(tx.clone()); - // `enhanced_keys_supported=true` enables Shift+Enter newline hint/behavior. - let inner = ChatComposer::new( - /*has_input_focus*/ true, - sender, - /*enhanced_keys_supported*/ true, - "Compose new task".to_string(), - /*disable_paste_burst*/ false, - ); - Self { inner, _tx: tx, rx } - } - - /// Returns true if the input is empty. - pub fn is_empty(&self) -> bool { - self.inner.is_empty() - } - - /// Clear the input text. - pub fn clear(&mut self) { - self.inner - .set_text_content(String::new(), Vec::new(), Vec::new()); - } - - /// Feed a key event into the composer and return a high-level action. - pub fn input(&mut self, key: KeyEvent) -> ComposerAction { - let action = match self.inner.handle_key_event(key).0 { - InputResult::Submitted { text, .. } => ComposerAction::Submitted(text), - InputResult::Queued { - text, - text_elements, - action: QueuedInputAction::Literal, - pending_pastes, - } => ComposerAction::Submitted( - ChatComposer::expand_pending_pastes(&text, text_elements, &pending_pastes).0, - ), - _ => ComposerAction::None, - }; - self.drain_app_events(); - action - } - - pub fn handle_paste(&mut self, pasted: String) -> bool { - let handled = self.inner.handle_paste(pasted); - self.drain_app_events(); - handled - } - - /// Override the footer hint items displayed under the composer. - /// Each tuple is rendered as "