Base: codex-main originale (prima del fork aKode)
This commit is contained in:
7
codex-rs/cloud-tasks/BUILD.bazel
Normal file
7
codex-rs/cloud-tasks/BUILD.bazel
Normal file
@@ -0,0 +1,7 @@
|
||||
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,
|
||||
)
|
||||
54
codex-rs/cloud-tasks/Cargo.toml
Normal file
54
codex-rs/cloud-tasks/Cargo.toml
Normal file
@@ -0,0 +1,54 @@
|
||||
[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 }
|
||||
534
codex-rs/cloud-tasks/src/app.rs
Normal file
534
codex-rs/cloud-tasks/src/app.rs
Normal file
@@ -0,0 +1,534 @@
|
||||
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<String>,
|
||||
pub is_pinned: bool,
|
||||
pub repo_hints: Option<String>, // 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<String>,
|
||||
pub result_level: Option<ApplyResultLevel>,
|
||||
pub skipped_paths: Vec<String>,
|
||||
pub conflict_paths: Vec<String>,
|
||||
pub diff_override: Option<String>,
|
||||
}
|
||||
|
||||
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<TaskSummary>,
|
||||
pub selected: usize,
|
||||
pub status: String,
|
||||
pub diff_overlay: Option<DiffOverlay>,
|
||||
pub spinner_start: Option<Instant>,
|
||||
pub refresh_inflight: bool,
|
||||
pub details_inflight: bool,
|
||||
// Environment filter state
|
||||
pub env_filter: Option<String>,
|
||||
pub env_modal: Option<EnvModalState>,
|
||||
pub apply_modal: Option<ApplyModalState>,
|
||||
pub best_of_modal: Option<BestOfModalState>,
|
||||
pub environments: Vec<EnvironmentRow>,
|
||||
pub env_last_loaded: Option<std::time::Instant>,
|
||||
pub env_loading: bool,
|
||||
pub env_error: Option<String>,
|
||||
// New Task page
|
||||
pub new_task: Option<crate::new_task::NewTaskPage>,
|
||||
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<String>,
|
||||
// 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<Vec<TaskSummary>> {
|
||||
// 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<TaskSummary> = 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<String>,
|
||||
pub text_lines: Vec<String>,
|
||||
pub prompt: Option<String>,
|
||||
pub attempts: Vec<AttemptView>,
|
||||
pub selected_attempt: usize,
|
||||
pub current_view: DetailView,
|
||||
pub base_turn_id: Option<String>,
|
||||
pub sibling_turn_ids: Vec<String>,
|
||||
pub attempt_total_hint: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct AttemptView {
|
||||
pub turn_id: Option<String>,
|
||||
pub status: codex_cloud_tasks_client::AttemptStatus,
|
||||
pub attempt_placement: Option<i64>,
|
||||
pub diff_lines: Vec<String>,
|
||||
pub text_lines: Vec<String>,
|
||||
pub prompt: Option<String>,
|
||||
pub diff_raw: Option<String>,
|
||||
}
|
||||
|
||||
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<usize>) -> 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<usize> {
|
||||
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!["<loading attempt>".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!["<no diff available>".to_string()]);
|
||||
} else {
|
||||
self.sd.set_content(diff_lines);
|
||||
}
|
||||
}
|
||||
DetailView::Prompt => {
|
||||
if text_lines.is_empty() {
|
||||
self.sd.set_content(vec!["<no output>".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<String>,
|
||||
result: anyhow::Result<Vec<TaskSummary>>,
|
||||
},
|
||||
// Background diff summary events were planned; removed for now to keep code minimal.
|
||||
/// Autodetection of a likely environment id finished
|
||||
EnvironmentAutodetected(anyhow::Result<crate::env_detect::AutodetectSelection>),
|
||||
/// Background completion of environment list fetch
|
||||
EnvironmentsLoaded(anyhow::Result<Vec<EnvironmentRow>>),
|
||||
DetailsDiffLoaded {
|
||||
id: TaskId,
|
||||
title: String,
|
||||
diff: String,
|
||||
},
|
||||
DetailsMessagesLoaded {
|
||||
id: TaskId,
|
||||
title: String,
|
||||
messages: Vec<String>,
|
||||
prompt: Option<String>,
|
||||
turn_id: Option<String>,
|
||||
sibling_turn_ids: Vec<String>,
|
||||
attempt_placement: Option<i64>,
|
||||
attempt_status: codex_cloud_tasks_client::AttemptStatus,
|
||||
},
|
||||
DetailsFailed {
|
||||
id: TaskId,
|
||||
title: String,
|
||||
error: String,
|
||||
},
|
||||
AttemptsLoaded {
|
||||
id: TaskId,
|
||||
attempts: Vec<codex_cloud_tasks_client::TurnAttempt>,
|
||||
},
|
||||
/// Background completion of new task submission
|
||||
NewTaskSubmitted(Result<codex_cloud_tasks_client::CreatedTask, String>),
|
||||
/// Background completion of apply preflight when opening modal or on demand
|
||||
ApplyPreflightFinished {
|
||||
id: TaskId,
|
||||
title: String,
|
||||
message: String,
|
||||
level: ApplyResultLevel,
|
||||
skipped: Vec<String>,
|
||||
conflicts: Vec<String>,
|
||||
},
|
||||
/// Background completion of apply action (actual patch application)
|
||||
ApplyFinished {
|
||||
id: TaskId,
|
||||
result: std::result::Result<codex_cloud_tasks_client::ApplyOutcome, String>,
|
||||
},
|
||||
}
|
||||
|
||||
// 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<Option<String>, Vec<&'static str>>,
|
||||
}
|
||||
|
||||
impl FakeBackend {
|
||||
async fn list_tasks(
|
||||
&self,
|
||||
env: Option<&str>,
|
||||
limit: Option<i64>,
|
||||
cursor: Option<&str>,
|
||||
) -> Result<codex_cloud_tasks_client::TaskListPage, CloudTaskError> {
|
||||
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<TaskSummary, CloudTaskError> {
|
||||
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<codex_cloud_tasks_client::TaskText, CloudTaskError> {
|
||||
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<i64>,
|
||||
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<String>> {
|
||||
Box::pin(async {
|
||||
Err(codex_cloud_tasks_client::CloudTaskError::Unimplemented(
|
||||
"not used in test",
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
fn get_task_messages(&self, _id: TaskId) -> CloudBackendFuture<'_, Vec<String>> {
|
||||
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<codex_cloud_tasks_client::TurnAttempt>> {
|
||||
Box::pin(async { Ok(Vec::new()) })
|
||||
}
|
||||
|
||||
fn apply_task(
|
||||
&self,
|
||||
_id: TaskId,
|
||||
_diff_override: Option<String>,
|
||||
) -> 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<String>,
|
||||
) -> 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");
|
||||
}
|
||||
}
|
||||
277
codex-rs/cloud-tasks/src/backend_auth_tests.rs
Normal file
277
codex-rs/cloud-tasks/src/backend_auth_tests.rs
Normal file
@@ -0,0 +1,277 @@
|
||||
//! 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(())
|
||||
}
|
||||
120
codex-rs/cloud-tasks/src/cli.rs
Normal file
120
codex-rs/cloud-tasks/src/cli.rs
Normal file
@@ -0,0 +1,120 @@
|
||||
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<Command>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
fn parse_attempts(input: &str) -> Result<usize, String> {
|
||||
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<i64, String> {
|
||||
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<String>,
|
||||
|
||||
/// 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<String>,
|
||||
|
||||
/// 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<usize>,
|
||||
}
|
||||
|
||||
#[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<usize>,
|
||||
}
|
||||
446
codex-rs/cloud-tasks/src/env_detect.rs
Normal file
446
codex-rs/cloud-tasks/src/env_detect.rs
Normal file
@@ -0,0 +1,446 @@
|
||||
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<ClientAuth>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Deserialize)]
|
||||
struct CodeEnvironment {
|
||||
id: String,
|
||||
#[serde(default)]
|
||||
label: Option<String>,
|
||||
#[serde(default)]
|
||||
is_pinned: Option<bool>,
|
||||
#[serde(default)]
|
||||
task_count: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AutodetectSelection {
|
||||
pub id: String,
|
||||
pub label: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) async fn autodetect_environment_id(
|
||||
http: &EnvironmentClient,
|
||||
base_url: &str,
|
||||
headers: &HeaderMap,
|
||||
desired_label: Option<String>,
|
||||
) -> anyhow::Result<AutodetectSelection> {
|
||||
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<String>,
|
||||
origins: &[SanitizedGitUrl],
|
||||
) -> anyhow::Result<AutodetectSelection> {
|
||||
// 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<CodeEnvironment> = 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::<Vec<CodeEnvironment>>(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::<serde_json::Value>(&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<CodeEnvironment> = 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<CodeEnvironment> {
|
||||
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<T: serde::de::DeserializeOwned>(
|
||||
http: &impl EnvironmentHttp,
|
||||
url: &str,
|
||||
headers: &HeaderMap,
|
||||
) -> anyhow::Result<T> {
|
||||
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::<T>(&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<Output = anyhow::Result<EnvironmentResponse>> + Send + 'a;
|
||||
}
|
||||
|
||||
impl EnvironmentHttp for EnvironmentClient {
|
||||
async fn get(&self, url: &str, headers: &HeaderMap) -> anyhow::Result<EnvironmentResponse> {
|
||||
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<SanitizedGitUrl> {
|
||||
// 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<SanitizedGitUrl>) -> Vec<SanitizedGitUrl> {
|
||||
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<Vec<crate::app::EnvironmentRow>> {
|
||||
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<Vec<crate::app::EnvironmentRow>> {
|
||||
let mut map: HashMap<String, crate::app::EnvironmentRow> = 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::<Vec<CodeEnvironment>>(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::<Vec<CodeEnvironment>>(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<crate::app::EnvironmentRow> = 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;
|
||||
130
codex-rs/cloud-tasks/src/env_detect_runtime_auth_tests.rs
Normal file
130
codex-rs/cloud-tasks/src/env_detect_runtime_auth_tests.rs
Normal file
@@ -0,0 +1,130 @@
|
||||
//! 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<CodexAuth>);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
362
codex-rs/cloud-tasks/src/env_detect_tests.rs
Normal file
362
codex-rs/cloud-tasks/src/env_detect_tests.rs
Normal file
@@ -0,0 +1,362 @@
|
||||
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<_>>(),
|
||||
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<String, EnvironmentResponse>,
|
||||
requests: Mutex<Vec<RecordedRequest>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct RecordedRequest {
|
||||
url: String,
|
||||
headers: HeaderMap,
|
||||
}
|
||||
|
||||
impl FakeHttp {
|
||||
fn new(responses: HashMap<String, EnvironmentResponse>) -> Self {
|
||||
Self {
|
||||
responses,
|
||||
requests: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
fn requests(&self) -> Vec<RecordedRequest> {
|
||||
self.requests.lock().expect("request lock").clone()
|
||||
}
|
||||
|
||||
fn requested_urls(&self) -> Vec<String> {
|
||||
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<EnvironmentResponse> {
|
||||
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(),
|
||||
}
|
||||
}
|
||||
2467
codex-rs/cloud-tasks/src/lib.rs
Normal file
2467
codex-rs/cloud-tasks/src/lib.rs
Normal file
File diff suppressed because it is too large
Load Diff
35
codex-rs/cloud-tasks/src/new_task.rs
Normal file
35
codex-rs/cloud-tasks/src/new_task.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use codex_tui::ComposerInput;
|
||||
|
||||
pub struct NewTaskPage {
|
||||
pub composer: ComposerInput,
|
||||
pub submitting: bool,
|
||||
pub env_id: Option<String>,
|
||||
pub best_of_n: usize,
|
||||
}
|
||||
|
||||
impl NewTaskPage {
|
||||
pub fn new(env_id: Option<String>, 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)
|
||||
}
|
||||
}
|
||||
208
codex-rs/cloud-tasks/src/scrollable_diff.rs
Normal file
208
codex-rs/cloud-tasks/src/scrollable_diff.rs
Normal file
@@ -0,0 +1,208 @@
|
||||
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<String>,
|
||||
wrapped: Vec<String>,
|
||||
wrapped_src_idx: Vec<usize>,
|
||||
wrap_cols: Option<u16>,
|
||||
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<String>) {
|
||||
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<u8> {
|
||||
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<String> = Vec::new();
|
||||
let mut out_idx: Vec<usize> = 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<usize> = 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;
|
||||
48
codex-rs/cloud-tasks/src/scrollable_diff_tests.rs
Normal file
48
codex-rs/cloud-tasks/src/scrollable_diff_tests.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
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::<Vec<_>>();
|
||||
assert_eq!(actual, expected);
|
||||
assert_eq!(diff.wrapped_src_indices(), [0, 0, 0, 0]);
|
||||
assert_eq!(diff.state.content_h, 4);
|
||||
}
|
||||
}
|
||||
1046
codex-rs/cloud-tasks/src/ui.rs
Normal file
1046
codex-rs/cloud-tasks/src/ui.rs
Normal file
File diff suppressed because it is too large
Load Diff
200
codex-rs/cloud-tasks/src/util.rs
Normal file
200
codex-rs/cloud-tasks/src/util.rs
Normal file
@@ -0,0 +1,200 @@
|
||||
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<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.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<String> {
|
||||
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::<http::Uri>().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<String>,
|
||||
config_overrides: &CliConfigOverrides,
|
||||
) -> anyhow::Result<(Option<Arc<AuthManager>>, HttpClientFactory, Option<Config>)> {
|
||||
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<Utc>, ts: DateTime<Utc>) -> 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<Utc>) -> 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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
39
codex-rs/cloud-tasks/tests/env_filter.rs
Normal file
39
codex-rs/cloud-tasks/tests/env_filter.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
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: "));
|
||||
}
|
||||
Reference in New Issue
Block a user