aKode fase 2a: rimossi cloud tasks, chatgpt apply, responses-api-proxy, codex app, remote control, guardian decisions; realtime senza fallback OpenAI; doctor senza sonde OpenAI
This commit is contained in:
@@ -72,7 +72,6 @@ runtime_archive(
|
||||
"//codex-rs/cli:release_files",
|
||||
"//codex-rs/code-mode-host:release_files",
|
||||
"//codex-rs/exec-server-cli:release_files",
|
||||
"//codex-rs/responses-api-proxy:release_files",
|
||||
] + select({
|
||||
"@platforms//os:linux": ["//codex-rs/bwrap:release_files"],
|
||||
"//conditions:default": [],
|
||||
|
||||
150
codex-rs/Cargo.lock
generated
150
codex-rs/Cargo.lock
generated
@@ -2100,7 +2100,6 @@ dependencies = [
|
||||
"codex-arg0",
|
||||
"codex-aws-auth",
|
||||
"codex-backend-client",
|
||||
"codex-chatgpt",
|
||||
"codex-cloud-config",
|
||||
"codex-code-mode",
|
||||
"codex-config",
|
||||
@@ -2211,7 +2210,6 @@ dependencies = [
|
||||
"codex-app-server-protocol",
|
||||
"codex-app-server-transport",
|
||||
"codex-arg0",
|
||||
"codex-cloud-client",
|
||||
"codex-config",
|
||||
"codex-core",
|
||||
"codex-exec-server",
|
||||
@@ -2522,34 +2520,6 @@ dependencies = [
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-chatgpt"
|
||||
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",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"uuid",
|
||||
"wiremock",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-cli"
|
||||
version = "0.0.0"
|
||||
@@ -2569,9 +2539,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",
|
||||
@@ -2595,7 +2563,6 @@ dependencies = [
|
||||
"codex-multi-env-copy-file",
|
||||
"codex-plugin",
|
||||
"codex-protocol",
|
||||
"codex-responses-api-proxy",
|
||||
"codex-rmcp-client",
|
||||
"codex-rollout",
|
||||
"codex-rollout-trace",
|
||||
@@ -2668,32 +2635,6 @@ dependencies = [
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-cloud-client"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-stream",
|
||||
"bytes",
|
||||
"codex-http-client",
|
||||
"futures",
|
||||
"http 1.4.0",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"pretty_assertions",
|
||||
"prost",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tonic",
|
||||
"tonic-prost",
|
||||
"tower",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-cloud-config"
|
||||
version = "0.0.0"
|
||||
@@ -2722,72 +2663,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"
|
||||
@@ -4745,30 +4620,6 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-responses-api-proxy"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bytes",
|
||||
"clap",
|
||||
"codex-http-client",
|
||||
"codex-process-hardening",
|
||||
"ctor 0.6.3",
|
||||
"http 1.4.0",
|
||||
"libc",
|
||||
"pretty_assertions",
|
||||
"reqwest 0.12.28",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tiny_http",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-test",
|
||||
"url",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-rmcp-client"
|
||||
version = "0.0.0"
|
||||
@@ -18223,7 +18074,6 @@ version = "1.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"zeroize_derive",
|
||||
]
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ members = [
|
||||
"agent-identity",
|
||||
"agent-roles",
|
||||
"backend-client",
|
||||
"cloud-client",
|
||||
"bwrap",
|
||||
"build-info",
|
||||
"ansi-escape",
|
||||
@@ -34,9 +33,6 @@ members = [
|
||||
"plugin-host",
|
||||
"codex-home",
|
||||
"cloud-config",
|
||||
"cloud-tasks",
|
||||
"cloud-tasks-client",
|
||||
"cloud-tasks-mock-client",
|
||||
"cli",
|
||||
"collaboration-mode-templates",
|
||||
"connectors",
|
||||
@@ -108,7 +104,6 @@ members = [
|
||||
"rollout",
|
||||
"rollout-trace",
|
||||
"rmcp-client",
|
||||
"responses-api-proxy",
|
||||
"runtime-agent-instance",
|
||||
"response-debug-context",
|
||||
"sandboxing",
|
||||
@@ -204,12 +199,9 @@ codex-arg0 = { path = "arg0" }
|
||||
codex-async-utils = { path = "async-utils" }
|
||||
codex-backend-client = { path = "backend-client" }
|
||||
codex-build-info = { path = "build-info" }
|
||||
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" }
|
||||
@@ -287,7 +279,6 @@ codex-protocol = { path = "protocol" }
|
||||
codex-protocol-test-support = { path = "protocol/tests/support" }
|
||||
codex-prompts = { path = "prompts" }
|
||||
codex-queue-extension = { path = "ext/queue" }
|
||||
codex-responses-api-proxy = { path = "responses-api-proxy" }
|
||||
codex-response-debug-context = { path = "response-debug-context" }
|
||||
codex-rmcp-client = { path = "rmcp-client" }
|
||||
codex-rollout = { path = "rollout" }
|
||||
|
||||
@@ -17,7 +17,6 @@ codex-app-server = { workspace = true }
|
||||
codex-app-server-protocol = { workspace = true }
|
||||
codex-app-server-transport = { workspace = true }
|
||||
codex-arg0 = { workspace = true }
|
||||
codex-cloud-client = { path = "../cloud-client" }
|
||||
codex-config = { workspace = true }
|
||||
codex-login = { workspace = true }
|
||||
codex-core = { workspace = true }
|
||||
|
||||
@@ -20,6 +20,22 @@ use std::sync::PoisonError;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
/// A local project's GitHub origins for a cloud coding thread.
|
||||
/// The native cloud backend was removed in aKode; the type stays for the channel API.
|
||||
#[derive(Clone)]
|
||||
pub struct ProjectEnvironment {
|
||||
pub name: String,
|
||||
pub origin_urls: Vec<String>,
|
||||
/// Working directory inside the managed environment, when a project selects one.
|
||||
pub cwd: Option<String>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ProjectEnvironment {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("ProjectEnvironment([redacted])")
|
||||
}
|
||||
}
|
||||
|
||||
/// Operations the cloud worker must handle without forwarding to another backend.
|
||||
/// Unsupported operations must return an explicit error; they must not claim success.
|
||||
pub enum CloudOperation {
|
||||
@@ -28,7 +44,7 @@ pub enum CloudOperation {
|
||||
StartProjectThread {
|
||||
request_id: RequestId,
|
||||
params: Box<codex_app_server_protocol::ThreadStartParams>,
|
||||
project: codex_cloud_client::ProjectEnvironment,
|
||||
project: ProjectEnvironment,
|
||||
},
|
||||
SubmitUserMessage(Box<TurnStartParams>),
|
||||
Notify(ClientNotification),
|
||||
@@ -81,19 +97,6 @@ impl CloudStreamLosses {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
pub(super) fn record(&self, thread_id: &str) {
|
||||
self.pending()
|
||||
.entry(thread_id.to_owned())
|
||||
.or_default()
|
||||
.remaining += 1;
|
||||
}
|
||||
|
||||
pub(super) fn supersede(&self, thread_id: &str) {
|
||||
if let Some(losses) = self.pending().get_mut(thread_id) {
|
||||
losses.superseded = losses.remaining;
|
||||
}
|
||||
}
|
||||
|
||||
fn should_deliver(&self, thread_id: &str) -> bool {
|
||||
let mut pending = self.pending();
|
||||
let Some(losses) = pending.get_mut(thread_id) else {
|
||||
@@ -195,7 +198,7 @@ impl CloudRequestHandle {
|
||||
&self,
|
||||
request_id: RequestId,
|
||||
params: codex_app_server_protocol::ThreadStartParams,
|
||||
project: codex_cloud_client::ProjectEnvironment,
|
||||
project: ProjectEnvironment,
|
||||
) -> io::Result<RequestResult> {
|
||||
self.send(CloudOperation::StartProjectThread {
|
||||
request_id,
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
//! Opens the internal Cloud preview with the selected ChatGPT credentials and local transport policy.
|
||||
|
||||
use super::start_worker;
|
||||
use crate::AppServerClient;
|
||||
use crate::legacy_core::config::Config;
|
||||
use codex_app_server_protocol as protocol;
|
||||
use codex_cloud_client as cloud;
|
||||
use codex_login::token_data::parse_jwt_expiration;
|
||||
use codex_protocol::account::PlanType;
|
||||
use color_eyre::eyre::Result;
|
||||
use color_eyre::eyre::bail;
|
||||
use color_eyre::eyre::eyre;
|
||||
|
||||
const ORIGIN: &str = "https://codex-cloud-backend.chatgpt.com";
|
||||
|
||||
pub async fn connect(config: &Config) -> Result<AppServerClient> {
|
||||
// The preview borrows Local's policy without owning credential updates.
|
||||
let factory = config.http_client_factory();
|
||||
let policy = factory.network_policy().clone().for_current_account();
|
||||
let factory = factory.with_network_policy(policy);
|
||||
let auth = config
|
||||
.auth_config()
|
||||
.load_auth(/*enable_codex_api_key_env*/ false)
|
||||
.await?
|
||||
.ok_or_else(|| eyre!("Sign in with ChatGPT and reopen Codex to use Cloud."))?;
|
||||
if !auth.is_chatgpt_auth() || auth.is_fedramp_account() {
|
||||
bail!("This account is not supported by the cloud conversation preview.");
|
||||
}
|
||||
let account_id = auth
|
||||
.get_account_id()
|
||||
.ok_or_else(|| eyre!("Cloud requires a selected account."))?;
|
||||
let token = auth.get_token()?;
|
||||
if let Ok(Some(expires)) = parse_jwt_expiration(&token)
|
||||
&& std::time::SystemTime::from(expires) <= std::time::SystemTime::now()
|
||||
{
|
||||
bail!("Your ChatGPT credential expired. Reopen Codex to reconnect.");
|
||||
}
|
||||
factory.network_policy().acquire(&ORIGIN.parse()?)?;
|
||||
let credentials = cloud::Credentials::new(&token, &account_id)?;
|
||||
let client = cloud::Client::new(&factory, ORIGIN, credentials)?;
|
||||
Ok(start_worker(
|
||||
client,
|
||||
protocol::GetAccountResponse {
|
||||
user_id: auth.get_chatgpt_user_id(),
|
||||
account: Some(protocol::Account::Chatgpt {
|
||||
email: auth.get_account_email(),
|
||||
plan_type: auth.account_plan_type().unwrap_or(PlanType::Unknown),
|
||||
workspace_name: None,
|
||||
}),
|
||||
requires_openai_auth: true,
|
||||
workspace_routing: None,
|
||||
},
|
||||
))
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
#![cfg(test)]
|
||||
|
||||
//! Ensures only a successfully attached thread can receive new turns.
|
||||
|
||||
use super::*;
|
||||
use futures::stream;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_replacement_keeps_old_thread_until_new_attachment_succeeds() -> Result<()> {
|
||||
let (output, mut notifications) = mpsc::unbounded_channel();
|
||||
let mut replies = Replies::default();
|
||||
replies
|
||||
.replace("old", async { Ok(stream::pending().boxed()) }, &output)
|
||||
.await?;
|
||||
|
||||
for failure in [
|
||||
Err(cloud::Error::InvalidResponse),
|
||||
Ok(stream::empty().boxed()),
|
||||
Ok(stream::iter([Err(cloud::Error::InvalidResponse)]).boxed()),
|
||||
] {
|
||||
assert!(
|
||||
replies
|
||||
.replace("new", async { failure }, &output)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
replies.admit_turn("old", &output)?;
|
||||
assert!(replies.admit_turn("new", &output).is_err());
|
||||
}
|
||||
|
||||
let (close, closed) = tokio::sync::oneshot::channel::<()>();
|
||||
let stream = stream::once(async move {
|
||||
let _ = closed.await;
|
||||
Err(cloud::Error::InvalidResponse)
|
||||
})
|
||||
.boxed();
|
||||
replies
|
||||
.replace("new", async { Ok(stream) }, &output)
|
||||
.await?;
|
||||
replies.detach("old");
|
||||
assert!(replies.admit_turn("old", &output).is_err());
|
||||
replies.admit_turn("new", &output)?;
|
||||
|
||||
let _ = close.send(());
|
||||
assert!(replies.admit_turn("new", &output).is_err());
|
||||
let AppServerEvent::ThreadStreamDisconnected(notification) = notifications.try_recv()? else {
|
||||
panic!("expected a disconnect notification");
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::to_value(protocol::ServerNotification::Error(*notification))?,
|
||||
serde_json::to_value(protocol::ServerNotification::Error(cloud_error(
|
||||
"new",
|
||||
"Cloud stream ended. Reopen the conversation to reconnect."
|
||||
)))?
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn successful_reopen_supersedes_only_earlier_losses_for_that_thread() -> Result<()> {
|
||||
let (mut client, _commands, output) = CloudClient::channel(/*capacity*/ 1);
|
||||
let mut replies = Replies {
|
||||
stream_losses: client.stream_losses.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
for id in ["reopened", "different", "reopened"] {
|
||||
let (sender, stream) = futures::channel::mpsc::unbounded();
|
||||
replies
|
||||
.replace(id, async { Ok(stream.boxed()) }, &output)
|
||||
.await?;
|
||||
drop(sender);
|
||||
replies.forward_next(&output).await;
|
||||
}
|
||||
assert!(
|
||||
replies
|
||||
.replace("reopened", async { Ok(stream::empty().boxed()) }, &output)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
// The first EOF was followed by a successful reopen. A different thread's
|
||||
// EOF and the reopened thread's newer EOF must still be delivered, in order.
|
||||
drop(output);
|
||||
for expected in ["different", "reopened"] {
|
||||
let Some(AppServerEvent::ThreadStreamDisconnected(error)) = client.next_event().await
|
||||
else {
|
||||
panic!("expected a thread stream disconnect");
|
||||
};
|
||||
assert_eq!(
|
||||
*error,
|
||||
cloud_error(
|
||||
expected,
|
||||
"Cloud stream ended. Reopen the conversation to reconnect."
|
||||
)
|
||||
);
|
||||
}
|
||||
assert!(client.next_event().await.is_none());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attachment_status_follows_its_server_notifications() -> Result<()> {
|
||||
let (output, _notifications) = mpsc::unbounded_channel();
|
||||
let mut replies = Replies::default();
|
||||
let notifications: [&[u8]; 3] = [
|
||||
b"\x1a\x0d\x12\x0b\x0a\x06\x22\x04\x0a\x02\x08\x01\x12\x01t", // t is waiting
|
||||
b"\x1a\x09\x12\x07\x0a\x02\x12\x00\x12\x01x", // x is idle
|
||||
b"\x1a\x09\x12\x07\x0a\x02\x12\x00\x12\x01t", // t is idle
|
||||
];
|
||||
let stream =
|
||||
stream::iter(notifications.map(|bytes| Ok(cloud::Event::Notification(bytes.into()))));
|
||||
replies
|
||||
.replace("t", async { Ok(stream.boxed()) }, &output)
|
||||
.await?;
|
||||
|
||||
let waiting = cloud::ThreadStatus::Active {
|
||||
active_flags: vec![cloud::ThreadActiveFlag::WaitingOnApproval],
|
||||
};
|
||||
assert_eq!(replies.thread_status("t"), Some(&waiting));
|
||||
replies.forward_next(&output).await;
|
||||
assert_eq!(replies.thread_status("t"), Some(&waiting));
|
||||
|
||||
replies.forward_next(&output).await;
|
||||
assert_eq!(replies.thread_status("t"), Some(&cloud::ThreadStatus::Idle));
|
||||
replies.forward_next(&output).await;
|
||||
assert_eq!(replies.thread_status("t"), Some(&cloud::ThreadStatus::Idle));
|
||||
|
||||
replies
|
||||
.replace("t", async { Ok(stream::pending().boxed()) }, &output)
|
||||
.await?;
|
||||
assert_eq!(replies.thread_status("t"), None);
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
//! Converts supported cloud transcript events without interpreting executor paths locally.
|
||||
|
||||
use codex_app_server_protocol as protocol;
|
||||
use codex_cloud_client as cloud;
|
||||
use codex_protocol::models::ImageDetail;
|
||||
use color_eyre::eyre::Result;
|
||||
use color_eyre::eyre::bail;
|
||||
|
||||
pub(super) fn turn(summary: cloud::TurnSummary) -> Result<protocol::Turn> {
|
||||
Ok(protocol::Turn {
|
||||
id: summary.id,
|
||||
root_turn_id: None,
|
||||
items: Vec::new(),
|
||||
items_view: protocol::TurnItemsView::NotLoaded,
|
||||
status: match summary.status {
|
||||
cloud::TurnStatus::Completed => protocol::TurnStatus::Completed,
|
||||
cloud::TurnStatus::Interrupted => protocol::TurnStatus::Interrupted,
|
||||
cloud::TurnStatus::Failed => protocol::TurnStatus::Failed,
|
||||
cloud::TurnStatus::InProgress => protocol::TurnStatus::InProgress,
|
||||
cloud::TurnStatus::Unknown(_) => {
|
||||
bail!("The cloud returned an unsupported turn status.");
|
||||
}
|
||||
},
|
||||
error: summary.error.map(|error| protocol::TurnError {
|
||||
message: error.message,
|
||||
additional_details: error.additional_details,
|
||||
codex_error_info: None,
|
||||
misalignment: None,
|
||||
}),
|
||||
started_at: summary.started_at,
|
||||
completed_at: summary.completed_at,
|
||||
duration_ms: summary.duration_ms,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn transcript(
|
||||
thread_id: String,
|
||||
update: cloud::TranscriptUpdate,
|
||||
) -> Result<Option<protocol::ServerNotification>> {
|
||||
use protocol::ServerNotification as Notification;
|
||||
Ok(Some(match update {
|
||||
cloud::TranscriptUpdate::TurnStarted(summary) => {
|
||||
Notification::TurnStarted(protocol::TurnStartedNotification {
|
||||
thread_id,
|
||||
turn: turn(summary)?,
|
||||
})
|
||||
}
|
||||
cloud::TranscriptUpdate::TurnCompleted(summary) => {
|
||||
Notification::TurnCompleted(protocol::TurnCompletedNotification {
|
||||
thread_id,
|
||||
turn: turn(summary)?,
|
||||
})
|
||||
}
|
||||
cloud::TranscriptUpdate::AgentMessageDelta(delta) => {
|
||||
Notification::AgentMessageDelta(protocol::AgentMessageDeltaNotification {
|
||||
thread_id,
|
||||
turn_id: delta.turn_id,
|
||||
item_id: delta.item_id,
|
||||
delta: delta.delta,
|
||||
})
|
||||
}
|
||||
cloud::TranscriptUpdate::ItemStarted(item) => {
|
||||
let Some(content) = item_summary(item.item) else {
|
||||
return Ok(None);
|
||||
};
|
||||
Notification::ItemStarted(protocol::ItemStartedNotification::new(
|
||||
thread_id,
|
||||
item.turn_id,
|
||||
content.payload,
|
||||
item.at_ms,
|
||||
))
|
||||
}
|
||||
cloud::TranscriptUpdate::ItemCompleted(item) => {
|
||||
let Some(content) = item_summary(item.item) else {
|
||||
return Ok(None);
|
||||
};
|
||||
Notification::ItemCompleted(protocol::ItemCompletedNotification::new(
|
||||
thread_id,
|
||||
item.turn_id,
|
||||
content.payload,
|
||||
/*started_at_ms*/ None,
|
||||
item.at_ms,
|
||||
))
|
||||
}
|
||||
cloud::TranscriptUpdate::CommandOutputDelta(_)
|
||||
| cloud::TranscriptUpdate::FileChangeOutputDelta(_)
|
||||
| cloud::TranscriptUpdate::FileChangePatchUpdated(_) => return Ok(None),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn item_summary(item: cloud::ItemSummary) -> Option<protocol::ThreadItem> {
|
||||
let payload = match item {
|
||||
cloud::ItemSummary::UserMessage {
|
||||
id,
|
||||
client_id,
|
||||
content,
|
||||
} => protocol::ThreadItemPayload::UserMessage {
|
||||
id,
|
||||
client_id,
|
||||
content: content
|
||||
.into_iter()
|
||||
.map(|item| match item {
|
||||
cloud::UserMessageInput::Text {
|
||||
text,
|
||||
text_elements,
|
||||
} => protocol::UserInput::Text {
|
||||
text,
|
||||
text_elements: text_elements
|
||||
.into_iter()
|
||||
.map(|element| {
|
||||
protocol::TextElement::new(
|
||||
protocol::ByteRange {
|
||||
start: element.start,
|
||||
end: element.end,
|
||||
},
|
||||
element.placeholder,
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
cloud::UserMessageInput::Image { image, detail } => {
|
||||
protocol::UserInput::Image {
|
||||
image: match image {
|
||||
cloud::ImageReference::Url(url) => {
|
||||
protocol::ImageReference::Inline { url }
|
||||
}
|
||||
cloud::ImageReference::FileId(file_id) => {
|
||||
protocol::ImageReference::File { file_id }
|
||||
}
|
||||
},
|
||||
detail: detail.map(|detail| match detail {
|
||||
cloud::ImageDetail::Auto => ImageDetail::Auto,
|
||||
cloud::ImageDetail::Low => ImageDetail::Low,
|
||||
cloud::ImageDetail::High => ImageDetail::High,
|
||||
cloud::ImageDetail::Original => ImageDetail::Original,
|
||||
}),
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
cloud::ItemSummary::AgentMessage {
|
||||
id,
|
||||
text,
|
||||
questions,
|
||||
} => protocol::ThreadItemPayload::AgentMessage {
|
||||
moderation: None,
|
||||
id,
|
||||
text,
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: questions.map(|questions| {
|
||||
questions
|
||||
.into_iter()
|
||||
.map(|question| protocol::AsyncUserInputQuestion {
|
||||
title: question.title,
|
||||
options: question.options,
|
||||
})
|
||||
.collect()
|
||||
}),
|
||||
},
|
||||
cloud::ItemSummary::Reasoning { .. }
|
||||
| cloud::ItemSummary::CommandExecution(_)
|
||||
| cloud::ItemSummary::FileChange { .. } => return None,
|
||||
};
|
||||
Some(protocol::ThreadItem::untimed(payload))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "events_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,98 +0,0 @@
|
||||
#![cfg(test)]
|
||||
//! Covers the user receipt and final assistant message presented by Cloud.
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn image_receipt_preserves_submission_identity_and_attachment() {
|
||||
let label = "[Image #1]";
|
||||
let actual = item_summary(cloud::ItemSummary::UserMessage {
|
||||
id: "item-1".into(),
|
||||
client_id: Some("submission-1".into()),
|
||||
content: vec![
|
||||
cloud::UserMessageInput::Image {
|
||||
image: cloud::ImageReference::FileId("file-synthetic".into()),
|
||||
detail: Some(cloud::ImageDetail::High),
|
||||
},
|
||||
cloud::UserMessageInput::Text {
|
||||
text: format!("{label} describe"),
|
||||
text_elements: vec![cloud::UserMessageTextElement {
|
||||
start: 0,
|
||||
end: label.len(),
|
||||
placeholder: Some(label.into()),
|
||||
}],
|
||||
},
|
||||
],
|
||||
});
|
||||
assert_eq!(
|
||||
actual,
|
||||
Some(protocol::ThreadItem::untimed(
|
||||
protocol::ThreadItemPayload::UserMessage {
|
||||
id: "item-1".into(),
|
||||
client_id: Some("submission-1".into()),
|
||||
content: vec![
|
||||
protocol::UserInput::Image {
|
||||
image: protocol::ImageReference::File {
|
||||
file_id: "file-synthetic".into(),
|
||||
},
|
||||
detail: Some(ImageDetail::High),
|
||||
},
|
||||
protocol::UserInput::Text {
|
||||
text: format!("{label} describe"),
|
||||
text_elements: vec![protocol::TextElement::new(
|
||||
protocol::ByteRange {
|
||||
start: 0,
|
||||
end: label.len(),
|
||||
},
|
||||
Some(label.into()),
|
||||
)],
|
||||
},
|
||||
],
|
||||
},
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_reply_preserves_the_full_text_questions_and_timestamp() -> Result<()> {
|
||||
let item = cloud::ItemSummary::AgentMessage {
|
||||
id: "reply".into(),
|
||||
text: "Choose one".into(),
|
||||
questions: Some(vec![cloud::AgentQuestion {
|
||||
title: "Which?".into(),
|
||||
options: Some(vec!["One".into(), "Two".into()]),
|
||||
}]),
|
||||
};
|
||||
let update = cloud::TranscriptUpdate::ItemCompleted(cloud::ItemLifecycle {
|
||||
turn_id: "turn".into(),
|
||||
at_ms: 45,
|
||||
item,
|
||||
});
|
||||
let Some(protocol::ServerNotification::ItemCompleted(actual)) =
|
||||
transcript("thread".into(), update)?
|
||||
else {
|
||||
panic!("expected a completed message");
|
||||
};
|
||||
assert_eq!(
|
||||
actual,
|
||||
protocol::ItemCompletedNotification::new(
|
||||
"thread".into(),
|
||||
"turn".into(),
|
||||
protocol::ThreadItemPayload::AgentMessage {
|
||||
moderation: None,
|
||||
id: "reply".into(),
|
||||
text: "Choose one".into(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: Some(vec![protocol::AsyncUserInputQuestion {
|
||||
title: "Which?".into(),
|
||||
options: Some(vec!["One".into(), "Two".into()]),
|
||||
}]),
|
||||
},
|
||||
/*started_at_ms*/ None,
|
||||
/*completed_at_ms*/ 45
|
||||
)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,348 +0,0 @@
|
||||
//! Adapts native Cloud requests and the currently open conversation’s reply stream.
|
||||
//! A replacement becomes active only after its native attachment opens successfully.
|
||||
|
||||
mod auth;
|
||||
mod events;
|
||||
mod requests;
|
||||
|
||||
use crate::AppServerClient;
|
||||
use crate::AppServerEvent;
|
||||
use crate::CloudClient;
|
||||
use crate::CloudOperation;
|
||||
use crate::cloud::CloudStreamLosses;
|
||||
use codex_app_server_protocol as protocol;
|
||||
use codex_cloud_client as cloud;
|
||||
use color_eyre::eyre::Result;
|
||||
use color_eyre::eyre::bail;
|
||||
use color_eyre::eyre::eyre;
|
||||
use futures::FutureExt;
|
||||
use futures::StreamExt;
|
||||
use futures::stream::BoxStream;
|
||||
use serde_json::Value;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
pub use auth::connect;
|
||||
|
||||
type ReplyStream = BoxStream<'static, Result<cloud::Event, cloud::Error>>;
|
||||
|
||||
/// Rejected locally before an admission request can be sent.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("{0}")]
|
||||
struct PreflightRejection(&'static str);
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("Cloud stream is not connected. Reopen the conversation before sending.")]
|
||||
struct MissingReplyAttachment;
|
||||
|
||||
struct Attachment {
|
||||
thread_id: String,
|
||||
stream: ReplyStream,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Replies {
|
||||
active: Option<Attachment>,
|
||||
stream_losses: CloudStreamLosses,
|
||||
// Keep the last observed status through EOF until this conversation is unloaded.
|
||||
latest_status: Option<(String, cloud::ThreadStatus)>,
|
||||
}
|
||||
|
||||
impl Replies {
|
||||
async fn forward_next(&mut self, output: &mpsc::UnboundedSender<AppServerEvent>) {
|
||||
let Some(active) = &mut self.active else {
|
||||
return std::future::pending().await;
|
||||
};
|
||||
match active.stream.next().await {
|
||||
Some(Ok(event)) => forward(&active.thread_id, event, output, &mut self.latest_status),
|
||||
Some(Err(_)) | None => {
|
||||
let error = cloud_error(
|
||||
&active.thread_id,
|
||||
"Cloud stream ended. Reopen the conversation to reconnect.",
|
||||
);
|
||||
self.active = None;
|
||||
self.stream_losses.record(&error.thread_id);
|
||||
let _ = output.send(AppServerEvent::ThreadStreamDisconnected(Box::new(error)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn while_listening<T>(
|
||||
&mut self,
|
||||
future: impl Future<Output = T>,
|
||||
output: &mpsc::UnboundedSender<AppServerEvent>,
|
||||
) -> T {
|
||||
tokio::pin!(future);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut future => return result,
|
||||
() = self.forward_next(output) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn replace(
|
||||
&mut self,
|
||||
id: &str,
|
||||
open: impl Future<Output = Result<ReplyStream, cloud::Error>>,
|
||||
output: &mpsc::UnboundedSender<AppServerEvent>,
|
||||
) -> Result<()> {
|
||||
let mut stream = self.while_listening(open, output).await?;
|
||||
// A server can close Attach immediately after returning successful headers.
|
||||
// A healthy idle stream needs no event to prove that it is ready.
|
||||
let first_event = match tokio::task::unconstrained(stream.next()).now_or_never() {
|
||||
Some(None | Some(Err(_))) => bail!(
|
||||
"Cloud conversation activated but its stream did not connect. Reopen it before sending."
|
||||
),
|
||||
Some(Some(Ok(event))) => Some(event),
|
||||
None => None,
|
||||
};
|
||||
self.active = Some(Attachment {
|
||||
thread_id: id.to_owned(),
|
||||
stream,
|
||||
});
|
||||
self.stream_losses.supersede(id);
|
||||
self.latest_status = None;
|
||||
if let Some(event) = first_event {
|
||||
forward(id, event, output, &mut self.latest_status);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn thread_status(&self, id: &str) -> Option<&cloud::ThreadStatus> {
|
||||
self.latest_status
|
||||
.as_ref()
|
||||
.filter(|(thread_id, _)| thread_id == id)
|
||||
.map(|(_, status)| status)
|
||||
}
|
||||
|
||||
fn detach(&mut self, id: &str) {
|
||||
if self.thread_status(id).is_some() {
|
||||
self.latest_status = None;
|
||||
}
|
||||
if self
|
||||
.active
|
||||
.as_ref()
|
||||
.is_some_and(|active| active.thread_id == id)
|
||||
{
|
||||
self.active = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn admit_turn(
|
||||
&mut self,
|
||||
id: &str,
|
||||
output: &mpsc::UnboundedSender<AppServerEvent>,
|
||||
) -> Result<(), MissingReplyAttachment> {
|
||||
// Notice a ready disconnect before sending. A continuous stream of events
|
||||
// must still allow commands to make progress.
|
||||
let _ = tokio::task::unconstrained(self.forward_next(output)).now_or_never();
|
||||
if self
|
||||
.active
|
||||
.as_ref()
|
||||
.is_none_or(|active| active.thread_id != id)
|
||||
{
|
||||
return Err(MissingReplyAttachment);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens an app-server client backed by the authenticated native Cloud client.
|
||||
fn start_worker(client: cloud::Client, account: protocol::GetAccountResponse) -> AppServerClient {
|
||||
let (app_client, commands, output) = CloudClient::channel(/*capacity*/ 32);
|
||||
let mut requests = requests::Requests {
|
||||
client,
|
||||
account,
|
||||
loaded: None,
|
||||
warned_partial_history: None,
|
||||
};
|
||||
let mut replies = Replies {
|
||||
stream_losses: app_client.stream_losses.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
run_worker(commands, &mut requests, &mut replies, &output).await;
|
||||
});
|
||||
AppServerClient::Cloud(app_client)
|
||||
}
|
||||
|
||||
async fn run_worker(
|
||||
mut commands: mpsc::Receiver<crate::CloudCommand>,
|
||||
requests: &mut requests::Requests,
|
||||
replies: &mut Replies,
|
||||
output: &mpsc::UnboundedSender<AppServerEvent>,
|
||||
) {
|
||||
loop {
|
||||
let command = tokio::select! {
|
||||
_ = output.closed() => return,
|
||||
() = replies.forward_next(output) => continue,
|
||||
command = commands.recv() => match command { Some(command) => command, None => return },
|
||||
};
|
||||
let user_message_submission =
|
||||
matches!(&command.operation, CloudOperation::SubmitUserMessage(_));
|
||||
let request = match command.operation {
|
||||
CloudOperation::Shutdown => {
|
||||
let _ = command.response.send(Ok(Ok(Value::Null)));
|
||||
return;
|
||||
}
|
||||
CloudOperation::Request(request) => {
|
||||
Ok((*request, cloud::SubmissionMode::StartIfIdle, None))
|
||||
}
|
||||
CloudOperation::StartProjectThread {
|
||||
request_id,
|
||||
params,
|
||||
project,
|
||||
} => Ok((
|
||||
protocol::ClientRequest::ThreadStart {
|
||||
request_id,
|
||||
params: *params,
|
||||
},
|
||||
cloud::SubmissionMode::StartIfIdle,
|
||||
Some(project),
|
||||
)),
|
||||
CloudOperation::SubmitUserMessage(params) => Ok((
|
||||
protocol::ClientRequest::TurnStart {
|
||||
// Native admission is keyed by the caller's stable message ID.
|
||||
request_id: protocol::RequestId::Integer(0),
|
||||
params: *params,
|
||||
},
|
||||
cloud::SubmissionMode::Steer,
|
||||
None,
|
||||
)),
|
||||
CloudOperation::Notify(_) => {
|
||||
Err(eyre!("Cloud client notifications are not supported yet."))
|
||||
}
|
||||
CloudOperation::Resolve { .. } | CloudOperation::Reject { .. } => Err(eyre!(
|
||||
"Answer this cloud approval in another client; TUI approval replies are not supported yet."
|
||||
)),
|
||||
};
|
||||
let result = match request {
|
||||
Ok((request, mode, project)) => tokio::select! {
|
||||
_ = output.closed() => return,
|
||||
result = handle_request(request, mode, project, requests, replies, output) => result,
|
||||
},
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
let result = result.map_err(|error| protocol::JSONRPCErrorError {
|
||||
code: if error
|
||||
.downcast_ref::<requests::UnsupportedOperation>()
|
||||
.is_some()
|
||||
{
|
||||
-32601
|
||||
} else if error.is::<PreflightRejection>()
|
||||
|| user_message_submission && error.is::<MissingReplyAttachment>()
|
||||
{
|
||||
-32602
|
||||
} else {
|
||||
-32000
|
||||
},
|
||||
message: error.to_string(),
|
||||
data: None,
|
||||
});
|
||||
let _ = command.response.send(Ok(result));
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_request(
|
||||
request: protocol::ClientRequest,
|
||||
mode: cloud::SubmissionMode,
|
||||
project: Option<cloud::ProjectEnvironment>,
|
||||
requests: &mut requests::Requests,
|
||||
replies: &mut Replies,
|
||||
output: &mpsc::UnboundedSender<AppServerEvent>,
|
||||
) -> Result<Value> {
|
||||
if let protocol::ClientRequest::ThreadRead { params, .. } = &request {
|
||||
return requests.read_thread(params, replies.thread_status(¶ms.thread_id));
|
||||
}
|
||||
if let protocol::ClientRequest::ThreadUnsubscribe { params, .. } = &request {
|
||||
let status = if requests
|
||||
.loaded
|
||||
.as_ref()
|
||||
.is_some_and(|loaded| loaded.thread.id == params.thread_id)
|
||||
{
|
||||
replies.detach(¶ms.thread_id);
|
||||
requests.loaded = None;
|
||||
protocol::ThreadUnsubscribeStatus::Unsubscribed
|
||||
} else {
|
||||
protocol::ThreadUnsubscribeStatus::NotSubscribed
|
||||
};
|
||||
return Ok(serde_json::json!({ "status": status }));
|
||||
}
|
||||
if let protocol::ClientRequest::TurnStart { params, .. } = &request {
|
||||
replies.admit_turn(¶ms.thread_id, output)?;
|
||||
}
|
||||
match replies
|
||||
.while_listening(requests.handle(request, mode, project, output), output)
|
||||
.await?
|
||||
{
|
||||
requests::Response::Value(value) => Ok(value),
|
||||
requests::Response::Attach(settings) => {
|
||||
let id = &settings.thread.id;
|
||||
let result = serde_json::to_value(&settings)?;
|
||||
replies
|
||||
.replace(id, requests.client.attach(id), output)
|
||||
.await?;
|
||||
requests.loaded = Some(settings);
|
||||
requests.warned_partial_history = None;
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn forward(
|
||||
id: &str,
|
||||
event: cloud::Event,
|
||||
output: &mpsc::UnboundedSender<AppServerEvent>,
|
||||
latest_status: &mut Option<(String, cloud::ThreadStatus)>,
|
||||
) {
|
||||
if let Some(status) = event.thread_status_for(id) {
|
||||
*latest_status = Some((id.to_owned(), status));
|
||||
return;
|
||||
}
|
||||
let notification = match event {
|
||||
cloud::Event::Transcript(event) => match events::transcript(event.thread_id, event.update) {
|
||||
Ok(Some(notification)) => notification,
|
||||
Ok(None) => return,
|
||||
Err(_) => protocol::ServerNotification::Error(cloud_error(
|
||||
id,
|
||||
"The cloud sent an unsupported transcript event.",
|
||||
)),
|
||||
},
|
||||
cloud::Event::ServerRequest(_) => protocol::ServerNotification::Warning(protocol::WarningNotification {
|
||||
thread_id: Some(id.to_owned()),
|
||||
message: "This cloud turn requested an unsupported interaction. Open it in another client to continue.".into(),
|
||||
}),
|
||||
cloud::Event::Notification(_) => return,
|
||||
};
|
||||
send_notification(output, notification);
|
||||
}
|
||||
|
||||
fn send_notification(
|
||||
output: &mpsc::UnboundedSender<AppServerEvent>,
|
||||
notification: protocol::ServerNotification,
|
||||
) {
|
||||
let _ = output.send(AppServerEvent::ServerNotification(Box::new(notification)));
|
||||
}
|
||||
|
||||
fn cloud_error(id: &str, message: &str) -> protocol::ErrorNotification {
|
||||
protocol::ErrorNotification {
|
||||
thread_id: id.to_owned(),
|
||||
turn_id: String::new(),
|
||||
will_retry: false,
|
||||
error: protocol::TurnError {
|
||||
message: message.to_owned(),
|
||||
additional_details: None,
|
||||
codex_error_info: None,
|
||||
misalignment: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "connection_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "submission_tests.rs"]
|
||||
mod submission_tests;
|
||||
@@ -1,201 +0,0 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn ordinary_multi_backend_resume_queries_cloud_interactive_threads_on_every_page() {
|
||||
// The mixed picker has no shared cwd/provider filter. It sends conventional
|
||||
// interactive source names, even when the connection belongs to Cloud.
|
||||
for (cursor, state_db_only) in [(None, true), (Some("page-2"), false)] {
|
||||
let params = serde_json::from_value(json!({
|
||||
"currentAccountOnly": true,
|
||||
"cursor": cursor,
|
||||
"limit": 25,
|
||||
"sortKey": "updated_at",
|
||||
"modelProviders": [],
|
||||
"sourceKinds": ["cli", "vscode"],
|
||||
"archived": false,
|
||||
"useStateDbOnly": state_db_only,
|
||||
}))
|
||||
.unwrap();
|
||||
let query = thread_list_query(params).unwrap();
|
||||
assert_eq!(query.cursor.as_deref(), cursor);
|
||||
assert_eq!(query.limit, Some(25));
|
||||
assert!(matches!(query.sort_key, cloud::ThreadSortKey::UpdatedAt));
|
||||
assert!(matches!(
|
||||
query.sort_direction,
|
||||
cloud::ThreadSortDirection::Desc
|
||||
));
|
||||
assert!(query.originators.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_filters_do_not_return_unrelated_cloud_rows() {
|
||||
for filter in [
|
||||
json!({"archived": true}),
|
||||
json!({"sourceKinds": ["exec"]}),
|
||||
json!({"attachedToThreadId": "other"}),
|
||||
json!({"modelProviders": ["other"]}),
|
||||
] {
|
||||
let params = serde_json::from_value(filter).unwrap();
|
||||
assert!(thread_list_query(params).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
fn message() -> protocol::TurnStartParams {
|
||||
let text = |text: &str| protocol::UserInput::Text {
|
||||
text: text.to_owned(),
|
||||
text_elements: Vec::new(),
|
||||
};
|
||||
protocol::TurnStartParams {
|
||||
thread_id: "thread-a".into(),
|
||||
client_user_message_id: Some("submission-a".into()),
|
||||
turn_trigger: Some("safety_recourse_follow_up".into()),
|
||||
input: vec![text("one"), text("two")],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_input_uses_stable_id_and_the_existing_cloud_configuration() {
|
||||
let request = cloud_message(message()).unwrap();
|
||||
assert_eq!(request.thread_id, "thread-a");
|
||||
assert_eq!(request.client_user_message_id, "submission-a");
|
||||
assert_eq!(
|
||||
request.input,
|
||||
vec![cloud::UserMessageInput::Text {
|
||||
text: "one\ntwo".into(),
|
||||
text_elements: Vec::new(),
|
||||
}]
|
||||
);
|
||||
assert_eq!(
|
||||
request.turn_trigger.as_deref(),
|
||||
Some("safety_recourse_follow_up")
|
||||
);
|
||||
assert!(matches!(request.mode, cloud::SubmissionMode::StartIfIdle));
|
||||
assert!(!request.shared_access);
|
||||
|
||||
for tier in ["default", "priority"] {
|
||||
assert!(
|
||||
cloud_message(protocol::TurnStartParams {
|
||||
service_tier_for_turn: Some(tier.into()),
|
||||
..message()
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
cloud_message(protocol::TurnStartParams {
|
||||
client_user_message_id: None,
|
||||
..message()
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_submission_keeps_attachment_markers_and_input_order() {
|
||||
let label = "[Image #1]";
|
||||
let request = cloud_message(protocol::TurnStartParams {
|
||||
input: vec![
|
||||
protocol::UserInput::Image {
|
||||
image: protocol::ImageReference::File {
|
||||
file_id: "file-synthetic".into(),
|
||||
},
|
||||
detail: Some(ImageDetail::High),
|
||||
},
|
||||
protocol::UserInput::Text {
|
||||
text: format!("{label} describe"),
|
||||
text_elements: vec![protocol::TextElement::new(
|
||||
protocol::ByteRange {
|
||||
start: 0,
|
||||
end: label.len(),
|
||||
},
|
||||
Some(label.into()),
|
||||
)],
|
||||
},
|
||||
],
|
||||
..message()
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
request.input,
|
||||
vec![
|
||||
cloud::UserMessageInput::Image {
|
||||
image: cloud::ImageReference::FileId("file-synthetic".into()),
|
||||
detail: Some(cloud::ImageDetail::High),
|
||||
},
|
||||
cloud::UserMessageInput::Text {
|
||||
text: format!("{label} describe"),
|
||||
text_elements: vec![cloud::UserMessageTextElement {
|
||||
start: 0,
|
||||
end: label.len(),
|
||||
placeholder: Some(label.into()),
|
||||
}],
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_and_queued_admissions_never_invent_a_running_turn() {
|
||||
for outcome in [
|
||||
cloud::AdmissionOutcome::Duplicate { turn_id: None },
|
||||
cloud::AdmissionOutcome::Duplicate {
|
||||
turn_id: Some("completed-or-running".into()),
|
||||
},
|
||||
cloud::AdmissionOutcome::Queued {
|
||||
submission_id: "queued".into(),
|
||||
},
|
||||
] {
|
||||
assert!(
|
||||
admitted_turn(outcome)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("already accepted")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admission_receipts_preserve_server_turns_and_duplicate_identity() -> Result<()> {
|
||||
let turn = |id: &str, status| cloud::TurnSummary {
|
||||
id: id.into(),
|
||||
status,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
};
|
||||
for (outcome, expected) in [
|
||||
(
|
||||
cloud::AdmissionOutcome::Started(turn("u", cloud::TurnStatus::InProgress)),
|
||||
("started", "u", protocol::TurnStatus::InProgress),
|
||||
),
|
||||
(
|
||||
cloud::AdmissionOutcome::Steered(turn("v", cloud::TurnStatus::Completed)),
|
||||
("steered", "v", protocol::TurnStatus::Completed),
|
||||
),
|
||||
] {
|
||||
let (kind, turn) = match admitted_message(outcome)? {
|
||||
CloudUserMessageReceipt::Started(turn) => ("started", turn),
|
||||
CloudUserMessageReceipt::Steered(turn) => ("steered", turn),
|
||||
CloudUserMessageReceipt::Duplicate { .. } => panic!("expected a turn"),
|
||||
};
|
||||
assert_eq!((kind, turn.id.as_str(), turn.status), expected);
|
||||
}
|
||||
for turn_id in [None, Some("original".into())] {
|
||||
let CloudUserMessageReceipt::Duplicate { turn_id: actual } =
|
||||
admitted_message(cloud::AdmissionOutcome::Duplicate {
|
||||
turn_id: turn_id.clone(),
|
||||
})?
|
||||
else {
|
||||
panic!("a duplicate must not become a running turn");
|
||||
};
|
||||
assert_eq!(actual, turn_id);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,410 +0,0 @@
|
||||
//! Maps conversation requests onto native Cloud operations.
|
||||
|
||||
use super::PreflightRejection;
|
||||
use super::events;
|
||||
use super::send_notification;
|
||||
use crate::CloudUserMessageReceipt;
|
||||
use codex_app_server_protocol as protocol;
|
||||
use codex_cloud_client as cloud;
|
||||
use codex_protocol::models::ImageDetail;
|
||||
use color_eyre::eyre::Result;
|
||||
use color_eyre::eyre::bail;
|
||||
use color_eyre::eyre::eyre;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("{0} is not supported by the cloud backend yet.")]
|
||||
pub(super) struct UnsupportedOperation(pub(super) String);
|
||||
|
||||
pub(super) struct Requests {
|
||||
pub(super) client: cloud::Client,
|
||||
pub(super) account: protocol::GetAccountResponse,
|
||||
pub(super) loaded: Option<Box<protocol::ThreadResumeResponse>>,
|
||||
pub(super) warned_partial_history: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) enum Response {
|
||||
Value(Value),
|
||||
Attach(Box<protocol::ThreadResumeResponse>),
|
||||
}
|
||||
|
||||
impl Requests {
|
||||
pub(super) fn read_thread(
|
||||
&self,
|
||||
params: &protocol::ThreadReadParams,
|
||||
status: Option<&cloud::ThreadStatus>,
|
||||
) -> Result<Value> {
|
||||
if params.include_turns {
|
||||
bail!("Use paginated history for cloud conversations.");
|
||||
}
|
||||
let loaded = self
|
||||
.loaded
|
||||
.as_deref()
|
||||
.filter(|loaded| loaded.thread.id == params.thread_id)
|
||||
.ok_or_else(|| eyre!("Open this cloud conversation before reading its transcript."))?;
|
||||
let mut thread = serde_json::to_value(&loaded.thread)?;
|
||||
if let Some(status) = status {
|
||||
thread["status"] = serde_json::to_value(status)?;
|
||||
}
|
||||
Ok(json!({"thread": thread, "readState": null}))
|
||||
}
|
||||
|
||||
pub(super) async fn handle(
|
||||
&mut self,
|
||||
request: protocol::ClientRequest,
|
||||
mode: cloud::SubmissionMode,
|
||||
project: Option<cloud::ProjectEnvironment>,
|
||||
output: &mpsc::UnboundedSender<crate::AppServerEvent>,
|
||||
) -> Result<Response> {
|
||||
use protocol::ClientRequest as Request;
|
||||
|
||||
let value = match request {
|
||||
Request::GetAccount { .. } => serde_json::to_value(&self.account)?,
|
||||
Request::ThreadList { params, .. } => {
|
||||
let query = thread_list_query(params)?;
|
||||
let mut page = self.client.list_threads(&query).await?;
|
||||
for thread in &mut page.data {
|
||||
use_paginated_history(thread);
|
||||
}
|
||||
serde_json::to_value(page)?
|
||||
}
|
||||
Request::ThreadStart { mut params, .. } => {
|
||||
let model = params.model.take();
|
||||
let provider = params.model_provider.take();
|
||||
if params.ephemeral == Some(false) {
|
||||
params.ephemeral = None;
|
||||
}
|
||||
if params != protocol::ThreadStartParams::default() {
|
||||
bail!(
|
||||
"Cloud conversations start with server defaults. Custom settings are not supported yet."
|
||||
);
|
||||
}
|
||||
let settings = self.client.prewarm_thread(model, provider, project).await?;
|
||||
return attach_response(settings);
|
||||
}
|
||||
Request::ThreadResume { params, .. } => {
|
||||
let supported = protocol::ThreadResumeParams {
|
||||
thread_id: params.thread_id.clone(),
|
||||
exclude_turns: true,
|
||||
..Default::default()
|
||||
};
|
||||
if params != supported {
|
||||
bail!(
|
||||
"Cloud conversations resume by ID with saved settings. Set excludeTurns to true and load history separately."
|
||||
);
|
||||
}
|
||||
let settings = self.client.activate(¶ms.thread_id).await?;
|
||||
return attach_response(settings);
|
||||
}
|
||||
Request::ThreadLoadedList { .. } => {
|
||||
let ids = self
|
||||
.loaded
|
||||
.iter()
|
||||
.map(|loaded| &loaded.thread.id)
|
||||
.collect::<Vec<_>>();
|
||||
json!({"data": ids, "nextCursor": null})
|
||||
}
|
||||
Request::ThreadTurnsList { params, .. } => {
|
||||
if params.items_view != Some(protocol::TurnItemsView::NotLoaded) {
|
||||
bail!("Read cloud turn items separately with thread/items/list.");
|
||||
}
|
||||
let page = self
|
||||
.client
|
||||
.list_turns(&cloud::ListTurnsRequest {
|
||||
thread_id: params.thread_id,
|
||||
page: cloud::HistoryQuery {
|
||||
cursor: params.cursor,
|
||||
limit: params.limit,
|
||||
order: history_order(
|
||||
params
|
||||
.sort_direction
|
||||
.unwrap_or(protocol::SortDirection::Desc),
|
||||
),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
serde_json::to_value(protocol::ThreadTurnsListResponse {
|
||||
data: page
|
||||
.data
|
||||
.into_iter()
|
||||
.map(|entry| events::turn(entry.summary))
|
||||
.collect::<Result<_>>()?,
|
||||
next_cursor: page.next_cursor,
|
||||
backwards_cursor: page.backwards_cursor,
|
||||
})?
|
||||
}
|
||||
Request::ThreadItemsList { params, .. } => {
|
||||
let cursor = match params.cursor {
|
||||
Some(protocol::ThreadItemsListCursor::Opaque(cursor)) => Some(cursor),
|
||||
None => None,
|
||||
Some(protocol::ThreadItemsListCursor::Anchor(_)) => {
|
||||
bail!("Cloud item anchors are not supported yet.")
|
||||
}
|
||||
};
|
||||
let page = self
|
||||
.client
|
||||
.list_items(&cloud::ListItemsRequest {
|
||||
thread_id: params.thread_id.clone(),
|
||||
turn_id: params.turn_id,
|
||||
page: cloud::HistoryQuery {
|
||||
cursor,
|
||||
limit: params.limit,
|
||||
order: history_order(
|
||||
params
|
||||
.sort_direction
|
||||
.unwrap_or(protocol::SortDirection::Asc),
|
||||
),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
let size = page.data.len();
|
||||
let data = page
|
||||
.data
|
||||
.into_iter()
|
||||
.filter_map(|entry| {
|
||||
Some(protocol::ThreadItemEntry {
|
||||
turn_id: entry.turn_id,
|
||||
item: events::item_summary(entry.summary?)?,
|
||||
output_deferred: false,
|
||||
started_at_ms: entry.started_at_ms,
|
||||
completed_at_ms: entry.completed_at_ms,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if data.len() != size
|
||||
&& self.warned_partial_history.as_ref() != Some(¶ms.thread_id)
|
||||
{
|
||||
self.warned_partial_history = Some(params.thread_id.clone());
|
||||
let warning = protocol::WarningNotification {
|
||||
thread_id: Some(params.thread_id),
|
||||
message: "Some Cloud history items cannot be displayed in this preview."
|
||||
.to_owned(),
|
||||
};
|
||||
send_notification(output, protocol::ServerNotification::Warning(warning));
|
||||
}
|
||||
serde_json::to_value(protocol::ThreadItemsListResponse {
|
||||
data,
|
||||
next_cursor: page.next_cursor,
|
||||
backwards_cursor: page.backwards_cursor,
|
||||
})?
|
||||
}
|
||||
Request::TurnStart { params, .. } => {
|
||||
let mut message = cloud_message(params)?;
|
||||
message.mode = mode;
|
||||
let admission = match self.client.add_user_message(&message).await {
|
||||
Err(cloud::MutationError::InvalidRequest) => {
|
||||
return Err(PreflightRejection(
|
||||
"The Cloud message is empty, invalid, or too large.",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
result => result?,
|
||||
};
|
||||
if matches!(mode, cloud::SubmissionMode::Steer) {
|
||||
serde_json::to_value(admitted_message(admission.outcome)?)?
|
||||
} else {
|
||||
let turn = admitted_turn(admission.outcome)?;
|
||||
serde_json::to_value(protocol::TurnStartResponse { turn })?
|
||||
}
|
||||
}
|
||||
Request::TurnInterrupt { params, .. } => {
|
||||
self.client
|
||||
.interrupt_turn(&cloud::InterruptTurnRequest {
|
||||
thread_id: params.thread_id,
|
||||
turn_id: params.turn_id,
|
||||
shared_access: false,
|
||||
})
|
||||
.await?;
|
||||
serde_json::to_value(protocol::TurnInterruptResponse {})?
|
||||
}
|
||||
other => return Err(UnsupportedOperation(other.method_name().to_owned()).into()),
|
||||
};
|
||||
Ok(Response::Value(value))
|
||||
}
|
||||
}
|
||||
|
||||
fn attach_response(mut settings: cloud::ThreadActivation) -> Result<Response> {
|
||||
use_paginated_history(&mut settings.thread);
|
||||
let resolved = serde_json::from_value(serde_json::to_value(settings)?)
|
||||
.map_err(|_| eyre!("The cloud returned unsupported conversation settings."))?;
|
||||
Ok(Response::Attach(resolved))
|
||||
}
|
||||
|
||||
// Cloud serves history in pages even when an older thread used the legacy rollout format.
|
||||
fn use_paginated_history(thread: &mut cloud::ThreadSnapshot) {
|
||||
thread.history_mode = cloud::ThreadHistoryMode::Paginated;
|
||||
}
|
||||
|
||||
fn thread_list_query(params: protocol::ThreadListParams) -> Result<cloud::ThreadListQuery> {
|
||||
use protocol::ThreadSourceKind::Cli;
|
||||
use protocol::ThreadSourceKind::VsCode;
|
||||
// The resume picker's ordinary interactive list maps to Cloud's own interactive default.
|
||||
// Its explicit CLI/VS Code defaults are conventional source names.
|
||||
let sources = params.source_kinds.as_deref().unwrap_or_default();
|
||||
if !matches!(sources, [] | [Cli, VsCode] | [VsCode, Cli])
|
||||
|| params.archived == Some(true)
|
||||
|| params.cwd.is_some()
|
||||
|| params.search_term.is_some()
|
||||
|| params.section_id.is_some()
|
||||
|| params.project_id.is_some()
|
||||
|| params.parent_thread_id.is_some()
|
||||
|| params.ancestor_thread_id.is_some()
|
||||
|| params.attached_to_thread_id.is_some()
|
||||
|| params
|
||||
.model_providers
|
||||
.as_ref()
|
||||
.is_some_and(|values| !values.is_empty())
|
||||
|| params
|
||||
.excluded_thread_ids
|
||||
.as_ref()
|
||||
.is_some_and(|values| !values.is_empty())
|
||||
{
|
||||
bail!("These cloud conversation filters are not supported yet.");
|
||||
}
|
||||
Ok(cloud::ThreadListQuery {
|
||||
cursor: params.cursor,
|
||||
limit: params.limit,
|
||||
originators: params.originators.unwrap_or_default(),
|
||||
sort_key: match params.sort_key {
|
||||
Some(protocol::ThreadSortKey::CreatedAt) | None => cloud::ThreadSortKey::CreatedAt,
|
||||
Some(protocol::ThreadSortKey::UpdatedAt) => cloud::ThreadSortKey::UpdatedAt,
|
||||
Some(protocol::ThreadSortKey::RecencyAt) => cloud::ThreadSortKey::RecencyAt,
|
||||
Some(protocol::ThreadSortKey::SectionPosition) => {
|
||||
bail!("Cloud section ordering is not supported yet.")
|
||||
}
|
||||
},
|
||||
sort_direction: match params.sort_direction {
|
||||
Some(protocol::SortDirection::Asc) => cloud::ThreadSortDirection::Asc,
|
||||
Some(protocol::SortDirection::Desc) | None => cloud::ThreadSortDirection::Desc,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn history_order(direction: protocol::SortDirection) -> cloud::HistoryOrder {
|
||||
match direction {
|
||||
protocol::SortDirection::Asc => cloud::HistoryOrder::Ascending,
|
||||
protocol::SortDirection::Desc => cloud::HistoryOrder::Descending,
|
||||
}
|
||||
}
|
||||
|
||||
fn cloud_message(
|
||||
mut params: protocol::TurnStartParams,
|
||||
) -> Result<cloud::AddUserMessageRequest, PreflightRejection> {
|
||||
let thread_id = std::mem::take(&mut params.thread_id);
|
||||
let client_user_message_id = params
|
||||
.client_user_message_id
|
||||
.take()
|
||||
.ok_or(PreflightRejection(
|
||||
"A cloud message needs a stable submission ID.",
|
||||
))?;
|
||||
let input = std::mem::take(&mut params.input);
|
||||
let turn_trigger = params.turn_trigger.take();
|
||||
if params != protocol::TurnStartParams::default() {
|
||||
return Err(PreflightRejection(
|
||||
"Changing cloud settings or sending structured input is not supported yet.",
|
||||
));
|
||||
}
|
||||
let mut content = Vec::with_capacity(input.len());
|
||||
for item in input {
|
||||
let item = match item {
|
||||
protocol::UserInput::Text {
|
||||
text,
|
||||
text_elements,
|
||||
} => {
|
||||
// Keep the existing line separation for consecutive plain text parts.
|
||||
if text_elements.is_empty()
|
||||
&& let Some(cloud::UserMessageInput::Text {
|
||||
text: previous,
|
||||
text_elements: previous_elements,
|
||||
}) = content.last_mut()
|
||||
&& previous_elements.is_empty()
|
||||
{
|
||||
previous.push('\n');
|
||||
previous.push_str(&text);
|
||||
continue;
|
||||
}
|
||||
cloud::UserMessageInput::Text {
|
||||
text,
|
||||
text_elements: text_elements
|
||||
.into_iter()
|
||||
.map(|element| cloud::UserMessageTextElement {
|
||||
placeholder: element.placeholder().map(str::to_owned),
|
||||
start: element.byte_range.start,
|
||||
end: element.byte_range.end,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
protocol::UserInput::Image { image, detail } => cloud::UserMessageInput::Image {
|
||||
image: match image {
|
||||
protocol::ImageReference::Inline { url } => cloud::ImageReference::Url(url),
|
||||
protocol::ImageReference::File { file_id } => {
|
||||
cloud::ImageReference::FileId(file_id)
|
||||
}
|
||||
},
|
||||
detail: detail.map(|detail| match detail {
|
||||
ImageDetail::Auto => cloud::ImageDetail::Auto,
|
||||
ImageDetail::Low => cloud::ImageDetail::Low,
|
||||
ImageDetail::High => cloud::ImageDetail::High,
|
||||
ImageDetail::Original => cloud::ImageDetail::Original,
|
||||
}),
|
||||
},
|
||||
protocol::UserInput::LocalImage { .. } => {
|
||||
return Err(PreflightRejection(
|
||||
"Prepare local images before sending them to Cloud.",
|
||||
));
|
||||
}
|
||||
protocol::UserInput::Audio { .. }
|
||||
| protocol::UserInput::LocalAudio { .. }
|
||||
| protocol::UserInput::Skill { .. }
|
||||
| protocol::UserInput::Mention { .. } => {
|
||||
return Err(PreflightRejection(
|
||||
"Cloud conversations currently accept text and images.",
|
||||
));
|
||||
}
|
||||
};
|
||||
content.push(item);
|
||||
}
|
||||
Ok(cloud::AddUserMessageRequest {
|
||||
thread_id,
|
||||
client_user_message_id,
|
||||
input: content,
|
||||
turn_trigger,
|
||||
mode: cloud::SubmissionMode::StartIfIdle,
|
||||
shared_access: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn admitted_message(outcome: cloud::AdmissionOutcome) -> Result<CloudUserMessageReceipt> {
|
||||
Ok(match outcome {
|
||||
cloud::AdmissionOutcome::Started(turn) => {
|
||||
CloudUserMessageReceipt::Started(events::turn(turn)?)
|
||||
}
|
||||
cloud::AdmissionOutcome::Steered(turn) => {
|
||||
CloudUserMessageReceipt::Steered(events::turn(turn)?)
|
||||
}
|
||||
cloud::AdmissionOutcome::Duplicate { turn_id } => {
|
||||
CloudUserMessageReceipt::Duplicate { turn_id }
|
||||
}
|
||||
cloud::AdmissionOutcome::Queued { .. } => bail!(
|
||||
"Cloud already accepted this message without returning a turn. Reopen the conversation to see its status before sending again."
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
fn admitted_turn(outcome: cloud::AdmissionOutcome) -> Result<protocol::Turn> {
|
||||
match admitted_message(outcome)? {
|
||||
CloudUserMessageReceipt::Started(turn) | CloudUserMessageReceipt::Steered(turn) => Ok(turn),
|
||||
CloudUserMessageReceipt::Duplicate { .. } => bail!(
|
||||
"Cloud already accepted this message without returning a turn. Reopen the conversation to see its status before sending again."
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "request_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,206 +0,0 @@
|
||||
#![cfg(test)]
|
||||
//! Exercises native admission and local validation through the command worker.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
fn submission(message_id: &str) -> protocol::TurnStartParams {
|
||||
protocol::TurnStartParams {
|
||||
thread_id: "t".into(),
|
||||
client_user_message_id: Some(message_id.into()),
|
||||
input: vec![protocol::UserInput::Text {
|
||||
text: "hello".into(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_submission_uses_one_admission_and_keeps_preflight_guards() -> Result<()> {
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir()?;
|
||||
let config = crate::legacy_core::config::ConfigBuilder::default()
|
||||
.codex_home(home.path().to_owned())
|
||||
.fallback_cwd(Some(home.path().to_owned()))
|
||||
.without_project_context()
|
||||
.build()
|
||||
.await?;
|
||||
let native = cloud::Client::new(
|
||||
&config.http_client_factory(),
|
||||
&server.uri(),
|
||||
cloud::Credentials::new("synthetic-bearer", "synthetic-account")?,
|
||||
)?;
|
||||
let account = protocol::GetAccountResponse {
|
||||
user_id: None,
|
||||
account: None,
|
||||
requires_openai_auth: true,
|
||||
workspace_routing: None,
|
||||
};
|
||||
let (client, commands, output) = crate::CloudClient::channel(/*capacity*/ 4);
|
||||
let client = crate::AppServerClient::Cloud(client);
|
||||
let handle = client.request_handle();
|
||||
let crate::AppServerRequestHandle::Cloud(cloud_handle) = &handle else {
|
||||
panic!("expected a Cloud handle");
|
||||
};
|
||||
let (reply_sender, stream) = futures::channel::mpsc::unbounded();
|
||||
let mut replies = Replies {
|
||||
active: Some(Attachment {
|
||||
thread_id: "t".into(),
|
||||
stream: stream.boxed(),
|
||||
}),
|
||||
..Replies::default()
|
||||
};
|
||||
let worker = tokio::spawn(async move {
|
||||
let mut requests = crate::cloud_backend::requests::Requests {
|
||||
client: native,
|
||||
account,
|
||||
loaded: None,
|
||||
warned_partial_history: None,
|
||||
};
|
||||
crate::cloud_backend::run_worker(commands, &mut requests, &mut replies, &output).await
|
||||
});
|
||||
let rpc = "/oaiproto.codex_app_server_backend.ThreadService/AddUserMessage";
|
||||
Mock::given(method("POST"))
|
||||
.and(path(rpc))
|
||||
.and(header("authorization", "Bearer synthetic-bearer"))
|
||||
.respond_with(ResponseTemplate::new(503))
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let url = "data:image/png;base64,iVBORw0KGgo=";
|
||||
let image = protocol::UserInput::Image {
|
||||
image: protocol::ImageReference::Inline { url: url.into() },
|
||||
detail: None,
|
||||
};
|
||||
let Err(crate::TypedRequestError::Server { source, .. }) = cloud_handle
|
||||
.submit_user_message(protocol::TurnStartParams {
|
||||
input: vec![image.clone()],
|
||||
..submission("x")
|
||||
})
|
||||
.await
|
||||
else {
|
||||
panic!("a lost receipt must remain uncertain");
|
||||
};
|
||||
assert_eq!(source.code, -32000);
|
||||
assert!(source.message.contains("mutation outcome unknown"));
|
||||
// Existing typed turn/start callers keep StartIfIdle and the same native error.
|
||||
let Err(crate::TypedRequestError::Server { source, .. }) = handle
|
||||
.request_typed::<protocol::TurnStartResponse>(protocol::ClientRequest::TurnStart {
|
||||
request_id: protocol::RequestId::Integer(1),
|
||||
params: protocol::TurnStartParams {
|
||||
input: vec![
|
||||
image,
|
||||
protocol::UserInput::Text {
|
||||
text: "describe the image".into(),
|
||||
text_elements: Vec::new(),
|
||||
},
|
||||
],
|
||||
..submission("m")
|
||||
},
|
||||
})
|
||||
.await
|
||||
else {
|
||||
panic!("ordinary turn/start must retain its server error");
|
||||
};
|
||||
assert_eq!(source.code, -32000);
|
||||
assert!(source.message.contains("mutation outcome unknown"));
|
||||
|
||||
for params in [
|
||||
protocol::TurnStartParams {
|
||||
model: Some("other".into()),
|
||||
..submission("invalid")
|
||||
},
|
||||
protocol::TurnStartParams {
|
||||
client_user_message_id: None,
|
||||
..submission("missing")
|
||||
},
|
||||
protocol::TurnStartParams {
|
||||
input: Vec::new(),
|
||||
..submission("empty")
|
||||
},
|
||||
protocol::TurnStartParams {
|
||||
thread_id: "other".into(),
|
||||
..submission("foreign")
|
||||
},
|
||||
] {
|
||||
let Err(crate::TypedRequestError::Server { source, .. }) =
|
||||
cloud_handle.submit_user_message(params).await
|
||||
else {
|
||||
panic!("invalid input must fail before admission");
|
||||
};
|
||||
assert_eq!(source.code, -32602);
|
||||
}
|
||||
let queued = handle
|
||||
.request(protocol::ClientRequest::TurnStart {
|
||||
request_id: protocol::RequestId::Integer(3),
|
||||
params: protocol::TurnStartParams {
|
||||
input: vec![protocol::UserInput::LocalImage {
|
||||
path: "queued.png".into(),
|
||||
detail: None,
|
||||
}],
|
||||
..submission("queued-image")
|
||||
},
|
||||
})
|
||||
.await?
|
||||
.expect_err("a queued attachment must fail before admission");
|
||||
assert_eq!(queued.code, -32602);
|
||||
assert_eq!(
|
||||
queued.message,
|
||||
"Prepare local images before sending them to Cloud."
|
||||
);
|
||||
let invalid_image = handle
|
||||
.request(protocol::ClientRequest::TurnStart {
|
||||
request_id: protocol::RequestId::Integer(4),
|
||||
params: protocol::TurnStartParams {
|
||||
input: vec![protocol::UserInput::Image {
|
||||
image: protocol::ImageReference::Inline { url: String::new() },
|
||||
detail: None,
|
||||
}],
|
||||
..submission("invalid-image")
|
||||
},
|
||||
})
|
||||
.await?
|
||||
.expect_err("an invalid image must fail before admission");
|
||||
assert_eq!(invalid_image.code, -32602);
|
||||
|
||||
drop(reply_sender);
|
||||
let Err(crate::TypedRequestError::Server { source, .. }) =
|
||||
cloud_handle.submit_user_message(submission("closed")).await
|
||||
else {
|
||||
panic!("a disconnected stream must reject input");
|
||||
};
|
||||
assert_eq!(source.code, -32602);
|
||||
let ordinary = handle
|
||||
.request(protocol::ClientRequest::TurnStart {
|
||||
request_id: protocol::RequestId::Integer(2),
|
||||
params: submission("closed"),
|
||||
})
|
||||
.await?
|
||||
.expect_err("ordinary turn/start keeps its existing disconnected error");
|
||||
assert_eq!(ordinary.code, -32000);
|
||||
|
||||
client.shutdown().await?;
|
||||
worker.await?;
|
||||
let calls = server.received_requests().await.unwrap();
|
||||
assert!(calls.iter().all(|request| {
|
||||
request
|
||||
.body
|
||||
.windows(url.len())
|
||||
.any(|bytes| bytes == url.as_bytes())
|
||||
}));
|
||||
assert_eq!(
|
||||
calls
|
||||
.iter()
|
||||
.map(|request| (request.body[7], *request.body.last().unwrap()))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![(b'x', 1), (b'm', 3)]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -21,8 +21,7 @@
|
||||
//! unread notifications cannot prevent request responses from being delivered.
|
||||
|
||||
mod cloud;
|
||||
pub mod cloud_backend;
|
||||
pub use codex_cloud_client::ProjectEnvironment;
|
||||
pub use cloud::ProjectEnvironment;
|
||||
mod path;
|
||||
mod remote;
|
||||
mod remote_websocket;
|
||||
@@ -725,7 +724,7 @@ impl AppServerRequestHandle {
|
||||
&self,
|
||||
request_id: RequestId,
|
||||
params: codex_app_server_protocol::ThreadStartParams,
|
||||
project: codex_cloud_client::ProjectEnvironment,
|
||||
project: ProjectEnvironment,
|
||||
) -> Result<codex_app_server_protocol::ThreadStartResponse, TypedRequestError> {
|
||||
let response = match self {
|
||||
Self::Cloud(handle) => {
|
||||
|
||||
@@ -33,11 +33,9 @@ initialize the connection, the TUI starts an embedded server instead. Explicit
|
||||
codex app-server daemon start
|
||||
codex app-server daemon restart
|
||||
codex app-server daemon update
|
||||
codex app-server daemon enable-remote-control
|
||||
codex app-server daemon disable-remote-control
|
||||
codex app-server daemon stop
|
||||
codex app-server daemon version
|
||||
codex app-server daemon bootstrap --remote-control
|
||||
codex app-server daemon bootstrap
|
||||
```
|
||||
|
||||
On success, every command writes exactly one JSON object to stdout. Consumers
|
||||
@@ -81,7 +79,7 @@ For a new Linux or macOS machine:
|
||||
|
||||
```sh
|
||||
curl -fsSL https://chatgpt.com/codex/install.sh | sh
|
||||
$HOME/.codex/packages/standalone/current/codex app-server daemon bootstrap --remote-control
|
||||
$HOME/.codex/packages/standalone/current/codex app-server daemon bootstrap
|
||||
```
|
||||
|
||||
On Windows, use a non-elevated PowerShell terminal whose host allows breakaway:
|
||||
@@ -89,7 +87,7 @@ On Windows, use a non-elevated PowerShell terminal whose host allows breakaway:
|
||||
```powershell
|
||||
irm https://chatgpt.com/codex/install.ps1 | iex
|
||||
$codexHome = if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $HOME '.codex' }
|
||||
& "$codexHome\packages\standalone\current\bin\codex.exe" app-server daemon bootstrap --remote-control
|
||||
& "$codexHome\packages\standalone\current\bin\codex.exe" app-server daemon bootstrap
|
||||
```
|
||||
|
||||
`bootstrap` can use any complete CLI package. If no daemon package is installed,
|
||||
@@ -165,25 +163,16 @@ JSON-RPC initialize handshake on the Unix control socket.
|
||||
|
||||
`restart` stops any managed daemon and starts it again.
|
||||
|
||||
`enable-remote-control` and `disable-remote-control` persist the launch setting
|
||||
for future starts. If a managed app-server is already running, they restart it
|
||||
so the new setting takes effect immediately.
|
||||
|
||||
Top-level `codex remote-control start` enables and persists remote control for
|
||||
the managed daemon, overriding a saved disabled value. It starts or bootstraps
|
||||
the daemon as needed. Plain `codex remote-control` uses the managed daemon when
|
||||
eligible; `codex remote-control --no-daemon` runs a separate foreground server.
|
||||
`codex remote-control stop` stops the managed daemon without clearing its saved
|
||||
remote-control preference.
|
||||
`daemon start` and `daemon restart` use that saved preference. `daemon bootstrap`
|
||||
sets it according to `--remote-control` (disabled when omitted).
|
||||
Remote control (the ChatGPT relay) was removed in aKode: the managed app-server
|
||||
is always launched without it, and the `codex remote-control` command and the
|
||||
`enable-remote-control` / `disable-remote-control` daemon subcommands no longer
|
||||
exist.
|
||||
|
||||
`stop` sends a graceful termination request first, then force-terminates the
|
||||
process after the configured grace window if it is still alive.
|
||||
|
||||
All mutating lifecycle commands are serialized per `CODEX_HOME`, so a concurrent
|
||||
`start`, `restart`, `enable-remote-control`, `disable-remote-control`, `stop`,
|
||||
or `bootstrap` does not race another in-flight lifecycle operation.
|
||||
`start`, `restart`, `stop`, or `bootstrap` does not race another in-flight lifecycle operation.
|
||||
|
||||
## State
|
||||
|
||||
|
||||
@@ -392,17 +392,10 @@ impl PidBackend {
|
||||
#[cfg(any(unix, windows))]
|
||||
fn command_args(&self) -> Vec<Cow<'_, str>> {
|
||||
let mut args = match &self.command_kind {
|
||||
PidCommandKind::AppServer {
|
||||
remote_control_enabled: true,
|
||||
} => vec![
|
||||
"app-server".into(),
|
||||
"--remote-control".into(),
|
||||
"--listen".into(),
|
||||
"unix://".into(),
|
||||
],
|
||||
PidCommandKind::AppServer {
|
||||
remote_control_enabled: false,
|
||||
} => vec!["app-server".into(), "--listen".into(), "unix://".into()],
|
||||
// aKode: remote control was removed, so the app server never gets `--remote-control`.
|
||||
PidCommandKind::AppServer { .. } => {
|
||||
vec!["app-server".into(), "--listen".into(), "unix://".into()]
|
||||
}
|
||||
PidCommandKind::UpdateLoop { restore_release } => {
|
||||
let mut args = vec![
|
||||
"app-server".into(),
|
||||
|
||||
@@ -712,7 +712,7 @@ fn update_loop_uses_hidden_app_server_subcommand() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_server_remote_control_uses_runtime_flag() {
|
||||
fn app_server_remote_control_setting_never_passes_runtime_flag() {
|
||||
let backend = PidBackend::new(
|
||||
"codex".into(),
|
||||
"app-server.pid".into(),
|
||||
@@ -723,7 +723,6 @@ fn app_server_remote_control_uses_runtime_flag() {
|
||||
backend.command_args(),
|
||||
vec![
|
||||
"app-server",
|
||||
"--remote-control",
|
||||
"--listen",
|
||||
"unix://",
|
||||
"--analytics-default-enabled"
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
//! Binds a transport connection to the authentication owner that established it.
|
||||
//! Owner revisions invalidate queued work even before transport closure is delivered.
|
||||
//! aKode: only remote control created these bindings; it was removed, so none are created today.
|
||||
|
||||
use codex_login::AuthChangeState;
|
||||
use codex_login::AuthManager;
|
||||
use std::io;
|
||||
use tokio::sync::watch;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -13,39 +12,8 @@ pub struct ConnectionAuth {
|
||||
}
|
||||
|
||||
impl ConnectionAuth {
|
||||
pub(crate) fn capture(auth_manager: &AuthManager) -> Self {
|
||||
let changes = auth_manager.auth_change_state_receiver();
|
||||
let owner_generation = changes.borrow().owner_generation;
|
||||
Self::new(changes, owner_generation)
|
||||
}
|
||||
|
||||
pub(crate) fn ensure_current(&self) -> io::Result<()> {
|
||||
if self.is_current() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"remote control authentication changed",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new(changes: watch::Receiver<AuthChangeState>, owner_generation: u64) -> Self {
|
||||
Self {
|
||||
changes,
|
||||
owner_generation,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_current(&self) -> bool {
|
||||
self.changes.borrow().owner_generation == self.owner_generation
|
||||
&& self.changes.has_changed().is_ok()
|
||||
}
|
||||
|
||||
pub(crate) async fn invalidated(&self) {
|
||||
let mut changes = self.changes.clone();
|
||||
let _ = changes
|
||||
.wait_for(|state| state.owner_generation != self.owner_generation)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
238
codex-rs/app-server-transport/src/transport/remote_control.rs
Normal file
238
codex-rs/app-server-transport/src/transport/remote_control.rs
Normal file
@@ -0,0 +1,238 @@
|
||||
//! aKode: remote control (the ChatGPT relay on chatgpt.com) was removed.
|
||||
//!
|
||||
//! This module keeps the process-facing API so the app server compiles unchanged, but it never
|
||||
//! opens a network connection: remote control always reports `Disabled`, enabling it fails, and
|
||||
//! pairing or client-management requests return an "unsupported" error.
|
||||
|
||||
use super::TransportEvent;
|
||||
use codex_app_server_protocol::RemoteControlClientsListParams;
|
||||
use codex_app_server_protocol::RemoteControlClientsListResponse;
|
||||
use codex_app_server_protocol::RemoteControlClientsRevokeParams;
|
||||
use codex_app_server_protocol::RemoteControlClientsRevokeResponse;
|
||||
use codex_app_server_protocol::RemoteControlConnectionStatus;
|
||||
use codex_app_server_protocol::RemoteControlPairingStartParams;
|
||||
use codex_app_server_protocol::RemoteControlPairingStartResponse;
|
||||
use codex_app_server_protocol::RemoteControlPairingStatusParams;
|
||||
use codex_app_server_protocol::RemoteControlPairingStatusResponse;
|
||||
use codex_app_server_protocol::RemoteControlStatusChangedNotification;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_login::AuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeAuthSlot;
|
||||
use codex_state::StateRuntime;
|
||||
use gethostname::gethostname;
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
const REMOTE_CONTROL_REMOVED_MESSAGE: &str = "remote control is not available in this build";
|
||||
|
||||
pub struct RemoteControlStartConfig {
|
||||
pub runtime_auth: Option<(RuntimeAuthSlot, RuntimeAuthMode)>,
|
||||
pub remote_control_url: String,
|
||||
pub installation_id: String,
|
||||
pub policy: RemoteControlPolicy,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RemoteControlPolicy {
|
||||
#[default]
|
||||
Allowed,
|
||||
DisabledByRequirements,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RemoteControlStartupMode {
|
||||
ResolvePersisted,
|
||||
DisabledEphemeral,
|
||||
EnabledEphemeral,
|
||||
}
|
||||
|
||||
/// Internal marker used by the daemon to disable remote control without requiring a new CLI flag.
|
||||
pub const REMOTE_CONTROL_DISABLED_ENV_VAR: &str =
|
||||
"CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED";
|
||||
|
||||
/// Reads and removes the daemon's internal disabled-start marker before worker threads start.
|
||||
pub fn take_remote_control_disabled_env() -> bool {
|
||||
let disabled =
|
||||
std::env::var_os(REMOTE_CONTROL_DISABLED_ENV_VAR).is_some_and(|value| value == "1");
|
||||
// SAFETY: app-server calls this synchronously at process startup, before spawning threads.
|
||||
unsafe { std::env::remove_var(REMOTE_CONTROL_DISABLED_ENV_VAR) };
|
||||
disabled
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RemoteControlUnavailable;
|
||||
|
||||
impl fmt::Display for RemoteControlUnavailable {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(REMOTE_CONTROL_REMOVED_MESSAGE)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RemoteControlUnavailable {}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RemoteControlDisabledByRequirements;
|
||||
|
||||
impl fmt::Display for RemoteControlDisabledByRequirements {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "remote control is disabled by managed requirements")
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RemoteControlDisabledByRequirements {}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RemoteControlEnableError {
|
||||
Unavailable(RemoteControlUnavailable),
|
||||
DisabledByRequirements(RemoteControlDisabledByRequirements),
|
||||
AuthenticationChanged,
|
||||
}
|
||||
|
||||
impl fmt::Display for RemoteControlEnableError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Unavailable(err) => err.fmt(f),
|
||||
Self::DisabledByRequirements(err) => err.fmt(f),
|
||||
Self::AuthenticationChanged => f.write_str("remote control authentication changed"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RemoteControlEnableError {}
|
||||
|
||||
/// Process-facing handle. Remote control is permanently disabled.
|
||||
#[derive(Clone)]
|
||||
pub struct RemoteControlHandle {
|
||||
policy: RemoteControlPolicy,
|
||||
status: Arc<watch::Sender<RemoteControlStatusChangedNotification>>,
|
||||
}
|
||||
|
||||
impl RemoteControlHandle {
|
||||
fn unsupported() -> io::Error {
|
||||
io::Error::new(io::ErrorKind::Unsupported, RemoteControlUnavailable)
|
||||
}
|
||||
|
||||
pub fn ensure_remote_control_allowed(&self) -> Result<(), RemoteControlDisabledByRequirements> {
|
||||
match self.policy {
|
||||
RemoteControlPolicy::Allowed => Ok(()),
|
||||
RemoteControlPolicy::DisabledByRequirements => Err(RemoteControlDisabledByRequirements),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn status(&self) -> RemoteControlStatusChangedNotification {
|
||||
self.status.borrow().clone()
|
||||
}
|
||||
|
||||
pub fn status_receiver(&self) -> watch::Receiver<RemoteControlStatusChangedNotification> {
|
||||
self.status.subscribe()
|
||||
}
|
||||
|
||||
pub fn enable_ephemeral(
|
||||
&self,
|
||||
) -> Result<RemoteControlStatusChangedNotification, RemoteControlEnableError> {
|
||||
self.ensure_remote_control_allowed()
|
||||
.map_err(RemoteControlEnableError::DisabledByRequirements)?;
|
||||
Err(RemoteControlEnableError::Unavailable(
|
||||
RemoteControlUnavailable,
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn disable_ephemeral(&self) -> RemoteControlStatusChangedNotification {
|
||||
self.status()
|
||||
}
|
||||
|
||||
pub async fn enable(
|
||||
&self,
|
||||
_app_server_client_name: Option<&str>,
|
||||
) -> io::Result<RemoteControlStatusChangedNotification> {
|
||||
self.ensure_remote_control_allowed()
|
||||
.map_err(|err| io::Error::new(io::ErrorKind::PermissionDenied, err))?;
|
||||
Err(Self::unsupported())
|
||||
}
|
||||
|
||||
pub async fn disable(
|
||||
&self,
|
||||
_app_server_client_name: Option<&str>,
|
||||
) -> io::Result<RemoteControlStatusChangedNotification> {
|
||||
self.ensure_remote_control_allowed()
|
||||
.map_err(|err| io::Error::new(io::ErrorKind::PermissionDenied, err))?;
|
||||
Ok(self.status())
|
||||
}
|
||||
|
||||
pub async fn resolve_persisted_preference(
|
||||
&self,
|
||||
_app_server_client_name: Option<&str>,
|
||||
) -> io::Result<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
pub async fn start_pairing(
|
||||
&self,
|
||||
_params: RemoteControlPairingStartParams,
|
||||
_app_server_client_name: Option<&str>,
|
||||
) -> io::Result<RemoteControlPairingStartResponse> {
|
||||
Err(Self::unsupported())
|
||||
}
|
||||
|
||||
pub async fn pairing_status(
|
||||
&self,
|
||||
_params: RemoteControlPairingStatusParams,
|
||||
) -> io::Result<RemoteControlPairingStatusResponse> {
|
||||
Err(Self::unsupported())
|
||||
}
|
||||
|
||||
pub async fn list_clients(
|
||||
&self,
|
||||
_params: RemoteControlClientsListParams,
|
||||
) -> io::Result<RemoteControlClientsListResponse> {
|
||||
Err(Self::unsupported())
|
||||
}
|
||||
|
||||
pub async fn revoke_client(
|
||||
&self,
|
||||
_params: RemoteControlClientsRevokeParams,
|
||||
) -> io::Result<RemoteControlClientsRevokeResponse> {
|
||||
Err(Self::unsupported())
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a handle that never connects. The task only keeps the client-name channel open
|
||||
/// until shutdown so local transports behave as before.
|
||||
pub async fn start_remote_control(
|
||||
config: RemoteControlStartConfig,
|
||||
_state_db: Option<Arc<StateRuntime>>,
|
||||
_auth_manager: Arc<AuthManager>,
|
||||
_transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
shutdown_token: CancellationToken,
|
||||
app_server_client_name_rx: Option<oneshot::Receiver<String>>,
|
||||
startup_mode: RemoteControlStartupMode,
|
||||
) -> io::Result<(JoinHandle<()>, RemoteControlHandle)> {
|
||||
if startup_mode == RemoteControlStartupMode::EnabledEphemeral {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
RemoteControlUnavailable,
|
||||
));
|
||||
}
|
||||
let (status, _) = watch::channel(RemoteControlStatusChangedNotification {
|
||||
status: RemoteControlConnectionStatus::Disabled,
|
||||
server_name: gethostname().to_string_lossy().trim().to_string(),
|
||||
installation_id: config.installation_id,
|
||||
environment_id: None,
|
||||
});
|
||||
let handle = RemoteControlHandle {
|
||||
policy: config.policy,
|
||||
status: Arc::new(status),
|
||||
};
|
||||
let task = tokio::spawn(async move {
|
||||
let _client_name_rx = app_server_client_name_rx;
|
||||
shutdown_token.cancelled().await;
|
||||
});
|
||||
Ok((task, handle))
|
||||
}
|
||||
@@ -1,488 +0,0 @@
|
||||
//! Credentials and recovery bound to one remote-control login lifetime.
|
||||
//! A request can refresh credentials, but cannot adopt a replacement authentication owner.
|
||||
|
||||
use axum::http::HeaderMap;
|
||||
use axum::http::HeaderValue;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::UnauthorizedRecovery;
|
||||
use codex_runtime_agent_instance::RuntimeAuthSlot;
|
||||
use std::io;
|
||||
use std::io::ErrorKind;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::watch;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct RemoteControlAuth {
|
||||
manager: Arc<AuthManager>,
|
||||
runtime_auth: Option<(RuntimeAuthSlot, RuntimeAuthMode)>,
|
||||
pub(super) owner: crate::ConnectionAuth,
|
||||
pub(super) network_policy: codex_http_client::NetworkPolicy,
|
||||
}
|
||||
|
||||
pub(super) struct RemoteControlRecovery {
|
||||
auth: RemoteControlAuth,
|
||||
recovery: UnauthorizedRecovery,
|
||||
}
|
||||
|
||||
impl RemoteControlAuth {
|
||||
pub(super) fn capture(
|
||||
manager: Arc<AuthManager>,
|
||||
runtime_auth: Option<(RuntimeAuthSlot, RuntimeAuthMode)>,
|
||||
) -> (Self, bool) {
|
||||
loop {
|
||||
let owner = crate::ConnectionAuth::capture(&manager);
|
||||
let authenticated = manager
|
||||
.auth_cached()
|
||||
.is_some_and(|auth| auth.uses_codex_backend() && auth.get_account_id().is_some());
|
||||
if owner.is_current() {
|
||||
return (
|
||||
Self {
|
||||
network_policy: manager.application_network_policy(),
|
||||
manager,
|
||||
runtime_auth,
|
||||
owner,
|
||||
},
|
||||
authenticated,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn ensure_current(&self) -> io::Result<()> {
|
||||
self.owner.ensure_current()
|
||||
}
|
||||
|
||||
pub(super) fn unauthorized_recovery(&self) -> RemoteControlRecovery {
|
||||
RemoteControlRecovery {
|
||||
auth: self.clone(),
|
||||
recovery: self.manager.unauthorized_recovery(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn auth_change_receiver(&self) -> watch::Receiver<u64> {
|
||||
self.manager.auth_change_receiver()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) use codex_http_client::CHATGPT_ACCOUNT_ID_HEADER as REMOTE_CONTROL_ACCOUNT_ID_HEADER;
|
||||
|
||||
pub(super) struct RemoteControlConnectionAuth {
|
||||
pub(super) http_client_factory: codex_http_client::HttpClientFactory,
|
||||
pub(super) auth: CodexAuth,
|
||||
pub(super) runtime_auth: Option<(RuntimeAuthSlot, RuntimeAuthMode)>,
|
||||
pub(super) account_id: String,
|
||||
}
|
||||
|
||||
impl RemoteControlConnectionAuth {
|
||||
pub(super) async fn request_context(
|
||||
&self,
|
||||
endpoint: &str,
|
||||
) -> io::Result<(codex_http_client::HttpClient, HeaderMap)> {
|
||||
if self.runtime_auth.is_some() {
|
||||
codex_model_provider::validate_runtime_destination(Some(endpoint))
|
||||
.map_err(io::Error::other)?;
|
||||
}
|
||||
let runtime = self
|
||||
.runtime_auth
|
||||
.as_ref()
|
||||
.filter(|_| codex_runtime_agent_instance::is_openai_api_url(endpoint))
|
||||
.map(|(slot, mode)| {
|
||||
slot.get()
|
||||
.cloned()
|
||||
.map(|manager| (manager, *mode))
|
||||
.ok_or_else(|| {
|
||||
io::Error::new(
|
||||
ErrorKind::WouldBlock,
|
||||
"runtime authentication is not initialized",
|
||||
)
|
||||
})
|
||||
})
|
||||
.transpose()?;
|
||||
// Keep runtime auth resolution from growing the caller's stack frame.
|
||||
let resolved = Box::pin(codex_model_provider::auth_provider_for_request(
|
||||
&self.auth,
|
||||
runtime.as_ref(),
|
||||
&HeaderMap::new(),
|
||||
))
|
||||
.await
|
||||
.map_err(|error| auth_error(error.into()))?;
|
||||
let factory = resolved
|
||||
.bind_http_client_factory(self.http_client_factory.clone())
|
||||
.map_err(auth_error)?;
|
||||
let client = request_client(&factory, endpoint).await?;
|
||||
let headers = request_headers(&resolved.auth, &self.account_id).await?;
|
||||
resolved
|
||||
.validate_headers(&headers)
|
||||
.map_err(io::Error::other)?;
|
||||
Ok((client, headers))
|
||||
}
|
||||
}
|
||||
|
||||
async fn request_headers(
|
||||
auth_provider: &SharedAuthProvider,
|
||||
account_id: &str,
|
||||
) -> io::Result<HeaderMap> {
|
||||
let mut headers = auth_provider
|
||||
.apply_auth_headers(codex_login::default_client::default_headers())
|
||||
.await
|
||||
.map_err(auth_error)?;
|
||||
headers.insert(
|
||||
REMOTE_CONTROL_ACCOUNT_ID_HEADER,
|
||||
HeaderValue::from_str(account_id).map_err(|err| {
|
||||
io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
format!("invalid remote control account id header: {err}"),
|
||||
)
|
||||
})?,
|
||||
);
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
pub(super) async fn load_remote_control_auth(
|
||||
auth: &RemoteControlAuth,
|
||||
) -> io::Result<RemoteControlConnectionAuth> {
|
||||
auth.ensure_current()?;
|
||||
let credentials = load_auth_manager(&auth.manager, auth.runtime_auth.clone()).await?;
|
||||
auth.ensure_current()?;
|
||||
Ok(credentials)
|
||||
}
|
||||
|
||||
async fn load_auth_manager(
|
||||
auth_manager: &Arc<AuthManager>,
|
||||
runtime_auth: Option<(RuntimeAuthSlot, RuntimeAuthMode)>,
|
||||
) -> io::Result<RemoteControlConnectionAuth> {
|
||||
let mut reloaded = false;
|
||||
let (auth, http_client_factory) = loop {
|
||||
let Some((auth, http_client_factory)) = auth_manager.auth_with_http_client_factory().await
|
||||
else {
|
||||
if reloaded {
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::PermissionDenied,
|
||||
"remote control requires ChatGPT authentication",
|
||||
));
|
||||
}
|
||||
auth_manager.reload().await;
|
||||
reloaded = true;
|
||||
continue;
|
||||
};
|
||||
if !auth.uses_codex_backend() {
|
||||
break (auth, http_client_factory);
|
||||
}
|
||||
if auth.get_account_id().is_none() && !reloaded {
|
||||
auth_manager.reload().await;
|
||||
reloaded = true;
|
||||
continue;
|
||||
}
|
||||
break (auth, http_client_factory);
|
||||
};
|
||||
|
||||
if !auth.uses_codex_backend() {
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::PermissionDenied,
|
||||
"remote control requires ChatGPT authentication; API key auth is not supported",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(RemoteControlConnectionAuth {
|
||||
http_client_factory,
|
||||
runtime_auth,
|
||||
account_id: auth.get_account_id().ok_or_else(|| {
|
||||
io::Error::new(
|
||||
ErrorKind::WouldBlock,
|
||||
"remote control enrollment is waiting for a ChatGPT account id",
|
||||
)
|
||||
})?,
|
||||
auth,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn request_client(
|
||||
factory: &codex_http_client::HttpClientFactory,
|
||||
endpoint: &str,
|
||||
) -> io::Result<codex_http_client::HttpClient> {
|
||||
codex_login::default_client::create_client_for_route_without_request_logging_async(
|
||||
factory.clone(),
|
||||
endpoint.to_string(),
|
||||
codex_http_client::ClientRouteClass::Api,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) fn is_policy_denial(error: &io::Error) -> bool {
|
||||
let Some(cause) = error.get_ref() else {
|
||||
return false;
|
||||
};
|
||||
cause.is::<codex_http_client::NetworkPolicyDenied>()
|
||||
}
|
||||
|
||||
pub(super) fn is_auth_error(error: &io::Error) -> bool {
|
||||
error.kind() == ErrorKind::PermissionDenied && !is_policy_denial(error)
|
||||
}
|
||||
|
||||
fn auth_error(error: codex_api::AuthError) -> io::Error {
|
||||
match error {
|
||||
codex_api::AuthError::Policy(denied) => io::Error::new(ErrorKind::PermissionDenied, denied),
|
||||
error => io::Error::other(error),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn request_error(error: codex_http_client::HttpError) -> io::Error {
|
||||
match error {
|
||||
codex_http_client::HttpError::Policy(denied) => {
|
||||
io::Error::new(ErrorKind::PermissionDenied, denied)
|
||||
}
|
||||
error => io::Error::other(error),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn recover_remote_control_auth(
|
||||
recovery: &mut RemoteControlRecovery,
|
||||
auth_change_rx: &mut watch::Receiver<u64>,
|
||||
) -> bool {
|
||||
if recovery.auth.ensure_current().is_err() {
|
||||
return false;
|
||||
}
|
||||
let auth_recovery = &mut recovery.recovery;
|
||||
if !auth_recovery.has_next() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mode = auth_recovery.mode_name();
|
||||
let step = auth_recovery.step_name();
|
||||
let auth_change_revision_before_recovery = *auth_change_rx.borrow();
|
||||
match auth_recovery.next().await {
|
||||
Ok(step_result) => {
|
||||
if recovery.auth.ensure_current().is_err() {
|
||||
return false;
|
||||
}
|
||||
if step_result.auth_state_changed() == Some(true) {
|
||||
mark_recovery_auth_change_seen(
|
||||
auth_change_rx,
|
||||
auth_change_revision_before_recovery,
|
||||
);
|
||||
}
|
||||
info!(
|
||||
"remote control auth recovery succeeded: mode={mode}, step={step}, auth_state_changed={:?}",
|
||||
step_result.auth_state_changed()
|
||||
);
|
||||
true
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("remote control auth recovery failed: mode={mode}, step={step}: {err}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn mark_recovery_auth_change_seen(
|
||||
auth_change_rx: &mut watch::Receiver<u64>,
|
||||
auth_change_revision_before_recovery: u64,
|
||||
) {
|
||||
let auth_change_revision_after_recovery = *auth_change_rx.borrow();
|
||||
if auth_change_revision_after_recovery == auth_change_revision_before_recovery.wrapping_add(1) {
|
||||
// Recovery updated the same watch that wakes the outer reconnect
|
||||
// loop. Mark only that single revision seen; if more revisions
|
||||
// arrived while recovery was in flight, leave them pending so the
|
||||
// reconnect loop still reacts to the later external auth change.
|
||||
auth_change_rx.borrow_and_update();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use codex_api::AuthProvider;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TestAuthProvider {
|
||||
account_ids: Vec<&'static str>,
|
||||
}
|
||||
|
||||
impl AuthProvider for TestAuthProvider {
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> {
|
||||
headers.insert(
|
||||
axum::http::header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer test-token"),
|
||||
);
|
||||
headers.insert("x-openai-fedramp", HeaderValue::from_static("true"));
|
||||
for account_id in &self.account_ids {
|
||||
headers.append("ChatGPT-Account-ID", HeaderValue::from_static(account_id));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn headers_for(
|
||||
account_id: &str,
|
||||
account_ids: Vec<&'static str>,
|
||||
) -> io::Result<HeaderMap> {
|
||||
let provider: SharedAuthProvider = Arc::new(TestAuthProvider { account_ids });
|
||||
request_headers(&provider, account_id).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn runtime_requests_reject_unsupported_openai_origins() -> anyhow::Result<()> {
|
||||
let credentials =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let (owner, _) = RemoteControlAuth::capture(
|
||||
Arc::clone(&credentials),
|
||||
Some((RuntimeAuthSlot::default(), mode)),
|
||||
);
|
||||
let auth = load_remote_control_auth(&owner).await?;
|
||||
for endpoint in [
|
||||
"https://chatgpt.com:8443/backend-api",
|
||||
"http://chatgpt.com/backend-api",
|
||||
] {
|
||||
assert!(
|
||||
auth.request_context(endpoint).await.is_err(),
|
||||
"unsupported OpenAI origins must not fall back to bearer auth"
|
||||
);
|
||||
}
|
||||
|
||||
let (_, headers) = auth
|
||||
.request_context("https://remote.example/control")
|
||||
.await?;
|
||||
assert_eq!(
|
||||
headers[axum::http::header::AUTHORIZATION],
|
||||
"Bearer Access Token"
|
||||
);
|
||||
assert_eq!(headers[REMOTE_CONTROL_ACCOUNT_ID_HEADER], "account_id");
|
||||
assert!(!headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn runtime_request_rejects_a_different_registered_account() -> anyhow::Result<()> {
|
||||
use codex_features::RuntimeAuthMode;
|
||||
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 serde_json::json;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/agent/register"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-other-account", "agent_host_id": "host",
|
||||
"actor": {"kind": "chatgpt", "user_id": "actor", "account_id": "another-account"},
|
||||
})))
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let credentials =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
let runtime = Arc::new(RuntimeAuthManager::new(
|
||||
Arc::clone(&credentials),
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: uuid::Uuid::nil(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: None,
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
format!("{}/agent/register", server.uri()).parse()?,
|
||||
));
|
||||
let slot = RuntimeAuthSlot::default();
|
||||
assert!(
|
||||
slot.set(runtime).is_ok(),
|
||||
"the runtime slot should be empty"
|
||||
);
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let (owner, _) = RemoteControlAuth::capture(
|
||||
Arc::clone(&credentials),
|
||||
Some((Arc::clone(&slot), mode)),
|
||||
);
|
||||
let auth = load_remote_control_auth(&owner).await?;
|
||||
let Err(error) = auth
|
||||
.request_context(
|
||||
"https://chatgpt.com/backend-api/wham/remote/control/server/enroll",
|
||||
)
|
||||
.await
|
||||
else {
|
||||
panic!("a different registered account must not authorize enrollment");
|
||||
};
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("chatgpt-account-id does not match")
|
||||
);
|
||||
}
|
||||
server.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_headers_adds_account_header_when_provider_omits_it() {
|
||||
let headers = headers_for("selected-account", Vec::new())
|
||||
.await
|
||||
.expect("request headers should build");
|
||||
|
||||
assert_eq!(
|
||||
headers
|
||||
.get_all(REMOTE_CONTROL_ACCOUNT_ID_HEADER)
|
||||
.iter()
|
||||
.map(|value| value.to_str().expect("account header should be text"))
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["selected-account"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_headers_replaces_provider_accounts_and_preserves_other_headers() {
|
||||
let headers = headers_for(
|
||||
"selected-account",
|
||||
vec!["provider-account-a", "provider-account-b"],
|
||||
)
|
||||
.await
|
||||
.expect("request headers should build");
|
||||
|
||||
assert_eq!(
|
||||
headers
|
||||
.get_all(REMOTE_CONTROL_ACCOUNT_ID_HEADER)
|
||||
.iter()
|
||||
.map(|value| value.to_str().expect("account header should be text"))
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["selected-account"]
|
||||
);
|
||||
assert_eq!(
|
||||
headers
|
||||
.get(axum::http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("Bearer test-token")
|
||||
);
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("x-openai-fedramp")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("true")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_headers_rejects_invalid_account_header_value() {
|
||||
let err = headers_for("invalid\naccount", Vec::new())
|
||||
.await
|
||||
.expect_err("invalid account header should fail");
|
||||
|
||||
assert_eq!(err.kind(), ErrorKind::InvalidInput);
|
||||
assert!(
|
||||
err.to_string()
|
||||
.starts_with("invalid remote control account id header:")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,944 +0,0 @@
|
||||
use super::CHANNEL_CAPACITY;
|
||||
use super::TransportEvent;
|
||||
use super::next_connection_id;
|
||||
use super::protocol::ClientEnvelope;
|
||||
pub use super::protocol::ClientEvent;
|
||||
pub use super::protocol::ClientId;
|
||||
use super::protocol::PongStatus;
|
||||
use super::protocol::ServerEvent;
|
||||
use super::protocol::StreamId;
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use crate::outgoing_message::QueuedOutgoingMessage;
|
||||
use crate::transport::ConnectionOrigin;
|
||||
use crate::transport::remote_control::QueuedServerEnvelope;
|
||||
use codex_app_server_protocol::JSONRPCMessage;
|
||||
use std::collections::HashMap;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::task::JoinSet;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
use tokio::time::timeout;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
const REMOTE_CONTROL_CLIENT_IDLE_TIMEOUT: Duration = Duration::from_secs(10 * 60);
|
||||
pub(crate) const REMOTE_CONTROL_IDLE_SWEEP_INTERVAL: Duration = Duration::from_secs(30);
|
||||
#[cfg(not(test))]
|
||||
const REMOTE_CONTROL_TRANSPORT_EVENT_SEND_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
#[cfg(test)]
|
||||
const REMOTE_CONTROL_TRANSPORT_EVENT_SEND_TIMEOUT: Duration = Duration::from_millis(10);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Stopped;
|
||||
|
||||
struct ClientState {
|
||||
connection_id: ConnectionId,
|
||||
disconnect_token: CancellationToken,
|
||||
last_activity_at: Instant,
|
||||
last_inbound_seq_id: Option<u64>,
|
||||
status_tx: watch::Sender<PongStatus>,
|
||||
}
|
||||
|
||||
pub(crate) struct ClientTracker {
|
||||
pub(super) auth: Option<crate::ConnectionAuth>,
|
||||
clients: HashMap<(ClientId, StreamId), ClientState>,
|
||||
legacy_stream_ids: HashMap<ClientId, StreamId>,
|
||||
join_set: JoinSet<(ClientId, StreamId)>,
|
||||
server_event_tx: mpsc::Sender<QueuedServerEnvelope>,
|
||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
shutdown_token: CancellationToken,
|
||||
}
|
||||
|
||||
impl ClientTracker {
|
||||
pub(crate) fn new(
|
||||
server_event_tx: mpsc::Sender<QueuedServerEnvelope>,
|
||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
shutdown_token: &CancellationToken,
|
||||
) -> Self {
|
||||
Self {
|
||||
auth: None,
|
||||
clients: HashMap::new(),
|
||||
legacy_stream_ids: HashMap::new(),
|
||||
join_set: JoinSet::new(),
|
||||
server_event_tx,
|
||||
transport_event_tx,
|
||||
shutdown_token: shutdown_token.child_token(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn bookkeep_join_set(&mut self) -> Option<(ClientId, StreamId)> {
|
||||
while let Some(join_result) = self.join_set.join_next().await {
|
||||
let Ok(client_key) = join_result else {
|
||||
continue;
|
||||
};
|
||||
return Some(client_key);
|
||||
}
|
||||
futures::future::pending().await
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&mut self) {
|
||||
self.shutdown_token.cancel();
|
||||
|
||||
while let Some(client_key) = self.clients.keys().next().cloned() {
|
||||
let _ = self.close_client(&client_key).await;
|
||||
}
|
||||
|
||||
self.drain_join_set().await;
|
||||
}
|
||||
|
||||
async fn drain_join_set(&mut self) {
|
||||
while self.join_set.join_next().await.is_some() {}
|
||||
}
|
||||
|
||||
pub(crate) async fn handle_message(
|
||||
&mut self,
|
||||
client_envelope: ClientEnvelope,
|
||||
) -> Result<(), Stopped> {
|
||||
let ClientEnvelope {
|
||||
client_id,
|
||||
event,
|
||||
stream_id,
|
||||
seq_id,
|
||||
cursor: _,
|
||||
} = client_envelope;
|
||||
let is_legacy_stream_id = stream_id.is_none();
|
||||
let is_initialize = matches!(&event, ClientEvent::ClientMessage { message } if remote_control_message_starts_connection(message));
|
||||
let stream_id = match stream_id {
|
||||
Some(stream_id) => stream_id,
|
||||
None if is_initialize => {
|
||||
// TODO(ruslan): delete this fallback once all clients are updated to send stream_id.
|
||||
self.legacy_stream_ids
|
||||
.remove(&client_id)
|
||||
.unwrap_or_else(StreamId::new_random)
|
||||
}
|
||||
None => self
|
||||
.legacy_stream_ids
|
||||
.get(&client_id)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| {
|
||||
if matches!(&event, ClientEvent::Ping) {
|
||||
StreamId::new_random()
|
||||
} else {
|
||||
StreamId(String::new())
|
||||
}
|
||||
}),
|
||||
};
|
||||
if stream_id.0.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let client_key = (client_id.clone(), stream_id.clone());
|
||||
match event {
|
||||
ClientEvent::ClientMessage { message } => {
|
||||
if let Some(seq_id) = seq_id
|
||||
&& let Some(client) = self.clients.get(&client_key)
|
||||
&& client
|
||||
.last_inbound_seq_id
|
||||
.is_some_and(|last_seq_id| last_seq_id >= seq_id)
|
||||
&& !is_initialize
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if is_initialize && self.clients.contains_key(&client_key) {
|
||||
self.close_client(&client_key).await?;
|
||||
}
|
||||
|
||||
if let Some(connection_id) = self.clients.get_mut(&client_key).map(|client| {
|
||||
client.last_activity_at = Instant::now();
|
||||
client.connection_id
|
||||
}) {
|
||||
self.send_transport_event(TransportEvent::IncomingMessage {
|
||||
connection_id,
|
||||
message,
|
||||
})
|
||||
.await?;
|
||||
self.record_inbound_message_delivery(&client_key, seq_id);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !is_initialize {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let connection_id = next_connection_id();
|
||||
let (writer_tx, writer_rx) =
|
||||
mpsc::channel::<QueuedOutgoingMessage>(CHANNEL_CAPACITY);
|
||||
let disconnect_token = self.shutdown_token.child_token();
|
||||
self.send_transport_event(TransportEvent::ConnectionOpened {
|
||||
connection_id,
|
||||
origin: ConnectionOrigin::RemoteControl,
|
||||
auth: self.auth.clone(),
|
||||
writer: writer_tx,
|
||||
disconnect_sender: Some(disconnect_token.clone()),
|
||||
})
|
||||
.await?;
|
||||
|
||||
let (status_tx, status_rx) = watch::channel(PongStatus::Active);
|
||||
self.join_set.spawn(Self::run_client_outbound(
|
||||
client_id.clone(),
|
||||
stream_id.clone(),
|
||||
self.server_event_tx.clone(),
|
||||
writer_rx,
|
||||
status_rx,
|
||||
disconnect_token.clone(),
|
||||
));
|
||||
self.clients.insert(
|
||||
client_key.clone(),
|
||||
ClientState {
|
||||
connection_id,
|
||||
disconnect_token,
|
||||
last_activity_at: Instant::now(),
|
||||
last_inbound_seq_id: None,
|
||||
status_tx,
|
||||
},
|
||||
);
|
||||
if is_legacy_stream_id {
|
||||
self.legacy_stream_ids.insert(client_id.clone(), stream_id);
|
||||
}
|
||||
if let Err(err) = self
|
||||
.send_transport_event(TransportEvent::IncomingMessage {
|
||||
connection_id,
|
||||
message,
|
||||
})
|
||||
.await
|
||||
{
|
||||
if let Some(client) = self.remove_client(&client_key) {
|
||||
client.disconnect_token.cancel();
|
||||
// The initialize send already timed out on this queue; preserve close
|
||||
// delivery without blocking reconnect on the same backpressure.
|
||||
drop(self.spawn_connection_closed(client.connection_id));
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
if !is_legacy_stream_id {
|
||||
self.record_inbound_message_delivery(&client_key, seq_id);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
ClientEvent::ClientMessageChunk { .. } | ClientEvent::Ack { .. } => Ok(()),
|
||||
ClientEvent::Ping => {
|
||||
if let Some(client) = self.clients.get_mut(&client_key) {
|
||||
client.last_activity_at = Instant::now();
|
||||
let _ = client.status_tx.send(PongStatus::Active);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let server_event_tx = self.server_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let server_envelope = QueuedServerEnvelope {
|
||||
event: ServerEvent::Pong {
|
||||
status: PongStatus::Unknown,
|
||||
},
|
||||
client_id,
|
||||
stream_id,
|
||||
write_complete_tx: None,
|
||||
};
|
||||
let _ = server_event_tx.send(server_envelope).await;
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
ClientEvent::ClientClosed => self.close_client(&client_key).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_client_outbound(
|
||||
client_id: ClientId,
|
||||
stream_id: StreamId,
|
||||
server_event_tx: mpsc::Sender<QueuedServerEnvelope>,
|
||||
mut writer_rx: mpsc::Receiver<QueuedOutgoingMessage>,
|
||||
mut status_rx: watch::Receiver<PongStatus>,
|
||||
disconnect_token: CancellationToken,
|
||||
) -> (ClientId, StreamId) {
|
||||
loop {
|
||||
let (event, write_complete_tx) = tokio::select! {
|
||||
_ = disconnect_token.cancelled() => {
|
||||
break;
|
||||
}
|
||||
queued_message = writer_rx.recv() => {
|
||||
let Some(queued_message) = queued_message else {
|
||||
break;
|
||||
};
|
||||
let event = ServerEvent::ServerMessage {
|
||||
message: Box::new(queued_message.message),
|
||||
};
|
||||
(event, queued_message.write_complete_tx)
|
||||
}
|
||||
changed = status_rx.changed() => {
|
||||
if changed.is_err() {
|
||||
break;
|
||||
}
|
||||
let event = ServerEvent::Pong { status: status_rx.borrow().clone() };
|
||||
(event, None)
|
||||
}
|
||||
};
|
||||
let send_result = tokio::select! {
|
||||
_ = disconnect_token.cancelled() => {
|
||||
break;
|
||||
}
|
||||
send_result = server_event_tx.send(QueuedServerEnvelope {
|
||||
event,
|
||||
client_id: client_id.clone(),
|
||||
stream_id: stream_id.clone(),
|
||||
write_complete_tx,
|
||||
}) => send_result,
|
||||
};
|
||||
if send_result.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
(client_id, stream_id)
|
||||
}
|
||||
|
||||
pub(crate) async fn close_expired_clients(
|
||||
&mut self,
|
||||
) -> Result<Vec<(ClientId, StreamId)>, Stopped> {
|
||||
let now = Instant::now();
|
||||
let expired_client_ids: Vec<(ClientId, StreamId)> = self
|
||||
.clients
|
||||
.iter()
|
||||
.filter_map(|(client_key, client)| {
|
||||
(!remote_control_client_is_alive(client, now)).then_some(client_key.clone())
|
||||
})
|
||||
.collect();
|
||||
for client_key in &expired_client_ids {
|
||||
self.close_client(client_key).await?;
|
||||
}
|
||||
Ok(expired_client_ids)
|
||||
}
|
||||
|
||||
pub(super) async fn close_client(
|
||||
&mut self,
|
||||
client_key: &(ClientId, StreamId),
|
||||
) -> Result<(), Stopped> {
|
||||
let Some(client) = self.remove_client(client_key) else {
|
||||
return Ok(());
|
||||
};
|
||||
client.disconnect_token.cancel();
|
||||
self.send_transport_event(TransportEvent::ConnectionClosed {
|
||||
connection_id: client.connection_id,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
fn remove_client(&mut self, client_key: &(ClientId, StreamId)) -> Option<ClientState> {
|
||||
let client = self.clients.remove(client_key)?;
|
||||
if self
|
||||
.legacy_stream_ids
|
||||
.get(&client_key.0)
|
||||
.is_some_and(|stream_id| stream_id == &client_key.1)
|
||||
{
|
||||
self.legacy_stream_ids.remove(&client_key.0);
|
||||
}
|
||||
Some(client)
|
||||
}
|
||||
|
||||
async fn send_transport_event(&self, event: TransportEvent) -> Result<(), Stopped> {
|
||||
let event = match event {
|
||||
TransportEvent::ConnectionClosed { connection_id } => {
|
||||
return self.send_connection_closed(connection_id).await;
|
||||
}
|
||||
event => event,
|
||||
};
|
||||
|
||||
let event_name = transport_event_name(&event);
|
||||
match timeout(
|
||||
REMOTE_CONTROL_TRANSPORT_EVENT_SEND_TIMEOUT,
|
||||
self.transport_event_tx.send(event),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(())) => Ok(()),
|
||||
Ok(Err(_)) => {
|
||||
warn!(
|
||||
transport_event = event_name,
|
||||
"remote control transport event receiver dropped"
|
||||
);
|
||||
Err(Stopped)
|
||||
}
|
||||
Err(_) => {
|
||||
warn!(
|
||||
transport_event = event_name,
|
||||
timeout = ?REMOTE_CONTROL_TRANSPORT_EVENT_SEND_TIMEOUT,
|
||||
"timed out forwarding remote control transport event"
|
||||
);
|
||||
Err(Stopped)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn record_inbound_message_delivery(
|
||||
&mut self,
|
||||
client_key: &(ClientId, StreamId),
|
||||
seq_id: Option<u64>,
|
||||
) {
|
||||
// Timed forwarding can fail, so only dedupe retries after app-server receives it.
|
||||
if let Some(seq_id) = seq_id
|
||||
&& let Some(client) = self.clients.get_mut(client_key)
|
||||
{
|
||||
client.last_inbound_seq_id = Some(seq_id);
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_connection_closed(&self, connection_id: ConnectionId) -> Result<(), Stopped> {
|
||||
// Worker shutdown can abort the caller; detach the cleanup event before awaiting it.
|
||||
match self.spawn_connection_closed(connection_id).await {
|
||||
Ok(result) => result,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
transport_event = "connection_closed",
|
||||
?err,
|
||||
"remote control transport event forwarding task failed"
|
||||
);
|
||||
Err(Stopped)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_connection_closed(
|
||||
&self,
|
||||
connection_id: ConnectionId,
|
||||
) -> JoinHandle<Result<(), Stopped>> {
|
||||
info!(
|
||||
connection_id = ?connection_id,
|
||||
"forwarding remote control connection closed transport event"
|
||||
);
|
||||
let transport_event_tx = self.transport_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
transport_event_tx
|
||||
.send(TransportEvent::ConnectionClosed { connection_id })
|
||||
.await
|
||||
.map_err(|_| {
|
||||
warn!(
|
||||
transport_event = "connection_closed",
|
||||
"remote control transport event receiver dropped"
|
||||
);
|
||||
Stopped
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn transport_event_name(event: &TransportEvent) -> &'static str {
|
||||
match event {
|
||||
TransportEvent::ConnectionOpened { .. } => "connection_opened",
|
||||
TransportEvent::ConnectionClosed { .. } => "connection_closed",
|
||||
TransportEvent::IncomingMessage { .. } => "incoming_message",
|
||||
TransportEvent::DaemonShutdown => "daemon_shutdown",
|
||||
}
|
||||
}
|
||||
|
||||
fn remote_control_message_starts_connection(message: &JSONRPCMessage) -> bool {
|
||||
matches!(
|
||||
message,
|
||||
JSONRPCMessage::Request(codex_app_server_protocol::JSONRPCRequest { method, .. })
|
||||
if method == "initialize"
|
||||
)
|
||||
}
|
||||
|
||||
fn remote_control_client_is_alive(client: &ClientState, now: Instant) -> bool {
|
||||
now.duration_since(client.last_activity_at) < REMOTE_CONTROL_CLIENT_IDLE_TIMEOUT
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::outgoing_message::OutgoingMessage;
|
||||
use crate::transport::remote_control::protocol::ClientEnvelope;
|
||||
use crate::transport::remote_control::protocol::ClientEvent;
|
||||
use codex_app_server_protocol::ConfigWarningNotification;
|
||||
use codex_app_server_protocol::JSONRPCRequest;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ServerNotificationEnvelope;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tokio::time::timeout;
|
||||
|
||||
fn initialize_envelope(client_id: &str) -> ClientEnvelope {
|
||||
initialize_envelope_with_stream_id(client_id, /*stream_id*/ None)
|
||||
}
|
||||
|
||||
fn initialize_envelope_with_stream_id(
|
||||
client_id: &str,
|
||||
stream_id: Option<&str>,
|
||||
) -> ClientEnvelope {
|
||||
ClientEnvelope {
|
||||
event: ClientEvent::ClientMessage {
|
||||
message: JSONRPCMessage::Request(JSONRPCRequest {
|
||||
id: RequestId::Integer(1),
|
||||
method: "initialize".to_string(),
|
||||
params: Some(json!({
|
||||
"clientInfo": {
|
||||
"name": "remote-test-client",
|
||||
"version": "0.1.0"
|
||||
}
|
||||
})),
|
||||
trace: None,
|
||||
}),
|
||||
},
|
||||
client_id: ClientId(client_id.to_string()),
|
||||
stream_id: stream_id.map(|stream_id| StreamId(stream_id.to_string())),
|
||||
seq_id: Some(0),
|
||||
cursor: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn initialized_notification() -> JSONRPCMessage {
|
||||
JSONRPCMessage::Notification(codex_app_server_protocol::JSONRPCNotification {
|
||||
method: "initialized".to_string(),
|
||||
params: None,
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_outbound_task_emits_connection_closed() {
|
||||
let (server_event_tx, _server_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let (transport_event_tx, mut transport_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let mut client_tracker =
|
||||
ClientTracker::new(server_event_tx, transport_event_tx, &shutdown_token);
|
||||
|
||||
client_tracker
|
||||
.handle_message(initialize_envelope("client-1"))
|
||||
.await
|
||||
.expect("initialize should open client");
|
||||
|
||||
let (connection_id, disconnect_sender) = match transport_event_rx
|
||||
.recv()
|
||||
.await
|
||||
.expect("connection opened should be sent")
|
||||
{
|
||||
TransportEvent::ConnectionOpened {
|
||||
connection_id,
|
||||
disconnect_sender: Some(disconnect_sender),
|
||||
..
|
||||
} => (connection_id, disconnect_sender),
|
||||
other => panic!("expected connection opened, got {other:?}"),
|
||||
};
|
||||
match transport_event_rx
|
||||
.recv()
|
||||
.await
|
||||
.expect("initialize should be forwarded")
|
||||
{
|
||||
TransportEvent::IncomingMessage {
|
||||
connection_id: incoming_connection_id,
|
||||
..
|
||||
} => assert_eq!(incoming_connection_id, connection_id),
|
||||
other => panic!("expected incoming initialize, got {other:?}"),
|
||||
}
|
||||
|
||||
disconnect_sender.cancel();
|
||||
let closed_client_id = timeout(Duration::from_secs(1), client_tracker.bookkeep_join_set())
|
||||
.await
|
||||
.expect("bookkeeping should process the closed task")
|
||||
.expect("closed task should return client id");
|
||||
assert_eq!(closed_client_id.0, ClientId("client-1".to_string()));
|
||||
client_tracker
|
||||
.close_client(&closed_client_id)
|
||||
.await
|
||||
.expect("closed client should emit connection closed");
|
||||
|
||||
match transport_event_rx
|
||||
.recv()
|
||||
.await
|
||||
.expect("connection closed should be sent")
|
||||
{
|
||||
TransportEvent::ConnectionClosed {
|
||||
connection_id: closed_connection_id,
|
||||
} => assert_eq!(closed_connection_id, connection_id),
|
||||
other => panic!("expected connection closed, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_cancels_blocked_outbound_forwarding() {
|
||||
let (server_event_tx, _server_event_rx) = mpsc::channel(1);
|
||||
let (transport_event_tx, mut transport_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let mut client_tracker =
|
||||
ClientTracker::new(server_event_tx.clone(), transport_event_tx, &shutdown_token);
|
||||
|
||||
server_event_tx
|
||||
.send(QueuedServerEnvelope {
|
||||
event: ServerEvent::Pong {
|
||||
status: PongStatus::Unknown,
|
||||
},
|
||||
client_id: ClientId("queued-client".to_string()),
|
||||
stream_id: StreamId("queued-stream".to_string()),
|
||||
write_complete_tx: None,
|
||||
})
|
||||
.await
|
||||
.expect("server event queue should accept prefill");
|
||||
|
||||
client_tracker
|
||||
.handle_message(initialize_envelope("client-1"))
|
||||
.await
|
||||
.expect("initialize should open client");
|
||||
|
||||
let writer = match transport_event_rx
|
||||
.recv()
|
||||
.await
|
||||
.expect("connection opened should be sent")
|
||||
{
|
||||
TransportEvent::ConnectionOpened { writer, .. } => writer,
|
||||
other => panic!("expected connection opened, got {other:?}"),
|
||||
};
|
||||
let _ = transport_event_rx
|
||||
.recv()
|
||||
.await
|
||||
.expect("initialize should be forwarded");
|
||||
|
||||
writer
|
||||
.send(QueuedOutgoingMessage::new(
|
||||
OutgoingMessage::AppServerNotification(ServerNotificationEnvelope {
|
||||
notification: ServerNotification::ConfigWarning(ConfigWarningNotification {
|
||||
summary: "test".to_string(),
|
||||
details: None,
|
||||
path: None,
|
||||
range: None,
|
||||
}),
|
||||
emitted_at_ms: Some(1_234),
|
||||
}),
|
||||
))
|
||||
.await
|
||||
.expect("writer should accept queued message");
|
||||
|
||||
timeout(Duration::from_secs(1), client_tracker.shutdown())
|
||||
.await
|
||||
.expect("shutdown should not hang on blocked server forwarding");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn non_close_transport_event_send_times_out_when_queue_stays_full() {
|
||||
let (server_event_tx, _server_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let (transport_event_tx, _transport_event_rx) = mpsc::channel(1);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let client_tracker =
|
||||
ClientTracker::new(server_event_tx, transport_event_tx.clone(), &shutdown_token);
|
||||
|
||||
transport_event_tx
|
||||
.send(TransportEvent::ConnectionClosed {
|
||||
connection_id: next_connection_id(),
|
||||
})
|
||||
.await
|
||||
.expect("transport event queue should accept prefill");
|
||||
|
||||
let send_result = client_tracker
|
||||
.send_transport_event(TransportEvent::IncomingMessage {
|
||||
connection_id: next_connection_id(),
|
||||
message: initialized_notification(),
|
||||
})
|
||||
.await;
|
||||
|
||||
assert!(send_result.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn incoming_message_timeout_does_not_advance_seq_id() {
|
||||
let (server_event_tx, _server_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let (transport_event_tx, mut transport_event_rx) = mpsc::channel(2);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let mut client_tracker =
|
||||
ClientTracker::new(server_event_tx, transport_event_tx.clone(), &shutdown_token);
|
||||
|
||||
client_tracker
|
||||
.handle_message(initialize_envelope_with_stream_id(
|
||||
"client-1",
|
||||
Some("stream-1"),
|
||||
))
|
||||
.await
|
||||
.expect("initialize should open client");
|
||||
let connection_id = match transport_event_rx.recv().await.expect("open event") {
|
||||
TransportEvent::ConnectionOpened { connection_id, .. } => connection_id,
|
||||
other => panic!("expected connection opened, got {other:?}"),
|
||||
};
|
||||
let _ = transport_event_rx.recv().await.expect("initialize event");
|
||||
|
||||
for _ in 0..2 {
|
||||
transport_event_tx
|
||||
.send(TransportEvent::ConnectionClosed {
|
||||
connection_id: next_connection_id(),
|
||||
})
|
||||
.await
|
||||
.expect("transport event queue should accept prefill");
|
||||
}
|
||||
|
||||
let retry_envelope = ClientEnvelope {
|
||||
event: ClientEvent::ClientMessage {
|
||||
message: initialized_notification(),
|
||||
},
|
||||
client_id: ClientId("client-1".to_string()),
|
||||
stream_id: Some(StreamId("stream-1".to_string())),
|
||||
seq_id: Some(1),
|
||||
cursor: None,
|
||||
};
|
||||
assert!(
|
||||
client_tracker
|
||||
.handle_message(retry_envelope.clone())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
for _ in 0..2 {
|
||||
let _ = transport_event_rx.recv().await.expect("prefilled event");
|
||||
}
|
||||
|
||||
client_tracker
|
||||
.handle_message(retry_envelope)
|
||||
.await
|
||||
.expect("retry should forward after timeout");
|
||||
match transport_event_rx.recv().await.expect("retried event") {
|
||||
TransportEvent::IncomingMessage {
|
||||
connection_id: queued_connection_id,
|
||||
..
|
||||
} => assert_eq!(queued_connection_id, connection_id),
|
||||
other => panic!("expected incoming message, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn initialize_timeout_closes_open_connection() {
|
||||
let (server_event_tx, _server_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let (transport_event_tx, mut transport_event_rx) = mpsc::channel(1);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let client_tracker =
|
||||
ClientTracker::new(server_event_tx, transport_event_tx, &shutdown_token);
|
||||
let handle_message = tokio::spawn(async move {
|
||||
let mut client_tracker = client_tracker;
|
||||
client_tracker
|
||||
.handle_message(initialize_envelope_with_stream_id(
|
||||
"client-1",
|
||||
Some("stream-1"),
|
||||
))
|
||||
.await
|
||||
});
|
||||
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::advance(
|
||||
REMOTE_CONTROL_TRANSPORT_EVENT_SEND_TIMEOUT + Duration::from_millis(1),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(handle_message.await.expect("handle message task").is_err());
|
||||
let connection_id = match transport_event_rx.recv().await.expect("open event") {
|
||||
TransportEvent::ConnectionOpened { connection_id, .. } => connection_id,
|
||||
other => panic!("expected connection opened, got {other:?}"),
|
||||
};
|
||||
|
||||
match transport_event_rx.recv().await.expect("close event") {
|
||||
TransportEvent::ConnectionClosed {
|
||||
connection_id: closed_connection_id,
|
||||
} => assert_eq!(closed_connection_id, connection_id),
|
||||
other => panic!("expected connection closed, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn close_client_waits_for_transport_event_queue_capacity() {
|
||||
let (server_event_tx, _server_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let (transport_event_tx, mut transport_event_rx) = mpsc::channel(2);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let mut client_tracker =
|
||||
ClientTracker::new(server_event_tx, transport_event_tx, &shutdown_token);
|
||||
|
||||
client_tracker
|
||||
.handle_message(initialize_envelope_with_stream_id(
|
||||
"client-1",
|
||||
Some("stream-1"),
|
||||
))
|
||||
.await
|
||||
.expect("initialize should open client");
|
||||
let connection_id = match transport_event_rx.recv().await.expect("open event") {
|
||||
TransportEvent::ConnectionOpened { connection_id, .. } => connection_id,
|
||||
other => panic!("expected connection opened, got {other:?}"),
|
||||
};
|
||||
let _ = transport_event_rx.recv().await.expect("initialize event");
|
||||
|
||||
for _ in 0..2 {
|
||||
client_tracker
|
||||
.transport_event_tx
|
||||
.send(TransportEvent::IncomingMessage {
|
||||
connection_id,
|
||||
message: initialized_notification(),
|
||||
})
|
||||
.await
|
||||
.expect("transport event queue should accept prefill");
|
||||
}
|
||||
|
||||
let client_key = (
|
||||
ClientId("client-1".to_string()),
|
||||
StreamId("stream-1".to_string()),
|
||||
);
|
||||
let close_client = client_tracker.close_client(&client_key);
|
||||
tokio::pin!(close_client);
|
||||
assert!(
|
||||
timeout(Duration::from_millis(20), &mut close_client)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
for _ in 0..2 {
|
||||
match transport_event_rx.recv().await.expect("prefilled event") {
|
||||
TransportEvent::IncomingMessage {
|
||||
connection_id: queued_connection_id,
|
||||
..
|
||||
} => assert_eq!(queued_connection_id, connection_id),
|
||||
other => panic!("expected incoming message, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
close_client
|
||||
.await
|
||||
.expect("close should forward after queue drains");
|
||||
match transport_event_rx.recv().await.expect("close event") {
|
||||
TransportEvent::ConnectionClosed {
|
||||
connection_id: closed_connection_id,
|
||||
} => assert_eq!(closed_connection_id, connection_id),
|
||||
other => panic!("expected connection closed, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn close_client_keeps_forwarding_after_caller_is_aborted() {
|
||||
let (server_event_tx, _server_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let (transport_event_tx, mut transport_event_rx) = mpsc::channel(2);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let mut client_tracker =
|
||||
ClientTracker::new(server_event_tx, transport_event_tx, &shutdown_token);
|
||||
|
||||
client_tracker
|
||||
.handle_message(initialize_envelope_with_stream_id(
|
||||
"client-1",
|
||||
Some("stream-1"),
|
||||
))
|
||||
.await
|
||||
.expect("initialize should open client");
|
||||
let connection_id = match transport_event_rx.recv().await.expect("open event") {
|
||||
TransportEvent::ConnectionOpened { connection_id, .. } => connection_id,
|
||||
other => panic!("expected connection opened, got {other:?}"),
|
||||
};
|
||||
let _ = transport_event_rx.recv().await.expect("initialize event");
|
||||
|
||||
for _ in 0..2 {
|
||||
client_tracker
|
||||
.transport_event_tx
|
||||
.send(TransportEvent::IncomingMessage {
|
||||
connection_id,
|
||||
message: initialized_notification(),
|
||||
})
|
||||
.await
|
||||
.expect("transport event queue should accept prefill");
|
||||
}
|
||||
|
||||
let client_key = (
|
||||
ClientId("client-1".to_string()),
|
||||
StreamId("stream-1".to_string()),
|
||||
);
|
||||
let mut close_client =
|
||||
tokio::spawn(async move { client_tracker.close_client(&client_key).await });
|
||||
assert!(
|
||||
timeout(Duration::from_millis(20), &mut close_client)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
close_client.abort();
|
||||
let _ = close_client.await;
|
||||
|
||||
for _ in 0..2 {
|
||||
let _ = transport_event_rx.recv().await.expect("prefilled event");
|
||||
}
|
||||
match timeout(Duration::from_secs(1), transport_event_rx.recv())
|
||||
.await
|
||||
.expect("close should be delivered")
|
||||
.expect("close event")
|
||||
{
|
||||
TransportEvent::ConnectionClosed {
|
||||
connection_id: closed_connection_id,
|
||||
} => assert_eq!(closed_connection_id, connection_id),
|
||||
other => panic!("expected connection closed, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialize_with_new_stream_id_opens_new_connection_for_same_client() {
|
||||
let (server_event_tx, _server_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let (transport_event_tx, mut transport_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let mut client_tracker =
|
||||
ClientTracker::new(server_event_tx, transport_event_tx, &shutdown_token);
|
||||
|
||||
client_tracker
|
||||
.handle_message(initialize_envelope_with_stream_id(
|
||||
"client-1",
|
||||
Some("stream-1"),
|
||||
))
|
||||
.await
|
||||
.expect("first initialize should open client");
|
||||
let first_connection_id = match transport_event_rx.recv().await.expect("open event") {
|
||||
TransportEvent::ConnectionOpened { connection_id, .. } => connection_id,
|
||||
other => panic!("expected connection opened, got {other:?}"),
|
||||
};
|
||||
let _ = transport_event_rx.recv().await.expect("initialize event");
|
||||
|
||||
client_tracker
|
||||
.handle_message(initialize_envelope_with_stream_id(
|
||||
"client-1",
|
||||
Some("stream-2"),
|
||||
))
|
||||
.await
|
||||
.expect("second initialize should open client");
|
||||
let second_connection_id = match transport_event_rx.recv().await.expect("open event") {
|
||||
TransportEvent::ConnectionOpened { connection_id, .. } => connection_id,
|
||||
other => panic!("expected connection opened, got {other:?}"),
|
||||
};
|
||||
|
||||
assert_ne!(first_connection_id, second_connection_id);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_initialize_without_stream_id_resets_inbound_seq_id() {
|
||||
let (server_event_tx, _server_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let (transport_event_tx, mut transport_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let mut client_tracker =
|
||||
ClientTracker::new(server_event_tx, transport_event_tx, &shutdown_token);
|
||||
|
||||
client_tracker
|
||||
.handle_message(initialize_envelope("client-1"))
|
||||
.await
|
||||
.expect("initialize should open client");
|
||||
let connection_id = match transport_event_rx.recv().await.expect("open event") {
|
||||
TransportEvent::ConnectionOpened { connection_id, .. } => connection_id,
|
||||
other => panic!("expected connection opened, got {other:?}"),
|
||||
};
|
||||
let _ = transport_event_rx.recv().await.expect("initialize event");
|
||||
|
||||
client_tracker
|
||||
.handle_message(ClientEnvelope {
|
||||
event: ClientEvent::ClientMessage {
|
||||
message: JSONRPCMessage::Notification(
|
||||
codex_app_server_protocol::JSONRPCNotification {
|
||||
method: "initialized".to_string(),
|
||||
params: None,
|
||||
},
|
||||
),
|
||||
},
|
||||
client_id: ClientId("client-1".to_string()),
|
||||
stream_id: None,
|
||||
seq_id: Some(0),
|
||||
cursor: None,
|
||||
})
|
||||
.await
|
||||
.expect("legacy followup should be forwarded");
|
||||
|
||||
match transport_event_rx.recv().await.expect("followup event") {
|
||||
TransportEvent::IncomingMessage {
|
||||
connection_id: incoming_connection_id,
|
||||
..
|
||||
} => assert_eq!(incoming_connection_id, connection_id),
|
||||
other => panic!("expected incoming message, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,311 +0,0 @@
|
||||
use super::auth::RemoteControlAuth;
|
||||
use super::auth::RemoteControlConnectionAuth;
|
||||
use super::auth::load_remote_control_auth;
|
||||
use super::auth::recover_remote_control_auth;
|
||||
use super::enroll::format_headers;
|
||||
use super::enroll::preview_remote_control_response_body;
|
||||
use super::protocol::normalize_remote_control_base_url;
|
||||
use axum::http::HeaderMap;
|
||||
use codex_app_server_protocol::RemoteControlClient;
|
||||
use codex_app_server_protocol::RemoteControlClientsListOrder;
|
||||
use codex_app_server_protocol::RemoteControlClientsListParams;
|
||||
use codex_app_server_protocol::RemoteControlClientsListResponse;
|
||||
use codex_app_server_protocol::RemoteControlClientsRevokeParams;
|
||||
use codex_app_server_protocol::RemoteControlClientsRevokeResponse;
|
||||
use serde::Deserialize;
|
||||
use std::io;
|
||||
use std::io::ErrorKind;
|
||||
use time::OffsetDateTime;
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
use url::Url;
|
||||
|
||||
const REMOTE_CONTROL_CLIENT_MANAGEMENT_TIMEOUT: std::time::Duration =
|
||||
std::time::Duration::from_secs(30);
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ListRemoteControlClientsResponse {
|
||||
items: Vec<RemoteControlClientResponse>,
|
||||
#[serde(default)]
|
||||
cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RemoteControlClientResponse {
|
||||
client_id: String,
|
||||
#[serde(default)]
|
||||
display_name: Option<String>,
|
||||
#[serde(default)]
|
||||
device_type: Option<String>,
|
||||
#[serde(default)]
|
||||
platform: Option<String>,
|
||||
#[serde(default)]
|
||||
os_version: Option<String>,
|
||||
#[serde(default)]
|
||||
device_model: Option<String>,
|
||||
#[serde(default)]
|
||||
app_version: Option<String>,
|
||||
#[serde(default)]
|
||||
last_seen_at: Option<String>,
|
||||
}
|
||||
|
||||
enum ClientManagementRequest<'a> {
|
||||
List {
|
||||
url: &'a Url,
|
||||
params: &'a RemoteControlClientsListParams,
|
||||
},
|
||||
Revoke {
|
||||
url: &'a Url,
|
||||
},
|
||||
}
|
||||
|
||||
struct ClientManagementResponse {
|
||||
status: axum::http::StatusCode,
|
||||
headers: HeaderMap,
|
||||
body: Vec<u8>,
|
||||
}
|
||||
|
||||
pub(super) async fn list_remote_control_clients(
|
||||
remote_control_url: &str,
|
||||
auth_manager: &RemoteControlAuth,
|
||||
params: RemoteControlClientsListParams,
|
||||
) -> io::Result<RemoteControlClientsListResponse> {
|
||||
if params.environment_id.is_empty() {
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
"remote control client list requires environmentId",
|
||||
));
|
||||
}
|
||||
if params
|
||||
.limit
|
||||
.is_some_and(|limit| !(1..=100).contains(&limit))
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
"remote control client list limit must be between 1 and 100",
|
||||
));
|
||||
}
|
||||
let url = environment_clients_url(remote_control_url, ¶ms.environment_id)?;
|
||||
let response = send_client_management_request(
|
||||
auth_manager,
|
||||
ClientManagementRequest::List {
|
||||
url: &url,
|
||||
params: ¶ms,
|
||||
},
|
||||
"list remote control clients",
|
||||
)
|
||||
.await?;
|
||||
let ClientManagementResponse {
|
||||
status,
|
||||
headers,
|
||||
body,
|
||||
} = response;
|
||||
let body_preview = preview_remote_control_response_body(&body);
|
||||
ensure_success_response(status, &headers, &url, &body_preview, "client list")?;
|
||||
let response = serde_json::from_slice::<ListRemoteControlClientsResponse>(&body).map_err(
|
||||
|err| {
|
||||
io::Error::other(format!(
|
||||
"failed to parse remote control client list response from `{url}`: HTTP {status}, {}, body: {body_preview}, decode error: {err}",
|
||||
format_headers(&headers)
|
||||
))
|
||||
},
|
||||
)?;
|
||||
Ok(RemoteControlClientsListResponse {
|
||||
data: response
|
||||
.items
|
||||
.into_iter()
|
||||
.map(RemoteControlClient::try_from)
|
||||
.collect::<io::Result<_>>()?,
|
||||
next_cursor: response.cursor,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn revoke_remote_control_client(
|
||||
remote_control_url: &str,
|
||||
auth_manager: &RemoteControlAuth,
|
||||
params: RemoteControlClientsRevokeParams,
|
||||
) -> io::Result<RemoteControlClientsRevokeResponse> {
|
||||
if params.environment_id.is_empty() {
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
"remote control client revoke requires environmentId",
|
||||
));
|
||||
}
|
||||
if params.client_id.is_empty() {
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
"remote control client revoke requires clientId",
|
||||
));
|
||||
}
|
||||
let mut url = environment_clients_url(remote_control_url, ¶ms.environment_id)?;
|
||||
url.path_segments_mut()
|
||||
.map_err(|()| {
|
||||
io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
"remote control URL cannot be a base",
|
||||
)
|
||||
})?
|
||||
.push(¶ms.client_id);
|
||||
let response = send_client_management_request(
|
||||
auth_manager,
|
||||
ClientManagementRequest::Revoke { url: &url },
|
||||
"revoke remote control client",
|
||||
)
|
||||
.await?;
|
||||
let ClientManagementResponse {
|
||||
status,
|
||||
headers,
|
||||
body,
|
||||
} = response;
|
||||
let body_preview = preview_remote_control_response_body(&body);
|
||||
ensure_success_response(status, &headers, &url, &body_preview, "client revoke")?;
|
||||
Ok(RemoteControlClientsRevokeResponse {})
|
||||
}
|
||||
|
||||
async fn send_client_management_request(
|
||||
auth_manager: &RemoteControlAuth,
|
||||
request: ClientManagementRequest<'_>,
|
||||
action: &str,
|
||||
) -> io::Result<ClientManagementResponse> {
|
||||
let mut auth_recovery = auth_manager.unauthorized_recovery();
|
||||
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
||||
let auth = load_remote_control_auth(auth_manager).await?;
|
||||
let response = send_client_management_request_once(&auth, &request, action).await?;
|
||||
if response.status.as_u16() != 401
|
||||
|| !recover_remote_control_auth(&mut auth_recovery, &mut auth_change_rx).await
|
||||
{
|
||||
return Ok(response);
|
||||
}
|
||||
let auth = load_remote_control_auth(auth_manager).await?;
|
||||
send_client_management_request_once(&auth, &request, action).await
|
||||
}
|
||||
|
||||
async fn send_client_management_request_once(
|
||||
auth: &RemoteControlConnectionAuth,
|
||||
request: &ClientManagementRequest<'_>,
|
||||
action: &str,
|
||||
) -> io::Result<ClientManagementResponse> {
|
||||
let endpoint = match request {
|
||||
ClientManagementRequest::List { url, .. } | ClientManagementRequest::Revoke { url } => {
|
||||
url.as_str()
|
||||
}
|
||||
};
|
||||
let (client, auth_headers) = auth.request_context(endpoint).await?;
|
||||
let request = match request {
|
||||
ClientManagementRequest::List { url, params } => {
|
||||
let mut query = Vec::new();
|
||||
if let Some(cursor) = ¶ms.cursor {
|
||||
query.push(("cursor", cursor.clone()));
|
||||
}
|
||||
if let Some(limit) = params.limit {
|
||||
query.push(("limit", limit.to_string()));
|
||||
}
|
||||
if let Some(order) = params.order {
|
||||
query.push((
|
||||
"order",
|
||||
match order {
|
||||
RemoteControlClientsListOrder::Asc => "asc",
|
||||
RemoteControlClientsListOrder::Desc => "desc",
|
||||
}
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
let mut url = (*url).clone();
|
||||
url.query_pairs_mut().extend_pairs(query);
|
||||
client.get(url)
|
||||
}
|
||||
ClientManagementRequest::Revoke { url } => client.delete((*url).clone()),
|
||||
};
|
||||
let response = request
|
||||
.timeout(REMOTE_CONTROL_CLIENT_MANAGEMENT_TIMEOUT)
|
||||
.headers(auth_headers)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
codex_http_client::HttpError::Policy(_) => super::auth::request_error(error),
|
||||
error => io::Error::other(format!("failed to {action}: {error}")),
|
||||
})?;
|
||||
let headers = response.headers().clone();
|
||||
let status = response.status();
|
||||
let body = response
|
||||
.bytes()
|
||||
.await
|
||||
.map_err(super::auth::request_error)?
|
||||
.to_vec();
|
||||
Ok(ClientManagementResponse {
|
||||
status,
|
||||
headers,
|
||||
body,
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_success_response(
|
||||
status: axum::http::StatusCode,
|
||||
headers: &HeaderMap,
|
||||
url: &Url,
|
||||
body_preview: &str,
|
||||
response_kind: &str,
|
||||
) -> io::Result<()> {
|
||||
if status.is_success() {
|
||||
return Ok(());
|
||||
}
|
||||
let error_kind = match status.as_u16() {
|
||||
400 => ErrorKind::InvalidInput,
|
||||
401 | 403 => ErrorKind::PermissionDenied,
|
||||
404 => ErrorKind::NotFound,
|
||||
_ => ErrorKind::Other,
|
||||
};
|
||||
Err(io::Error::new(
|
||||
error_kind,
|
||||
format!(
|
||||
"remote control {response_kind} failed at `{url}`: HTTP {status}, {}, body: {body_preview}",
|
||||
format_headers(headers)
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
fn environment_clients_url(remote_control_url: &str, environment_id: &str) -> io::Result<Url> {
|
||||
let mut url = normalize_remote_control_base_url(remote_control_url)?
|
||||
.join("wham/remote/control/environments")
|
||||
.map_err(io::Error::other)?;
|
||||
url.path_segments_mut()
|
||||
.map_err(|()| {
|
||||
io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
"remote control URL cannot be a base",
|
||||
)
|
||||
})?
|
||||
.push(environment_id)
|
||||
.push("clients");
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
impl TryFrom<RemoteControlClientResponse> for RemoteControlClient {
|
||||
type Error = io::Error;
|
||||
|
||||
fn try_from(client: RemoteControlClientResponse) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
client_id: client.client_id,
|
||||
display_name: client.display_name,
|
||||
device_type: client.device_type,
|
||||
platform: client.platform,
|
||||
os_version: client.os_version,
|
||||
device_model: client.device_model,
|
||||
app_version: client.app_version,
|
||||
last_seen_at: client
|
||||
.last_seen_at
|
||||
.map(|last_seen_at| {
|
||||
OffsetDateTime::parse(&last_seen_at, &Rfc3339)
|
||||
.map(OffsetDateTime::unix_timestamp)
|
||||
.map_err(|err| {
|
||||
io::Error::new(
|
||||
ErrorKind::InvalidData,
|
||||
format!(
|
||||
"failed to parse remote control client last_seen_at `{last_seen_at}`: {err}"
|
||||
),
|
||||
)
|
||||
})
|
||||
})
|
||||
.transpose()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,369 +0,0 @@
|
||||
//! Owns the current login's relay session and the process-facing handle.
|
||||
//! Replacement happens before cleanup; retired sessions cannot publish into their replacements.
|
||||
|
||||
use super::auth::RemoteControlAuth;
|
||||
use super::*;
|
||||
use futures::FutureExt;
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use tokio_util::task::TaskTracker;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RemoteControlHandle {
|
||||
pub(super) inner: Arc<RemoteControl>,
|
||||
}
|
||||
|
||||
struct CurrentSession {
|
||||
authenticated: bool,
|
||||
session: Arc<RemoteControlSession>,
|
||||
}
|
||||
|
||||
pub(super) struct RemoteControl {
|
||||
config: RemoteControlStartConfig,
|
||||
state_db: Option<Arc<StateRuntime>>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
shutdown: CancellationToken,
|
||||
tasks: TaskTracker,
|
||||
current: StdMutex<Option<CurrentSession>>,
|
||||
startup: RemoteControlDesiredState,
|
||||
persistence: RemoteControlPersistence,
|
||||
client_name: RemoteControlPairingPersistenceKey,
|
||||
requires_client_name: bool,
|
||||
status: watch::Sender<RemoteControlStatusChangedNotification>,
|
||||
session_changed: watch::Sender<()>,
|
||||
}
|
||||
|
||||
impl RemoteControl {
|
||||
pub(super) fn session(&self) -> Arc<RemoteControlSession> {
|
||||
let mut current = self
|
||||
.current
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(current) = current.as_ref()
|
||||
&& current.session.auth_manager.owner.is_current()
|
||||
{
|
||||
return current.session.clone();
|
||||
}
|
||||
let (auth, authenticated) =
|
||||
RemoteControlAuth::capture(self.auth_manager.clone(), self.config.runtime_auth.clone());
|
||||
let desired = match current.take() {
|
||||
Some(previous) => {
|
||||
previous.session.shutdown_token.cancel();
|
||||
if previous.authenticated {
|
||||
RemoteControlDesiredState::Disabled
|
||||
} else {
|
||||
// Startup or an explicit enable while signed out may wait for first login.
|
||||
*previous.session.desired_state_tx.borrow()
|
||||
}
|
||||
}
|
||||
None => self.startup,
|
||||
};
|
||||
let session = self.start_session(auth, desired);
|
||||
self.status.send_replace(session.status());
|
||||
*current = Some(CurrentSession {
|
||||
authenticated,
|
||||
session: session.clone(),
|
||||
});
|
||||
self.session_changed.send_replace(());
|
||||
session
|
||||
}
|
||||
|
||||
fn start_session(
|
||||
&self,
|
||||
auth_manager: RemoteControlAuth,
|
||||
desired: RemoteControlDesiredState,
|
||||
) -> Arc<RemoteControlSession> {
|
||||
let shutdown = self.shutdown.child_token();
|
||||
let (desired_state_tx, _) = watch::channel(desired);
|
||||
let desired_state_tx = Arc::new(desired_state_tx);
|
||||
let current_enrollment =
|
||||
Arc::new(RemoteControlEnrollmentState::new(/*enrollment*/ None));
|
||||
let server_name = gethostname().to_string_lossy().trim().to_string();
|
||||
let (status_tx, _) = watch::channel(RemoteControlStatusChangedNotification {
|
||||
status: if desired.is_enabled() {
|
||||
RemoteControlConnectionStatus::Connecting
|
||||
} else {
|
||||
RemoteControlConnectionStatus::Disabled
|
||||
},
|
||||
server_name: server_name.clone(),
|
||||
installation_id: self.config.installation_id.clone(),
|
||||
environment_id: None,
|
||||
});
|
||||
let session = Arc::new(RemoteControlSession {
|
||||
policy: self.config.policy,
|
||||
shutdown_token: shutdown.clone(),
|
||||
desired_state_tx: desired_state_tx.clone(),
|
||||
desired_state_rpc_lock: Arc::new(Semaphore::new(1)),
|
||||
persistence: self.persistence.clone(),
|
||||
status_tx: Arc::new(status_tx.clone()),
|
||||
state_db: self.state_db.clone(),
|
||||
remote_control_url: self.config.remote_control_url.clone(),
|
||||
current_enrollment: current_enrollment.clone(),
|
||||
pairing_persistence_key: self.client_name.clone(),
|
||||
pairing_persistence_key_required: self.requires_client_name,
|
||||
auth_manager: auth_manager.clone(),
|
||||
});
|
||||
let websocket = RemoteControlWebsocket::new(
|
||||
websocket::RemoteControlWebsocketConfig {
|
||||
remote_control_url: self.config.remote_control_url.clone(),
|
||||
installation_id: self.config.installation_id.clone(),
|
||||
remote_control_target: None,
|
||||
server_name,
|
||||
},
|
||||
self.state_db.clone(),
|
||||
auth_manager,
|
||||
RemoteControlChannels {
|
||||
transport_event_tx: self.transport_event_tx.clone(),
|
||||
status_publisher: RemoteControlStatusPublisher::new(status_tx),
|
||||
current_enrollment,
|
||||
pairing_persistence_key: self.client_name.clone(),
|
||||
persistence: self.persistence.clone(),
|
||||
},
|
||||
shutdown.clone(),
|
||||
desired_state_tx,
|
||||
);
|
||||
let client_name_rx = if self.requires_client_name {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let mut names = self.client_name.subscribe();
|
||||
self.tasks.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = shutdown.cancelled() => {}
|
||||
name = names.wait_for(Option::is_some) => {
|
||||
if let Ok(name) = name
|
||||
&& let Some(name) = name.as_ref()
|
||||
{
|
||||
let _ = tx.send(name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Some(rx)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let process_shutdown = self.shutdown.clone();
|
||||
let failed_session = session.clone();
|
||||
self.tasks.spawn(async move {
|
||||
if let Err(panic) = AssertUnwindSafe(websocket.run(client_name_rx))
|
||||
.catch_unwind()
|
||||
.await
|
||||
{
|
||||
tracing::error!("remote control websocket task panicked");
|
||||
failed_session.publish_status(RemoteControlConnectionStatus::Disabled);
|
||||
process_shutdown.cancel();
|
||||
std::panic::resume_unwind(panic);
|
||||
}
|
||||
});
|
||||
session
|
||||
}
|
||||
}
|
||||
|
||||
impl RemoteControlSession {
|
||||
async fn run<T>(
|
||||
&self,
|
||||
operation: impl std::future::Future<Output = io::Result<T>>,
|
||||
) -> io::Result<T> {
|
||||
self.auth_manager.ensure_current()?;
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.auth_manager.owner.invalidated() => {
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "remote control authentication changed"))
|
||||
}
|
||||
result = operation => {
|
||||
self.auth_manager.ensure_current()?;
|
||||
result
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RemoteControlHandle {
|
||||
pub fn ensure_remote_control_allowed(&self) -> Result<(), RemoteControlDisabledByRequirements> {
|
||||
self.inner.session().ensure_remote_control_allowed()
|
||||
}
|
||||
|
||||
pub fn status(&self) -> RemoteControlStatusChangedNotification {
|
||||
self.inner.session().status()
|
||||
}
|
||||
|
||||
pub fn status_receiver(&self) -> watch::Receiver<RemoteControlStatusChangedNotification> {
|
||||
self.inner.session();
|
||||
self.inner.status.subscribe()
|
||||
}
|
||||
|
||||
pub fn enable_ephemeral(
|
||||
&self,
|
||||
) -> Result<RemoteControlStatusChangedNotification, RemoteControlEnableError> {
|
||||
self.inner.session().enable_ephemeral()
|
||||
}
|
||||
|
||||
pub async fn disable_ephemeral(&self) -> RemoteControlStatusChangedNotification {
|
||||
self.inner.session().disable_ephemeral().await
|
||||
}
|
||||
|
||||
pub async fn enable(
|
||||
&self,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> io::Result<RemoteControlStatusChangedNotification> {
|
||||
let session = self.inner.session();
|
||||
session.run(session.enable(app_server_client_name)).await
|
||||
}
|
||||
|
||||
pub async fn disable(
|
||||
&self,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> io::Result<RemoteControlStatusChangedNotification> {
|
||||
let session = self.inner.session();
|
||||
session.run(session.disable(app_server_client_name)).await
|
||||
}
|
||||
|
||||
pub async fn resolve_persisted_preference(
|
||||
&self,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> io::Result<bool> {
|
||||
let session = self.inner.session();
|
||||
session
|
||||
.run(session.resolve_persisted_preference(app_server_client_name))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn start_pairing(
|
||||
&self,
|
||||
params: RemoteControlPairingStartParams,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> io::Result<RemoteControlPairingStartResponse> {
|
||||
let session = self.inner.session();
|
||||
session
|
||||
.run(session.start_pairing(params, app_server_client_name))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn pairing_status(
|
||||
&self,
|
||||
params: RemoteControlPairingStatusParams,
|
||||
) -> io::Result<RemoteControlPairingStatusResponse> {
|
||||
let session = self.inner.session();
|
||||
session.run(session.pairing_status(params)).await
|
||||
}
|
||||
|
||||
pub async fn list_clients(
|
||||
&self,
|
||||
params: RemoteControlClientsListParams,
|
||||
) -> io::Result<RemoteControlClientsListResponse> {
|
||||
let session = self.inner.session();
|
||||
session.run(session.list_clients(params)).await
|
||||
}
|
||||
|
||||
pub async fn revoke_client(
|
||||
&self,
|
||||
params: RemoteControlClientsRevokeParams,
|
||||
) -> io::Result<RemoteControlClientsRevokeResponse> {
|
||||
let session = self.inner.session();
|
||||
session.run(session.revoke_client(params)).await
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start_remote_control(
|
||||
config: RemoteControlStartConfig,
|
||||
state_db: Option<Arc<StateRuntime>>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
shutdown_token: CancellationToken,
|
||||
app_server_client_name_rx: Option<oneshot::Receiver<String>>,
|
||||
startup_mode: RemoteControlStartupMode,
|
||||
) -> io::Result<(JoinHandle<()>, RemoteControlHandle)> {
|
||||
let startup =
|
||||
if config.policy == RemoteControlPolicy::DisabledByRequirements || state_db.is_none() {
|
||||
RemoteControlDesiredState::Disabled
|
||||
} else {
|
||||
match startup_mode {
|
||||
RemoteControlStartupMode::ResolvePersisted => RemoteControlDesiredState::Unknown,
|
||||
RemoteControlStartupMode::DisabledEphemeral => RemoteControlDesiredState::Disabled,
|
||||
RemoteControlStartupMode::EnabledEphemeral => {
|
||||
normalize_remote_control_url(&config.remote_control_url)?;
|
||||
RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let (status, _) = watch::channel(RemoteControlStatusChangedNotification {
|
||||
status: RemoteControlConnectionStatus::Disabled,
|
||||
server_name: gethostname().to_string_lossy().trim().to_string(),
|
||||
installation_id: config.installation_id.clone(),
|
||||
environment_id: None,
|
||||
});
|
||||
let inner = Arc::new(RemoteControl {
|
||||
config,
|
||||
state_db,
|
||||
auth_manager,
|
||||
transport_event_tx,
|
||||
shutdown: shutdown_token,
|
||||
tasks: TaskTracker::new(),
|
||||
current: StdMutex::new(None),
|
||||
startup,
|
||||
persistence: RemoteControlPersistence::default(),
|
||||
client_name: watch::channel(None).0,
|
||||
requires_client_name: app_server_client_name_rx.is_some(),
|
||||
status,
|
||||
session_changed: watch::channel(()).0,
|
||||
});
|
||||
inner.session();
|
||||
if let Some(rx) = app_server_client_name_rx {
|
||||
let names = inner.client_name.clone();
|
||||
let shutdown = inner.shutdown.clone();
|
||||
inner.tasks.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = shutdown.cancelled() => {}
|
||||
name = rx => match name {
|
||||
Ok(name) => { names.send_replace(Some(name)); }
|
||||
Err(_) => shutdown.cancel(),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let handle = RemoteControlHandle {
|
||||
inner: inner.clone(),
|
||||
};
|
||||
let task = tokio::spawn(async move {
|
||||
let mut session_changed = inner.session_changed.subscribe();
|
||||
loop {
|
||||
// Reconcile on both API entry and notification delivery, so watcher latency is harmless.
|
||||
let session = inner.session();
|
||||
let mut status = session.status_receiver();
|
||||
session_changed.borrow_and_update();
|
||||
{
|
||||
let current = inner
|
||||
.current
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if current
|
||||
.as_ref()
|
||||
.is_some_and(|current| Arc::ptr_eq(¤t.session, &session))
|
||||
&& session.auth_manager.owner.is_current()
|
||||
{
|
||||
inner.status.send_if_modified(|current| {
|
||||
let next = status.borrow_and_update().clone();
|
||||
if *current == next {
|
||||
return false;
|
||||
}
|
||||
*current = next;
|
||||
true
|
||||
});
|
||||
}
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = inner.shutdown.cancelled() => break,
|
||||
_ = session.auth_manager.owner.invalidated() => {}
|
||||
_ = session_changed.changed() => {}
|
||||
_ = status.changed() => {}
|
||||
}
|
||||
}
|
||||
inner.tasks.close();
|
||||
inner.tasks.wait().await;
|
||||
inner.persistence.tasks.close();
|
||||
inner.persistence.tasks.wait().await;
|
||||
});
|
||||
Ok((task, handle))
|
||||
}
|
||||
@@ -1,155 +0,0 @@
|
||||
use super::RemoteControlEnableError;
|
||||
use super::RemoteControlSession;
|
||||
use super::RemoteControlUnavailable;
|
||||
use super::protocol::normalize_remote_control_url;
|
||||
use super::publish_current_enrollment;
|
||||
use super::websocket::RemoteControlStatusPublisher;
|
||||
use codex_app_server_protocol::RemoteControlStatusChangedNotification;
|
||||
use codex_state::RemoteControlEnrollmentRecord;
|
||||
use std::io;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum RemoteControlDesiredState {
|
||||
// `Unknown` exists only on plain startup before auth and enrollment scope resolve. Persisted
|
||||
// `1` is `Enabled { persistence_preference: Some(true) }`; `0`, `NULL`, or no row are
|
||||
// `Disabled`. Runtime-only enable is `Enabled { persistence_preference: None }`, so new rows
|
||||
// keep `NULL`; durable RPC enable uses `Some(true)`, so new rows get `1`. Durable disable writes
|
||||
// `0` before entering `Disabled`; runtime-only disable does not write. `Disabled` carries no
|
||||
// preference because disabled sessions do not create enrollments.
|
||||
Unknown,
|
||||
Disabled,
|
||||
Enabled {
|
||||
persistence_preference: Option<bool>,
|
||||
},
|
||||
}
|
||||
impl RemoteControlDesiredState {
|
||||
pub(super) fn is_enabled(self) -> bool {
|
||||
matches!(self, Self::Enabled { .. })
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn desired_state_from_persisted_enrollment(
|
||||
enrollment: Option<RemoteControlEnrollmentRecord>,
|
||||
) -> RemoteControlDesiredState {
|
||||
if enrollment.and_then(|enrollment| enrollment.remote_control_enabled) == Some(true) {
|
||||
RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: Some(true),
|
||||
}
|
||||
} else {
|
||||
RemoteControlDesiredState::Disabled
|
||||
}
|
||||
}
|
||||
|
||||
impl RemoteControlSession {
|
||||
pub async fn resolve_persisted_preference(
|
||||
&self,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> io::Result<bool> {
|
||||
if self.ensure_remote_control_allowed().is_err() {
|
||||
return Ok(false);
|
||||
}
|
||||
let _transition = self
|
||||
.desired_state_rpc_lock
|
||||
.acquire()
|
||||
.await
|
||||
.unwrap_or_else(|_| unreachable!());
|
||||
if !matches!(
|
||||
*self.desired_state_tx.borrow(),
|
||||
RemoteControlDesiredState::Unknown
|
||||
) {
|
||||
return Ok(self.desired_state_tx.borrow().is_enabled());
|
||||
}
|
||||
|
||||
let state_db = self
|
||||
.state_db
|
||||
.as_deref()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, RemoteControlUnavailable))?;
|
||||
let auth = super::auth::load_remote_control_auth(&self.auth_manager).await?;
|
||||
let remote_control_target = normalize_remote_control_url(&self.remote_control_url)?;
|
||||
let app_server_client_name = self.pairing_persistence_key(app_server_client_name)?;
|
||||
let _persistence =
|
||||
super::persistence::read_lock(&self.auth_manager, &self.persistence).await?;
|
||||
let enrollment = state_db
|
||||
.get_remote_control_enrollment(
|
||||
&remote_control_target.websocket_url,
|
||||
&auth.account_id,
|
||||
app_server_client_name.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
let desired_state = desired_state_from_persisted_enrollment(enrollment);
|
||||
self.desired_state_tx.send_if_modified(|state| {
|
||||
if !matches!(*state, RemoteControlDesiredState::Unknown) {
|
||||
return false;
|
||||
}
|
||||
*state = desired_state;
|
||||
true
|
||||
});
|
||||
Ok(self.desired_state_tx.borrow().is_enabled())
|
||||
}
|
||||
|
||||
pub async fn enable(
|
||||
&self,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> io::Result<RemoteControlStatusChangedNotification> {
|
||||
self.ensure_remote_control_allowed()
|
||||
.map_err(|err| io::Error::new(io::ErrorKind::PermissionDenied, err))?;
|
||||
let _transition = self
|
||||
.desired_state_rpc_lock
|
||||
.acquire()
|
||||
.await
|
||||
.unwrap_or_else(|_| unreachable!());
|
||||
let state_db = self
|
||||
.state_db
|
||||
.as_deref()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, RemoteControlUnavailable))?;
|
||||
let mut auth = super::auth::load_remote_control_auth(&self.auth_manager).await?;
|
||||
let remote_control_target = normalize_remote_control_url(&self.remote_control_url)?;
|
||||
let app_server_client_name = self.pairing_persistence_key(app_server_client_name)?;
|
||||
let app_server_client_name = app_server_client_name.as_deref();
|
||||
let status = self.status();
|
||||
let mut current_enrollment = self.current_enrollment.lock().await;
|
||||
let (enrollment, _) = self
|
||||
.load_or_enroll_server(
|
||||
¤t_enrollment,
|
||||
&mut auth,
|
||||
&status.installation_id,
|
||||
&status.server_name,
|
||||
app_server_client_name,
|
||||
super::RemoteControlEnrollmentSelection::ReuseOrCreate,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let current_auth = super::auth::load_remote_control_auth(&self.auth_manager).await?;
|
||||
if current_auth.account_id != auth.account_id {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"remote control account changed during enrollment",
|
||||
));
|
||||
}
|
||||
|
||||
self.set_preference(
|
||||
state_db,
|
||||
&remote_control_target,
|
||||
&auth.account_id,
|
||||
app_server_client_name,
|
||||
/*enabled*/ true,
|
||||
Some(&enrollment),
|
||||
)
|
||||
.await?;
|
||||
publish_current_enrollment(&mut current_enrollment, &enrollment);
|
||||
self.enable_with_preference(Some(true)).map_err(|err| {
|
||||
let kind = match err {
|
||||
RemoteControlEnableError::Unavailable(_) => io::ErrorKind::NotFound,
|
||||
RemoteControlEnableError::AuthenticationChanged => io::ErrorKind::Interrupted,
|
||||
RemoteControlEnableError::DisabledByRequirements(_) => {
|
||||
io::ErrorKind::PermissionDenied
|
||||
}
|
||||
};
|
||||
io::Error::new(kind, err)
|
||||
})?;
|
||||
RemoteControlStatusPublisher::new(self.status_tx.as_ref().clone())
|
||||
.publish_environment_id(Some(enrollment.environment_id));
|
||||
Ok(self.status())
|
||||
}
|
||||
}
|
||||
@@ -1,782 +0,0 @@
|
||||
use super::auth::request_client;
|
||||
use super::pairing_unavailable_error;
|
||||
use super::protocol::RemoteControlPairingStatusRequest;
|
||||
use super::protocol::RemoteControlPairingStatusResponse as BackendRemoteControlPairingStatusResponse;
|
||||
use super::protocol::RemoteControlTarget;
|
||||
use super::protocol::StartRemoteControlPairingRequest;
|
||||
use super::protocol::StartRemoteControlPairingResponse;
|
||||
use super::server_api::RemoteControlServerRequestError;
|
||||
use super::server_api::retry_after_with_jitter;
|
||||
use axum::http::HeaderMap;
|
||||
use axum::http::StatusCode;
|
||||
use codex_app_server_protocol::RemoteControlPairingStartResponse;
|
||||
use codex_app_server_protocol::RemoteControlPairingStatusResponse;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_state::RemoteControlEnrollmentRecord;
|
||||
use codex_state::StateRuntime;
|
||||
use std::io;
|
||||
use std::io::ErrorKind;
|
||||
use time::OffsetDateTime;
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
const REMOTE_CONTROL_PAIRING_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
const REMOTE_CONTROL_RESPONSE_BODY_MAX_BYTES: usize = 4096;
|
||||
const REMOTE_CONTROL_SERVER_TOKEN_REFRESH_SKEW_SECS: i64 = 5 * 60;
|
||||
|
||||
const REQUEST_ID_HEADER: &str = "x-request-id";
|
||||
const OAI_REQUEST_ID_HEADER: &str = "x-oai-request-id";
|
||||
const CF_RAY_HEADER: &str = "cf-ray";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) struct RemoteControlEnrollment {
|
||||
pub(super) remote_control_target: RemoteControlTarget,
|
||||
pub(super) account_id: String,
|
||||
pub(super) environment_id: String,
|
||||
pub(super) server_id: String,
|
||||
pub(super) server_name: String,
|
||||
pub(super) remote_control_token: Option<String>,
|
||||
pub(super) expires_at: Option<OffsetDateTime>,
|
||||
pub(super) next_refresh_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum RemoteControlServerTokenRefreshRequirement {
|
||||
Required,
|
||||
Proactive,
|
||||
NotNeeded,
|
||||
}
|
||||
|
||||
impl RemoteControlEnrollment {
|
||||
pub(super) async fn start_pairing(
|
||||
&self,
|
||||
http_client_factory: &HttpClientFactory,
|
||||
request: StartRemoteControlPairingRequest,
|
||||
) -> io::Result<RemoteControlPairingStartResponse> {
|
||||
if self.server_token_refresh_requirement()
|
||||
== RemoteControlServerTokenRefreshRequirement::Required
|
||||
{
|
||||
return Err(pairing_unavailable_error());
|
||||
}
|
||||
let remote_control_token = self
|
||||
.remote_control_token
|
||||
.as_deref()
|
||||
.ok_or_else(pairing_unavailable_error)?;
|
||||
|
||||
let response = request_client(http_client_factory, &self.remote_control_target.pair_url)
|
||||
.await?
|
||||
.post(&self.remote_control_target.pair_url)
|
||||
.timeout(REMOTE_CONTROL_PAIRING_TIMEOUT)
|
||||
.bearer_auth(remote_control_token)
|
||||
.json(&request)
|
||||
.send()
|
||||
.await
|
||||
.map_err(super::auth::request_error)?;
|
||||
let headers = response.headers().clone();
|
||||
let status = response.status();
|
||||
let retry_at = retry_after_with_jitter(&headers, OffsetDateTime::now_utc());
|
||||
let body = response.bytes().await.map_err(|err| {
|
||||
if matches!(err, codex_http_client::HttpError::Policy(_))
|
||||
&& !(retry_at.is_some() && matches!(status.as_u16(), 429 | 503))
|
||||
{
|
||||
return super::auth::request_error(err);
|
||||
}
|
||||
pairing_response_error(
|
||||
format!(
|
||||
"failed to read remote control pairing response from `{}`: {err}",
|
||||
self.remote_control_target.pair_url
|
||||
),
|
||||
status,
|
||||
retry_at,
|
||||
ErrorKind::Other,
|
||||
)
|
||||
})?;
|
||||
let body_preview = preview_remote_control_response_body(&body);
|
||||
if !status.is_success() {
|
||||
let error_kind = match status.as_u16() {
|
||||
401 | 403 => ErrorKind::PermissionDenied,
|
||||
404 => ErrorKind::NotFound,
|
||||
_ => ErrorKind::Other,
|
||||
};
|
||||
return Err(pairing_response_error(
|
||||
format!(
|
||||
"remote control pairing failed at `{}`: HTTP {status}, {}, body: {body_preview}",
|
||||
self.remote_control_target.pair_url,
|
||||
format_headers(&headers)
|
||||
),
|
||||
status,
|
||||
retry_at,
|
||||
error_kind,
|
||||
));
|
||||
}
|
||||
|
||||
let pairing = serde_json::from_slice::<StartRemoteControlPairingResponse>(&body).map_err(
|
||||
|err| {
|
||||
io::Error::other(format!(
|
||||
"failed to parse remote control pairing response from `{}`: HTTP {status}, {}, body: {body_preview}, decode error: {err}",
|
||||
self.remote_control_target.pair_url,
|
||||
format_headers(&headers)
|
||||
))
|
||||
},
|
||||
)?;
|
||||
let StartRemoteControlPairingResponse {
|
||||
pairing_code,
|
||||
manual_pairing_code,
|
||||
server_id,
|
||||
environment_id,
|
||||
expires_at,
|
||||
} = pairing;
|
||||
if server_id != self.server_id || environment_id != self.environment_id {
|
||||
return Err(io::Error::other(format!(
|
||||
"remote control pairing returned mismatched enrollment: expected server_id={}, environment_id={}; got server_id={}, environment_id={}",
|
||||
self.server_id, self.environment_id, server_id, environment_id
|
||||
)));
|
||||
}
|
||||
let expires_at = OffsetDateTime::parse(&expires_at, &Rfc3339)
|
||||
.map_err(|err| {
|
||||
io::Error::new(
|
||||
ErrorKind::InvalidData,
|
||||
format!(
|
||||
"failed to parse remote control pairing response from `{}`: HTTP {status}, {}, body: {body_preview}, expires_at parse error: {err}",
|
||||
self.remote_control_target.pair_url,
|
||||
format_headers(&headers)
|
||||
),
|
||||
)
|
||||
})?
|
||||
.unix_timestamp();
|
||||
|
||||
Ok(RemoteControlPairingStartResponse {
|
||||
pairing_code,
|
||||
manual_pairing_code,
|
||||
environment_id,
|
||||
expires_at,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn pairing_status(
|
||||
&self,
|
||||
http_client_factory: &HttpClientFactory,
|
||||
request: RemoteControlPairingStatusRequest,
|
||||
) -> io::Result<RemoteControlPairingStatusResponse> {
|
||||
if self.server_token_refresh_requirement()
|
||||
== RemoteControlServerTokenRefreshRequirement::Required
|
||||
{
|
||||
return Err(pairing_unavailable_error());
|
||||
}
|
||||
let remote_control_token = self
|
||||
.remote_control_token
|
||||
.as_deref()
|
||||
.ok_or_else(pairing_unavailable_error)?;
|
||||
|
||||
let response = request_client(
|
||||
http_client_factory,
|
||||
&self.remote_control_target.pair_status_url,
|
||||
)
|
||||
.await?
|
||||
.post(&self.remote_control_target.pair_status_url)
|
||||
.timeout(REMOTE_CONTROL_PAIRING_TIMEOUT)
|
||||
.bearer_auth(remote_control_token)
|
||||
.json(&request)
|
||||
.send()
|
||||
.await
|
||||
.map_err(super::auth::request_error)?;
|
||||
let headers = response.headers().clone();
|
||||
let status = response.status();
|
||||
let retry_at = retry_after_with_jitter(&headers, OffsetDateTime::now_utc());
|
||||
let body = response.bytes().await.map_err(|err| {
|
||||
if matches!(err, codex_http_client::HttpError::Policy(_))
|
||||
&& !(retry_at.is_some() && matches!(status.as_u16(), 429 | 503))
|
||||
{
|
||||
return super::auth::request_error(err);
|
||||
}
|
||||
pairing_response_error(
|
||||
format!(
|
||||
"failed to read remote control pairing status response from `{}`: {err}",
|
||||
self.remote_control_target.pair_status_url
|
||||
),
|
||||
status,
|
||||
retry_at,
|
||||
ErrorKind::Other,
|
||||
)
|
||||
})?;
|
||||
let body_preview = preview_remote_control_response_body(&body);
|
||||
if !status.is_success() {
|
||||
let error_kind = match status.as_u16() {
|
||||
401 | 403 => ErrorKind::PermissionDenied,
|
||||
404 | 410 => ErrorKind::InvalidInput,
|
||||
_ => ErrorKind::Other,
|
||||
};
|
||||
return Err(pairing_response_error(
|
||||
format!(
|
||||
"remote control pairing status failed at `{}`: HTTP {status}, {}, body: {body_preview}",
|
||||
self.remote_control_target.pair_status_url,
|
||||
format_headers(&headers)
|
||||
),
|
||||
status,
|
||||
retry_at,
|
||||
error_kind,
|
||||
));
|
||||
}
|
||||
|
||||
let response = serde_json::from_slice::<BackendRemoteControlPairingStatusResponse>(&body)
|
||||
.map_err(|err| {
|
||||
io::Error::other(format!(
|
||||
"failed to parse remote control pairing status response from `{}`: HTTP {status}, {}, body: {body_preview}, decode error: {err}",
|
||||
self.remote_control_target.pair_status_url,
|
||||
format_headers(&headers)
|
||||
))
|
||||
})?;
|
||||
Ok(RemoteControlPairingStatusResponse {
|
||||
claimed: response.claimed,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn server_token_refresh_requirement(
|
||||
&self,
|
||||
) -> RemoteControlServerTokenRefreshRequirement {
|
||||
self.server_token_refresh_requirement_at(OffsetDateTime::now_utc())
|
||||
}
|
||||
|
||||
pub(super) fn should_refresh_server_token(&self) -> bool {
|
||||
self.server_token_refresh_requirement()
|
||||
!= RemoteControlServerTokenRefreshRequirement::NotNeeded
|
||||
}
|
||||
|
||||
pub(super) fn server_token_refresh_requirement_at(
|
||||
&self,
|
||||
now: OffsetDateTime,
|
||||
) -> RemoteControlServerTokenRefreshRequirement {
|
||||
let Some(expires_at) = self.remote_control_token.as_ref().and(self.expires_at) else {
|
||||
return RemoteControlServerTokenRefreshRequirement::Required;
|
||||
};
|
||||
if expires_at <= now {
|
||||
return RemoteControlServerTokenRefreshRequirement::Required;
|
||||
}
|
||||
if expires_at > now + time::Duration::seconds(REMOTE_CONTROL_SERVER_TOKEN_REFRESH_SKEW_SECS)
|
||||
|| self
|
||||
.next_refresh_at
|
||||
.is_some_and(|next_refresh_at| next_refresh_at > now)
|
||||
{
|
||||
return RemoteControlServerTokenRefreshRequirement::NotNeeded;
|
||||
}
|
||||
RemoteControlServerTokenRefreshRequirement::Proactive
|
||||
}
|
||||
|
||||
pub(super) fn clear_server_token(&mut self) {
|
||||
self.remote_control_token = None;
|
||||
self.expires_at = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn pairing_response_error(
|
||||
message: String,
|
||||
status: StatusCode,
|
||||
retry_at: Option<OffsetDateTime>,
|
||||
fallback_kind: ErrorKind,
|
||||
) -> io::Error {
|
||||
if matches!(
|
||||
status,
|
||||
StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE
|
||||
) {
|
||||
RemoteControlServerRequestError::io_error(
|
||||
message,
|
||||
Some(status),
|
||||
retry_at,
|
||||
/*timed_out*/ false,
|
||||
)
|
||||
} else {
|
||||
io::Error::new(fallback_kind, message)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn load_persisted_remote_control_enrollment(
|
||||
state_db: Option<&StateRuntime>,
|
||||
remote_control_target: &RemoteControlTarget,
|
||||
account_id: &str,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> io::Result<Option<RemoteControlEnrollment>> {
|
||||
let Some(state_db) = state_db else {
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::NotFound,
|
||||
format!(
|
||||
"remote control enrollment cache unavailable because sqlite state db is disabled: websocket_url={}, account_id={}, app_server_client_name={:?}",
|
||||
remote_control_target.websocket_url, account_id, app_server_client_name
|
||||
),
|
||||
));
|
||||
};
|
||||
let enrollment = match state_db
|
||||
.get_remote_control_enrollment(
|
||||
&remote_control_target.websocket_url,
|
||||
account_id,
|
||||
app_server_client_name,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(enrollment) => enrollment,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"failed to load persisted remote control enrollment: websocket_url={}, account_id={}, app_server_client_name={:?}, err={err}",
|
||||
remote_control_target.websocket_url, account_id, app_server_client_name
|
||||
);
|
||||
return Err(io::Error::other(err));
|
||||
}
|
||||
};
|
||||
|
||||
match enrollment {
|
||||
Some(enrollment) => {
|
||||
info!(
|
||||
"reusing persisted remote control enrollment: websocket_url={}, account_id={}, app_server_client_name={:?}, server_id={}, environment_id={}",
|
||||
remote_control_target.websocket_url,
|
||||
account_id,
|
||||
app_server_client_name,
|
||||
enrollment.server_id,
|
||||
enrollment.environment_id
|
||||
);
|
||||
Ok(Some(RemoteControlEnrollment {
|
||||
remote_control_target: remote_control_target.clone(),
|
||||
account_id: enrollment.account_id,
|
||||
environment_id: enrollment.environment_id,
|
||||
server_id: enrollment.server_id,
|
||||
server_name: enrollment.server_name,
|
||||
remote_control_token: None,
|
||||
expires_at: None,
|
||||
next_refresh_at: None,
|
||||
}))
|
||||
}
|
||||
None => {
|
||||
info!(
|
||||
"no persisted remote control enrollment found: websocket_url={}, account_id={}, app_server_client_name={:?}",
|
||||
remote_control_target.websocket_url, account_id, app_server_client_name
|
||||
);
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn update_persisted_remote_control_enrollment(
|
||||
state_db: Option<&StateRuntime>,
|
||||
remote_control_target: &RemoteControlTarget,
|
||||
account_id: &str,
|
||||
app_server_client_name: Option<&str>,
|
||||
enrollment: Option<&RemoteControlEnrollment>,
|
||||
remote_control_enabled: Option<bool>,
|
||||
) -> io::Result<()> {
|
||||
let Some(state_db) = state_db else {
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::NotFound,
|
||||
format!(
|
||||
"remote control enrollment persistence unavailable because sqlite state db is disabled: websocket_url={}, account_id={}, app_server_client_name={:?}, has_enrollment={}",
|
||||
remote_control_target.websocket_url,
|
||||
account_id,
|
||||
app_server_client_name,
|
||||
enrollment.is_some()
|
||||
),
|
||||
));
|
||||
};
|
||||
if let &Some(enrollment) = &enrollment
|
||||
&& enrollment.account_id != account_id
|
||||
{
|
||||
return Err(io::Error::other(format!(
|
||||
"enrollment account_id does not match expected account_id `{account_id}`"
|
||||
)));
|
||||
}
|
||||
|
||||
if let Some(enrollment) = enrollment {
|
||||
state_db
|
||||
.upsert_remote_control_enrollment(&RemoteControlEnrollmentRecord {
|
||||
websocket_url: remote_control_target.websocket_url.clone(),
|
||||
account_id: account_id.to_string(),
|
||||
app_server_client_name: app_server_client_name.map(str::to_string),
|
||||
server_id: enrollment.server_id.clone(),
|
||||
environment_id: enrollment.environment_id.clone(),
|
||||
server_name: enrollment.server_name.clone(),
|
||||
remote_control_enabled,
|
||||
})
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
info!(
|
||||
"persisted remote control enrollment: websocket_url={}, account_id={}, app_server_client_name={:?}, server_id={}, environment_id={}",
|
||||
remote_control_target.websocket_url,
|
||||
account_id,
|
||||
app_server_client_name,
|
||||
enrollment.server_id,
|
||||
enrollment.environment_id
|
||||
);
|
||||
Ok(())
|
||||
} else {
|
||||
let rows_affected = state_db
|
||||
.delete_remote_control_enrollment(
|
||||
&remote_control_target.websocket_url,
|
||||
account_id,
|
||||
app_server_client_name,
|
||||
)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
info!(
|
||||
"cleared persisted remote control enrollment: websocket_url={}, account_id={}, app_server_client_name={:?}, rows_affected={rows_affected}",
|
||||
remote_control_target.websocket_url, account_id, app_server_client_name
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn preview_remote_control_response_body(body: &[u8]) -> String {
|
||||
let body = String::from_utf8_lossy(body);
|
||||
let trimmed = body.trim();
|
||||
if trimmed.is_empty() {
|
||||
return "<empty>".to_string();
|
||||
}
|
||||
let redacted = redact_remote_control_response_body(trimmed);
|
||||
if redacted.len() <= REMOTE_CONTROL_RESPONSE_BODY_MAX_BYTES {
|
||||
return redacted;
|
||||
}
|
||||
|
||||
let mut cut = REMOTE_CONTROL_RESPONSE_BODY_MAX_BYTES;
|
||||
while !redacted.is_char_boundary(cut) {
|
||||
cut = cut.saturating_sub(1);
|
||||
}
|
||||
let mut truncated = redacted[..cut].to_string();
|
||||
truncated.push_str("...");
|
||||
truncated
|
||||
}
|
||||
|
||||
fn redact_remote_control_response_body(body: &str) -> String {
|
||||
let Ok(mut body_json) = serde_json::from_str::<serde_json::Value>(body) else {
|
||||
return body.to_string();
|
||||
};
|
||||
let Some(body_object) = body_json.as_object_mut() else {
|
||||
return body.to_string();
|
||||
};
|
||||
for sensitive_field in [
|
||||
"remote_control_token",
|
||||
"pairing_code",
|
||||
"manual_pairing_code",
|
||||
] {
|
||||
if let Some(value) = body_object.get_mut(sensitive_field) {
|
||||
*value = serde_json::Value::String("<redacted>".to_string());
|
||||
}
|
||||
}
|
||||
body_json.to_string()
|
||||
}
|
||||
|
||||
pub(crate) fn format_headers(headers: &HeaderMap) -> String {
|
||||
let request_id_str = headers
|
||||
.get(REQUEST_ID_HEADER)
|
||||
.or_else(|| headers.get(OAI_REQUEST_ID_HEADER))
|
||||
.map(|value| value.to_str().unwrap_or("<invalid utf-8>").to_owned())
|
||||
.unwrap_or_else(|| "<none>".to_owned());
|
||||
let cf_ray_str = headers
|
||||
.get(CF_RAY_HEADER)
|
||||
.map(|value| value.to_str().unwrap_or("<invalid utf-8>").to_owned())
|
||||
.unwrap_or_else(|| "<none>".to_owned());
|
||||
format!("request-id: {request_id_str}, cf-ray: {cf_ray_str}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::transport::remote_control::auth::RemoteControlConnectionAuth;
|
||||
use crate::transport::remote_control::protocol::normalize_remote_control_url;
|
||||
use crate::transport::remote_control::server_api::enroll_remote_control_server;
|
||||
use codex_state::StateRuntime;
|
||||
use codex_utils_absolute_path::test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
async fn remote_control_state_runtime(codex_home: &TempDir) -> Arc<StateRuntime> {
|
||||
StateRuntime::init(
|
||||
codex_state::SqliteConfig::new_for_testing(codex_home.path().abs()),
|
||||
"test-provider".to_string(),
|
||||
)
|
||||
.await
|
||||
.expect("state runtime should initialize")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_remote_control_response_body_redacts_server_token() {
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&preview_remote_control_response_body(
|
||||
br#"{"server_id":"srv_e_test","remote_control_token":"secret","pairing_code":"pairing-code","manual_pairing_code":"ABCD-EFGH"}"#
|
||||
))
|
||||
.expect("redacted response preview should stay valid json"),
|
||||
json!({
|
||||
"server_id": "srv_e_test",
|
||||
"remote_control_token": "<redacted>",
|
||||
"pairing_code": "<redacted>",
|
||||
"manual_pairing_code": "<redacted>",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn persisted_remote_control_enrollment_round_trips_by_target_and_account() {
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let first_target = normalize_remote_control_url("https://chatgpt.com/remote/control")
|
||||
.expect("first target should parse");
|
||||
let second_target =
|
||||
normalize_remote_control_url("https://api.chatgpt-staging.com/other/control")
|
||||
.expect("second target should parse");
|
||||
let first_enrollment = RemoteControlEnrollment {
|
||||
remote_control_target: first_target.clone(),
|
||||
account_id: "account-a".to_string(),
|
||||
environment_id: "env_first".to_string(),
|
||||
server_id: "srv_e_first".to_string(),
|
||||
server_name: "first-server".to_string(),
|
||||
remote_control_token: None,
|
||||
expires_at: None,
|
||||
next_refresh_at: None,
|
||||
};
|
||||
let second_enrollment = RemoteControlEnrollment {
|
||||
remote_control_target: second_target.clone(),
|
||||
account_id: "account-a".to_string(),
|
||||
environment_id: "env_second".to_string(),
|
||||
server_id: "srv_e_second".to_string(),
|
||||
server_name: "second-server".to_string(),
|
||||
remote_control_token: None,
|
||||
expires_at: None,
|
||||
next_refresh_at: None,
|
||||
};
|
||||
|
||||
update_persisted_remote_control_enrollment(
|
||||
Some(state_db.as_ref()),
|
||||
&first_target,
|
||||
"account-a",
|
||||
Some("desktop-client"),
|
||||
Some(&first_enrollment),
|
||||
/*remote_control_enabled*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("first enrollment should persist");
|
||||
update_persisted_remote_control_enrollment(
|
||||
Some(state_db.as_ref()),
|
||||
&second_target,
|
||||
"account-a",
|
||||
Some("desktop-client"),
|
||||
Some(&second_enrollment),
|
||||
/*remote_control_enabled*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("second enrollment should persist");
|
||||
|
||||
assert_eq!(
|
||||
load_persisted_remote_control_enrollment(
|
||||
Some(state_db.as_ref()),
|
||||
&first_target,
|
||||
"account-a",
|
||||
Some("desktop-client"),
|
||||
)
|
||||
.await
|
||||
.expect("first enrollment should load"),
|
||||
Some(first_enrollment.clone())
|
||||
);
|
||||
assert_eq!(
|
||||
load_persisted_remote_control_enrollment(
|
||||
Some(state_db.as_ref()),
|
||||
&first_target,
|
||||
"account-b",
|
||||
Some("desktop-client"),
|
||||
)
|
||||
.await
|
||||
.expect("missing account should load"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
load_persisted_remote_control_enrollment(
|
||||
Some(state_db.as_ref()),
|
||||
&second_target,
|
||||
"account-a",
|
||||
Some("desktop-client"),
|
||||
)
|
||||
.await
|
||||
.expect("second enrollment should load"),
|
||||
Some(second_enrollment)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn clearing_persisted_remote_control_enrollment_removes_only_matching_entry() {
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let first_target = normalize_remote_control_url("https://chatgpt.com/remote/control")
|
||||
.expect("first target should parse");
|
||||
let second_target =
|
||||
normalize_remote_control_url("https://api.chatgpt-staging.com/other/control")
|
||||
.expect("second target should parse");
|
||||
let first_enrollment = RemoteControlEnrollment {
|
||||
remote_control_target: first_target.clone(),
|
||||
account_id: "account-a".to_string(),
|
||||
environment_id: "env_first".to_string(),
|
||||
server_id: "srv_e_first".to_string(),
|
||||
server_name: "first-server".to_string(),
|
||||
remote_control_token: None,
|
||||
expires_at: None,
|
||||
next_refresh_at: None,
|
||||
};
|
||||
let second_enrollment = RemoteControlEnrollment {
|
||||
remote_control_target: second_target.clone(),
|
||||
account_id: "account-a".to_string(),
|
||||
environment_id: "env_second".to_string(),
|
||||
server_id: "srv_e_second".to_string(),
|
||||
server_name: "second-server".to_string(),
|
||||
remote_control_token: None,
|
||||
expires_at: None,
|
||||
next_refresh_at: None,
|
||||
};
|
||||
|
||||
update_persisted_remote_control_enrollment(
|
||||
Some(state_db.as_ref()),
|
||||
&first_target,
|
||||
"account-a",
|
||||
/*app_server_client_name*/ None,
|
||||
Some(&first_enrollment),
|
||||
/*remote_control_enabled*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("first enrollment should persist");
|
||||
update_persisted_remote_control_enrollment(
|
||||
Some(state_db.as_ref()),
|
||||
&second_target,
|
||||
"account-a",
|
||||
/*app_server_client_name*/ None,
|
||||
Some(&second_enrollment),
|
||||
/*remote_control_enabled*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("second enrollment should persist");
|
||||
|
||||
update_persisted_remote_control_enrollment(
|
||||
Some(state_db.as_ref()),
|
||||
&first_target,
|
||||
"account-a",
|
||||
/*app_server_client_name*/ None,
|
||||
/*enrollment*/ None,
|
||||
/*remote_control_enabled*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("matching enrollment should clear");
|
||||
|
||||
assert_eq!(
|
||||
load_persisted_remote_control_enrollment(
|
||||
Some(state_db.as_ref()),
|
||||
&first_target,
|
||||
"account-a",
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("cleared enrollment should load"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
load_persisted_remote_control_enrollment(
|
||||
Some(state_db.as_ref()),
|
||||
&second_target,
|
||||
"account-a",
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("remaining enrollment should load"),
|
||||
Some(second_enrollment)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn enroll_remote_control_server_parse_failure_includes_response_body() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = format!(
|
||||
"http://127.0.0.1:{}/backend-api/",
|
||||
listener
|
||||
.local_addr()
|
||||
.expect("listener should have a local addr")
|
||||
.port()
|
||||
);
|
||||
let remote_control_target =
|
||||
normalize_remote_control_url(&remote_control_url).expect("target should parse");
|
||||
let enroll_url = remote_control_target.enroll_url.clone();
|
||||
let response_body = json!({
|
||||
"server_id": "srv_e_test",
|
||||
"environment_id": "env_test",
|
||||
});
|
||||
let expected_body = response_body.to_string();
|
||||
let server_task = tokio::spawn(async move {
|
||||
let stream = accept_http_request(&listener).await;
|
||||
respond_with_json(stream, response_body).await;
|
||||
});
|
||||
|
||||
let err = enroll_remote_control_server(
|
||||
&remote_control_target,
|
||||
&RemoteControlConnectionAuth {
|
||||
http_client_factory: codex_http_client::HttpClientFactory::new(
|
||||
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
|
||||
),
|
||||
auth: codex_login::CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
runtime_auth: None,
|
||||
account_id: "account_id".to_string(),
|
||||
},
|
||||
"11111111-1111-4111-8111-111111111111",
|
||||
"test-server",
|
||||
)
|
||||
.await
|
||||
.expect_err("invalid response should fail to parse");
|
||||
|
||||
server_task.await.expect("server task should succeed");
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
format!(
|
||||
"failed to parse remote control server enrollment response from `{enroll_url}`: HTTP 200 OK, request-id: <none>, cf-ray: <none>, body: {expected_body}, decode error: missing field `remote_control_token` at line 1 column {}",
|
||||
expected_body.len()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
async fn accept_http_request(listener: &TcpListener) -> TcpStream {
|
||||
let (stream, _) = timeout(Duration::from_secs(5), listener.accept())
|
||||
.await
|
||||
.expect("HTTP request should arrive in time")
|
||||
.expect("listener accept should succeed");
|
||||
let mut reader = BufReader::new(stream);
|
||||
|
||||
let mut request_line = String::new();
|
||||
reader
|
||||
.read_line(&mut request_line)
|
||||
.await
|
||||
.expect("request line should read");
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
reader
|
||||
.read_line(&mut line)
|
||||
.await
|
||||
.expect("header line should read");
|
||||
if line == "\r\n" {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
reader.into_inner()
|
||||
}
|
||||
|
||||
async fn respond_with_json(mut stream: TcpStream, body: serde_json::Value) {
|
||||
let body = body.to_string();
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
);
|
||||
stream
|
||||
.write_all(response.as_bytes())
|
||||
.await
|
||||
.expect("response should write");
|
||||
stream.flush().await.expect("response should flush");
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
use serde::Deserialize;
|
||||
|
||||
pub(super) const REMOTE_CONTROL_HOST_DEVICE_KIND_HEADER: &str = "x-codex-host-device-kind";
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
const MAC_MINI_HOST_DEVICE_KIND: &str = "mac_mini";
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
#[derive(Deserialize)]
|
||||
struct MacHardwareProfile {
|
||||
#[serde(rename = "SPHardwareDataType")]
|
||||
hardware: Vec<MacHardware>,
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
#[derive(Deserialize)]
|
||||
struct MacHardware {
|
||||
machine_name: String,
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn host_device_kind_from_profile(profile: &[u8]) -> serde_json::Result<Option<&'static str>> {
|
||||
let profile: MacHardwareProfile = serde_json::from_slice(profile)?;
|
||||
Ok(profile
|
||||
.hardware
|
||||
.first()
|
||||
.is_some_and(|hardware| hardware.machine_name == "Mac mini")
|
||||
.then_some(MAC_MINI_HOST_DEVICE_KIND))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(super) async fn host_device_kind() -> Option<&'static str> {
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use tokio::process::Command;
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
static HOST_DEVICE_KIND: OnceCell<Option<&'static str>> = OnceCell::const_new();
|
||||
|
||||
HOST_DEVICE_KIND
|
||||
.get_or_try_init(|| async {
|
||||
let output = tokio::time::timeout(
|
||||
Duration::from_secs(2),
|
||||
Command::new("/usr/sbin/system_profiler")
|
||||
.args(["-detailLevel", "mini", "SPHardwareDataType", "-json"])
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.output(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ())?
|
||||
.map_err(|_| ())?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Err(());
|
||||
}
|
||||
|
||||
host_device_kind_from_profile(&output.stdout).map_err(|_| ())
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.copied()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub(super) async fn host_device_kind() -> Option<&'static str> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "host_device_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,38 +0,0 @@
|
||||
use super::host_device_kind_from_profile;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn recognizes_only_the_exact_mac_mini_hardware_name() {
|
||||
let mac_mini_profile = br#"{"SPHardwareDataType":[{"machine_name":"Mac mini"}]}"#;
|
||||
let macbook_profile = br#"{"SPHardwareDataType":[{"machine_name":"MacBook Pro"}]}"#;
|
||||
let misleading_profile = br#"{"SPHardwareDataType":[{"machine_name":"Not a Mac mini"}]}"#;
|
||||
|
||||
assert_eq!(
|
||||
host_device_kind_from_profile(mac_mini_profile).expect("valid Mac mini hardware profile"),
|
||||
Some("mac_mini")
|
||||
);
|
||||
assert_eq!(
|
||||
host_device_kind_from_profile(macbook_profile).expect("valid MacBook hardware profile"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
host_device_kind_from_profile(misleading_profile)
|
||||
.expect("valid non-Mac-mini hardware profile"),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_missing_hardware_profiles() {
|
||||
assert_eq!(
|
||||
host_device_kind_from_profile(br#"{"SPHardwareDataType":[]}"#)
|
||||
.expect("valid empty hardware profile"),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_malformed_hardware_profiles_so_they_remain_retryable() {
|
||||
assert!(host_device_kind_from_profile(br#"{"machine_name":"Mac mini"}"#).is_err());
|
||||
assert!(host_device_kind_from_profile(b"not json").is_err());
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,165 +0,0 @@
|
||||
//! Serializes enrollment storage across login sessions.
|
||||
//! An admitted SQLite write keeps its permit until completion even if its caller is cancelled.
|
||||
//! Process shutdown drains admitted writes after stopping the session workers.
|
||||
|
||||
use super::RemoteControlSession;
|
||||
use super::auth::RemoteControlAuth;
|
||||
use super::desired_state::RemoteControlDesiredState;
|
||||
use super::enroll::RemoteControlEnrollment;
|
||||
use super::enroll::update_persisted_remote_control_enrollment;
|
||||
use super::protocol::RemoteControlTarget;
|
||||
use codex_state::StateRuntime;
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::SemaphorePermit;
|
||||
use tokio::sync::watch;
|
||||
use tokio_util::task::TaskTracker;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "persistence_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct RemoteControlPersistence {
|
||||
semaphore: Arc<Semaphore>,
|
||||
pub(super) tasks: TaskTracker,
|
||||
}
|
||||
|
||||
impl Default for RemoteControlPersistence {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
semaphore: Arc::new(Semaphore::new(1)),
|
||||
tasks: TaskTracker::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RemoteControlPersistence {
|
||||
pub(super) async fn lock(&self) -> SemaphorePermit<'_> {
|
||||
self.semaphore
|
||||
.acquire()
|
||||
.await
|
||||
.unwrap_or_else(|_| unreachable!())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn read_lock<'a>(
|
||||
auth: &RemoteControlAuth,
|
||||
lock: &'a RemoteControlPersistence,
|
||||
) -> io::Result<SemaphorePermit<'a>> {
|
||||
let permit = lock.lock().await;
|
||||
auth.ensure_current()?;
|
||||
Ok(permit)
|
||||
}
|
||||
|
||||
async fn commit<T: Send + 'static>(
|
||||
auth: &RemoteControlAuth,
|
||||
lock: &RemoteControlPersistence,
|
||||
operation: impl Future<Output = io::Result<T>> + Send + 'static,
|
||||
) -> io::Result<T> {
|
||||
// Register before checking admission. Shutdown either observes this token or rejects us.
|
||||
let task = lock.tasks.token();
|
||||
if lock.tasks.is_closed() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"remote control is shutting down",
|
||||
));
|
||||
}
|
||||
let auth = auth.clone();
|
||||
let semaphore = lock.semaphore.clone();
|
||||
tokio::spawn(async move {
|
||||
let _task = task;
|
||||
let _permit = semaphore.acquire_owned().await.map_err(io::Error::other)?;
|
||||
auth.ensure_current()?;
|
||||
operation.await
|
||||
})
|
||||
.await
|
||||
.map_err(io::Error::other)?
|
||||
}
|
||||
|
||||
pub(super) async fn save_enrollment(
|
||||
auth: &RemoteControlAuth,
|
||||
lock: &RemoteControlPersistence,
|
||||
state_db: &StateRuntime,
|
||||
enrollment: &RemoteControlEnrollment,
|
||||
client_name: Option<&str>,
|
||||
desired: &watch::Sender<RemoteControlDesiredState>,
|
||||
) -> io::Result<()> {
|
||||
let state_db = state_db.clone();
|
||||
let enrollment = enrollment.clone();
|
||||
let client_name = client_name.map(str::to_owned);
|
||||
let desired = desired.clone();
|
||||
commit(auth, lock, async move {
|
||||
let preference = match *desired.borrow() {
|
||||
RemoteControlDesiredState::Enabled {
|
||||
persistence_preference,
|
||||
} => persistence_preference,
|
||||
RemoteControlDesiredState::Disabled | RemoteControlDesiredState::Unknown => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"remote control disabled during enrollment",
|
||||
));
|
||||
}
|
||||
};
|
||||
update_persisted_remote_control_enrollment(
|
||||
Some(&state_db),
|
||||
&enrollment.remote_control_target,
|
||||
&enrollment.account_id,
|
||||
client_name.as_deref(),
|
||||
Some(&enrollment),
|
||||
preference,
|
||||
)
|
||||
.await
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
impl RemoteControlSession {
|
||||
pub(super) async fn set_preference(
|
||||
&self,
|
||||
state_db: &StateRuntime,
|
||||
target: &RemoteControlTarget,
|
||||
account_id: &str,
|
||||
client_name: Option<&str>,
|
||||
enabled: bool,
|
||||
fallback_enrollment: Option<&RemoteControlEnrollment>,
|
||||
) -> io::Result<()> {
|
||||
let state_db = state_db.clone();
|
||||
let target = target.clone();
|
||||
let account_id = account_id.to_owned();
|
||||
let client_name = client_name.map(str::to_owned);
|
||||
let enrollment = fallback_enrollment.cloned();
|
||||
let desired = self.desired_state_tx.as_ref().clone();
|
||||
commit(&self.auth_manager, &self.persistence, async move {
|
||||
let updated = state_db
|
||||
.set_remote_control_enabled(
|
||||
&target.websocket_url,
|
||||
&account_id,
|
||||
client_name.as_deref(),
|
||||
enabled,
|
||||
)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
if updated == 0
|
||||
&& let Some(enrollment) = enrollment
|
||||
{
|
||||
update_persisted_remote_control_enrollment(
|
||||
Some(&state_db),
|
||||
&target,
|
||||
&account_id,
|
||||
client_name.as_deref(),
|
||||
Some(&enrollment),
|
||||
Some(enabled),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
if !enabled {
|
||||
desired.send_replace(RemoteControlDesiredState::Disabled);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
//! Checks the persistence boundary when an operation loses its caller.
|
||||
|
||||
use super::*;
|
||||
use codex_core::test_support::auth_manager_from_auth;
|
||||
use codex_login::CodexAuth;
|
||||
use futures::poll;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_commit_keeps_its_permit_and_is_drained() -> io::Result<()> {
|
||||
let auth = RemoteControlAuth::capture(
|
||||
auth_manager_from_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
|
||||
/*runtime_auth*/ None,
|
||||
)
|
||||
.0;
|
||||
let persistence = RemoteControlPersistence::default();
|
||||
let writes = Arc::new(tokio::sync::Mutex::new(Vec::new()));
|
||||
let (started_tx, started_rx) = oneshot::channel();
|
||||
let (release_tx, release_rx) = oneshot::channel();
|
||||
let old_writes = writes.clone();
|
||||
let mut old = Box::pin(commit(&auth, &persistence, async move {
|
||||
started_tx.send(()).expect("test receiver is open");
|
||||
release_rx.await.map_err(io::Error::other)?;
|
||||
old_writes.lock().await.push("old");
|
||||
Ok(())
|
||||
}));
|
||||
assert!(poll!(&mut old).is_pending());
|
||||
started_rx.await.map_err(io::Error::other)?;
|
||||
drop(old);
|
||||
|
||||
let new_writes = writes.clone();
|
||||
let mut new = Box::pin(commit(&auth, &persistence, async move {
|
||||
new_writes.lock().await.push("new");
|
||||
Ok(())
|
||||
}));
|
||||
assert!(poll!(&mut new).is_pending());
|
||||
persistence.tasks.close();
|
||||
let mut drained = Box::pin(persistence.tasks.wait());
|
||||
assert!(poll!(&mut drained).is_pending());
|
||||
release_tx.send(()).expect("commit still owns its receiver");
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), drained).await?;
|
||||
new.await?;
|
||||
assert_eq!(*writes.lock().await, vec!["old", "new"]);
|
||||
let error = commit::<()>(&auth, &persistence, async {
|
||||
panic!("closed storage must reject new work")
|
||||
})
|
||||
.await
|
||||
.expect_err("shutdown closes admission");
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,417 +0,0 @@
|
||||
use crate::outgoing_message::OutgoingMessage;
|
||||
use codex_app_server_protocol::ClientResponsePayload;
|
||||
use codex_app_server_protocol::JSONRPCMessage;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::io;
|
||||
use std::io::ErrorKind;
|
||||
use url::Host;
|
||||
use url::Url;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) struct RemoteControlTarget {
|
||||
pub(super) websocket_url: String,
|
||||
pub(super) enroll_url: String,
|
||||
pub(super) refresh_url: String,
|
||||
pub(super) pair_url: String,
|
||||
pub(super) pair_status_url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(super) struct EnrollRemoteServerRequest {
|
||||
pub(super) name: String,
|
||||
pub(super) os: &'static str,
|
||||
pub(super) arch: &'static str,
|
||||
pub(super) app_server_version: &'static str,
|
||||
pub(super) installation_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(super) struct EnrollRemoteServerResponse {
|
||||
pub(super) server_id: String,
|
||||
pub(super) environment_id: String,
|
||||
pub(super) remote_control_token: String,
|
||||
pub(super) expires_at: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(super) struct RefreshRemoteServerRequest {
|
||||
pub(super) server_id: String,
|
||||
pub(super) installation_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(super) struct StartRemoteControlPairingRequest {
|
||||
pub(super) manual_code: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(super) struct StartRemoteControlPairingResponse {
|
||||
pub(super) pairing_code: String,
|
||||
pub(super) manual_pairing_code: Option<String>,
|
||||
pub(super) server_id: String,
|
||||
pub(super) environment_id: String,
|
||||
pub(super) expires_at: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(super) struct RemoteControlPairingStatusRequest {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub(super) pairing_code: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub(super) manual_pairing_code: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) enum RemoteControlPairingStatusCode {
|
||||
PairingCode(String),
|
||||
ManualPairingCode(String),
|
||||
}
|
||||
|
||||
impl From<RemoteControlPairingStatusCode> for RemoteControlPairingStatusRequest {
|
||||
fn from(code: RemoteControlPairingStatusCode) -> Self {
|
||||
match code {
|
||||
RemoteControlPairingStatusCode::PairingCode(pairing_code) => Self {
|
||||
pairing_code: Some(pairing_code),
|
||||
manual_pairing_code: None,
|
||||
},
|
||||
RemoteControlPairingStatusCode::ManualPairingCode(manual_pairing_code) => Self {
|
||||
pairing_code: None,
|
||||
manual_pairing_code: Some(manual_pairing_code),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(super) struct RemoteControlPairingStatusResponse {
|
||||
pub(super) claimed: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct ClientId(pub String);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct StreamId(pub String);
|
||||
|
||||
impl StreamId {
|
||||
pub fn new_random() -> Self {
|
||||
Self(uuid::Uuid::now_v7().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ClientEvent {
|
||||
ClientMessage {
|
||||
message: JSONRPCMessage,
|
||||
},
|
||||
ClientMessageChunk {
|
||||
segment_id: usize,
|
||||
segment_count: usize,
|
||||
message_size_bytes: usize,
|
||||
message_chunk_base64: String,
|
||||
},
|
||||
/// Backend-generated acknowledgement for all server envelopes addressed to
|
||||
/// `client_id` and `stream_id` whose envelope `seq_id` is less than or equal
|
||||
/// to this ack's `seq_id`. Chunk acknowledgements carry `segment_id` so the
|
||||
/// sender can retain only the still-unacked wire chunks on reconnect.
|
||||
Ack {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
segment_id: Option<usize>,
|
||||
},
|
||||
Ping,
|
||||
ClientClosed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) struct ClientEnvelope {
|
||||
#[serde(flatten)]
|
||||
pub(crate) event: ClientEvent,
|
||||
#[serde(rename = "client_id")]
|
||||
pub(crate) client_id: ClientId,
|
||||
#[serde(rename = "stream_id", skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) stream_id: Option<StreamId>,
|
||||
/// For `Ack`, this is the backend-generated per-stream cursor over
|
||||
/// `ServerEnvelope.seq_id`.
|
||||
#[serde(rename = "seq_id", skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) seq_id: Option<u64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PongStatus {
|
||||
Active,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ServerEvent {
|
||||
ServerMessage {
|
||||
message: Box<OutgoingMessage>,
|
||||
},
|
||||
ServerMessageChunk {
|
||||
segment_id: usize,
|
||||
segment_count: usize,
|
||||
message_size_bytes: usize,
|
||||
message_chunk_base64: String,
|
||||
},
|
||||
#[allow(dead_code)]
|
||||
Ack,
|
||||
Pong {
|
||||
status: PongStatus,
|
||||
},
|
||||
}
|
||||
|
||||
impl ServerEvent {
|
||||
pub(super) fn item_list_response_id(&self) -> Option<&RequestId> {
|
||||
if let Self::ServerMessage { message } = self
|
||||
&& let OutgoingMessage::Response(response) = message.as_ref()
|
||||
&& matches!(
|
||||
response.result.as_ref(),
|
||||
ClientResponsePayload::ThreadItemsList(_)
|
||||
)
|
||||
{
|
||||
Some(&response.id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn segment_id(&self) -> Option<usize> {
|
||||
match self {
|
||||
Self::ServerMessageChunk { segment_id, .. } => Some(*segment_id),
|
||||
Self::ServerMessage { .. } | Self::Ack | Self::Pong { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) struct ServerEnvelope {
|
||||
#[serde(flatten)]
|
||||
pub(crate) event: ServerEvent,
|
||||
#[serde(rename = "client_id")]
|
||||
pub(crate) client_id: ClientId,
|
||||
#[serde(rename = "stream_id")]
|
||||
pub(crate) stream_id: StreamId,
|
||||
#[serde(rename = "seq_id")]
|
||||
pub(crate) seq_id: u64,
|
||||
}
|
||||
|
||||
fn is_allowed_remote_control_chatgpt_host(host: &Option<Host<&str>>) -> bool {
|
||||
let Some(Host::Domain(host)) = *host else {
|
||||
return false;
|
||||
};
|
||||
host == "chatgpt.com"
|
||||
|| host == "chatgpt-staging.com"
|
||||
|| host.ends_with(".chatgpt.com")
|
||||
|| host.ends_with(".chatgpt-staging.com")
|
||||
}
|
||||
|
||||
fn is_localhost(host: &Option<Host<&str>>) -> bool {
|
||||
match host {
|
||||
Some(Host::Domain("localhost")) => true,
|
||||
Some(Host::Ipv4(ip)) => ip.is_loopback(),
|
||||
Some(Host::Ipv6(ip)) => ip.is_loopback(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn normalize_remote_control_url(
|
||||
remote_control_url: &str,
|
||||
) -> io::Result<RemoteControlTarget> {
|
||||
let remote_control_url = normalize_remote_control_base_url(remote_control_url)?;
|
||||
let map_url_parse_error = |err: url::ParseError| -> io::Error {
|
||||
io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
format!("invalid remote control URL `{remote_control_url}`: {err}"),
|
||||
)
|
||||
};
|
||||
|
||||
let enroll_url = remote_control_url
|
||||
.join("wham/remote/control/server/enroll")
|
||||
.map_err(map_url_parse_error)?;
|
||||
let refresh_url = remote_control_url
|
||||
.join("wham/remote/control/server/refresh")
|
||||
.map_err(map_url_parse_error)?;
|
||||
let pair_url = remote_control_url
|
||||
.join("wham/remote/control/server/pair")
|
||||
.map_err(map_url_parse_error)?;
|
||||
let pair_status_url = remote_control_url
|
||||
.join("wham/remote/control/server/pair/status")
|
||||
.map_err(map_url_parse_error)?;
|
||||
let mut websocket_url = remote_control_url
|
||||
.join("wham/remote/control/server")
|
||||
.map_err(map_url_parse_error)?;
|
||||
websocket_url
|
||||
.set_scheme(if enroll_url.scheme() == "https" {
|
||||
"wss"
|
||||
} else {
|
||||
"ws"
|
||||
})
|
||||
.map_err(|()| {
|
||||
io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
format!("invalid remote control URL `{remote_control_url}`"),
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(RemoteControlTarget {
|
||||
websocket_url: websocket_url.to_string(),
|
||||
enroll_url: enroll_url.to_string(),
|
||||
refresh_url: refresh_url.to_string(),
|
||||
pair_url: pair_url.to_string(),
|
||||
pair_status_url: pair_status_url.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn normalize_remote_control_base_url(remote_control_url: &str) -> io::Result<Url> {
|
||||
let map_url_parse_error = |err: url::ParseError| -> io::Error {
|
||||
io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
format!("invalid remote control URL `{remote_control_url}`: {err}"),
|
||||
)
|
||||
};
|
||||
let map_scheme_error = |_: ()| -> io::Error {
|
||||
io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
format!(
|
||||
"invalid remote control URL `{remote_control_url}`; expected HTTPS URL for chatgpt.com or chatgpt-staging.com, or HTTP/HTTPS URL for localhost"
|
||||
),
|
||||
)
|
||||
};
|
||||
|
||||
let mut remote_control_url = Url::parse(remote_control_url).map_err(map_url_parse_error)?;
|
||||
if !remote_control_url.path().ends_with('/') {
|
||||
let normalized_path = format!("{}/", remote_control_url.path());
|
||||
remote_control_url.set_path(&normalized_path);
|
||||
}
|
||||
|
||||
let host = remote_control_url.host();
|
||||
match remote_control_url.scheme() {
|
||||
"https" if is_localhost(&host) || is_allowed_remote_control_chatgpt_host(&host) => {}
|
||||
"http" if is_localhost(&host) => {}
|
||||
_ => return Err(map_scheme_error(())),
|
||||
}
|
||||
|
||||
Ok(remote_control_url)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn normalize_remote_control_url_accepts_chatgpt_https_urls() {
|
||||
assert_eq!(
|
||||
normalize_remote_control_url("https://chatgpt.com/backend-api")
|
||||
.expect("chatgpt.com URL should normalize"),
|
||||
RemoteControlTarget {
|
||||
websocket_url: "wss://chatgpt.com/backend-api/wham/remote/control/server"
|
||||
.to_string(),
|
||||
enroll_url: "https://chatgpt.com/backend-api/wham/remote/control/server/enroll"
|
||||
.to_string(),
|
||||
refresh_url: "https://chatgpt.com/backend-api/wham/remote/control/server/refresh"
|
||||
.to_string(),
|
||||
pair_url: "https://chatgpt.com/backend-api/wham/remote/control/server/pair"
|
||||
.to_string(),
|
||||
pair_status_url:
|
||||
"https://chatgpt.com/backend-api/wham/remote/control/server/pair/status"
|
||||
.to_string(),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_remote_control_url("https://api.chatgpt-staging.com/backend-api")
|
||||
.expect("chatgpt-staging.com subdomain URL should normalize"),
|
||||
RemoteControlTarget {
|
||||
websocket_url:
|
||||
"wss://api.chatgpt-staging.com/backend-api/wham/remote/control/server"
|
||||
.to_string(),
|
||||
enroll_url:
|
||||
"https://api.chatgpt-staging.com/backend-api/wham/remote/control/server/enroll"
|
||||
.to_string(),
|
||||
refresh_url:
|
||||
"https://api.chatgpt-staging.com/backend-api/wham/remote/control/server/refresh"
|
||||
.to_string(),
|
||||
pair_url:
|
||||
"https://api.chatgpt-staging.com/backend-api/wham/remote/control/server/pair"
|
||||
.to_string(),
|
||||
pair_status_url:
|
||||
"https://api.chatgpt-staging.com/backend-api/wham/remote/control/server/pair/status"
|
||||
.to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_remote_control_url_accepts_localhost_urls() {
|
||||
assert_eq!(
|
||||
normalize_remote_control_url("http://localhost:8080/backend-api")
|
||||
.expect("localhost http URL should normalize"),
|
||||
RemoteControlTarget {
|
||||
websocket_url: "ws://localhost:8080/backend-api/wham/remote/control/server"
|
||||
.to_string(),
|
||||
enroll_url: "http://localhost:8080/backend-api/wham/remote/control/server/enroll"
|
||||
.to_string(),
|
||||
refresh_url: "http://localhost:8080/backend-api/wham/remote/control/server/refresh"
|
||||
.to_string(),
|
||||
pair_url: "http://localhost:8080/backend-api/wham/remote/control/server/pair"
|
||||
.to_string(),
|
||||
pair_status_url:
|
||||
"http://localhost:8080/backend-api/wham/remote/control/server/pair/status"
|
||||
.to_string(),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_remote_control_url("https://localhost:8443/backend-api")
|
||||
.expect("localhost https URL should normalize"),
|
||||
RemoteControlTarget {
|
||||
websocket_url: "wss://localhost:8443/backend-api/wham/remote/control/server"
|
||||
.to_string(),
|
||||
enroll_url: "https://localhost:8443/backend-api/wham/remote/control/server/enroll"
|
||||
.to_string(),
|
||||
refresh_url:
|
||||
"https://localhost:8443/backend-api/wham/remote/control/server/refresh"
|
||||
.to_string(),
|
||||
pair_url: "https://localhost:8443/backend-api/wham/remote/control/server/pair"
|
||||
.to_string(),
|
||||
pair_status_url:
|
||||
"https://localhost:8443/backend-api/wham/remote/control/server/pair/status"
|
||||
.to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_remote_control_url_rejects_unsupported_urls() {
|
||||
for remote_control_url in [
|
||||
"http://chatgpt.com/backend-api",
|
||||
"http://example.com/backend-api",
|
||||
"https://example.com/backend-api",
|
||||
"https://chat.openai.com/backend-api",
|
||||
"https://chatgpt.com.evil.com/backend-api",
|
||||
"https://evilchatgpt.com/backend-api",
|
||||
"https://foo.localhost/backend-api",
|
||||
] {
|
||||
let err = normalize_remote_control_url(remote_control_url)
|
||||
.expect_err("unsupported URL should be rejected");
|
||||
|
||||
assert_eq!(err.kind(), ErrorKind::InvalidInput);
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
format!(
|
||||
"invalid remote control URL `{remote_control_url}`; expected HTTPS URL for chatgpt.com or chatgpt-staging.com, or HTTP/HTTPS URL for localhost"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,311 +0,0 @@
|
||||
//! Exercise actor-authenticated remote control operations and separate relay capabilities.
|
||||
|
||||
use super::auth::RemoteControlAuth;
|
||||
use super::auth::load_remote_control_auth;
|
||||
use super::clients::list_remote_control_clients;
|
||||
use super::clients::revoke_remote_control_client;
|
||||
use super::protocol::StartRemoteControlPairingRequest;
|
||||
use super::protocol::normalize_remote_control_url;
|
||||
use super::server_api::enroll_remote_control_server;
|
||||
use super::server_api::refresh_remote_control_server;
|
||||
use base64::Engine;
|
||||
use codex_app_server_protocol::RemoteControlClientsListParams;
|
||||
use codex_app_server_protocol::RemoteControlClientsRevokeParams;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::DestinationPolicy;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::NetworkPolicyController;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::AuthRouteConfig;
|
||||
use codex_login::default_client::ResidencyRequirement;
|
||||
use codex_login::default_client::set_default_client_residency_requirement;
|
||||
use codex_runtime_agent_instance::AgentHostAuthorization;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeAuthSlot;
|
||||
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
|
||||
use codex_runtime_agent_instance::RuntimeRole;
|
||||
use core_test_support::runtime_auth::PROBE_SERVER;
|
||||
use core_test_support::runtime_auth::run_harness_through_proxy;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn actor_requests_share_runtime_and_pairing_keeps_its_server_token() -> anyhow::Result<()> {
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(
|
||||
json!({
|
||||
"iss": "https://auth.openai.com/", "session_id": "remote-control-login",
|
||||
"https://api.openai.com/auth": {"user_id": "actor", "chatgpt_account_id": "account_id"}
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
let token = format!("header.{claims}.signature");
|
||||
if let Ok(server) = std::env::var(PROBE_SERVER) {
|
||||
set_default_client_residency_requirement(Some(ResidencyRequirement::Us));
|
||||
let home = tempfile::tempdir()?;
|
||||
codex_login::auth::login_with_chatgpt_auth_tokens(
|
||||
home.path(),
|
||||
&token,
|
||||
"account_id",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?;
|
||||
let controller = NetworkPolicyController::default();
|
||||
let policy = controller.policy();
|
||||
let credentials = Arc::new(
|
||||
AuthManager::new(
|
||||
home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::Ephemeral,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
/*chatgpt_base_url*/ None,
|
||||
AuthKeyringBackendKind::Direct,
|
||||
AuthRouteConfig::from_http_client_factory(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
.with_network_policy(policy.clone()),
|
||||
),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
let runtime = Arc::new(RuntimeAuthManager::new(
|
||||
Arc::clone(&credentials),
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: uuid::Uuid::nil(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: Some("codex".into()),
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
"https://auth.openai.com/agent/register".parse()?,
|
||||
));
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let slot = RuntimeAuthSlot::default();
|
||||
let (owner, _) = RemoteControlAuth::capture(
|
||||
Arc::clone(&credentials),
|
||||
Some((Arc::clone(&slot), mode)),
|
||||
);
|
||||
let auth = load_remote_control_auth(&owner).await?;
|
||||
let Err(error) = enroll_remote_control_server(
|
||||
&normalize_remote_control_url("https://chatgpt.com/backend-api")?,
|
||||
&auth,
|
||||
"installation",
|
||||
"server",
|
||||
)
|
||||
.await
|
||||
else {
|
||||
panic!("enrollment requires the harness runtime");
|
||||
};
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::WouldBlock);
|
||||
assert!(
|
||||
slot.set(Arc::clone(&runtime)).is_ok(),
|
||||
"the harness should fill its empty runtime slot"
|
||||
);
|
||||
controller.unavailable(policy.revision());
|
||||
let auth = load_remote_control_auth(&owner).await?;
|
||||
let Err(error) = enroll_remote_control_server(
|
||||
&normalize_remote_control_url("https://chatgpt.com/backend-api")?,
|
||||
&auth,
|
||||
"installation",
|
||||
"server",
|
||||
)
|
||||
.await
|
||||
else {
|
||||
panic!("managed policy must block the request");
|
||||
};
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
|
||||
assert!(super::auth::is_policy_denial(&error));
|
||||
assert!(!super::auth::is_auth_error(&error));
|
||||
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
|
||||
for base in [
|
||||
"https://chatgpt.com/backend-api".to_owned(),
|
||||
format!("{server}/custom/backend-api"),
|
||||
] {
|
||||
let auth = load_remote_control_auth(&owner).await?;
|
||||
let mut enrollment = enroll_remote_control_server(
|
||||
&normalize_remote_control_url(&base)?,
|
||||
&auth,
|
||||
"installation",
|
||||
"server",
|
||||
)
|
||||
.await?;
|
||||
enrollment.remote_control_token = None;
|
||||
refresh_remote_control_server(&auth, "installation", &mut enrollment).await?;
|
||||
let clients = list_remote_control_clients(
|
||||
&base,
|
||||
&owner,
|
||||
RemoteControlClientsListParams {
|
||||
environment_id: "env".into(),
|
||||
cursor: None,
|
||||
limit: None,
|
||||
order: None,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
assert!(clients.data.is_empty());
|
||||
revoke_remote_control_client(
|
||||
&base,
|
||||
&owner,
|
||||
RemoteControlClientsRevokeParams {
|
||||
environment_id: "env".into(),
|
||||
client_id: "client".into(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let pairing = enrollment
|
||||
.start_pairing(
|
||||
&auth.http_client_factory,
|
||||
StartRemoteControlPairingRequest { manual_code: false },
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(pairing.pairing_code, "pairing");
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/agent/register"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-remote-control", "agent_host_id": "host",
|
||||
"actor": {"kind": "chatgpt", "user_id": "actor", "account_id": "account_id"}
|
||||
})))
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
for prefix in ["/backend-api", "/custom/backend-api"] {
|
||||
for suffix in ["server/enroll", "server/refresh"] {
|
||||
Mock::given(method("POST")).and(path(format!("{prefix}/wham/remote/control/{suffix}")))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"server_id": "server", "environment_id": "env", "remote_control_token": "relay-capability", "expires_at": "2999-01-01T00:00:00Z"
|
||||
}))).expect(/*r*/ 2).mount(&server).await;
|
||||
}
|
||||
Mock::given(method("GET"))
|
||||
.and(path(format!(
|
||||
"{prefix}/wham/remote/control/environments/env/clients"
|
||||
)))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 307).insert_header(
|
||||
"location",
|
||||
format!("{prefix}/wham/remote/control/environments/env/redirected-clients"),
|
||||
))
|
||||
.expect(/*r*/ 2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path(format!(
|
||||
"{prefix}/wham/remote/control/environments/env/redirected-clients"
|
||||
)))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(/*s*/ 200)
|
||||
.set_body_json(json!({"items": [], "cursor": null})),
|
||||
)
|
||||
.expect(/*r*/ 2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("DELETE"))
|
||||
.and(path(format!(
|
||||
"{prefix}/wham/remote/control/environments/env/clients/client"
|
||||
)))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 307).insert_header(
|
||||
"location",
|
||||
format!("https://api.openai.org{prefix}/wham/remote/control/environments/env/client-redirected"),
|
||||
))
|
||||
.expect(/*r*/ 2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("DELETE"))
|
||||
.and(path(format!(
|
||||
"{prefix}/wham/remote/control/environments/env/client-redirected"
|
||||
)))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 204))
|
||||
.expect(/*r*/ 2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("POST")).and(path(format!("{prefix}/wham/remote/control/server/pair")))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"server_id": "server", "environment_id": "env", "pairing_code": "pairing", "manual_pairing_code": null, "expires_at": "2999-01-01T00:00:00Z"
|
||||
}))).expect(/*r*/ 2).mount(&server).await;
|
||||
}
|
||||
run_harness_through_proxy(&server, "transport::remote_control::runtime_auth_tests::actor_requests_share_runtime_and_pairing_keeps_its_server_token", /*realtime_target*/ None).await?;
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let mut proofs = HashSet::new();
|
||||
let mut dual = 0;
|
||||
for request in requests.iter().filter(|r| {
|
||||
r.url.path().contains("/wham/remote/control/")
|
||||
&& !r.url.path().ends_with("/redirected-clients")
|
||||
&& !r.url.path().ends_with("/client-redirected")
|
||||
}) {
|
||||
let authorization = request.headers["authorization"].to_str()?;
|
||||
if !request.url.path().ends_with("/pair") {
|
||||
assert_eq!(request.headers["x-openai-internal-codex-residency"], "us");
|
||||
}
|
||||
if request.url.path().ends_with("/pair") {
|
||||
assert_eq!(authorization, "Bearer relay-capability");
|
||||
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
|
||||
} else if request.url.path().starts_with("/custom/") {
|
||||
assert_eq!(authorization, format!("Bearer {token}"));
|
||||
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
|
||||
} else {
|
||||
assert_eq!(request.headers["chatgpt-account-id"], "account_id");
|
||||
let proof = if let Some(proof) = request.headers.get("x-openai-agent-assertion") {
|
||||
dual += 1;
|
||||
assert_eq!(authorization, format!("Bearer {token}"));
|
||||
proof.to_str()?
|
||||
} else {
|
||||
authorization.strip_prefix("AgentAssertion ").unwrap()
|
||||
};
|
||||
let payload: serde_json::Value = serde_json::from_slice(
|
||||
&base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(proof.split('.').nth(/*n*/ 2).unwrap())?,
|
||||
)?;
|
||||
assert_eq!(payload["runtime_agent_instance"], "runtime-remote-control");
|
||||
assert!(proofs.insert(proof.to_owned()));
|
||||
}
|
||||
}
|
||||
assert_eq!((dual, proofs.len()), (4, 8));
|
||||
for prefix in ["/backend-api", "/custom/backend-api"] {
|
||||
let original = format!("{prefix}/wham/remote/control/environments/env/clients");
|
||||
let redirected =
|
||||
format!("{prefix}/wham/remote/control/environments/env/redirected-clients");
|
||||
let originals: Vec<_> = requests
|
||||
.iter()
|
||||
.filter(|r| r.url.path() == original)
|
||||
.collect();
|
||||
let redirects: Vec<_> = requests
|
||||
.iter()
|
||||
.filter(|r| r.url.path() == redirected)
|
||||
.collect();
|
||||
assert_eq!(originals.len(), 2);
|
||||
assert_eq!(redirects.len(), 2);
|
||||
for (original, redirected) in originals.into_iter().zip(redirects) {
|
||||
assert_eq!(
|
||||
redirected.headers.get("authorization"),
|
||||
original.headers.get("authorization")
|
||||
);
|
||||
assert_eq!(
|
||||
redirected.headers.get("x-openai-agent-assertion"),
|
||||
original.headers.get("x-openai-agent-assertion")
|
||||
);
|
||||
}
|
||||
}
|
||||
let cross_origin: Vec<_> = requests
|
||||
.iter()
|
||||
.filter(|r| r.url.path().ends_with("/client-redirected"))
|
||||
.collect();
|
||||
assert_eq!(cross_origin.len(), 4);
|
||||
for request in cross_origin {
|
||||
assert!(!request.headers.contains_key("authorization"));
|
||||
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
server.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,469 +0,0 @@
|
||||
use super::protocol::ClientEnvelope;
|
||||
use super::protocol::ClientEvent;
|
||||
use super::protocol::ClientId;
|
||||
use super::protocol::ServerEnvelope;
|
||||
use super::protocol::ServerEvent;
|
||||
use super::protocol::StreamId;
|
||||
use crate::outgoing_message::OutgoingMessage;
|
||||
use crate::transport::response_serialization_error;
|
||||
use base64::DecodeSliceError;
|
||||
use base64::Engine;
|
||||
use codex_app_server_protocol::JSONRPCMessage;
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::io::ErrorKind;
|
||||
use std::io::Write;
|
||||
use tokio::time::Instant;
|
||||
use tracing::warn;
|
||||
|
||||
pub(super) const REMOTE_CONTROL_SEGMENT_TARGET_BYTES: usize = 100 * 1024;
|
||||
pub(super) const REMOTE_CONTROL_SEGMENT_MAX_BYTES: usize = 150 * 1024;
|
||||
pub(super) const REMOTE_CONTROL_REASSEMBLED_MAX_BYTES: usize = 100 * 1024 * 1024;
|
||||
pub(super) const REMOTE_CONTROL_SEGMENT_COUNT_MAX: usize = 1024;
|
||||
const REMOTE_CONTROL_SEGMENT_ASSEMBLY_MAX_COUNT: usize = 128;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ClientSegmentAssembly {
|
||||
stream_id: StreamId,
|
||||
metadata: ClientSegmentMetadata,
|
||||
raw: Vec<u8>,
|
||||
next_segment_id: usize,
|
||||
last_chunk_seen_at: Instant,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct ClientSegmentMetadata {
|
||||
seq_id: u64,
|
||||
segment_count: usize,
|
||||
message_size_bytes: usize,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct ClientSegmentReassembler {
|
||||
assemblies: HashMap<ClientId, ClientSegmentAssembly>,
|
||||
}
|
||||
|
||||
pub(super) enum ClientSegmentObservation {
|
||||
Forward(Box<ClientEnvelope>),
|
||||
Pending,
|
||||
Dropped,
|
||||
}
|
||||
|
||||
impl ClientSegmentReassembler {
|
||||
pub(super) fn observe(&mut self, envelope: ClientEnvelope) -> ClientSegmentObservation {
|
||||
let ClientEvent::ClientMessageChunk {
|
||||
segment_id,
|
||||
segment_count,
|
||||
message_size_bytes,
|
||||
message_chunk_base64,
|
||||
} = &envelope.event
|
||||
else {
|
||||
return ClientSegmentObservation::Forward(Box::new(envelope));
|
||||
};
|
||||
let segment_id = *segment_id;
|
||||
let segment_count = *segment_count;
|
||||
let message_size_bytes = *message_size_bytes;
|
||||
|
||||
let Some(metadata) = ClientSegmentMetadata::from_envelope(&envelope) else {
|
||||
warn!(
|
||||
client_id = envelope.client_id.0.as_str(),
|
||||
"dropping segmented remote-control client envelope without seq_id"
|
||||
);
|
||||
return ClientSegmentObservation::Dropped;
|
||||
};
|
||||
let Some(stream_id) = envelope.stream_id.clone() else {
|
||||
warn!(
|
||||
client_id = envelope.client_id.0.as_str(),
|
||||
"dropping segmented remote-control client envelope without stream_id"
|
||||
);
|
||||
return ClientSegmentObservation::Dropped;
|
||||
};
|
||||
if self.should_ignore_chunk(&envelope.client_id, &stream_id, metadata.seq_id, segment_id) {
|
||||
return ClientSegmentObservation::Dropped;
|
||||
}
|
||||
if segment_count == 0
|
||||
|| segment_count > REMOTE_CONTROL_SEGMENT_COUNT_MAX
|
||||
|| segment_id >= segment_count
|
||||
|| message_size_bytes == 0
|
||||
|| message_size_bytes > REMOTE_CONTROL_REASSEMBLED_MAX_BYTES
|
||||
|| message_chunk_base64.is_empty()
|
||||
{
|
||||
warn!(
|
||||
client_id = envelope.client_id.0.as_str(),
|
||||
"dropping invalid segmented remote-control client envelope"
|
||||
);
|
||||
self.remove_assembly(&envelope.client_id, &stream_id);
|
||||
return ClientSegmentObservation::Dropped;
|
||||
}
|
||||
|
||||
let now = Instant::now();
|
||||
match self.assemblies.get(&envelope.client_id) {
|
||||
Some(assembly) if assembly.stream_id != stream_id => {
|
||||
warn!(
|
||||
client_id = envelope.client_id.0.as_str(),
|
||||
"resetting segmented remote-control client envelope after stream change"
|
||||
);
|
||||
self.assemblies.insert(
|
||||
envelope.client_id.clone(),
|
||||
ClientSegmentAssembly {
|
||||
stream_id: stream_id.clone(),
|
||||
metadata: metadata.clone(),
|
||||
raw: Vec::new(),
|
||||
next_segment_id: 0,
|
||||
last_chunk_seen_at: now,
|
||||
},
|
||||
);
|
||||
}
|
||||
Some(_) => {}
|
||||
None => {
|
||||
self.evict_assemblies_if_full();
|
||||
self.assemblies.insert(
|
||||
envelope.client_id.clone(),
|
||||
ClientSegmentAssembly {
|
||||
stream_id: stream_id.clone(),
|
||||
metadata: metadata.clone(),
|
||||
raw: Vec::new(),
|
||||
next_segment_id: 0,
|
||||
last_chunk_seen_at: now,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
let result = {
|
||||
let Some(assembly) = self.assemblies.get_mut(&envelope.client_id) else {
|
||||
warn!(
|
||||
client_id = envelope.client_id.0.as_str(),
|
||||
"dropping segmented remote-control client envelope without assembly"
|
||||
);
|
||||
return ClientSegmentObservation::Dropped;
|
||||
};
|
||||
if metadata.seq_id < assembly.metadata.seq_id {
|
||||
AssemblyUpdate::Ignore
|
||||
} else if assembly.metadata != metadata {
|
||||
warn!(
|
||||
client_id = envelope.client_id.0.as_str(),
|
||||
"resetting segmented remote-control client envelope after metadata mismatch"
|
||||
);
|
||||
AssemblyUpdate::Drop
|
||||
} else if segment_id < assembly.next_segment_id {
|
||||
AssemblyUpdate::Pending
|
||||
} else if segment_id != assembly.next_segment_id {
|
||||
warn!(
|
||||
client_id = envelope.client_id.0.as_str(),
|
||||
"dropping out-of-order segmented remote-control client envelope"
|
||||
);
|
||||
AssemblyUpdate::Drop
|
||||
} else {
|
||||
assembly.last_chunk_seen_at = now;
|
||||
let chunk_start = assembly.raw.len();
|
||||
let decoded_chunk_len = base64::decoded_len_estimate(message_chunk_base64.len());
|
||||
let chunk_end = usize::min(
|
||||
message_size_bytes,
|
||||
chunk_start.saturating_add(decoded_chunk_len),
|
||||
);
|
||||
assembly.raw.resize(chunk_end, 0);
|
||||
match base64::engine::general_purpose::STANDARD.decode_slice(
|
||||
message_chunk_base64.as_bytes(),
|
||||
&mut assembly.raw[chunk_start..],
|
||||
) {
|
||||
Ok(decoded_chunk_len) => {
|
||||
assembly.raw.truncate(chunk_start + decoded_chunk_len);
|
||||
assembly.next_segment_id += 1;
|
||||
if assembly.next_segment_id < segment_count {
|
||||
AssemblyUpdate::Pending
|
||||
} else if assembly.raw.len() != message_size_bytes {
|
||||
warn!(
|
||||
client_id = envelope.client_id.0.as_str(),
|
||||
"dropping reassembled remote-control client envelope with mismatched size"
|
||||
);
|
||||
AssemblyUpdate::Drop
|
||||
} else {
|
||||
match serde_json::from_slice::<JSONRPCMessage>(&assembly.raw) {
|
||||
Ok(message) => AssemblyUpdate::Complete(message),
|
||||
Err(err) => {
|
||||
warn!(
|
||||
client_id = envelope.client_id.0.as_str(),
|
||||
"dropping invalid reassembled remote-control client envelope: {err}"
|
||||
);
|
||||
AssemblyUpdate::Drop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(DecodeSliceError::OutputSliceTooSmall) => {
|
||||
warn!(
|
||||
client_id = envelope.client_id.0.as_str(),
|
||||
"dropping segmented remote-control client envelope after size overflow"
|
||||
);
|
||||
AssemblyUpdate::Drop
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
client_id = envelope.client_id.0.as_str(),
|
||||
"dropping segmented remote-control client envelope with invalid base64: {err}"
|
||||
);
|
||||
AssemblyUpdate::Drop
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
match result {
|
||||
AssemblyUpdate::Pending => ClientSegmentObservation::Pending,
|
||||
AssemblyUpdate::Ignore => ClientSegmentObservation::Dropped,
|
||||
AssemblyUpdate::Drop => {
|
||||
self.remove_assembly(&envelope.client_id, &stream_id);
|
||||
ClientSegmentObservation::Dropped
|
||||
}
|
||||
AssemblyUpdate::Complete(message) => {
|
||||
self.remove_assembly(&envelope.client_id, &stream_id);
|
||||
ClientSegmentObservation::Forward(Box::new(ClientEnvelope {
|
||||
event: ClientEvent::ClientMessage { message },
|
||||
..envelope
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn invalidate_stream(&mut self, client_id: &ClientId, stream_id: &StreamId) {
|
||||
self.remove_assembly(client_id, stream_id);
|
||||
}
|
||||
|
||||
pub(super) fn invalidate_client(&mut self, client_id: &ClientId) {
|
||||
self.assemblies.remove(client_id);
|
||||
}
|
||||
|
||||
pub(super) fn should_ignore_chunk(
|
||||
&self,
|
||||
client_id: &ClientId,
|
||||
stream_id: &StreamId,
|
||||
seq_id: u64,
|
||||
segment_id: usize,
|
||||
) -> bool {
|
||||
self.assemblies.get(client_id).is_some_and(|assembly| {
|
||||
assembly.stream_id == *stream_id
|
||||
&& (seq_id < assembly.metadata.seq_id
|
||||
|| (seq_id == assembly.metadata.seq_id
|
||||
&& segment_id < assembly.next_segment_id))
|
||||
})
|
||||
}
|
||||
|
||||
fn remove_assembly(&mut self, client_id: &ClientId, stream_id: &StreamId) {
|
||||
if self
|
||||
.assemblies
|
||||
.get(client_id)
|
||||
.is_some_and(|assembly| &assembly.stream_id == stream_id)
|
||||
{
|
||||
self.assemblies.remove(client_id);
|
||||
}
|
||||
}
|
||||
|
||||
fn evict_assemblies_if_full(&mut self) {
|
||||
while self.assemblies.len() >= REMOTE_CONTROL_SEGMENT_ASSEMBLY_MAX_COUNT {
|
||||
let Some(client_id) = self
|
||||
.assemblies
|
||||
.iter()
|
||||
.min_by_key(|(_, assembly)| assembly.last_chunk_seen_at)
|
||||
.map(|(client_id, _)| client_id.clone())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
self.assemblies.remove(&client_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum AssemblyUpdate {
|
||||
Pending,
|
||||
Ignore,
|
||||
Drop,
|
||||
Complete(JSONRPCMessage),
|
||||
}
|
||||
|
||||
impl ClientSegmentMetadata {
|
||||
fn from_envelope(envelope: &ClientEnvelope) -> Option<Self> {
|
||||
let ClientEvent::ClientMessageChunk {
|
||||
segment_count,
|
||||
message_size_bytes,
|
||||
..
|
||||
} = &envelope.event
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
Some(Self {
|
||||
seq_id: envelope.seq_id?,
|
||||
segment_count: *segment_count,
|
||||
message_size_bytes: *message_size_bytes,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn split_server_envelope_for_transport(
|
||||
envelope: ServerEnvelope,
|
||||
) -> io::Result<Vec<ServerEnvelope>> {
|
||||
if !matches!(envelope.event, ServerEvent::ServerMessage { .. }) {
|
||||
return Ok(vec![envelope]);
|
||||
}
|
||||
|
||||
let envelope_size_bytes = match serialized_len(&envelope) {
|
||||
Ok(envelope_size_bytes) => envelope_size_bytes,
|
||||
Err(err) => {
|
||||
let ServerEvent::ServerMessage { message } = envelope.event else {
|
||||
unreachable!("server message variant checked above");
|
||||
};
|
||||
let OutgoingMessage::Response(response) = *message else {
|
||||
return Err(err);
|
||||
};
|
||||
return Ok(vec![ServerEnvelope {
|
||||
event: ServerEvent::ServerMessage {
|
||||
message: Box::new(response_serialization_error(response.id, err)),
|
||||
},
|
||||
client_id: envelope.client_id,
|
||||
stream_id: envelope.stream_id,
|
||||
seq_id: envelope.seq_id,
|
||||
}]);
|
||||
}
|
||||
};
|
||||
if envelope_size_bytes <= REMOTE_CONTROL_SEGMENT_MAX_BYTES {
|
||||
return Ok(vec![envelope]);
|
||||
}
|
||||
|
||||
let ServerEvent::ServerMessage { message } = envelope.event.clone() else {
|
||||
unreachable!("server message variant checked above");
|
||||
};
|
||||
let raw = serde_json::to_vec(message.as_ref()).map_err(io::Error::other)?;
|
||||
let message_size_bytes = raw.len();
|
||||
if message_size_bytes > REMOTE_CONTROL_REASSEMBLED_MAX_BYTES {
|
||||
warn!("dropping remote-control server envelope that exceeds reassembled size limit");
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let minimal_segment_count =
|
||||
usize::min(message_size_bytes.max(1), REMOTE_CONTROL_SEGMENT_COUNT_MAX);
|
||||
let minimal_chunk = &raw[..usize::min(raw.len(), 1)];
|
||||
if serialized_chunk_len(
|
||||
&envelope,
|
||||
/*segment_id*/ 0,
|
||||
minimal_segment_count,
|
||||
message_size_bytes,
|
||||
minimal_chunk,
|
||||
)? > REMOTE_CONTROL_SEGMENT_MAX_BYTES
|
||||
{
|
||||
warn!("dropping remote-control server envelope that cannot fit within segment size limit");
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let mut segment_count = usize::max(
|
||||
2,
|
||||
message_size_bytes.div_ceil(REMOTE_CONTROL_SEGMENT_TARGET_BYTES),
|
||||
);
|
||||
loop {
|
||||
let chunk_size = usize::max(1, message_size_bytes.div_ceil(segment_count));
|
||||
segment_count = message_size_bytes.div_ceil(chunk_size);
|
||||
let segments_fit = raw
|
||||
.chunks(chunk_size)
|
||||
.enumerate()
|
||||
.all(|(segment_id, chunk)| {
|
||||
serialized_chunk_len(
|
||||
&envelope,
|
||||
segment_id,
|
||||
segment_count,
|
||||
message_size_bytes,
|
||||
chunk,
|
||||
)
|
||||
.is_ok_and(|size| size <= REMOTE_CONTROL_SEGMENT_MAX_BYTES)
|
||||
});
|
||||
if segments_fit {
|
||||
return raw
|
||||
.chunks(chunk_size)
|
||||
.enumerate()
|
||||
.map(|(segment_id, chunk)| {
|
||||
build_chunk_envelope(
|
||||
&envelope,
|
||||
segment_id,
|
||||
segment_count,
|
||||
message_size_bytes,
|
||||
chunk,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
if chunk_size == 1 {
|
||||
warn!(
|
||||
"dropping remote-control server envelope that cannot fit within segment size limit"
|
||||
);
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let next_segment_count = segment_count + 1;
|
||||
let next_chunk_size = usize::max(1, message_size_bytes.div_ceil(next_segment_count));
|
||||
segment_count = if next_chunk_size == chunk_size {
|
||||
message_size_bytes
|
||||
} else {
|
||||
next_segment_count
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn serialized_chunk_len(
|
||||
envelope: &ServerEnvelope,
|
||||
segment_id: usize,
|
||||
segment_count: usize,
|
||||
message_size_bytes: usize,
|
||||
chunk: &[u8],
|
||||
) -> io::Result<usize> {
|
||||
serialized_len(&build_chunk_envelope(
|
||||
envelope,
|
||||
segment_id,
|
||||
segment_count,
|
||||
message_size_bytes,
|
||||
chunk,
|
||||
)?)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct CountingWriter {
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl Write for CountingWriter {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
self.len += buf.len();
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn serialized_len(value: &impl serde::Serialize) -> io::Result<usize> {
|
||||
let mut writer = CountingWriter::default();
|
||||
serde_json::to_writer(&mut writer, value).map_err(io::Error::other)?;
|
||||
Ok(writer.len)
|
||||
}
|
||||
|
||||
fn build_chunk_envelope(
|
||||
envelope: &ServerEnvelope,
|
||||
segment_id: usize,
|
||||
segment_count: usize,
|
||||
message_size_bytes: usize,
|
||||
chunk: &[u8],
|
||||
) -> io::Result<ServerEnvelope> {
|
||||
if segment_count > REMOTE_CONTROL_SEGMENT_COUNT_MAX {
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::InvalidData,
|
||||
"remote-control segment count exceeds maximum",
|
||||
));
|
||||
}
|
||||
Ok(ServerEnvelope {
|
||||
event: ServerEvent::ServerMessageChunk {
|
||||
segment_id,
|
||||
segment_count,
|
||||
message_size_bytes,
|
||||
message_chunk_base64: base64::engine::general_purpose::STANDARD.encode(chunk),
|
||||
},
|
||||
client_id: envelope.client_id.clone(),
|
||||
stream_id: envelope.stream_id.clone(),
|
||||
seq_id: envelope.seq_id,
|
||||
})
|
||||
}
|
||||
@@ -1,450 +0,0 @@
|
||||
use super::protocol::ClientEnvelope;
|
||||
use super::protocol::ClientEvent;
|
||||
use super::protocol::ClientId;
|
||||
use super::protocol::ServerEnvelope;
|
||||
use super::protocol::ServerEvent;
|
||||
use super::protocol::StreamId;
|
||||
use super::segment::ClientSegmentObservation;
|
||||
use super::segment::ClientSegmentReassembler;
|
||||
use super::segment::REMOTE_CONTROL_SEGMENT_MAX_BYTES;
|
||||
use super::segment::split_server_envelope_for_transport;
|
||||
use crate::outgoing_message::OutgoingMessage;
|
||||
#[cfg(unix)]
|
||||
use crate::outgoing_message::OutgoingResponse;
|
||||
use base64::Engine;
|
||||
#[cfg(unix)]
|
||||
use codex_app_server_protocol::ClientResponsePayload;
|
||||
use codex_app_server_protocol::ConfigWarningNotification;
|
||||
#[cfg(unix)]
|
||||
use codex_app_server_protocol::InitializeResponse;
|
||||
use codex_app_server_protocol::JSONRPCMessage;
|
||||
use codex_app_server_protocol::JSONRPCNotification;
|
||||
#[cfg(unix)]
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ServerNotificationEnvelope;
|
||||
#[cfg(unix)]
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
#[cfg(unix)]
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn reassembles_client_message_chunks() {
|
||||
let message = JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: "initialized".to_string(),
|
||||
params: None,
|
||||
});
|
||||
let raw = serde_json::to_vec(&message).expect("message should serialize");
|
||||
let split = raw.len() / 2;
|
||||
let client_id = ClientId("client-1".to_string());
|
||||
let stream_id = Some(StreamId("stream-1".to_string()));
|
||||
let mut reassembler = ClientSegmentReassembler::default();
|
||||
|
||||
assert!(matches!(
|
||||
reassembler.observe(chunk_envelope(
|
||||
client_id.clone(),
|
||||
stream_id.clone(),
|
||||
/*seq_id*/ 7,
|
||||
/*segment_id*/ 0,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
&raw[..split],
|
||||
)),
|
||||
ClientSegmentObservation::Pending
|
||||
));
|
||||
let reassembled = match reassembler.observe(chunk_envelope(
|
||||
client_id.clone(),
|
||||
stream_id,
|
||||
/*seq_id*/ 7,
|
||||
/*segment_id*/ 1,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
&raw[split..],
|
||||
)) {
|
||||
ClientSegmentObservation::Forward(reassembled) => *reassembled,
|
||||
ClientSegmentObservation::Pending | ClientSegmentObservation::Dropped => {
|
||||
panic!("message should reassemble")
|
||||
}
|
||||
};
|
||||
assert_eq!(reassembled.client_id, client_id);
|
||||
assert_eq!(
|
||||
reassembled.stream_id,
|
||||
Some(StreamId("stream-1".to_string()))
|
||||
);
|
||||
assert_eq!(reassembled.seq_id, Some(7));
|
||||
assert_eq!(reassembled.cursor, None);
|
||||
match reassembled.event {
|
||||
ClientEvent::ClientMessage {
|
||||
message: reassembled_message,
|
||||
} => assert_eq!(reassembled_message, message),
|
||||
other => panic!("expected client message, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_large_server_messages_into_wire_chunks() {
|
||||
let envelope = ServerEnvelope {
|
||||
event: ServerEvent::ServerMessage {
|
||||
message: Box::new(OutgoingMessage::AppServerNotification(
|
||||
ServerNotificationEnvelope {
|
||||
notification: ServerNotification::ConfigWarning(ConfigWarningNotification {
|
||||
summary: "x".repeat(REMOTE_CONTROL_SEGMENT_MAX_BYTES),
|
||||
details: None,
|
||||
path: None,
|
||||
range: None,
|
||||
}),
|
||||
emitted_at_ms: Some(1_234),
|
||||
},
|
||||
)),
|
||||
},
|
||||
client_id: ClientId("client-1".to_string()),
|
||||
stream_id: StreamId("stream-1".to_string()),
|
||||
seq_id: 9,
|
||||
};
|
||||
|
||||
let segments = split_server_envelope_for_transport(envelope).expect("split should succeed");
|
||||
|
||||
assert!(segments.len() > 1);
|
||||
assert!(
|
||||
segments
|
||||
.iter()
|
||||
.all(|segment| matches!(segment.event, ServerEvent::ServerMessageChunk { .. }))
|
||||
);
|
||||
assert!(segments.iter().all(|segment| segment.seq_id == 9));
|
||||
assert!(segments.iter().all(|segment| {
|
||||
serde_json::to_vec(segment)
|
||||
.expect("segment should serialize")
|
||||
.len()
|
||||
<= REMOTE_CONTROL_SEGMENT_MAX_BYTES
|
||||
}));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn invalid_response_becomes_remote_control_jsonrpc_error() {
|
||||
use std::ffi::OsString;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
use std::path::PathBuf;
|
||||
|
||||
let codex_home = AbsolutePathBuf::from_absolute_path(PathBuf::from(OsString::from_vec(vec![
|
||||
b'/', b'b', b'a', b'd', 0xff,
|
||||
])))
|
||||
.expect("non-UTF-8 Unix paths are valid absolute paths");
|
||||
let envelope = ServerEnvelope {
|
||||
event: ServerEvent::ServerMessage {
|
||||
message: Box::new(OutgoingMessage::Response(OutgoingResponse {
|
||||
id: RequestId::Integer(7),
|
||||
result: Box::new(ClientResponsePayload::Initialize(InitializeResponse {
|
||||
user_agent: "codex-test-agent".to_string(),
|
||||
codex_home,
|
||||
platform_family: "unix".to_string(),
|
||||
platform_os: "linux".to_string(),
|
||||
})),
|
||||
})),
|
||||
},
|
||||
client_id: ClientId("client-1".to_string()),
|
||||
stream_id: StreamId("stream-1".to_string()),
|
||||
seq_id: 9,
|
||||
};
|
||||
|
||||
let envelopes = split_server_envelope_for_transport(envelope)
|
||||
.expect("invalid response should become a remote-control JSON-RPC error");
|
||||
assert_eq!(
|
||||
serde_json::to_value(envelopes).expect("error envelope should serialize"),
|
||||
json!([{
|
||||
"type": "server_message",
|
||||
"client_id": "client-1",
|
||||
"stream_id": "stream-1",
|
||||
"seq_id": 9,
|
||||
"message": {
|
||||
"id": 7,
|
||||
"error": {
|
||||
"code": -32603,
|
||||
"message": "failed to serialize response: path contains invalid UTF-8 characters",
|
||||
}
|
||||
}
|
||||
}])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalidates_incomplete_stream_assemblies() {
|
||||
let message = JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: "initialized".to_string(),
|
||||
params: None,
|
||||
});
|
||||
let raw = serde_json::to_vec(&message).expect("message should serialize");
|
||||
let split = raw.len() / 2;
|
||||
let client_id = ClientId("client-1".to_string());
|
||||
let stream_id = StreamId("stream-1".to_string());
|
||||
let mut reassembler = ClientSegmentReassembler::default();
|
||||
|
||||
assert!(matches!(
|
||||
reassembler.observe(chunk_envelope(
|
||||
client_id.clone(),
|
||||
Some(stream_id.clone()),
|
||||
/*seq_id*/ 7,
|
||||
/*segment_id*/ 0,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
&raw[..split],
|
||||
)),
|
||||
ClientSegmentObservation::Pending
|
||||
));
|
||||
reassembler.invalidate_stream(&client_id, &stream_id);
|
||||
assert!(matches!(
|
||||
reassembler.observe(chunk_envelope(
|
||||
client_id,
|
||||
Some(stream_id),
|
||||
/*seq_id*/ 7,
|
||||
/*segment_id*/ 1,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
&raw[split..],
|
||||
)),
|
||||
ClientSegmentObservation::Dropped
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resets_incomplete_client_assembly_when_stream_changes() {
|
||||
let message = JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: "initialized".to_string(),
|
||||
params: None,
|
||||
});
|
||||
let raw = serde_json::to_vec(&message).expect("message should serialize");
|
||||
let split = raw.len() / 2;
|
||||
let client_id = ClientId("client-1".to_string());
|
||||
let first_stream_id = StreamId("stream-1".to_string());
|
||||
let second_stream_id = StreamId("stream-2".to_string());
|
||||
let mut reassembler = ClientSegmentReassembler::default();
|
||||
|
||||
assert!(matches!(
|
||||
reassembler.observe(chunk_envelope(
|
||||
client_id.clone(),
|
||||
Some(first_stream_id.clone()),
|
||||
/*seq_id*/ 7,
|
||||
/*segment_id*/ 0,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
&raw[..split],
|
||||
)),
|
||||
ClientSegmentObservation::Pending
|
||||
));
|
||||
assert!(matches!(
|
||||
reassembler.observe(chunk_envelope(
|
||||
client_id.clone(),
|
||||
Some(second_stream_id.clone()),
|
||||
/*seq_id*/ 8,
|
||||
/*segment_id*/ 0,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
&raw[..split],
|
||||
)),
|
||||
ClientSegmentObservation::Pending
|
||||
));
|
||||
let reassembled = match reassembler.observe(chunk_envelope(
|
||||
client_id.clone(),
|
||||
Some(second_stream_id),
|
||||
/*seq_id*/ 8,
|
||||
/*segment_id*/ 1,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
&raw[split..],
|
||||
)) {
|
||||
ClientSegmentObservation::Forward(reassembled) => *reassembled,
|
||||
ClientSegmentObservation::Pending | ClientSegmentObservation::Dropped => {
|
||||
panic!("replacement stream should reassemble")
|
||||
}
|
||||
};
|
||||
assert_eq!(
|
||||
reassembled.stream_id,
|
||||
Some(StreamId("stream-2".to_string()))
|
||||
);
|
||||
assert!(matches!(
|
||||
reassembler.observe(chunk_envelope(
|
||||
client_id,
|
||||
Some(first_stream_id),
|
||||
/*seq_id*/ 7,
|
||||
/*segment_id*/ 1,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
&raw[split..],
|
||||
)),
|
||||
ClientSegmentObservation::Dropped
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_stale_chunks_without_dropping_newer_assembly() {
|
||||
let message = JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: "initialized".to_string(),
|
||||
params: None,
|
||||
});
|
||||
let raw = serde_json::to_vec(&message).expect("message should serialize");
|
||||
let split = raw.len() / 2;
|
||||
let client_id = ClientId("client-1".to_string());
|
||||
let stream_id = Some(StreamId("stream-1".to_string()));
|
||||
let mut reassembler = ClientSegmentReassembler::default();
|
||||
|
||||
assert!(matches!(
|
||||
reassembler.observe(chunk_envelope(
|
||||
client_id.clone(),
|
||||
stream_id.clone(),
|
||||
/*seq_id*/ 8,
|
||||
/*segment_id*/ 0,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
&raw[..split],
|
||||
)),
|
||||
ClientSegmentObservation::Pending
|
||||
));
|
||||
assert!(matches!(
|
||||
reassembler.observe(chunk_envelope(
|
||||
client_id.clone(),
|
||||
stream_id.clone(),
|
||||
/*seq_id*/ 7,
|
||||
/*segment_id*/ 0,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
&raw[..split],
|
||||
)),
|
||||
ClientSegmentObservation::Dropped
|
||||
));
|
||||
assert!(matches!(
|
||||
reassembler.observe(chunk_envelope(
|
||||
client_id,
|
||||
stream_id,
|
||||
/*seq_id*/ 8,
|
||||
/*segment_id*/ 1,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
&raw[split..],
|
||||
)),
|
||||
ClientSegmentObservation::Forward(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_invalid_stale_chunks_without_dropping_newer_assembly() {
|
||||
let message = JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: "initialized".to_string(),
|
||||
params: None,
|
||||
});
|
||||
let raw = serde_json::to_vec(&message).expect("message should serialize");
|
||||
let split = raw.len() / 2;
|
||||
let client_id = ClientId("client-1".to_string());
|
||||
let stream_id = Some(StreamId("stream-1".to_string()));
|
||||
let mut reassembler = ClientSegmentReassembler::default();
|
||||
|
||||
assert!(matches!(
|
||||
reassembler.observe(chunk_envelope(
|
||||
client_id.clone(),
|
||||
stream_id.clone(),
|
||||
/*seq_id*/ 8,
|
||||
/*segment_id*/ 0,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
&raw[..split],
|
||||
)),
|
||||
ClientSegmentObservation::Pending
|
||||
));
|
||||
assert!(matches!(
|
||||
reassembler.observe(chunk_envelope(
|
||||
client_id.clone(),
|
||||
stream_id.clone(),
|
||||
/*seq_id*/ 7,
|
||||
/*segment_id*/ 1,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
b"",
|
||||
)),
|
||||
ClientSegmentObservation::Dropped
|
||||
));
|
||||
assert!(matches!(
|
||||
reassembler.observe(chunk_envelope(
|
||||
client_id,
|
||||
stream_id,
|
||||
/*seq_id*/ 8,
|
||||
/*segment_id*/ 1,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
&raw[split..],
|
||||
)),
|
||||
ClientSegmentObservation::Forward(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_invalid_duplicate_chunks_without_dropping_current_assembly() {
|
||||
let message = JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: "initialized".to_string(),
|
||||
params: None,
|
||||
});
|
||||
let raw = serde_json::to_vec(&message).expect("message should serialize");
|
||||
let split = raw.len() / 2;
|
||||
let client_id = ClientId("client-1".to_string());
|
||||
let stream_id = Some(StreamId("stream-1".to_string()));
|
||||
let mut reassembler = ClientSegmentReassembler::default();
|
||||
|
||||
assert!(matches!(
|
||||
reassembler.observe(chunk_envelope(
|
||||
client_id.clone(),
|
||||
stream_id.clone(),
|
||||
/*seq_id*/ 8,
|
||||
/*segment_id*/ 0,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
&raw[..split],
|
||||
)),
|
||||
ClientSegmentObservation::Pending
|
||||
));
|
||||
assert!(matches!(
|
||||
reassembler.observe(chunk_envelope(
|
||||
client_id.clone(),
|
||||
stream_id.clone(),
|
||||
/*seq_id*/ 8,
|
||||
/*segment_id*/ 0,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
b"",
|
||||
)),
|
||||
ClientSegmentObservation::Dropped
|
||||
));
|
||||
assert!(matches!(
|
||||
reassembler.observe(chunk_envelope(
|
||||
client_id,
|
||||
stream_id,
|
||||
/*seq_id*/ 8,
|
||||
/*segment_id*/ 1,
|
||||
/*segment_count*/ 2,
|
||||
raw.len(),
|
||||
&raw[split..],
|
||||
)),
|
||||
ClientSegmentObservation::Forward(_)
|
||||
));
|
||||
}
|
||||
|
||||
fn chunk_envelope(
|
||||
client_id: ClientId,
|
||||
stream_id: Option<StreamId>,
|
||||
seq_id: u64,
|
||||
segment_id: usize,
|
||||
segment_count: usize,
|
||||
message_size_bytes: usize,
|
||||
chunk: &[u8],
|
||||
) -> ClientEnvelope {
|
||||
ClientEnvelope {
|
||||
event: ClientEvent::ClientMessageChunk {
|
||||
segment_id,
|
||||
segment_count,
|
||||
message_size_bytes,
|
||||
message_chunk_base64: base64::engine::general_purpose::STANDARD.encode(chunk),
|
||||
},
|
||||
client_id,
|
||||
stream_id,
|
||||
seq_id: Some(seq_id),
|
||||
cursor: None,
|
||||
}
|
||||
}
|
||||
@@ -1,388 +0,0 @@
|
||||
use super::auth::RemoteControlConnectionAuth;
|
||||
use super::enroll::RemoteControlEnrollment;
|
||||
use super::enroll::RemoteControlServerTokenRefreshRequirement;
|
||||
use super::enroll::format_headers;
|
||||
use super::enroll::preview_remote_control_response_body;
|
||||
use super::protocol::EnrollRemoteServerRequest;
|
||||
use super::protocol::EnrollRemoteServerResponse;
|
||||
use super::protocol::RefreshRemoteServerRequest;
|
||||
use super::protocol::RemoteControlTarget;
|
||||
use axum::http::HeaderMap;
|
||||
use axum::http::StatusCode;
|
||||
use rand::Rng;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use std::io::ErrorKind;
|
||||
use std::time::Duration;
|
||||
use time::OffsetDateTime;
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
use tracing::warn;
|
||||
|
||||
const REMOTE_CONTROL_RETRY_AFTER_JITTER_MAX_MILLIS: u64 = 30_000;
|
||||
|
||||
const REMOTE_CONTROL_ENROLL_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const REMOTE_CONTROL_SERVER_TOKEN_REFRESH_BACKOFF_MIN_SECS: u64 = 24;
|
||||
const REMOTE_CONTROL_SERVER_TOKEN_REFRESH_BACKOFF_MAX_SECS: u64 = 36;
|
||||
|
||||
pub(super) const REMOTE_CONTROL_INSTALLATION_ID_HEADER: &str = "x-codex-installation-id";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct RemoteControlServerRequestError {
|
||||
message: String,
|
||||
status: Option<StatusCode>,
|
||||
retry_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
impl RemoteControlServerRequestError {
|
||||
pub(super) fn retry_deferred(retry_at: OffsetDateTime) -> io::Error {
|
||||
io::Error::new(
|
||||
ErrorKind::WouldBlock,
|
||||
Self {
|
||||
message: format!("remote control retry deferred until {retry_at}"),
|
||||
status: None,
|
||||
retry_at: Some(retry_at),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn io_error(
|
||||
message: String,
|
||||
status: Option<StatusCode>,
|
||||
retry_at: Option<OffsetDateTime>,
|
||||
timed_out: bool,
|
||||
) -> io::Error {
|
||||
let kind = match status {
|
||||
Some(StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) => ErrorKind::PermissionDenied,
|
||||
Some(StatusCode::NOT_FOUND) => ErrorKind::NotFound,
|
||||
Some(status) if timed_out && !status.is_client_error() => ErrorKind::TimedOut,
|
||||
None if timed_out => ErrorKind::TimedOut,
|
||||
Some(_) | None => ErrorKind::Other,
|
||||
};
|
||||
io::Error::new(
|
||||
kind,
|
||||
Self {
|
||||
message,
|
||||
status,
|
||||
retry_at,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn is_transient(&self, kind: ErrorKind) -> bool {
|
||||
kind == ErrorKind::TimedOut
|
||||
|| self.status.is_none()
|
||||
|| self.status.is_some_and(|status| {
|
||||
status == StatusCode::TOO_MANY_REQUESTS || status.is_server_error()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RemoteControlServerRequestError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(&self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RemoteControlServerRequestError {}
|
||||
|
||||
pub(super) async fn enroll_remote_control_server(
|
||||
remote_control_target: &RemoteControlTarget,
|
||||
auth: &RemoteControlConnectionAuth,
|
||||
installation_id: &str,
|
||||
server_name: &str,
|
||||
) -> io::Result<RemoteControlEnrollment> {
|
||||
let enroll_url = &remote_control_target.enroll_url;
|
||||
let request = EnrollRemoteServerRequest {
|
||||
name: server_name.to_string(),
|
||||
os: std::env::consts::OS,
|
||||
arch: std::env::consts::ARCH,
|
||||
app_server_version: env!("CARGO_PKG_VERSION"),
|
||||
installation_id: installation_id.to_string(),
|
||||
};
|
||||
let enrollment_response = send_remote_control_server_request::<_, EnrollRemoteServerResponse>(
|
||||
enroll_url,
|
||||
auth,
|
||||
installation_id,
|
||||
&request,
|
||||
"enroll",
|
||||
"server enrollment",
|
||||
REMOTE_CONTROL_ENROLL_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
let mut enrollment = RemoteControlEnrollment {
|
||||
remote_control_target: remote_control_target.clone(),
|
||||
account_id: auth.account_id.clone(),
|
||||
environment_id: enrollment_response.environment_id,
|
||||
server_id: enrollment_response.server_id,
|
||||
server_name: server_name.to_string(),
|
||||
remote_control_token: None,
|
||||
expires_at: None,
|
||||
next_refresh_at: None,
|
||||
};
|
||||
update_remote_control_server_token(
|
||||
&mut enrollment,
|
||||
enroll_url,
|
||||
enrollment_response.remote_control_token,
|
||||
enrollment_response.expires_at,
|
||||
)?;
|
||||
Ok(enrollment)
|
||||
}
|
||||
|
||||
pub(super) async fn refresh_remote_control_server(
|
||||
auth: &RemoteControlConnectionAuth,
|
||||
installation_id: &str,
|
||||
enrollment: &mut RemoteControlEnrollment,
|
||||
) -> io::Result<()> {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let refresh_requirement = enrollment.server_token_refresh_requirement_at(now);
|
||||
if refresh_requirement == RemoteControlServerTokenRefreshRequirement::NotNeeded {
|
||||
return Ok(());
|
||||
}
|
||||
if refresh_requirement == RemoteControlServerTokenRefreshRequirement::Required
|
||||
&& let Some(next_refresh_at) = enrollment.next_refresh_at
|
||||
&& next_refresh_at > now
|
||||
{
|
||||
return Err(RemoteControlServerRequestError::retry_deferred(
|
||||
next_refresh_at,
|
||||
));
|
||||
}
|
||||
let refresh_url = enrollment.remote_control_target.refresh_url.clone();
|
||||
let request = RefreshRemoteServerRequest {
|
||||
server_id: enrollment.server_id.clone(),
|
||||
installation_id: installation_id.to_string(),
|
||||
};
|
||||
let refreshed = match send_remote_control_server_request::<_, EnrollRemoteServerResponse>(
|
||||
&refresh_url,
|
||||
auth,
|
||||
installation_id,
|
||||
&request,
|
||||
"refresh",
|
||||
"server refresh",
|
||||
REMOTE_CONTROL_ENROLL_TIMEOUT,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(refreshed) => refreshed,
|
||||
Err(err) => {
|
||||
let Some(refresh_error) = remote_control_server_request_error(&err) else {
|
||||
return Err(err);
|
||||
};
|
||||
if !refresh_error.is_transient(err.kind()) {
|
||||
return Err(err);
|
||||
}
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let refresh_is_required = enrollment.server_token_refresh_requirement_at(now)
|
||||
== RemoteControlServerTokenRefreshRequirement::Required;
|
||||
let (refresh_delay, next_refresh_at) = refresh_deferral(refresh_error.retry_at, now);
|
||||
enrollment.next_refresh_at = Some(next_refresh_at);
|
||||
// An explicit server deadline takes precedence over valid-token fallback.
|
||||
// Keep the token, but let callers defer new requests until this deadline.
|
||||
if refresh_is_required
|
||||
|| refresh_error
|
||||
.retry_at
|
||||
.is_some_and(|retry_at| retry_at > now)
|
||||
{
|
||||
warn!(
|
||||
refresh_url,
|
||||
server_id = %enrollment.server_id,
|
||||
environment_id = %enrollment.environment_id,
|
||||
error = %err,
|
||||
?refresh_delay,
|
||||
%next_refresh_at,
|
||||
"remote control server token refresh failed; deferring new requests"
|
||||
);
|
||||
return Err(err);
|
||||
}
|
||||
warn!(
|
||||
refresh_url,
|
||||
server_id = %enrollment.server_id,
|
||||
environment_id = %enrollment.environment_id,
|
||||
error = %err,
|
||||
?refresh_delay,
|
||||
%next_refresh_at,
|
||||
"proactive remote control server token refresh failed; continuing with valid token"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
if refreshed.server_id != enrollment.server_id
|
||||
|| refreshed.environment_id != enrollment.environment_id
|
||||
{
|
||||
return Err(io::Error::other(format!(
|
||||
"remote control server refresh returned mismatched enrollment: expected server_id={}, environment_id={}; got server_id={}, environment_id={}",
|
||||
enrollment.server_id,
|
||||
enrollment.environment_id,
|
||||
refreshed.server_id,
|
||||
refreshed.environment_id
|
||||
)));
|
||||
}
|
||||
|
||||
update_remote_control_server_token(
|
||||
enrollment,
|
||||
&refresh_url,
|
||||
refreshed.remote_control_token,
|
||||
refreshed.expires_at,
|
||||
)
|
||||
}
|
||||
|
||||
async fn send_remote_control_server_request<Request, Response>(
|
||||
url: &str,
|
||||
auth: &RemoteControlConnectionAuth,
|
||||
installation_id: &str,
|
||||
request: &Request,
|
||||
action: &str,
|
||||
response_kind: &str,
|
||||
timeout: Duration,
|
||||
) -> io::Result<Response>
|
||||
where
|
||||
Request: Serialize,
|
||||
Response: DeserializeOwned,
|
||||
{
|
||||
let (client, auth_headers) = auth.request_context(url).await?;
|
||||
let response = client
|
||||
.post(url)
|
||||
.timeout(timeout)
|
||||
.headers(auth_headers)
|
||||
.header(REMOTE_CONTROL_INSTALLATION_ID_HEADER, installation_id)
|
||||
.json(request)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|err| {
|
||||
if matches!(err, codex_http_client::HttpError::Policy(_)) {
|
||||
return super::auth::request_error(err);
|
||||
}
|
||||
let timed_out = err.is_timeout();
|
||||
RemoteControlServerRequestError::io_error(
|
||||
format!("failed to {action} remote control server at `{url}`: {err}"),
|
||||
/*status*/ None,
|
||||
/*retry_at*/ None,
|
||||
timed_out,
|
||||
)
|
||||
})?;
|
||||
let headers = response.headers().clone();
|
||||
let status = response.status();
|
||||
let retry_at = retry_after_with_jitter(&headers, OffsetDateTime::now_utc());
|
||||
let body = response.bytes().await.map_err(|err| {
|
||||
if matches!(err, codex_http_client::HttpError::Policy(_))
|
||||
&& !(retry_at.is_some() && (status.as_u16() == 429 || status.is_server_error()))
|
||||
{
|
||||
return super::auth::request_error(err);
|
||||
}
|
||||
let timed_out = err.is_timeout();
|
||||
RemoteControlServerRequestError::io_error(
|
||||
format!("failed to read remote control {response_kind} response from `{url}`: {err}"),
|
||||
Some(status),
|
||||
retry_at,
|
||||
timed_out,
|
||||
)
|
||||
})?;
|
||||
let body_preview = preview_remote_control_response_body(&body);
|
||||
if !status.is_success() {
|
||||
let headers_str = format_headers(&headers);
|
||||
return Err(RemoteControlServerRequestError::io_error(
|
||||
format!(
|
||||
"remote control {response_kind} failed at `{url}`: HTTP {status}, {headers_str}, body: {body_preview}"
|
||||
),
|
||||
Some(status),
|
||||
retry_at,
|
||||
/*timed_out*/ false,
|
||||
));
|
||||
}
|
||||
|
||||
serde_json::from_slice::<Response>(&body).map_err(|err| {
|
||||
let headers_str = format_headers(&headers);
|
||||
io::Error::other(format!(
|
||||
"failed to parse remote control {response_kind} response from `{url}`: HTTP {status}, {headers_str}, body: {body_preview}, decode error: {err}"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
fn update_remote_control_server_token(
|
||||
enrollment: &mut RemoteControlEnrollment,
|
||||
url: &str,
|
||||
token: String,
|
||||
expires_at: String,
|
||||
) -> io::Result<()> {
|
||||
let expires_at = OffsetDateTime::parse(&expires_at, &Rfc3339).map_err(|err| {
|
||||
io::Error::other(format!(
|
||||
"failed to parse remote control server token expiry from `{url}`: {err}"
|
||||
))
|
||||
})?;
|
||||
enrollment.remote_control_token = Some(token);
|
||||
enrollment.expires_at = Some(expires_at);
|
||||
enrollment.next_refresh_at = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remote_control_server_request_error(
|
||||
err: &io::Error,
|
||||
) -> Option<&RemoteControlServerRequestError> {
|
||||
err.get_ref()?.downcast_ref()
|
||||
}
|
||||
|
||||
pub(super) fn remote_control_retry_at(err: &io::Error) -> Option<OffsetDateTime> {
|
||||
let request_error = remote_control_server_request_error(err)?;
|
||||
if !request_error.is_transient(err.kind()) {
|
||||
return None;
|
||||
}
|
||||
request_error.retry_at
|
||||
}
|
||||
|
||||
pub(super) fn remote_control_retry_delay(err: &io::Error) -> Option<Duration> {
|
||||
Duration::try_from(remote_control_retry_at(err)? - OffsetDateTime::now_utc()).ok()
|
||||
}
|
||||
|
||||
pub(super) fn retry_after_with_jitter(
|
||||
headers: &HeaderMap,
|
||||
received_at: OffsetDateTime,
|
||||
) -> Option<OffsetDateTime> {
|
||||
let retry_at = parse_retry_after(headers, received_at)?;
|
||||
// Keep the server's deadline as a lower bound, then spread clients across
|
||||
// the next 30 seconds. Sample once per response so retries share a deadline.
|
||||
let jitter = time::Duration::milliseconds(
|
||||
rand::rng().random_range(0..=REMOTE_CONTROL_RETRY_AFTER_JITTER_MAX_MILLIS) as i64,
|
||||
);
|
||||
Some(retry_at.checked_add(jitter).unwrap_or(retry_at))
|
||||
}
|
||||
|
||||
fn parse_retry_after(headers: &HeaderMap, received_at: OffsetDateTime) -> Option<OffsetDateTime> {
|
||||
let retry_after = headers
|
||||
.get(axum::http::header::RETRY_AFTER)?
|
||||
.to_str()
|
||||
.ok()?;
|
||||
let retry_at = if let Ok(seconds) = retry_after.parse::<u64>() {
|
||||
let seconds = i64::try_from(seconds).ok()?;
|
||||
received_at.checked_add(time::Duration::seconds(seconds))?
|
||||
} else {
|
||||
OffsetDateTime::from(httpdate::parse_http_date(retry_after).ok()?)
|
||||
};
|
||||
(retry_at >= received_at).then_some(retry_at)
|
||||
}
|
||||
|
||||
fn refresh_deferral(
|
||||
retry_at: Option<OffsetDateTime>,
|
||||
now: OffsetDateTime,
|
||||
) -> (Duration, OffsetDateTime) {
|
||||
if let Some(retry_at) = retry_at
|
||||
&& let Ok(delay) = Duration::try_from(retry_at - now)
|
||||
&& !delay.is_zero()
|
||||
{
|
||||
return (delay, retry_at);
|
||||
}
|
||||
let delay = remote_control_server_token_refresh_backoff();
|
||||
let next_refresh_at = now + time::Duration::seconds(delay.as_secs() as i64);
|
||||
(delay, next_refresh_at)
|
||||
}
|
||||
|
||||
fn remote_control_server_token_refresh_backoff() -> Duration {
|
||||
Duration::from_secs(rand::rng().random_range(
|
||||
REMOTE_CONTROL_SERVER_TOKEN_REFRESH_BACKOFF_MIN_SECS
|
||||
..=REMOTE_CONTROL_SERVER_TOKEN_REFRESH_BACKOFF_MAX_SECS,
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "server_api_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,325 +0,0 @@
|
||||
use super::*;
|
||||
use crate::transport::remote_control::protocol::normalize_remote_control_url;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::time::SystemTime;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
const TEST_REQUEST_TIMEOUT: Duration = Duration::from_millis(100);
|
||||
|
||||
fn auth() -> RemoteControlConnectionAuth {
|
||||
RemoteControlConnectionAuth {
|
||||
http_client_factory: codex_http_client::HttpClientFactory::new(
|
||||
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
|
||||
),
|
||||
auth: codex_login::CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
runtime_auth: None,
|
||||
account_id: "account-a".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_transient_timeout(err: &io::Error, expected_status: Option<StatusCode>) {
|
||||
let request_error = remote_control_server_request_error(err)
|
||||
.expect("request error should preserve refresh metadata");
|
||||
assert_eq!(
|
||||
(
|
||||
err.kind(),
|
||||
request_error.status,
|
||||
request_error.is_transient(err.kind()),
|
||||
),
|
||||
(ErrorKind::TimedOut, expected_status, true)
|
||||
);
|
||||
}
|
||||
|
||||
async fn timed_out_request(partial_response: Option<&'static [u8]>) -> io::Error {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let url = format!(
|
||||
"http://{}/backend-api/wham/remote/control/server/refresh",
|
||||
listener
|
||||
.local_addr()
|
||||
.expect("listener should have a local address")
|
||||
);
|
||||
let (request_done_tx, request_done_rx) = oneshot::channel();
|
||||
let server_task = tokio::spawn(async move {
|
||||
let (mut stream, _) = listener.accept().await.expect("request should connect");
|
||||
if let Some(partial_response) = partial_response {
|
||||
stream
|
||||
.write_all(partial_response)
|
||||
.await
|
||||
.expect("partial response should write");
|
||||
}
|
||||
request_done_rx
|
||||
.await
|
||||
.expect("test should report request completion");
|
||||
});
|
||||
|
||||
let err = send_remote_control_server_request::<_, serde_json::Value>(
|
||||
&url,
|
||||
&auth(),
|
||||
"installation-id",
|
||||
&json!({"server_id": "server-id"}),
|
||||
"refresh",
|
||||
"server refresh",
|
||||
TEST_REQUEST_TIMEOUT,
|
||||
)
|
||||
.await
|
||||
.expect_err("incomplete response should time out");
|
||||
request_done_tx
|
||||
.send(())
|
||||
.expect("server should wait for request completion");
|
||||
server_task.await.expect("server task should finish");
|
||||
err
|
||||
}
|
||||
|
||||
fn enrollment(now: OffsetDateTime) -> RemoteControlEnrollment {
|
||||
RemoteControlEnrollment {
|
||||
remote_control_target: normalize_remote_control_url("http://localhost/backend-api/")
|
||||
.expect("target should normalize"),
|
||||
account_id: "account-a".to_string(),
|
||||
environment_id: "env_first".to_string(),
|
||||
server_id: "srv_e_first".to_string(),
|
||||
server_name: "first-server".to_string(),
|
||||
remote_control_token: Some("token".to_string()),
|
||||
expires_at: Some(now + time::Duration::seconds(300)),
|
||||
next_refresh_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_enrollment_classifies_server_token_refresh_requirement() {
|
||||
let now =
|
||||
OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("test timestamp should parse");
|
||||
let enrollment = enrollment(now);
|
||||
let cases = [
|
||||
(
|
||||
enrollment.clone(),
|
||||
RemoteControlServerTokenRefreshRequirement::Proactive,
|
||||
),
|
||||
(
|
||||
RemoteControlEnrollment {
|
||||
expires_at: Some(now + time::Duration::seconds(301)),
|
||||
..enrollment.clone()
|
||||
},
|
||||
RemoteControlServerTokenRefreshRequirement::NotNeeded,
|
||||
),
|
||||
(
|
||||
RemoteControlEnrollment {
|
||||
next_refresh_at: Some(now + time::Duration::seconds(30)),
|
||||
..enrollment.clone()
|
||||
},
|
||||
RemoteControlServerTokenRefreshRequirement::NotNeeded,
|
||||
),
|
||||
(
|
||||
RemoteControlEnrollment {
|
||||
next_refresh_at: Some(now),
|
||||
..enrollment.clone()
|
||||
},
|
||||
RemoteControlServerTokenRefreshRequirement::Proactive,
|
||||
),
|
||||
(
|
||||
RemoteControlEnrollment {
|
||||
remote_control_token: None,
|
||||
..enrollment.clone()
|
||||
},
|
||||
RemoteControlServerTokenRefreshRequirement::Required,
|
||||
),
|
||||
(
|
||||
RemoteControlEnrollment {
|
||||
expires_at: None,
|
||||
..enrollment.clone()
|
||||
},
|
||||
RemoteControlServerTokenRefreshRequirement::Required,
|
||||
),
|
||||
(
|
||||
RemoteControlEnrollment {
|
||||
expires_at: Some(now),
|
||||
next_refresh_at: Some(now + time::Duration::hours(1)),
|
||||
..enrollment
|
||||
},
|
||||
RemoteControlServerTokenRefreshRequirement::Required,
|
||||
),
|
||||
];
|
||||
|
||||
for (enrollment, expected) in cases {
|
||||
assert_eq!(
|
||||
enrollment.server_token_refresh_requirement_at(now),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_server_request_error_classifies_status_before_timeout() {
|
||||
let cases = [
|
||||
(None, true, ErrorKind::TimedOut, true),
|
||||
(Some(StatusCode::OK), true, ErrorKind::TimedOut, true),
|
||||
(
|
||||
Some(StatusCode::TOO_MANY_REQUESTS),
|
||||
false,
|
||||
ErrorKind::Other,
|
||||
true,
|
||||
),
|
||||
(Some(StatusCode::BAD_GATEWAY), false, ErrorKind::Other, true),
|
||||
(
|
||||
Some(StatusCode::UNAUTHORIZED),
|
||||
true,
|
||||
ErrorKind::PermissionDenied,
|
||||
false,
|
||||
),
|
||||
(
|
||||
Some(StatusCode::FORBIDDEN),
|
||||
true,
|
||||
ErrorKind::PermissionDenied,
|
||||
false,
|
||||
),
|
||||
(
|
||||
Some(StatusCode::NOT_FOUND),
|
||||
true,
|
||||
ErrorKind::NotFound,
|
||||
false,
|
||||
),
|
||||
(Some(StatusCode::BAD_REQUEST), true, ErrorKind::Other, false),
|
||||
(None, false, ErrorKind::Other, true),
|
||||
];
|
||||
|
||||
for (status, timed_out, expected_kind, expected_transient) in cases {
|
||||
let err = RemoteControlServerRequestError::io_error(
|
||||
String::new(),
|
||||
status,
|
||||
/*retry_at*/ None,
|
||||
timed_out,
|
||||
);
|
||||
let request_error = remote_control_server_request_error(&err)
|
||||
.expect("request error should preserve refresh metadata");
|
||||
assert_eq!(
|
||||
(err.kind(), request_error.is_transient(err.kind())),
|
||||
(expected_kind, expected_transient)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_timeout_before_response_headers_is_transient() {
|
||||
let err = timed_out_request(/*partial_response*/ None).await;
|
||||
assert_transient_timeout(&err, /*expected_status*/ None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn response_body_timeout_is_transient() {
|
||||
let err = timed_out_request(Some(b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\n\r\n{")).await;
|
||||
assert_transient_timeout(&err, Some(StatusCode::OK));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_after_supports_delta_seconds_and_http_dates() {
|
||||
let now =
|
||||
OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("test timestamp should parse");
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
axum::http::header::RETRY_AFTER,
|
||||
axum::http::HeaderValue::from_static("120"),
|
||||
);
|
||||
assert_eq!(
|
||||
parse_retry_after(&headers, now),
|
||||
Some(now + time::Duration::seconds(120))
|
||||
);
|
||||
|
||||
let retry_at = now + time::Duration::seconds(90);
|
||||
let retry_at_system = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_090);
|
||||
headers.insert(
|
||||
axum::http::header::RETRY_AFTER,
|
||||
httpdate::fmt_http_date(retry_at_system)
|
||||
.parse()
|
||||
.expect("HTTP date should be a valid header value"),
|
||||
);
|
||||
assert_eq!(parse_retry_after(&headers, now), Some(retry_at));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_or_expired_retry_after_uses_bounded_fallback() {
|
||||
let now =
|
||||
OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("test timestamp should parse");
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
axum::http::header::RETRY_AFTER,
|
||||
axum::http::HeaderValue::from_static("invalid"),
|
||||
);
|
||||
assert_eq!(parse_retry_after(&headers, now), None);
|
||||
|
||||
headers.insert(
|
||||
axum::http::header::RETRY_AFTER,
|
||||
httpdate::fmt_http_date(SystemTime::UNIX_EPOCH + Duration::from_secs(1_699_999_999))
|
||||
.parse()
|
||||
.expect("HTTP date should be a valid header value"),
|
||||
);
|
||||
assert_eq!(parse_retry_after(&headers, now), None);
|
||||
|
||||
let expired_while_reading_body = Some(now + time::Duration::seconds(1));
|
||||
for retry_at in [None, expired_while_reading_body] {
|
||||
let deferred_at = now + time::Duration::seconds(2);
|
||||
let (delay, next_refresh_at) = refresh_deferral(retry_at, deferred_at);
|
||||
assert!(
|
||||
(Duration::from_secs(REMOTE_CONTROL_SERVER_TOKEN_REFRESH_BACKOFF_MIN_SECS)
|
||||
..=Duration::from_secs(REMOTE_CONTROL_SERVER_TOKEN_REFRESH_BACKOFF_MAX_SECS,))
|
||||
.contains(&delay)
|
||||
);
|
||||
assert_eq!(
|
||||
next_refresh_at,
|
||||
deferred_at + time::Duration::seconds(delay.as_secs() as i64)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_date_retry_after_preserves_absolute_deadline() {
|
||||
let received_at =
|
||||
OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("test timestamp should parse");
|
||||
let retry_at = received_at + time::Duration::seconds(120);
|
||||
let body_read_at = received_at + time::Duration::seconds(30);
|
||||
|
||||
assert_eq!(
|
||||
refresh_deferral(Some(retry_at), body_read_at),
|
||||
(Duration::from_secs(90), retry_at)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_after_jitter_never_shortens_the_server_deadline() {
|
||||
let now =
|
||||
OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("test timestamp should parse");
|
||||
for value in ["120", "Tue, 14 Nov 2023 22:15:20 GMT"] {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
axum::http::header::RETRY_AFTER,
|
||||
value.parse().expect("retry hint should be a valid header"),
|
||||
);
|
||||
let deadline = retry_after_with_jitter(&headers, now)
|
||||
.expect("a valid retry hint should produce a deadline");
|
||||
assert!(
|
||||
(now + time::Duration::seconds(120)..=now + time::Duration::seconds(150))
|
||||
.contains(&deadline)
|
||||
);
|
||||
// Reading the response body must not start a new relative wait or resample jitter.
|
||||
let (delay, deferred_until) =
|
||||
refresh_deferral(Some(deadline), now + time::Duration::seconds(30));
|
||||
assert_eq!(deferred_until, deadline);
|
||||
assert!((Duration::from_secs(90)..=Duration::from_secs(120)).contains(&delay));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_retry_after_preserves_bounded_jitter() {
|
||||
let now = OffsetDateTime::UNIX_EPOCH;
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
axum::http::header::RETRY_AFTER,
|
||||
axum::http::HeaderValue::from_static("0"),
|
||||
);
|
||||
let deadline = retry_after_with_jitter(&headers, now)
|
||||
.expect("a zero-second retry hint should produce a deadline");
|
||||
assert!((now..=now + time::Duration::seconds(30)).contains(&deadline));
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,424 +0,0 @@
|
||||
use super::super::clients::list_remote_control_clients;
|
||||
use super::super::clients::revoke_remote_control_client;
|
||||
use super::*;
|
||||
use codex_app_server_protocol::RemoteControlClient;
|
||||
use codex_app_server_protocol::RemoteControlClientsListOrder;
|
||||
use codex_app_server_protocol::RemoteControlClientsListParams;
|
||||
use codex_app_server_protocol::RemoteControlClientsListResponse;
|
||||
use codex_app_server_protocol::RemoteControlClientsRevokeParams;
|
||||
use codex_app_server_protocol::RemoteControlClientsRevokeResponse;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn client_management_handle(
|
||||
remote_control_url: String,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
) -> RemoteControlSession {
|
||||
let desired_state_tx = watch::channel(RemoteControlDesiredState::Disabled).0;
|
||||
let (status_tx, _status_rx) = watch::channel(RemoteControlStatusChangedNotification {
|
||||
status: RemoteControlConnectionStatus::Disabled,
|
||||
server_name: test_server_name(),
|
||||
installation_id: TEST_INSTALLATION_ID.to_string(),
|
||||
environment_id: None,
|
||||
});
|
||||
RemoteControlSession {
|
||||
policy: RemoteControlPolicy::Allowed,
|
||||
shutdown_token: CancellationToken::new(),
|
||||
desired_state_tx: Arc::new(desired_state_tx),
|
||||
desired_state_rpc_lock: Arc::new(Semaphore::new(1)),
|
||||
persistence: RemoteControlPersistence::default(),
|
||||
status_tx: Arc::new(status_tx),
|
||||
state_db: None,
|
||||
remote_control_url,
|
||||
current_enrollment: Arc::new(RemoteControlEnrollmentState::new(/*enrollment*/ None)),
|
||||
pairing_persistence_key: watch::channel(None).0,
|
||||
pairing_persistence_key_required: false,
|
||||
auth_manager: auth::RemoteControlAuth::capture(auth_manager, /*runtime_auth*/ None).0,
|
||||
}
|
||||
}
|
||||
|
||||
fn empty_client_list() -> serde_json::Value {
|
||||
json!({
|
||||
"items": [],
|
||||
"cursor": null,
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_control_handle_lists_clients_while_disabled() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let server_task = tokio::spawn(async move {
|
||||
let request = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
request.request_line,
|
||||
"GET /backend-api/wham/remote/control/environments/env%20%2F%3F/clients?cursor=cursor+%2F%3F&limit=10&order=asc HTTP/1.1"
|
||||
);
|
||||
assert_eq!(
|
||||
request.headers.get("authorization"),
|
||||
Some(&"Bearer Access Token".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
request.headers.get_all(REMOTE_CONTROL_ACCOUNT_ID_HEADER),
|
||||
vec!["account_id"]
|
||||
);
|
||||
respond_with_json(
|
||||
request.stream,
|
||||
json!({
|
||||
"items": [{
|
||||
"client_id": "client-123",
|
||||
"account_user_id": "user-123",
|
||||
"enrollment_status": "enrolled_device_key",
|
||||
"display_name": "Anton Phone",
|
||||
"device_type": "phone",
|
||||
"platform": "ios",
|
||||
"os_version": "19.0",
|
||||
"device_model": "iPhone",
|
||||
"app_version": "1.2.3",
|
||||
"last_seen_at": "2026-03-05T07:00:00Z",
|
||||
"last_seen_city": "San Francisco",
|
||||
}],
|
||||
"cursor": "next-cursor",
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
});
|
||||
let handle = client_management_handle(remote_control_url, remote_control_auth_manager());
|
||||
|
||||
let response = handle
|
||||
.list_clients(RemoteControlClientsListParams {
|
||||
environment_id: "env /?".to_string(),
|
||||
cursor: Some("cursor /?".to_string()),
|
||||
limit: Some(10),
|
||||
order: Some(RemoteControlClientsListOrder::Asc),
|
||||
})
|
||||
.await
|
||||
.expect("client list should succeed while remote control is disabled");
|
||||
server_task.await.expect("server task should finish");
|
||||
|
||||
assert_eq!(
|
||||
response,
|
||||
RemoteControlClientsListResponse {
|
||||
data: vec![RemoteControlClient {
|
||||
client_id: "client-123".to_string(),
|
||||
display_name: Some("Anton Phone".to_string()),
|
||||
device_type: Some("phone".to_string()),
|
||||
platform: Some("ios".to_string()),
|
||||
os_version: Some("19.0".to_string()),
|
||||
device_model: Some("iPhone".to_string()),
|
||||
app_version: Some("1.2.3".to_string()),
|
||||
last_seen_at: Some(1_772_694_000),
|
||||
}],
|
||||
next_cursor: Some("next-cursor".to_string()),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_control_handle_revokes_client_while_disabled() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let server_task = tokio::spawn(async move {
|
||||
let request = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
request.request_line,
|
||||
"DELETE /backend-api/wham/remote/control/environments/env%20%2F%3F/clients/client%20%2F%3F HTTP/1.1"
|
||||
);
|
||||
assert_eq!(
|
||||
request.headers.get("authorization"),
|
||||
Some(&"Bearer Access Token".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
request.headers.get_all(REMOTE_CONTROL_ACCOUNT_ID_HEADER),
|
||||
vec!["account_id"]
|
||||
);
|
||||
respond_with_status(request.stream, "204 No Content", "").await;
|
||||
});
|
||||
let handle = client_management_handle(remote_control_url, remote_control_auth_manager());
|
||||
|
||||
let response = handle
|
||||
.revoke_client(RemoteControlClientsRevokeParams {
|
||||
environment_id: "env /?".to_string(),
|
||||
client_id: "client /?".to_string(),
|
||||
})
|
||||
.await
|
||||
.expect("client revoke should succeed while remote control is disabled");
|
||||
server_task.await.expect("server task should finish");
|
||||
|
||||
assert_eq!(response, RemoteControlClientsRevokeResponse {});
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_remote_control_clients_recovers_auth_after_unauthorized() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let server_task = tokio::spawn(async move {
|
||||
let stale_request = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
stale_request.headers.get("authorization"),
|
||||
Some(&"Bearer stale-token".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
stale_request
|
||||
.headers
|
||||
.get_all(REMOTE_CONTROL_ACCOUNT_ID_HEADER),
|
||||
vec!["account_id"]
|
||||
);
|
||||
respond_with_status(stale_request.stream, "401 Unauthorized", "").await;
|
||||
|
||||
let recovered_request = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
recovered_request.headers.get("authorization"),
|
||||
Some(&"Bearer fresh-token".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
recovered_request
|
||||
.headers
|
||||
.get_all(REMOTE_CONTROL_ACCOUNT_ID_HEADER),
|
||||
vec!["account_id"]
|
||||
);
|
||||
respond_with_json(recovered_request.stream, empty_client_list()).await;
|
||||
});
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let mut stale_auth = remote_control_auth_dot_json(Some("account_id"));
|
||||
stale_auth
|
||||
.tokens
|
||||
.as_mut()
|
||||
.expect("stale auth should include tokens")
|
||||
.access_token = "stale-token".to_string();
|
||||
save_auth(
|
||||
codex_home.path(),
|
||||
&stale_auth,
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.expect("stale auth should save");
|
||||
let auth_manager = AuthManager::shared(
|
||||
codex_home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
/*chatgpt_base_url*/ None,
|
||||
AuthKeyringBackendKind::default(),
|
||||
codex_login::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.await;
|
||||
let mut fresh_auth = remote_control_auth_dot_json(Some("account_id"));
|
||||
fresh_auth
|
||||
.tokens
|
||||
.as_mut()
|
||||
.expect("fresh auth should include tokens")
|
||||
.access_token = "fresh-token".to_string();
|
||||
save_auth(
|
||||
codex_home.path(),
|
||||
&fresh_auth,
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.expect("fresh auth should save");
|
||||
|
||||
let response = list_remote_control_clients(
|
||||
&remote_control_url,
|
||||
&auth::RemoteControlAuth::capture(auth_manager.clone(), /*runtime_auth*/ None).0,
|
||||
RemoteControlClientsListParams {
|
||||
environment_id: "env-123".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("client list should recover auth");
|
||||
server_task.await.expect("server task should finish");
|
||||
|
||||
assert_eq!(
|
||||
response,
|
||||
RemoteControlClientsListResponse {
|
||||
data: Vec::new(),
|
||||
next_cursor: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_remote_control_clients_retries_unauthorized_only_once() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let server_task = tokio::spawn(async move {
|
||||
let stale_request = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
stale_request.headers.get("authorization"),
|
||||
Some(&"Bearer stale-token".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
stale_request
|
||||
.headers
|
||||
.get_all(REMOTE_CONTROL_ACCOUNT_ID_HEADER),
|
||||
vec!["account_id"]
|
||||
);
|
||||
respond_with_status(stale_request.stream, "401 Unauthorized", "").await;
|
||||
|
||||
let recovered_request = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
recovered_request.headers.get("authorization"),
|
||||
Some(&"Bearer fresh-token".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
recovered_request
|
||||
.headers
|
||||
.get_all(REMOTE_CONTROL_ACCOUNT_ID_HEADER),
|
||||
vec!["account_id"]
|
||||
);
|
||||
respond_with_status(recovered_request.stream, "401 Unauthorized", "").await;
|
||||
|
||||
assert!(
|
||||
timeout(Duration::from_millis(100), accept_http_request(&listener))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
});
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let mut stale_auth = remote_control_auth_dot_json(Some("account_id"));
|
||||
stale_auth
|
||||
.tokens
|
||||
.as_mut()
|
||||
.expect("stale auth should include tokens")
|
||||
.access_token = "stale-token".to_string();
|
||||
save_auth(
|
||||
codex_home.path(),
|
||||
&stale_auth,
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.expect("stale auth should save");
|
||||
let auth_manager = AuthManager::shared(
|
||||
codex_home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
/*chatgpt_base_url*/ None,
|
||||
AuthKeyringBackendKind::default(),
|
||||
codex_login::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.await;
|
||||
let mut fresh_auth = remote_control_auth_dot_json(Some("account_id"));
|
||||
fresh_auth
|
||||
.tokens
|
||||
.as_mut()
|
||||
.expect("fresh auth should include tokens")
|
||||
.access_token = "fresh-token".to_string();
|
||||
save_auth(
|
||||
codex_home.path(),
|
||||
&fresh_auth,
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.expect("fresh auth should save");
|
||||
|
||||
let err = list_remote_control_clients(
|
||||
&remote_control_url,
|
||||
&auth::RemoteControlAuth::capture(auth_manager.clone(), /*runtime_auth*/ None).0,
|
||||
RemoteControlClientsListParams {
|
||||
environment_id: "env-123".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("second unauthorized response should fail");
|
||||
server_task.await.expect("server task should finish");
|
||||
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn revoke_remote_control_client_does_not_retry_forbidden() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let server_task = tokio::spawn(async move {
|
||||
let request = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
request.headers.get("authorization"),
|
||||
Some(&"Bearer Access Token".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
request.headers.get_all(REMOTE_CONTROL_ACCOUNT_ID_HEADER),
|
||||
vec!["account_id"]
|
||||
);
|
||||
respond_with_status_and_headers(
|
||||
request.stream,
|
||||
"403 Forbidden",
|
||||
&[("x-request-id", "request-123"), ("cf-ray", "ray-123")],
|
||||
"forbidden",
|
||||
)
|
||||
.await;
|
||||
});
|
||||
|
||||
let err = revoke_remote_control_client(
|
||||
&remote_control_url,
|
||||
&auth::RemoteControlAuth::capture(
|
||||
remote_control_auth_manager(),
|
||||
/*runtime_auth*/ None,
|
||||
)
|
||||
.0,
|
||||
RemoteControlClientsRevokeParams {
|
||||
environment_id: "env-123".to_string(),
|
||||
client_id: "client-123".to_string(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("forbidden revoke should fail");
|
||||
server_task.await.expect("server task should finish");
|
||||
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied);
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
format!(
|
||||
"remote control client revoke failed at `{remote_control_url}wham/remote/control/environments/env-123/clients/client-123`: HTTP 403 Forbidden, request-id: request-123, cf-ray: ray-123, body: forbidden"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_remote_control_clients_preserves_decode_error_context() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let server_task = tokio::spawn(async move {
|
||||
let request = accept_http_request(&listener).await;
|
||||
respond_with_status(request.stream, "200 OK", "{").await;
|
||||
});
|
||||
|
||||
let err = list_remote_control_clients(
|
||||
&remote_control_url,
|
||||
&auth::RemoteControlAuth::capture(
|
||||
remote_control_auth_manager(),
|
||||
/*runtime_auth*/ None,
|
||||
)
|
||||
.0,
|
||||
RemoteControlClientsListParams {
|
||||
environment_id: "env-123".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("malformed client list should fail");
|
||||
server_task.await.expect("server task should finish");
|
||||
|
||||
assert!(
|
||||
err.to_string().contains(
|
||||
"failed to parse remote control client list response from `http://127.0.0.1:"
|
||||
)
|
||||
);
|
||||
assert!(err.to_string().contains("HTTP 200 OK"));
|
||||
assert!(err.to_string().contains("body: {"));
|
||||
assert!(err.to_string().contains("decode error:"));
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,349 +0,0 @@
|
||||
//! Exercises overload deadlines and automatic reconnect backoff over real connections.
|
||||
//! Auth reloads must respect the deadline; shutdown must remain prompt.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn rate_limited_enrollment_respects_retry_after() {
|
||||
assert_overload_retry_after("429 Too Many Requests", /*reject_enrollment*/ true).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rate_limited_websocket_respects_retry_after() {
|
||||
assert_overload_retry_after("429 Too Many Requests", /*reject_enrollment*/ false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn enrollment_resumes_after_retry_after() {
|
||||
assert_overload_retry_after("503 Service Unavailable", /*reject_enrollment*/ true).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn websocket_resumes_after_retry_after() {
|
||||
assert_overload_retry_after("503 Service Unavailable", /*reject_enrollment*/ false).await;
|
||||
}
|
||||
|
||||
async fn assert_overload_retry_after(status: &str, reject_enrollment: bool) {
|
||||
let verify_recovery = status == "503 Service Unavailable";
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let (transport_event_tx, _transport_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let auth_manager = remote_control_auth_manager_with_home(&codex_home);
|
||||
let mut initial_auth = remote_control_auth_dot_json(Some("account_id"));
|
||||
initial_auth
|
||||
.tokens
|
||||
.as_mut()
|
||||
.expect("fixture should contain tokens")
|
||||
.access_token = "Initial Access Token".to_string();
|
||||
save_auth(
|
||||
codex_home.path(),
|
||||
&initial_auth,
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.expect("initial credentials should save");
|
||||
auth_manager.reload().await;
|
||||
let (remote_task, remote_handle) = start_remote_control(
|
||||
RemoteControlStartConfig {
|
||||
runtime_auth: None,
|
||||
remote_control_url: remote_control_url_for_listener(&listener),
|
||||
installation_id: TEST_INSTALLATION_ID.to_string(),
|
||||
policy: RemoteControlPolicy::Allowed,
|
||||
},
|
||||
Some(remote_control_state_runtime(&codex_home).await),
|
||||
auth_manager.clone(),
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
RemoteControlStartupMode::EnabledEphemeral,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start");
|
||||
let mut status_rx = remote_handle.status_receiver();
|
||||
let mut rejected_request = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
rejected_request.request_line,
|
||||
"POST /backend-api/wham/remote/control/server/enroll HTTP/1.1"
|
||||
);
|
||||
if !reject_enrollment {
|
||||
respond_with_json(
|
||||
rejected_request.stream,
|
||||
remote_control_server_token_response(
|
||||
"srv_e_test",
|
||||
"env_test",
|
||||
TEST_REMOTE_CONTROL_SERVER_TOKEN,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
rejected_request = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
rejected_request.request_line,
|
||||
"GET /backend-api/wham/remote/control/server HTTP/1.1"
|
||||
);
|
||||
}
|
||||
let response_started_at = std::time::Instant::now();
|
||||
respond_with_status_and_headers(
|
||||
rejected_request.stream,
|
||||
status,
|
||||
&[("Retry-After", if verify_recovery { "3" } else { "120" })],
|
||||
"overloaded",
|
||||
)
|
||||
.await;
|
||||
timeout(
|
||||
Duration::from_secs(5),
|
||||
status_rx.wait_for(|status| status.status == RemoteControlConnectionStatus::Errored),
|
||||
)
|
||||
.await
|
||||
.expect("the overload response should be processed")
|
||||
.expect("the status channel should remain open");
|
||||
|
||||
let auth_changes = auth_manager.auth_change_receiver();
|
||||
save_auth(
|
||||
codex_home.path(),
|
||||
&remote_control_auth_dot_json(Some("account_id")),
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.expect("updated credentials should save");
|
||||
auth_manager.reload().await;
|
||||
assert!(
|
||||
auth_changes
|
||||
.has_changed()
|
||||
.expect("auth watch should remain open")
|
||||
);
|
||||
|
||||
if !verify_recovery {
|
||||
let pairing_error = timeout(
|
||||
Duration::from_secs(1),
|
||||
remote_handle.start_pairing(
|
||||
RemoteControlPairingStartParams::default(),
|
||||
/*app_server_client_name*/ None,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("pairing should report the active retry delay promptly")
|
||||
.expect_err("pairing must respect the shared server retry delay");
|
||||
let retry_delay = server_api::remote_control_retry_delay(&pairing_error)
|
||||
.expect("pairing should preserve the overload retry deadline");
|
||||
assert!(
|
||||
retry_delay >= Duration::from_secs(120).saturating_sub(response_started_at.elapsed()),
|
||||
"pairing must preserve the full remaining Retry-After interval"
|
||||
);
|
||||
assert!(
|
||||
timeout(Duration::from_secs(2), listener.accept())
|
||||
.await
|
||||
.is_err(),
|
||||
"no enrollment, refresh or handshake should retry before Retry-After ({status})"
|
||||
);
|
||||
remote_handle.disable_ephemeral().await;
|
||||
assert!(
|
||||
timeout(Duration::from_secs(2), listener.accept())
|
||||
.await
|
||||
.is_err(),
|
||||
"disabling remote control must stop connection attempts"
|
||||
);
|
||||
remote_handle
|
||||
.enable_ephemeral()
|
||||
.expect("remote control should enable again");
|
||||
assert!(
|
||||
timeout(Duration::from_secs(2), listener.accept())
|
||||
.await
|
||||
.is_err(),
|
||||
"re-enabling remote control must preserve the server retry delay"
|
||||
);
|
||||
}
|
||||
if !reject_enrollment {
|
||||
assert_eq!(
|
||||
remote_handle
|
||||
.inner
|
||||
.session()
|
||||
.current_enrollment
|
||||
.snapshot()
|
||||
.and_then(|enrollment| enrollment.remote_control_token),
|
||||
Some(TEST_REMOTE_CONTROL_SERVER_TOKEN.to_string()),
|
||||
"overload must preserve the enrolled token"
|
||||
);
|
||||
}
|
||||
if verify_recovery {
|
||||
remote_handle.disable_ephemeral().await;
|
||||
remote_handle
|
||||
.enable_ephemeral()
|
||||
.expect("remote control should enable again");
|
||||
let (stream, _) = timeout(Duration::from_secs(45), listener.accept())
|
||||
.await
|
||||
.expect("retry should resume after the server delay and bounded jitter")
|
||||
.expect("retry connection should succeed");
|
||||
assert!(
|
||||
response_started_at.elapsed() >= Duration::from_secs(3),
|
||||
"the retry must wait for the full Retry-After interval"
|
||||
);
|
||||
let mut reader = BufReader::new(stream);
|
||||
let mut request_line = String::new();
|
||||
timeout(Duration::from_secs(5), reader.read_line(&mut request_line))
|
||||
.await
|
||||
.expect("retry should send the request promptly")
|
||||
.expect("retry request should read");
|
||||
assert_eq!(
|
||||
request_line.trim_end(),
|
||||
if reject_enrollment {
|
||||
"POST /backend-api/wham/remote/control/server/enroll HTTP/1.1"
|
||||
} else {
|
||||
"GET /backend-api/wham/remote/control/server HTTP/1.1"
|
||||
}
|
||||
);
|
||||
}
|
||||
shutdown_token.cancel();
|
||||
timeout(Duration::from_secs(1), remote_task)
|
||||
.await
|
||||
.expect("shutdown must interrupt the server retry delay")
|
||||
.expect("remote task should finish");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconnect_backoff_covers_refresh_and_resets_after_healthy_connection() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let (transport_event_tx, _transport_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let (remote_task, remote_handle) = start_remote_control(
|
||||
RemoteControlStartConfig {
|
||||
runtime_auth: None,
|
||||
remote_control_url: remote_control_url_for_listener(&listener),
|
||||
installation_id: TEST_INSTALLATION_ID.to_string(),
|
||||
policy: RemoteControlPolicy::Allowed,
|
||||
},
|
||||
Some(remote_control_state_runtime(&codex_home).await),
|
||||
remote_control_auth_manager(),
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
RemoteControlStartupMode::EnabledEphemeral,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start");
|
||||
let mut status_rx = remote_handle.status_receiver();
|
||||
let enroll_request = accept_http_request(&listener).await;
|
||||
respond_with_json(
|
||||
enroll_request.stream,
|
||||
remote_control_server_token_response(
|
||||
"srv_e_test",
|
||||
"env_test",
|
||||
TEST_REMOTE_CONTROL_SERVER_TOKEN,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let mut websocket = accept_remote_control_connection(&listener).await;
|
||||
status_rx
|
||||
.wait_for(|status| status.status == RemoteControlConnectionStatus::Connected)
|
||||
.await
|
||||
.expect("initial connection should succeed");
|
||||
|
||||
// Make the next connection require token work before its handshake.
|
||||
remote_handle
|
||||
.inner
|
||||
.session()
|
||||
.current_enrollment
|
||||
.lock()
|
||||
.await
|
||||
.as_mut()
|
||||
.expect("enrollment should exist")
|
||||
.clear_server_token();
|
||||
let disconnected_at = tokio::time::Instant::now();
|
||||
websocket.close(None).await.expect("websocket should close");
|
||||
drop(websocket);
|
||||
let refresh_request =
|
||||
accept_http_request_with_timeout(&listener, Duration::from_secs(45)).await;
|
||||
assert_eq!(
|
||||
refresh_request.request_line,
|
||||
"POST /backend-api/wham/remote/control/server/refresh HTTP/1.1"
|
||||
);
|
||||
assert!(
|
||||
disconnected_at.elapsed() >= Duration::from_millis(2_500),
|
||||
"the first automatic reconnect must wait before refreshing its token"
|
||||
);
|
||||
respond_with_json(
|
||||
refresh_request.stream,
|
||||
remote_control_server_token_response(
|
||||
"srv_e_test",
|
||||
"env_test",
|
||||
TEST_REFRESHED_REMOTE_CONTROL_SERVER_TOKEN,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let mut websocket = accept_remote_control_connection(&listener).await;
|
||||
status_rx
|
||||
.wait_for(|status| status.status == RemoteControlConnectionStatus::Connected)
|
||||
.await
|
||||
.expect("reconnect should succeed");
|
||||
|
||||
let disconnected_at = tokio::time::Instant::now();
|
||||
websocket.close(None).await.expect("websocket should close");
|
||||
drop(websocket);
|
||||
let mut websocket =
|
||||
accept_remote_control_connection_with_timeout(&listener, Duration::from_secs(45)).await;
|
||||
assert!(
|
||||
disconnected_at.elapsed() >= Duration::from_secs(5),
|
||||
"a short-lived connection must retain the increased backoff"
|
||||
);
|
||||
status_rx
|
||||
.wait_for(|status| status.status == RemoteControlConnectionStatus::Connected)
|
||||
.await
|
||||
.expect("reconnect should succeed");
|
||||
|
||||
// Skip most of the healthy interval without crossing the 60-second pong timeout.
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(45)).await;
|
||||
tokio::time::resume();
|
||||
// Drive the socket so tungstenite answers pings while we cross the reset threshold.
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(Duration::from_secs(16)) => {}
|
||||
_ = async {
|
||||
while let Some(frame) = websocket.next().await {
|
||||
frame.expect("healthy connection should remain readable");
|
||||
}
|
||||
} => panic!("healthy connection should remain open"),
|
||||
}
|
||||
websocket.close(None).await.expect("websocket should close");
|
||||
drop(websocket);
|
||||
let mut websocket =
|
||||
accept_remote_control_connection_with_timeout(&listener, Duration::from_secs(8)).await;
|
||||
status_rx
|
||||
.wait_for(|status| status.status == RemoteControlConnectionStatus::Connected)
|
||||
.await
|
||||
.expect("reconnect should succeed");
|
||||
|
||||
websocket.close(None).await.expect("websocket should close");
|
||||
drop(websocket);
|
||||
status_rx
|
||||
.wait_for(|status| status.status == RemoteControlConnectionStatus::Connecting)
|
||||
.await
|
||||
.expect("closed socket should enter reconnect backoff");
|
||||
remote_handle.disable_ephemeral().await;
|
||||
// Re-enable immediately, before the websocket task can observe the disabled state.
|
||||
remote_handle
|
||||
.enable_ephemeral()
|
||||
.expect("remote control should enable again");
|
||||
let mut websocket =
|
||||
accept_remote_control_connection_with_timeout(&listener, Duration::from_secs(2)).await;
|
||||
status_rx
|
||||
.wait_for(|status| status.status == RemoteControlConnectionStatus::Connected)
|
||||
.await
|
||||
.expect("explicit connection should succeed");
|
||||
websocket.close(None).await.expect("websocket should close");
|
||||
drop(websocket);
|
||||
status_rx
|
||||
.wait_for(|status| status.status == RemoteControlConnectionStatus::Connecting)
|
||||
.await
|
||||
.expect("closed socket should enter reconnect backoff");
|
||||
shutdown_token.cancel();
|
||||
timeout(Duration::from_secs(1), remote_task)
|
||||
.await
|
||||
.expect("shutdown must interrupt reconnect backoff")
|
||||
.expect("remote task should finish");
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,768 +0,0 @@
|
||||
use super::tests::TEST_HTTP_ACCEPT_TIMEOUT;
|
||||
use super::tests::TEST_INSTALLATION_ID;
|
||||
use super::tests::TEST_REMOTE_CONTROL_SERVER_TOKEN;
|
||||
use super::tests::accept_http_request;
|
||||
use super::tests::enabled_desired_state_sender;
|
||||
use super::tests::remote_control_auth_dot_json;
|
||||
use super::tests::remote_control_auth_manager;
|
||||
use super::tests::remote_control_enrollment;
|
||||
use super::tests::remote_control_state_runtime;
|
||||
use super::tests::remote_control_status_channel;
|
||||
use super::tests::remote_control_url_for_listener;
|
||||
use super::tests::respond_with_status_and_headers;
|
||||
use super::tests::test_current_enrollment;
|
||||
use super::*;
|
||||
use crate::transport::remote_control::protocol::normalize_remote_control_url;
|
||||
use crate::transport::remote_control::server_api::remote_control_retry_at;
|
||||
use crate::transport::remote_control::tests::remote_control_handle_with_current_enrollment;
|
||||
use codex_app_server_protocol::RemoteControlPairingStartParams;
|
||||
use codex_app_server_protocol::RemoteControlPairingStatusParams;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::save_auth;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
use tokio_tungstenite::WebSocketStream;
|
||||
use tokio_tungstenite::accept_async;
|
||||
|
||||
async fn connect_test_websocket(
|
||||
remote_control_target: &RemoteControlTarget,
|
||||
state_db: &StateRuntime,
|
||||
auth_manager: &Arc<AuthManager>,
|
||||
current_enrollment: &CurrentRemoteControlEnrollment,
|
||||
) -> io::Result<()> {
|
||||
let session_auth = RemoteControlAuth::capture(auth_manager.clone(), /*runtime_auth*/ None).0;
|
||||
let mut auth_recovery = session_auth.unauthorized_recovery();
|
||||
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
||||
let (status_publisher, _) = remote_control_status_channel();
|
||||
let desired_state_tx = enabled_desired_state_sender();
|
||||
let persistence = RemoteControlPersistence::default();
|
||||
connect_remote_control_websocket(
|
||||
remote_control_target,
|
||||
Some(state_db),
|
||||
RemoteControlAuthContext {
|
||||
auth_manager: &session_auth,
|
||||
auth_recovery: &mut auth_recovery,
|
||||
auth_change_rx: &mut auth_change_rx,
|
||||
},
|
||||
current_enrollment,
|
||||
RemoteControlConnectOptions {
|
||||
installation_id: TEST_INSTALLATION_ID,
|
||||
server_name: "test-server",
|
||||
subscribe_cursor: None,
|
||||
app_server_client_name: None,
|
||||
desired_state_tx: &desired_state_tx,
|
||||
persistence: &persistence,
|
||||
},
|
||||
&status_publisher,
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn proactive_refresh_failure_uses_valid_token_for_websocket_connect() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let remote_control_target =
|
||||
normalize_remote_control_url(&remote_control_url).expect("target should parse");
|
||||
let server_task = tokio::spawn(async move {
|
||||
let (stream, request_line) = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
request_line,
|
||||
"POST /backend-api/wham/remote/control/server/refresh HTTP/1.1"
|
||||
);
|
||||
respond_with_status_and_headers(stream, "502 Bad Gateway", &[], "upstream unavailable")
|
||||
.await;
|
||||
accept_test_websocket(&listener).await
|
||||
});
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let auth_manager = remote_control_auth_manager();
|
||||
let mut enrollment = remote_control_enrollment(Some(TEST_REMOTE_CONTROL_SERVER_TOKEN));
|
||||
enrollment.expires_at = Some(time::OffsetDateTime::now_utc() + time::Duration::minutes(4));
|
||||
let current_enrollment = test_current_enrollment(Some(enrollment));
|
||||
|
||||
let refresh_started_at = time::OffsetDateTime::now_utc();
|
||||
connect_test_websocket(
|
||||
&remote_control_target,
|
||||
state_db.as_ref(),
|
||||
&auth_manager,
|
||||
¤t_enrollment,
|
||||
)
|
||||
.await
|
||||
.expect("valid token should allow websocket connect after proactive refresh failure");
|
||||
let refresh_completed_at = time::OffsetDateTime::now_utc();
|
||||
let server_websocket = server_task.await.expect("server task should succeed");
|
||||
|
||||
let enrollment = current_enrollment
|
||||
.lock()
|
||||
.await
|
||||
.clone()
|
||||
.expect("enrollment should remain available");
|
||||
assert_eq!(
|
||||
enrollment.remote_control_token.as_deref(),
|
||||
Some(TEST_REMOTE_CONTROL_SERVER_TOKEN)
|
||||
);
|
||||
let next_refresh_at = enrollment
|
||||
.next_refresh_at
|
||||
.expect("transient refresh should set a retry deadline");
|
||||
assert!(
|
||||
(refresh_started_at + time::Duration::seconds(24)
|
||||
..=refresh_completed_at + time::Duration::seconds(36))
|
||||
.contains(&next_refresh_at)
|
||||
);
|
||||
drop(server_websocket);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn proactive_refresh_connection_failure_uses_valid_token_for_websocket_connect() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let remote_control_target =
|
||||
normalize_remote_control_url(&remote_control_url).expect("target should parse");
|
||||
let server_task = tokio::spawn(async move {
|
||||
let (stream, request_line) = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
request_line,
|
||||
"POST /backend-api/wham/remote/control/server/refresh HTTP/1.1"
|
||||
);
|
||||
drop(stream);
|
||||
accept_test_websocket(&listener).await
|
||||
});
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let auth_manager = remote_control_auth_manager();
|
||||
let mut enrollment = remote_control_enrollment(Some(TEST_REMOTE_CONTROL_SERVER_TOKEN));
|
||||
enrollment.expires_at = Some(time::OffsetDateTime::now_utc() + time::Duration::minutes(4));
|
||||
let current_enrollment = test_current_enrollment(Some(enrollment));
|
||||
|
||||
connect_test_websocket(
|
||||
&remote_control_target,
|
||||
state_db.as_ref(),
|
||||
&auth_manager,
|
||||
¤t_enrollment,
|
||||
)
|
||||
.await
|
||||
.expect("valid token should allow websocket connect after refresh connection failure");
|
||||
let server_websocket = server_task.await.expect("server task should succeed");
|
||||
|
||||
assert!(
|
||||
current_enrollment
|
||||
.snapshot()
|
||||
.and_then(|enrollment| enrollment.next_refresh_at)
|
||||
.is_some(),
|
||||
"connection failure should set a retry deadline"
|
||||
);
|
||||
drop(server_websocket);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn websocket_retry_after_throttles_pairing_refresh() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let remote_control_target =
|
||||
normalize_remote_control_url(&remote_control_url).expect("target should parse");
|
||||
let server_task = tokio::spawn(async move {
|
||||
let (stream, request_line) = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
request_line,
|
||||
"POST /backend-api/wham/remote/control/server/refresh HTTP/1.1"
|
||||
);
|
||||
respond_with_status_and_headers(
|
||||
stream,
|
||||
"502 Bad Gateway",
|
||||
&[("retry-after", "120")],
|
||||
"upstream unavailable",
|
||||
)
|
||||
.await;
|
||||
listener
|
||||
});
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let auth_manager = remote_control_auth_manager();
|
||||
let mut remote_handle =
|
||||
remote_control_handle_with_current_enrollment(&remote_control_url, auth_manager.clone());
|
||||
remote_handle.state_db = Some(state_db.clone());
|
||||
remote_handle
|
||||
.current_enrollment
|
||||
.lock()
|
||||
.await
|
||||
.as_mut()
|
||||
.expect("current enrollment should exist")
|
||||
.expires_at = Some(time::OffsetDateTime::now_utc() + time::Duration::minutes(4));
|
||||
let current_enrollment = remote_handle.current_enrollment.clone();
|
||||
let refresh_started_at = time::OffsetDateTime::now_utc();
|
||||
let refresh_error = connect_test_websocket(
|
||||
&remote_control_target,
|
||||
state_db.as_ref(),
|
||||
&auth_manager,
|
||||
¤t_enrollment,
|
||||
)
|
||||
.await
|
||||
.expect_err("an explicit server deadline must defer the handshake even with a valid token");
|
||||
let refresh_completed_at = time::OffsetDateTime::now_utc();
|
||||
let next_refresh_at = current_enrollment
|
||||
.snapshot()
|
||||
.and_then(|enrollment| enrollment.next_refresh_at)
|
||||
.expect("Retry-After should set a retry deadline");
|
||||
assert!(
|
||||
(refresh_started_at + time::Duration::seconds(120)
|
||||
..=refresh_completed_at + time::Duration::seconds(150))
|
||||
.contains(&next_refresh_at)
|
||||
);
|
||||
|
||||
let pairing_error = remote_handle
|
||||
.start_pairing(
|
||||
RemoteControlPairingStartParams::default(),
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect_err("the refresh deadline must also defer pairing");
|
||||
let listener = server_task.await.expect("server task should succeed");
|
||||
assert_eq!(
|
||||
remote_control_retry_at(&refresh_error),
|
||||
Some(next_refresh_at)
|
||||
);
|
||||
assert_eq!(
|
||||
remote_control_retry_at(&pairing_error),
|
||||
Some(next_refresh_at)
|
||||
);
|
||||
assert_eq!(
|
||||
current_enrollment
|
||||
.snapshot()
|
||||
.and_then(|enrollment| enrollment.remote_control_token),
|
||||
Some(TEST_REMOTE_CONTROL_SERVER_TOKEN.to_string())
|
||||
);
|
||||
timeout(Duration::from_millis(100), listener.accept())
|
||||
.await
|
||||
.expect_err("no handshake or pairing should bypass the proactive refresh deadline");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pairing_http_date_retry_after_throttles_websocket_refresh() {
|
||||
for status in [
|
||||
"429 Too Many Requests",
|
||||
"503 Service Unavailable",
|
||||
"502 Bad Gateway",
|
||||
] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let remote_control_target =
|
||||
normalize_remote_control_url(&remote_control_url).expect("target should parse");
|
||||
let retry_after =
|
||||
httpdate::fmt_http_date(std::time::SystemTime::now() + Duration::from_secs(120));
|
||||
let expected_next_refresh_at = time::OffsetDateTime::from(
|
||||
httpdate::parse_http_date(&retry_after).expect("Retry-After date should parse"),
|
||||
);
|
||||
let server_task = tokio::spawn(async move {
|
||||
let (refresh_stream, request_line) = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
request_line,
|
||||
"POST /backend-api/wham/remote/control/server/refresh HTTP/1.1"
|
||||
);
|
||||
respond_with_status_and_headers(
|
||||
refresh_stream,
|
||||
status,
|
||||
&[("retry-after", &retry_after)],
|
||||
"upstream unavailable",
|
||||
)
|
||||
.await;
|
||||
listener
|
||||
});
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let auth_manager = remote_control_auth_manager();
|
||||
let mut remote_handle = remote_control_handle_with_current_enrollment(
|
||||
&remote_control_url,
|
||||
auth_manager.clone(),
|
||||
);
|
||||
remote_handle.state_db = Some(state_db.clone());
|
||||
remote_handle
|
||||
.current_enrollment
|
||||
.lock()
|
||||
.await
|
||||
.as_mut()
|
||||
.expect("current enrollment should exist")
|
||||
.expires_at = Some(time::OffsetDateTime::now_utc() + time::Duration::minutes(4));
|
||||
let current_enrollment = remote_handle.current_enrollment.clone();
|
||||
|
||||
let refresh_error = remote_handle
|
||||
.start_pairing(
|
||||
RemoteControlPairingStartParams::default(),
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect_err("an explicit server deadline must defer pairing even with a valid token");
|
||||
let listener = server_task.await.expect("server task should succeed");
|
||||
let retry_at = remote_control_retry_at(&refresh_error)
|
||||
.expect("the proactive refresh response should preserve its deadline");
|
||||
let enrollment = current_enrollment
|
||||
.snapshot()
|
||||
.expect("enrollment should remain");
|
||||
assert_eq!(enrollment.next_refresh_at, Some(retry_at));
|
||||
assert_eq!(
|
||||
enrollment.remote_control_token.as_deref(),
|
||||
Some(TEST_REMOTE_CONTROL_SERVER_TOKEN)
|
||||
);
|
||||
assert!(
|
||||
(expected_next_refresh_at..=expected_next_refresh_at + time::Duration::seconds(30))
|
||||
.contains(&retry_at)
|
||||
);
|
||||
let connect_error = connect_test_websocket(
|
||||
&remote_control_target,
|
||||
state_db.as_ref(),
|
||||
&auth_manager,
|
||||
¤t_enrollment,
|
||||
)
|
||||
.await
|
||||
.expect_err("the refresh deadline must also defer the handshake");
|
||||
assert_eq!(remote_control_retry_at(&connect_error), Some(retry_at));
|
||||
let pairing_error = remote_handle
|
||||
.start_pairing(
|
||||
RemoteControlPairingStartParams::default(),
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect_err("another pairing request must retain the same deadline");
|
||||
assert_eq!(remote_control_retry_at(&pairing_error), Some(retry_at));
|
||||
timeout(Duration::from_millis(100), listener.accept())
|
||||
.await
|
||||
.expect_err("no pairing, refresh or handshake should bypass the deadline");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pairing_during_pending_handshake_respects_later_overload() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let remote_control_target =
|
||||
normalize_remote_control_url(&remote_control_url).expect("target should parse");
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let auth_manager = remote_control_auth_manager();
|
||||
let mut remote_handle =
|
||||
remote_control_handle_with_current_enrollment(&remote_control_url, auth_manager.clone());
|
||||
remote_handle.state_db = Some(state_db.clone());
|
||||
let current_enrollment = remote_handle.current_enrollment.clone();
|
||||
let connect = connect_test_websocket(
|
||||
&remote_control_target,
|
||||
state_db.as_ref(),
|
||||
&auth_manager,
|
||||
¤t_enrollment,
|
||||
);
|
||||
tokio::pin!(connect);
|
||||
let (handshake_stream, request_line) = tokio::select! {
|
||||
result = &mut connect => panic!("handshake should wait for its response: {result:?}"),
|
||||
request = accept_http_request(&listener) => request,
|
||||
};
|
||||
assert_eq!(
|
||||
request_line,
|
||||
"GET /backend-api/wham/remote/control/server HTTP/1.1"
|
||||
);
|
||||
|
||||
let pairing = remote_handle.start_pairing(
|
||||
RemoteControlPairingStartParams::default(),
|
||||
/*app_server_client_name*/ None,
|
||||
);
|
||||
tokio::pin!(pairing);
|
||||
let (pairing_stream, request_line) = tokio::select! {
|
||||
result = &mut pairing => panic!("pairing should wait for its response: {result:?}"),
|
||||
request = accept_http_request(&listener) => request,
|
||||
};
|
||||
assert_eq!(
|
||||
request_line,
|
||||
"POST /backend-api/wham/remote/control/server/pair HTTP/1.1"
|
||||
);
|
||||
respond_with_status_and_headers(
|
||||
pairing_stream,
|
||||
"200 OK",
|
||||
&[],
|
||||
r#"{"pairing_code":"pairing-code","manual_pairing_code":"ABCD-EFGH","server_id":"srv_e_test","environment_id":"env_test","expires_at":"3026-05-22T12:34:56Z"}"#,
|
||||
)
|
||||
.await;
|
||||
timeout(Duration::from_secs(1), pairing)
|
||||
.await
|
||||
.expect("pairing must stay responsive while the handshake is pending")
|
||||
.expect("pairing should succeed before any overload is observed");
|
||||
respond_with_status_and_headers(
|
||||
handshake_stream,
|
||||
"503 Service Unavailable",
|
||||
&[("Retry-After", "120")],
|
||||
"overloaded",
|
||||
)
|
||||
.await;
|
||||
let connect_error = connect
|
||||
.await
|
||||
.expect_err("the handshake should report overload");
|
||||
let retry_at = remote_control_retry_at(&connect_error)
|
||||
.expect("the handshake should preserve its retry deadline");
|
||||
let pairing_error = timeout(
|
||||
Duration::from_secs(1),
|
||||
remote_handle.start_pairing(
|
||||
RemoteControlPairingStartParams::default(),
|
||||
/*app_server_client_name*/ None,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("new pairing should report the deadline promptly")
|
||||
.expect_err("new pairing must honor the handshake deadline");
|
||||
assert_eq!(remote_control_retry_at(&pairing_error), Some(retry_at));
|
||||
timeout(Duration::from_millis(100), listener.accept())
|
||||
.await
|
||||
.expect_err("new pairing must not bypass the newly recorded deadline");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pairing_auth_recovery_respects_concurrent_handshake_overload() {
|
||||
for (pairing_status, auth_endpoint) in
|
||||
[("401 Unauthorized", "refresh"), ("404 Not Found", "enroll")]
|
||||
{
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let remote_control_target =
|
||||
normalize_remote_control_url(&remote_control_url).expect("target should parse");
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
save_auth(
|
||||
codex_home.path(),
|
||||
&remote_control_auth_dot_json("stale-token"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.expect("stale auth should save");
|
||||
let auth_manager = AuthManager::shared(
|
||||
codex_home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
/*chatgpt_base_url*/ None,
|
||||
AuthKeyringBackendKind::default(),
|
||||
codex_login::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.await;
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let mut remote_handle = remote_control_handle_with_current_enrollment(
|
||||
&remote_control_url,
|
||||
auth_manager.clone(),
|
||||
);
|
||||
remote_handle.state_db = Some(state_db.clone());
|
||||
let current_enrollment = remote_handle.current_enrollment.clone();
|
||||
let connect = connect_test_websocket(
|
||||
&remote_control_target,
|
||||
state_db.as_ref(),
|
||||
&auth_manager,
|
||||
¤t_enrollment,
|
||||
);
|
||||
tokio::pin!(connect);
|
||||
let (handshake_stream, request_line) = tokio::select! {
|
||||
result = &mut connect => panic!("handshake should wait for its response: {result:?}"),
|
||||
request = accept_http_request(&listener) => request,
|
||||
};
|
||||
assert_eq!(
|
||||
request_line,
|
||||
"GET /backend-api/wham/remote/control/server HTTP/1.1"
|
||||
);
|
||||
|
||||
let pairing = remote_handle.start_pairing(
|
||||
RemoteControlPairingStartParams::default(),
|
||||
/*app_server_client_name*/ None,
|
||||
);
|
||||
tokio::pin!(pairing);
|
||||
let (pairing_stream, request_line) = tokio::select! {
|
||||
result = &mut pairing => panic!("pairing should wait for its response: {result:?}"),
|
||||
request = accept_http_request(&listener) => request,
|
||||
};
|
||||
assert_eq!(
|
||||
request_line,
|
||||
"POST /backend-api/wham/remote/control/server/pair HTTP/1.1"
|
||||
);
|
||||
respond_with_status_and_headers(pairing_stream, pairing_status, &[], "retry auth").await;
|
||||
let (auth_stream, request_line) = tokio::select! {
|
||||
result = &mut pairing => panic!("auth should wait for its response: {result:?}"),
|
||||
request = accept_http_request(&listener) => request,
|
||||
};
|
||||
assert_eq!(
|
||||
request_line,
|
||||
format!("POST /backend-api/wham/remote/control/server/{auth_endpoint} HTTP/1.1")
|
||||
);
|
||||
|
||||
respond_with_status_and_headers(
|
||||
handshake_stream,
|
||||
"503 Service Unavailable",
|
||||
&[("Retry-After", "120")],
|
||||
"overloaded",
|
||||
)
|
||||
.await;
|
||||
let connect_error = connect
|
||||
.await
|
||||
.expect_err("the handshake should report overload");
|
||||
let retry_at = remote_control_retry_at(&connect_error)
|
||||
.expect("the handshake should preserve its retry deadline");
|
||||
save_auth(
|
||||
codex_home.path(),
|
||||
&remote_control_auth_dot_json("fresh-token"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.expect("replacement auth should save");
|
||||
respond_with_status_and_headers(auth_stream, "401 Unauthorized", &[], "stale auth").await;
|
||||
let pairing_error = timeout(TEST_HTTP_ACCEPT_TIMEOUT, pairing)
|
||||
.await
|
||||
.expect("auth recovery should report the deadline promptly")
|
||||
.expect_err("auth recovery must honor the handshake deadline");
|
||||
assert_eq!(remote_control_retry_at(&pairing_error), Some(retry_at));
|
||||
timeout(Duration::from_millis(100), listener.accept())
|
||||
.await
|
||||
.expect_err("auth recovery must not send another request during overload");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pairing_overload_defers_pairing_and_websocket_requests() {
|
||||
for status in ["429 Too Many Requests", "503 Service Unavailable"] {
|
||||
for check_status in [false, true] {
|
||||
for incomplete_body in [false, true] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let remote_control_target =
|
||||
normalize_remote_control_url(&remote_control_url).expect("target should parse");
|
||||
let server_task = tokio::spawn(async move {
|
||||
let (mut stream, request_line) = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
request_line,
|
||||
if check_status {
|
||||
"POST /backend-api/wham/remote/control/server/pair/status HTTP/1.1"
|
||||
} else {
|
||||
"POST /backend-api/wham/remote/control/server/pair HTTP/1.1"
|
||||
}
|
||||
);
|
||||
if incomplete_body {
|
||||
stream.write_all(format!(
|
||||
"HTTP/1.1 {status}\r\nContent-Length: 100\r\nRetry-After: 120\r\nConnection: close\r\n\r\npartial"
|
||||
).as_bytes()).await.expect("partial response should send");
|
||||
stream.shutdown().await.expect("response should close");
|
||||
} else {
|
||||
respond_with_status_and_headers(
|
||||
stream,
|
||||
status,
|
||||
&[("Retry-After", "120")],
|
||||
"overloaded",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
listener
|
||||
});
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let auth_manager = remote_control_auth_manager();
|
||||
let mut remote_handle = remote_control_handle_with_current_enrollment(
|
||||
&remote_control_url,
|
||||
auth_manager.clone(),
|
||||
);
|
||||
remote_handle.state_db = Some(state_db.clone());
|
||||
let current_enrollment = remote_handle.current_enrollment.clone();
|
||||
let status_params = || RemoteControlPairingStatusParams {
|
||||
pairing_code: Some("pairing-code".to_string()),
|
||||
manual_pairing_code: None,
|
||||
};
|
||||
let response = if check_status {
|
||||
remote_handle
|
||||
.pairing_status(status_params())
|
||||
.await
|
||||
.map(|_| ())
|
||||
} else {
|
||||
remote_handle
|
||||
.start_pairing(
|
||||
RemoteControlPairingStartParams::default(),
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
};
|
||||
let error = response.expect_err("pairing should report overload");
|
||||
let listener = server_task.await.expect("server task should succeed");
|
||||
let retry_at = remote_control_retry_at(&error)
|
||||
.expect("even a partial response must preserve the retry deadline");
|
||||
let pairing_error = remote_handle
|
||||
.start_pairing(
|
||||
RemoteControlPairingStartParams::default(),
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect_err("pairing must wait for the server deadline");
|
||||
let status_error = remote_handle
|
||||
.pairing_status(status_params())
|
||||
.await
|
||||
.expect_err("pairing status must wait for the server deadline");
|
||||
let connect_error = connect_test_websocket(
|
||||
&remote_control_target,
|
||||
state_db.as_ref(),
|
||||
&auth_manager,
|
||||
¤t_enrollment,
|
||||
)
|
||||
.await
|
||||
.expect_err("the handshake must wait for the same deadline");
|
||||
for error in [pairing_error, status_error, connect_error] {
|
||||
assert_eq!(remote_control_retry_at(&error), Some(retry_at));
|
||||
}
|
||||
assert_eq!(
|
||||
current_enrollment
|
||||
.snapshot()
|
||||
.and_then(|enrollment| enrollment.remote_control_token),
|
||||
Some(TEST_REMOTE_CONTROL_SERVER_TOKEN.to_string()),
|
||||
);
|
||||
timeout(Duration::from_millis(100), listener.accept())
|
||||
.await
|
||||
.expect_err("no remote-control request should bypass the pairing deadline");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn assert_refresh_failure_blocks_websocket(
|
||||
expires_in: time::Duration,
|
||||
response_delay: Duration,
|
||||
) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let remote_control_target =
|
||||
normalize_remote_control_url(&remote_control_url).expect("target should parse");
|
||||
let (connects_done_tx, connects_done_rx) = oneshot::channel();
|
||||
let server_task = tokio::spawn(async move {
|
||||
let (stream, request_line) = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
request_line,
|
||||
"POST /backend-api/wham/remote/control/server/refresh HTTP/1.1"
|
||||
);
|
||||
tokio::time::sleep(response_delay).await;
|
||||
respond_with_status_and_headers(
|
||||
stream,
|
||||
"502 Bad Gateway",
|
||||
&[("retry-after", "120")],
|
||||
"upstream unavailable",
|
||||
)
|
||||
.await;
|
||||
assert_no_connection_until_connect_finishes(&listener, connects_done_rx).await;
|
||||
});
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let auth_manager = remote_control_auth_manager();
|
||||
let mut enrollment = remote_control_enrollment(Some(TEST_REMOTE_CONTROL_SERVER_TOKEN));
|
||||
enrollment.expires_at = Some(time::OffsetDateTime::now_utc() + expires_in);
|
||||
let current_enrollment = test_current_enrollment(Some(enrollment));
|
||||
|
||||
let refresh_started_at = time::OffsetDateTime::now_utc();
|
||||
let refresh_err = connect_test_websocket(
|
||||
&remote_control_target,
|
||||
state_db.as_ref(),
|
||||
&auth_manager,
|
||||
¤t_enrollment,
|
||||
)
|
||||
.await
|
||||
.expect_err("required refresh failure should block websocket connect");
|
||||
let refresh_completed_at = time::OffsetDateTime::now_utc();
|
||||
let deferred_err = connect_test_websocket(
|
||||
&remote_control_target,
|
||||
state_db.as_ref(),
|
||||
&auth_manager,
|
||||
¤t_enrollment,
|
||||
)
|
||||
.await
|
||||
.expect_err("required refresh deadline should block websocket reconnect");
|
||||
connects_done_tx
|
||||
.send(())
|
||||
.expect("server should wait for connect attempts to finish");
|
||||
|
||||
server_task.await.expect("server task should succeed");
|
||||
assert!(refresh_err.to_string().contains("HTTP 502 Bad Gateway"));
|
||||
assert_eq!(deferred_err.kind(), io::ErrorKind::WouldBlock);
|
||||
let retry_at = remote_control_retry_at(&refresh_err)
|
||||
.expect("the overload response should retain its retry deadline");
|
||||
assert_eq!(remote_control_retry_at(&deferred_err), Some(retry_at));
|
||||
let next_refresh_at = current_enrollment
|
||||
.snapshot()
|
||||
.and_then(|enrollment| enrollment.next_refresh_at)
|
||||
.expect("required refresh failure should set a retry deadline");
|
||||
assert!(
|
||||
(refresh_started_at + time::Duration::seconds(120)
|
||||
..=refresh_completed_at + time::Duration::seconds(150))
|
||||
.contains(&next_refresh_at)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn expired_token_refresh_failure_throttles_reconnect_without_websocket() {
|
||||
assert_refresh_failure_blocks_websocket(-time::Duration::seconds(1), Duration::ZERO).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn token_expiring_during_refresh_failure_throttles_reconnect_without_websocket() {
|
||||
assert_refresh_failure_blocks_websocket(
|
||||
time::Duration::seconds(1),
|
||||
Duration::from_millis(1_200),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn websocket_auth_failure_does_not_clear_rotated_server_token() {
|
||||
let attempted_enrollment = remote_control_enrollment(Some("old-token"));
|
||||
let mut rotated_enrollment = attempted_enrollment.clone();
|
||||
rotated_enrollment.remote_control_token = Some("new-token".to_string());
|
||||
rotated_enrollment.expires_at =
|
||||
Some(time::OffsetDateTime::now_utc() + time::Duration::hours(1));
|
||||
let current_enrollment = test_current_enrollment(Some(rotated_enrollment.clone()));
|
||||
|
||||
clear_remote_control_server_token_if_matches(¤t_enrollment, &attempted_enrollment)
|
||||
.await
|
||||
.expect("matching enrollment identity should remain available");
|
||||
|
||||
assert_eq!(current_enrollment.snapshot(), Some(rotated_enrollment));
|
||||
}
|
||||
|
||||
async fn accept_test_websocket(listener: &TcpListener) -> WebSocketStream<TcpStream> {
|
||||
let (stream, _) = timeout(TEST_HTTP_ACCEPT_TIMEOUT, listener.accept())
|
||||
.await
|
||||
.expect("websocket request should arrive in time")
|
||||
.expect("listener accept should succeed");
|
||||
accept_async(stream)
|
||||
.await
|
||||
.expect("websocket handshake should succeed")
|
||||
}
|
||||
|
||||
async fn assert_no_connection_until_connect_finishes(
|
||||
listener: &TcpListener,
|
||||
mut connect_done_rx: oneshot::Receiver<()>,
|
||||
) {
|
||||
tokio::select! {
|
||||
accepted = listener.accept() => {
|
||||
accepted.expect("unexpected websocket connection should be accepted");
|
||||
panic!("required refresh failure must not proceed to websocket connect");
|
||||
}
|
||||
connect_done = &mut connect_done_rx => {
|
||||
connect_done.expect("connect completion should be reported");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
//! Checks sustained handshake failures and recovery through the reconnect loop.
|
||||
|
||||
use super::tests::TEST_INSTALLATION_ID;
|
||||
use super::tests::TEST_REMOTE_CONTROL_SERVER_TOKEN;
|
||||
use super::tests::enabled_desired_state_sender;
|
||||
use super::tests::remote_control_auth_manager;
|
||||
use super::tests::remote_control_enrollment;
|
||||
use super::tests::remote_control_state_runtime;
|
||||
use super::tests::remote_control_status_channel;
|
||||
use super::tests::remote_control_url_for_listener;
|
||||
use super::tests::test_current_enrollment;
|
||||
use super::*;
|
||||
use crate::transport::remote_control::protocol::normalize_remote_control_url;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
use tokio::time::timeout;
|
||||
use tokio_tungstenite::accept_hdr_async;
|
||||
use tungstenite::handshake::server::Request;
|
||||
use tungstenite::handshake::server::Response;
|
||||
|
||||
#[tokio::test]
|
||||
async fn repeated_conflicts_without_cursor_stay_at_cap_and_recover() {
|
||||
assert_conflict_recovery(/*subscribe_cursor*/ None).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn repeated_conflicts_stay_at_backoff_cap_and_recover() {
|
||||
assert_conflict_recovery(Some("stale-cursor")).await;
|
||||
}
|
||||
|
||||
async fn assert_conflict_recovery(subscribe_cursor: Option<&str>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let remote_control_target = normalize_remote_control_url(&remote_control_url).unwrap();
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let mut enrollment = remote_control_enrollment(Some(TEST_REMOTE_CONTROL_SERVER_TOKEN));
|
||||
enrollment.remote_control_target = remote_control_target.clone();
|
||||
let current_enrollment = test_current_enrollment(Some(enrollment.clone()));
|
||||
let (status_publisher, _status_rx) = remote_control_status_channel();
|
||||
let (transport_event_tx, _transport_event_rx) = mpsc::channel(/*buffer*/ 1);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let mut websocket = RemoteControlWebsocket::new(
|
||||
RemoteControlWebsocketConfig {
|
||||
remote_control_url,
|
||||
remote_control_target: Some(remote_control_target),
|
||||
installation_id: TEST_INSTALLATION_ID.to_string(),
|
||||
server_name: "test-server".to_string(),
|
||||
},
|
||||
Some(state_db),
|
||||
RemoteControlAuth::capture(remote_control_auth_manager(), /*runtime_auth*/ None).0,
|
||||
RemoteControlChannels {
|
||||
transport_event_tx,
|
||||
status_publisher,
|
||||
current_enrollment: current_enrollment.clone(),
|
||||
pairing_persistence_key: watch::channel(/*init*/ None).0,
|
||||
persistence: RemoteControlPersistence::default(),
|
||||
},
|
||||
shutdown_token.clone(),
|
||||
Arc::new(enabled_desired_state_sender()),
|
||||
);
|
||||
// Start at the cap and advance the retry waits below. Keep socket I/O on
|
||||
// real time so a pending handshake cannot auto-advance its own timeout.
|
||||
websocket.reconnect_attempt = 9;
|
||||
websocket.state.lock().await.subscribe_cursor = subscribe_cursor.map(str::to_string);
|
||||
let connect_task = tokio::spawn(async move {
|
||||
let outcome = websocket
|
||||
.connect(&shutdown_token, /*app_server_client_name*/ None)
|
||||
.await;
|
||||
(websocket, outcome)
|
||||
});
|
||||
|
||||
let mut rejected_at = None;
|
||||
for attempt in 0..3 {
|
||||
let (mut stream, _) = timeout(Duration::from_secs(40), listener.accept())
|
||||
.await
|
||||
.expect("connection should retry within the capped delay")
|
||||
.unwrap();
|
||||
if let Some(rejected_at) = rejected_at {
|
||||
assert!(
|
||||
Instant::now().duration_since(rejected_at) >= Duration::from_secs(15),
|
||||
"sustained HTTP 409 responses must not restart fast retries"
|
||||
);
|
||||
}
|
||||
rejected_at = Some(Instant::now());
|
||||
let result = accept_hdr_async(&mut stream, |request: &Request, response: Response| {
|
||||
assert_eq!(
|
||||
request.uri().path(),
|
||||
"/backend-api/wham/remote/control/server"
|
||||
);
|
||||
assert_eq!(
|
||||
request
|
||||
.headers()
|
||||
.get(REMOTE_CONTROL_SUBSCRIBE_CURSOR_HEADER),
|
||||
subscribe_cursor
|
||||
.map(HeaderValue::from_str)
|
||||
.transpose()
|
||||
.unwrap()
|
||||
.as_ref(),
|
||||
);
|
||||
if attempt < 2 {
|
||||
Err(tungstenite::http::Response::builder()
|
||||
.status(/*status*/ 409)
|
||||
.body(/*body*/ None)
|
||||
.unwrap())
|
||||
} else {
|
||||
Ok(response)
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if attempt < 2 {
|
||||
assert!(result.is_err());
|
||||
drop(result);
|
||||
// The peer closes the rejected socket while processing the 409.
|
||||
// On this current-thread runtime it then enters the retry sleep
|
||||
// before we can observe EOF, so the clock advance cannot race it.
|
||||
assert_eq!(stream.read(&mut [0]).await.unwrap(), 0);
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(13)).await;
|
||||
tokio::time::resume();
|
||||
assert!(
|
||||
timeout(Duration::from_secs(1), listener.accept())
|
||||
.await
|
||||
.is_err(),
|
||||
"sustained HTTP 409 responses must not restart fast retries"
|
||||
);
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(17)).await;
|
||||
tokio::time::resume();
|
||||
} else {
|
||||
let _server_connection = result.expect("available ownership should allow recovery");
|
||||
let (mut websocket, outcome) = connect_task.await.unwrap();
|
||||
assert!(matches!(outcome, ConnectOutcome::Connected(_)));
|
||||
assert_eq!(websocket.reconnect_attempt, 11);
|
||||
assert!(
|
||||
next_reconnect_delay(&mut websocket.reconnect_attempt) >= Duration::from_secs(15),
|
||||
"a successful handshake must not reset backoff before the connection stays healthy"
|
||||
);
|
||||
assert_eq!(current_enrollment.snapshot(), Some(enrollment));
|
||||
assert_eq!(
|
||||
websocket.state.lock().await.subscribe_cursor.as_deref(),
|
||||
subscribe_cursor,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconnect_backoff_stays_capped_during_sustained_failures() {
|
||||
let mut reconnect_attempt = 0;
|
||||
for max_delay in [5, 10, 20] {
|
||||
let delay = next_reconnect_delay(&mut reconnect_attempt);
|
||||
assert!(delay >= Duration::from_secs(max_delay) / 2);
|
||||
assert!(delay <= Duration::from_secs(max_delay));
|
||||
}
|
||||
for mut reconnect_attempt in [reconnect_attempt, 9, u64::MAX] {
|
||||
for _ in 0..1000 {
|
||||
let delay = next_reconnect_delay(&mut reconnect_attempt);
|
||||
assert!(delay >= Duration::from_secs(15));
|
||||
assert!(delay <= Duration::from_secs(30));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,7 +72,6 @@ codex-user-verification = { workspace = true }
|
||||
codex-utils-pty = { workspace = true }
|
||||
codex-backend-client = { workspace = true }
|
||||
codex-file-search = { workspace = true }
|
||||
codex-chatgpt = { workspace = true }
|
||||
codex-login = { workspace = true }
|
||||
codex-runtime-agent-instance = { workspace = true }
|
||||
codex-image-generation-extension = { workspace = true }
|
||||
|
||||
@@ -55,6 +55,7 @@ fn chatgpt_client(factory: HttpClientFactory) -> HttpClient {
|
||||
}
|
||||
|
||||
/// Make a GET request to the ChatGPT backend API.
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn chatgpt_get_request<T: DeserializeOwned>(
|
||||
config: &Config,
|
||||
path: String,
|
||||
@@ -99,7 +99,7 @@ async fn helpers_use_captured_auth_and_strip_cross_origin_proofs() {
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let metadata = crate::connectors::read_connector_metadata(
|
||||
let metadata = crate::chatgpt_connectors::read_connector_metadata(
|
||||
&config,
|
||||
&auth,
|
||||
Some(&runtime),
|
||||
@@ -261,7 +261,7 @@ async fn connector_requests_reject_unsupported_openai_destinations() {
|
||||
},
|
||||
));
|
||||
|
||||
let directory_error = crate::connectors::list_all_connectors_with_options(
|
||||
let directory_error = crate::chatgpt_connectors::list_all_connectors_with_options(
|
||||
&config,
|
||||
Some(&auth),
|
||||
Some(&runtime),
|
||||
@@ -270,7 +270,7 @@ async fn connector_requests_reject_unsupported_openai_destinations() {
|
||||
)
|
||||
.await
|
||||
.expect_err("reject unsupported directory destination");
|
||||
let metadata_error = crate::connectors::read_connector_metadata(
|
||||
let metadata_error = crate::chatgpt_connectors::read_connector_metadata(
|
||||
&config,
|
||||
&auth,
|
||||
Some(&runtime),
|
||||
@@ -2,8 +2,10 @@ use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::chatgpt_client::chatgpt_get_request_with_timeout;
|
||||
use crate::chatgpt_client::chatgpt_post_request_with_timeout;
|
||||
mod chatgpt_client;
|
||||
|
||||
use self::chatgpt_client::chatgpt_get_request_with_timeout;
|
||||
use self::chatgpt_client::chatgpt_post_request_with_timeout;
|
||||
|
||||
use codex_connectors::AppInfo;
|
||||
use codex_connectors::AppToolPolicyEvaluator;
|
||||
@@ -68,7 +70,7 @@ pub async fn list_all_connectors(config: &Config) -> anyhow::Result<Vec<AppInfo>
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut config = config.clone();
|
||||
let (auth, runtime) = crate::chatgpt_client::standalone_auth(&mut config).await?;
|
||||
let (auth, runtime) = self::chatgpt_client::standalone_auth(&mut config).await?;
|
||||
list_all_connectors_with_options(
|
||||
&config,
|
||||
Some(&auth),
|
||||
@@ -104,7 +104,7 @@ pub(crate) fn thread_extensions(
|
||||
git_attribution_base_url,
|
||||
http_client_factory,
|
||||
);
|
||||
codex_guardian_v2::install(&mut builder, auth_manager.clone(), thread_manager);
|
||||
codex_guardian_v2::install(&mut builder, thread_manager);
|
||||
codex_memories_extension::install(&mut builder, codex_otel::global());
|
||||
codex_mcp_extension::install(&mut builder);
|
||||
codex_mcp_extension::install_plugins(&mut builder, environment_manager);
|
||||
|
||||
@@ -104,6 +104,8 @@ mod app_server_tracing;
|
||||
mod attestation;
|
||||
mod auth_mode;
|
||||
mod bespoke_event_handling;
|
||||
#[doc(hidden)]
|
||||
pub mod chatgpt_connectors;
|
||||
mod code_mode_host;
|
||||
mod codex_home_metrics;
|
||||
mod command_exec;
|
||||
|
||||
@@ -70,17 +70,14 @@ struct AppServerArgs {
|
||||
#[arg(long = "disable-plugin-startup-tasks-for-tests", hide = true)]
|
||||
disable_plugin_startup_tasks_for_tests: bool,
|
||||
|
||||
/// Enable remote control for this app-server process without changing persistence.
|
||||
#[arg(long = "remote-control", hide = true)]
|
||||
remote_control: bool,
|
||||
|
||||
/// Save loaded threads during managed daemon shutdown.
|
||||
#[arg(long, hide = true)]
|
||||
managed_daemon: bool,
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let remote_control_disabled = codex_app_server::take_remote_control_disabled_env();
|
||||
// aKode: remote control is not available; still consume the daemon's internal marker.
|
||||
let _ = codex_app_server::take_remote_control_disabled_env();
|
||||
arg0_dispatch_or_else(move |arg0_paths: Arg0DispatchPaths| async move {
|
||||
let AppServerArgs {
|
||||
cloud_skills_snapshot,
|
||||
@@ -92,7 +89,6 @@ fn main() -> anyhow::Result<()> {
|
||||
strict_config,
|
||||
#[cfg(debug_assertions)]
|
||||
disable_plugin_startup_tasks_for_tests,
|
||||
remote_control,
|
||||
managed_daemon,
|
||||
} = AppServerArgs::parse();
|
||||
let loader_overrides = if disable_managed_config_from_debug_env() {
|
||||
@@ -115,11 +111,7 @@ fn main() -> anyhow::Result<()> {
|
||||
runtime_options.plugin_startup_tasks = PluginStartupTasks::Skip;
|
||||
}
|
||||
runtime_options.remote_control_startup_mode =
|
||||
match (remote_control, remote_control_disabled) {
|
||||
(true, _) => codex_app_server::RemoteControlStartupMode::EnabledEphemeral,
|
||||
(false, true) => codex_app_server::RemoteControlStartupMode::DisabledEphemeral,
|
||||
(false, false) => codex_app_server::RemoteControlStartupMode::ResolvePersisted,
|
||||
};
|
||||
codex_app_server::RemoteControlStartupMode::DisabledEphemeral;
|
||||
|
||||
let exit = run_main_with_transport_options(
|
||||
arg0_paths,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::bespoke_event_handling::apply_bespoke_event_handling;
|
||||
use crate::chatgpt_connectors as connectors;
|
||||
use crate::command_exec::CommandExecManager;
|
||||
use crate::command_exec::StartCommandExecParams;
|
||||
use crate::config_manager::ConfigManager;
|
||||
@@ -328,7 +329,6 @@ use codex_backend_client::RateLimitResetCreditDetails as BackendRateLimitResetCr
|
||||
use codex_backend_client::RateLimitResetCreditsDetails as BackendRateLimitResetCreditsDetails;
|
||||
use codex_backend_client::RequestError as BackendRequestError;
|
||||
use codex_backend_client::TokenUsageProfile;
|
||||
use codex_chatgpt::connectors;
|
||||
use codex_config::CloudConfigBundleLoadError;
|
||||
use codex_config::CloudConfigBundleLoadErrorCode;
|
||||
use codex_config::ConfigLayerStack;
|
||||
|
||||
@@ -32,7 +32,7 @@ pub struct StartupConfigArgs {
|
||||
pub startup_sign_out: bool,
|
||||
|
||||
/// Validate configuration and print requirements as JSON without starting the app server.
|
||||
#[arg(long, conflicts_with_all = ["listen", "stdio", "remote_control", "managed_daemon"])]
|
||||
#[arg(long, conflicts_with_all = ["listen", "stdio", "managed_daemon"])]
|
||||
pub print_startup_config: bool,
|
||||
|
||||
/// ClientInfo JSON used for configuration/auth request identity.
|
||||
|
||||
@@ -18,6 +18,7 @@ use axum::http::StatusCode;
|
||||
use axum::http::header::AUTHORIZATION;
|
||||
use axum::routing::any;
|
||||
use axum::routing::post;
|
||||
use codex_app_server::chatgpt_connectors as connectors;
|
||||
use codex_app_server_protocol::AppsReadParams;
|
||||
use codex_app_server_protocol::AppsReadResponse;
|
||||
use codex_app_server_protocol::ConnectorMetadata;
|
||||
@@ -26,7 +27,6 @@ use codex_app_server_protocol::LoginAccountResponse;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::ThreadStartResponse;
|
||||
use codex_chatgpt::connectors;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
|
||||
@@ -130,7 +130,6 @@ mod rate_limits;
|
||||
mod rate_limits_identity;
|
||||
mod realtime_conversation;
|
||||
mod recommended_plugins;
|
||||
mod remote_control;
|
||||
#[cfg(debug_assertions)]
|
||||
mod remote_thread_store;
|
||||
mod request_permissions;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,631 +0,0 @@
|
||||
//! Exercises login lifetime boundaries through public RPCs and a real relay websocket.
|
||||
|
||||
use super::*;
|
||||
use app_test_support::ChatGptIdTokenClaims;
|
||||
use app_test_support::encode_id_token;
|
||||
use codex_app_server_protocol::ChatgptAuthTokensRefreshResponse;
|
||||
use codex_app_server_protocol::ServerRequest;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tokio_tungstenite::WebSocketStream;
|
||||
|
||||
struct RelayClient {
|
||||
socket: WebSocketStream<TcpStream>,
|
||||
next_seq: u64,
|
||||
}
|
||||
|
||||
impl RelayClient {
|
||||
async fn send(&mut self, message: Value) -> Result<()> {
|
||||
self.socket
|
||||
.send(Message::Text(
|
||||
json!({
|
||||
"type": "client_message", "client_id": "client-a", "stream_id": "stream-a",
|
||||
"seq_id": self.next_seq, "cursor": format!("cursor-{}", self.next_seq),
|
||||
"message": message,
|
||||
})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await?;
|
||||
self.next_seq += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn response(&mut self, id: i64) -> Result<Value> {
|
||||
timeout(DEFAULT_TIMEOUT, async {
|
||||
loop {
|
||||
let message = self.socket.next().await.context("relay disconnected")??;
|
||||
if let Message::Text(text) = message {
|
||||
let envelope: Value = serde_json::from_str(&text)?;
|
||||
if envelope["type"] == "server_message" && envelope["message"]["id"] == id {
|
||||
return Ok(envelope["message"].clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
async fn closed(&mut self) -> Result<()> {
|
||||
timeout(DEFAULT_TIMEOUT, async {
|
||||
loop {
|
||||
match self.socket.next().await {
|
||||
None | Some(Err(_)) | Some(Ok(Message::Close(_))) => return,
|
||||
Some(Ok(_)) => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn assert_account(&mut self, app: &mut TestAppServer) -> Result<()> {
|
||||
let local = app.send_request("account/read", Some(json!({}))).await?;
|
||||
let expected: Value = timeout(DEFAULT_TIMEOUT, app.read_response(local)).await??;
|
||||
self.send(json!({"id": 2, "method": "account/read", "params": {}}))
|
||||
.await?;
|
||||
assert_eq!(
|
||||
self.response(/*id*/ 2).await?.get("result"),
|
||||
Some(&expected)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn external_token(user: &str, account: &str, revision: &str) -> Result<String> {
|
||||
encode_id_token(
|
||||
&ChatGptIdTokenClaims::new()
|
||||
.chatgpt_account_id(account)
|
||||
.chatgpt_user_id(user)
|
||||
.plan_type("pro")
|
||||
.email(format!("{revision}@example.com")),
|
||||
)
|
||||
}
|
||||
|
||||
async fn login(app: &mut TestAppServer, user: &str, account: &str, revision: &str) -> Result<()> {
|
||||
let id = app
|
||||
.send_chatgpt_auth_tokens_login_request(
|
||||
external_token(user, account, revision)?,
|
||||
account.to_string(),
|
||||
Some("pro".to_string()),
|
||||
)
|
||||
.await?;
|
||||
wait_for_response(app, id).await
|
||||
}
|
||||
|
||||
async fn open_relay(app: &mut TestAppServer, listener: &TcpListener) -> Result<RelayClient> {
|
||||
let id = app.send_remote_control_ephemeral_enable_request().await?;
|
||||
wait_for_response(app, id).await?;
|
||||
let request = timeout(DEFAULT_TIMEOUT, read_http_request(listener)).await??;
|
||||
assert!(
|
||||
request.request_line.contains("/server/enroll ")
|
||||
|| request.request_line.contains("/server/refresh "),
|
||||
"{}",
|
||||
request.request_line
|
||||
);
|
||||
respond_with_json(
|
||||
request.reader.into_inner(),
|
||||
json!({
|
||||
"server_id": "server-id", "environment_id": "environment-id",
|
||||
"remote_control_token": "remote-control-token", "expires_at": "3026-05-22T12:34:56Z",
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
let (stream, _) = timeout(DEFAULT_TIMEOUT, listener.accept()).await??;
|
||||
let socket = timeout(
|
||||
DEFAULT_TIMEOUT,
|
||||
tokio_tungstenite::accept_hdr_async(
|
||||
stream,
|
||||
|request: &tokio_tungstenite::tungstenite::handshake::server::Request, response| {
|
||||
assert!(!request.headers().contains_key("x-codex-subscribe-cursor"));
|
||||
Ok(response)
|
||||
},
|
||||
),
|
||||
)
|
||||
.await??;
|
||||
let mut relay = RelayClient {
|
||||
socket,
|
||||
next_seq: 0,
|
||||
};
|
||||
// A replacement must not retain the old logical client or replay its unacknowledged results.
|
||||
relay
|
||||
.socket
|
||||
.send(Message::Text(
|
||||
json!({
|
||||
"type": "ping", "client_id": "client-a", "stream_id": "stream-a",
|
||||
})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await?;
|
||||
timeout(DEFAULT_TIMEOUT, async {
|
||||
loop {
|
||||
let message = relay
|
||||
.socket
|
||||
.next()
|
||||
.await
|
||||
.context("relay disconnected before pong")??;
|
||||
if let Message::Text(text) = message {
|
||||
let envelope: Value = serde_json::from_str(&text)?;
|
||||
assert_ne!(envelope["type"], "server_message");
|
||||
if envelope["type"] == "pong" {
|
||||
assert_eq!(envelope["status"], "unknown");
|
||||
return Ok::<(), anyhow::Error>(());
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await??;
|
||||
relay
|
||||
.send(json!({"id": 1, "method": "initialize", "params": {
|
||||
"clientInfo": {"name": "remote-auth-test", "version": "0.1.0"},
|
||||
"capabilities": {"experimentalApi": true},
|
||||
}}))
|
||||
.await?;
|
||||
assert!(relay.response(/*id*/ 1).await?.get("result").is_some());
|
||||
relay.send(json!({"method": "initialized"})).await?;
|
||||
Ok(relay)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn same_owner_refresh_preserves_live_relay() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let listener = configured_remote_control_listener(home.path()).await?;
|
||||
let mut app = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.without_auto_env()
|
||||
.build_initialized()
|
||||
.await?;
|
||||
login(&mut app, "user-a", "account-a", "initial").await?;
|
||||
let mut relay = open_relay(&mut app, &listener).await?;
|
||||
login(&mut app, "user-a", "account-a", "refreshed").await?;
|
||||
relay.assert_account(&mut app).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn owner_change_retires_live_relay() -> Result<()> {
|
||||
for (user, account) in [("user-b", "account-a"), ("user-a", "account-b")] {
|
||||
let home = TempDir::new()?;
|
||||
let listener = configured_remote_control_listener(home.path()).await?;
|
||||
let mut app = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.without_auto_env()
|
||||
.build_initialized()
|
||||
.await?;
|
||||
login(&mut app, "user-a", "account-a", "initial").await?;
|
||||
let mut old = open_relay(&mut app, &listener).await?;
|
||||
old.assert_account(&mut app).await?;
|
||||
login(&mut app, user, account, "replacement").await?;
|
||||
old.closed().await?;
|
||||
let id = app.send_remote_control_status_read_request().await?;
|
||||
let status: RemoteControlStatusReadResponse =
|
||||
timeout(DEFAULT_TIMEOUT, app.read_response(id)).await??;
|
||||
assert_eq!(status.status, RemoteControlConnectionStatus::Disabled);
|
||||
let mut fresh = open_relay(&mut app, &listener).await?;
|
||||
fresh.assert_account(&mut app).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn owner_change_discards_pending_and_queued_pairing() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let listener = configured_remote_control_listener(home.path()).await?;
|
||||
let mut app = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.without_auto_env()
|
||||
.build_initialized()
|
||||
.await?;
|
||||
login(&mut app, "user-a", "account-a", "initial").await?;
|
||||
let mut old = open_relay(&mut app, &listener).await?;
|
||||
let pending = app
|
||||
.send_remote_control_pairing_start_request(RemoteControlPairingStartParams {
|
||||
manual_code: false,
|
||||
})
|
||||
.await?;
|
||||
let held = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
|
||||
assert!(held.request_line.contains("/server/pair "));
|
||||
old.send(
|
||||
json!({"id": 3, "method": "remoteControl/pairing/start", "params": {"manualCode": false}}),
|
||||
)
|
||||
.await?;
|
||||
// account/read uses another queue. Its response proves the prior pairing RPC was received.
|
||||
old.assert_account(&mut app).await?;
|
||||
login(&mut app, "user-b", "account-a", "replacement").await?;
|
||||
let mut fresh = open_relay(&mut app, &listener).await?;
|
||||
let sentinel = app
|
||||
.send_remote_control_pairing_start_request(RemoteControlPairingStartParams {
|
||||
manual_code: true,
|
||||
})
|
||||
.await?;
|
||||
// The old socket can already be cancelled, so delivery of this obsolete response is optional.
|
||||
let _ = respond_with_json(held.reader.into_inner(), json!({
|
||||
"pairing_code": "obsolete", "server_id": "server-id", "environment_id": "environment-id",
|
||||
"expires_at": "3026-05-22T12:34:56Z",
|
||||
})).await;
|
||||
let next = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
|
||||
assert!(next.request_line.contains("/server/pair "));
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(&next.body)?,
|
||||
json!({"manual_code": true})
|
||||
);
|
||||
respond_with_json(
|
||||
next.reader.into_inner(),
|
||||
json!({
|
||||
"pairing_code": "current", "server_id": "server-id", "manual_pairing_code": "ABCD-EFGH",
|
||||
"environment_id": "environment-id", "expires_at": "3026-05-22T12:34:56Z",
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
timeout(
|
||||
DEFAULT_TIMEOUT,
|
||||
app.read_stream_until_error_message(RequestId::Integer(pending)),
|
||||
)
|
||||
.await??;
|
||||
wait_for_response(&mut app, sentinel).await?;
|
||||
old.closed().await?;
|
||||
fresh.assert_account(&mut app).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn client_revoke_retry_stays_with_original_owner() -> Result<()> {
|
||||
for refreshed_user in ["user-a", "user-b"] {
|
||||
let home = TempDir::new()?;
|
||||
let listener = configured_remote_control_listener(home.path()).await?;
|
||||
let mut app = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.without_auto_env()
|
||||
.build_initialized()
|
||||
.await?;
|
||||
login(&mut app, "user-a", "account-a", "initial").await?;
|
||||
let old = app
|
||||
.send_remote_control_clients_revoke_request(RemoteControlClientsRevokeParams {
|
||||
environment_id: "environment-id".to_string(),
|
||||
client_id: "old-client".to_string(),
|
||||
})
|
||||
.await?;
|
||||
let first = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
|
||||
assert_eq!(
|
||||
first.request_line,
|
||||
"DELETE /backend-api/wham/remote/control/environments/environment-id/clients/old-client HTTP/1.1"
|
||||
);
|
||||
respond_with_status(first.reader.into_inner(), "401 Unauthorized", "expired").await?;
|
||||
let request = timeout(DEFAULT_TIMEOUT, app.read_stream_until_request_message()).await??;
|
||||
let ServerRequest::ChatgptAuthTokensRefresh { request_id, .. } = request else {
|
||||
anyhow::bail!("expected external authentication refresh");
|
||||
};
|
||||
app.send_response(
|
||||
request_id,
|
||||
serde_json::to_value(ChatgptAuthTokensRefreshResponse {
|
||||
access_token: external_token(refreshed_user, "account-a", "refreshed")?,
|
||||
chatgpt_account_id: "account-a".to_string(),
|
||||
chatgpt_plan_type: Some("pro".to_string()),
|
||||
})?,
|
||||
)
|
||||
.await?;
|
||||
let (next_id, client) = if refreshed_user == "user-a" {
|
||||
(old, "old-client")
|
||||
} else {
|
||||
timeout(
|
||||
DEFAULT_TIMEOUT,
|
||||
app.read_stream_until_error_message(RequestId::Integer(old)),
|
||||
)
|
||||
.await??;
|
||||
login(&mut app, refreshed_user, "account-a", "refreshed").await?;
|
||||
let id = app
|
||||
.send_remote_control_clients_revoke_request(RemoteControlClientsRevokeParams {
|
||||
environment_id: "environment-id".to_string(),
|
||||
client_id: "new-client".to_string(),
|
||||
})
|
||||
.await?;
|
||||
(id, "new-client")
|
||||
};
|
||||
let next = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
|
||||
assert_eq!(
|
||||
next.request_line,
|
||||
format!(
|
||||
"DELETE /backend-api/wham/remote/control/environments/environment-id/clients/{client} HTTP/1.1"
|
||||
)
|
||||
);
|
||||
respond_with_json(next.reader.into_inner(), json!({})).await?;
|
||||
let result: RemoteControlClientsRevokeResponse =
|
||||
timeout(DEFAULT_TIMEOUT, app.read_response(next_id)).await??;
|
||||
assert_eq!(result, RemoteControlClientsRevokeResponse {});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn owner_change_rejects_queued_client_revoke() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let listener = configured_remote_control_listener(home.path()).await?;
|
||||
let mut app = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.without_auto_env()
|
||||
.build_initialized()
|
||||
.await?;
|
||||
login(&mut app, "user-a", "account-a", "initial").await?;
|
||||
let mut relay = open_relay(&mut app, &listener).await?;
|
||||
let pending = app
|
||||
.send_remote_control_clients_revoke_request(RemoteControlClientsRevokeParams {
|
||||
environment_id: "environment-id".to_string(),
|
||||
client_id: "pending".to_string(),
|
||||
})
|
||||
.await?;
|
||||
let held = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
|
||||
relay
|
||||
.send(
|
||||
json!({"id": 3, "method": "remoteControl/client/revoke", "params": {
|
||||
"environmentId": "environment-id", "clientId": "obsolete",
|
||||
}}),
|
||||
)
|
||||
.await?;
|
||||
relay.assert_account(&mut app).await?;
|
||||
login(&mut app, "user-b", "account-a", "replacement").await?;
|
||||
let sentinel = app
|
||||
.send_remote_control_clients_revoke_request(RemoteControlClientsRevokeParams {
|
||||
environment_id: "environment-id".to_string(),
|
||||
client_id: "current".to_string(),
|
||||
})
|
||||
.await?;
|
||||
let _ = respond_with_json(held.reader.into_inner(), json!({})).await;
|
||||
// Client management works even while disabled, so disablement cannot mask a missing gate.
|
||||
let next = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
|
||||
assert_eq!(
|
||||
next.request_line,
|
||||
"DELETE /backend-api/wham/remote/control/environments/environment-id/clients/current HTTP/1.1"
|
||||
);
|
||||
respond_with_json(next.reader.into_inner(), json!({})).await?;
|
||||
timeout(
|
||||
DEFAULT_TIMEOUT,
|
||||
app.read_stream_until_error_message(RequestId::Integer(pending)),
|
||||
)
|
||||
.await??;
|
||||
wait_for_response(&mut app, sentinel).await?;
|
||||
relay.closed().await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn logout_login_enable_recovers_first_unauthorized_enrollment() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let listener = configured_remote_control_listener(home.path()).await?;
|
||||
let oauth = wiremock::MockServer::start().await;
|
||||
wiremock::Mock::given(wiremock::matchers::path("/oauth/revoke"))
|
||||
.respond_with(wiremock::ResponseTemplate::new(/*s*/ 200))
|
||||
.expect(1)
|
||||
.mount(&oauth)
|
||||
.await;
|
||||
let revoke_url = format!("{}/oauth/revoke", oauth.uri());
|
||||
let mut app = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.with_env_overrides(&[("CODEX_REVOKE_TOKEN_URL_OVERRIDE", Some(revoke_url.as_str()))])
|
||||
.without_auto_env()
|
||||
.build_initialized()
|
||||
.await?;
|
||||
let enabled = app.send_remote_control_ephemeral_enable_request().await?;
|
||||
wait_for_response(&mut app, enabled).await?;
|
||||
let (_, reader) = timeout(DEFAULT_TIMEOUT, read_enroll_request(&listener)).await??;
|
||||
respond_with_json(
|
||||
reader.into_inner(),
|
||||
serde_json::json!({
|
||||
"server_id": "server-a", "environment_id": "environment-a",
|
||||
"remote_control_token": "token-a", "expires_at": "3026-05-22T12:34:56Z",
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
let (stream, _) = timeout(DEFAULT_TIMEOUT, listener.accept()).await??;
|
||||
let mut websocket = timeout(DEFAULT_TIMEOUT, accept_async(stream)).await??;
|
||||
let logout = app.send_logout_account_request().await?;
|
||||
wait_for_response(&mut app, logout).await?;
|
||||
timeout(DEFAULT_TIMEOUT, async {
|
||||
loop {
|
||||
let notification = app
|
||||
.read_stream_until_notification_message("remoteControl/status/changed")
|
||||
.await?;
|
||||
let status: RemoteControlStatusChangedNotification =
|
||||
serde_json::from_value(notification.params.context("status params")?)?;
|
||||
if status.status == RemoteControlConnectionStatus::Disabled {
|
||||
return Ok::<(), anyhow::Error>(());
|
||||
}
|
||||
}
|
||||
})
|
||||
.await??;
|
||||
assert!(matches!(
|
||||
timeout(DEFAULT_TIMEOUT, websocket.next()).await?,
|
||||
None | Some(Err(_)) | Some(Ok(Message::Close(_)))
|
||||
));
|
||||
|
||||
let token = encode_id_token(
|
||||
&ChatGptIdTokenClaims::new()
|
||||
.chatgpt_account_id("account_b")
|
||||
.chatgpt_user_id("user_b")
|
||||
.plan_type("pro"),
|
||||
)?;
|
||||
let login = app
|
||||
.send_chatgpt_auth_tokens_login_request(
|
||||
token.clone(),
|
||||
"account_b".to_string(),
|
||||
Some("pro".to_string()),
|
||||
)
|
||||
.await?;
|
||||
wait_for_response(&mut app, login).await?;
|
||||
let enabled = app.send_remote_control_ephemeral_enable_request().await?;
|
||||
wait_for_response(&mut app, enabled).await?;
|
||||
let (line, reader) = timeout(DEFAULT_TIMEOUT, read_enroll_request(&listener)).await??;
|
||||
assert_eq!(
|
||||
line,
|
||||
"POST /backend-api/wham/remote/control/server/enroll HTTP/1.1"
|
||||
);
|
||||
respond_with_status(reader.into_inner(), "401 Unauthorized", "expired token").await?;
|
||||
let request = timeout(DEFAULT_TIMEOUT, app.read_stream_until_request_message()).await??;
|
||||
let ServerRequest::ChatgptAuthTokensRefresh { request_id, .. } = request else {
|
||||
anyhow::bail!("expected token refresh after the new owner's 401");
|
||||
};
|
||||
let refreshed_token = encode_id_token(
|
||||
&ChatGptIdTokenClaims::new()
|
||||
.chatgpt_account_id("account_b")
|
||||
.chatgpt_user_id("user_b")
|
||||
.plan_type("pro")
|
||||
.email("refreshed@example.com"),
|
||||
)?;
|
||||
app.send_response(
|
||||
request_id,
|
||||
serde_json::to_value(ChatgptAuthTokensRefreshResponse {
|
||||
access_token: refreshed_token,
|
||||
chatgpt_account_id: "account_b".to_string(),
|
||||
chatgpt_plan_type: Some("pro".to_string()),
|
||||
})?,
|
||||
)
|
||||
.await?;
|
||||
let (_, reader) = timeout(DEFAULT_TIMEOUT, read_enroll_request(&listener)).await??;
|
||||
respond_with_json(
|
||||
reader.into_inner(),
|
||||
serde_json::json!({
|
||||
"server_id": "server-b", "environment_id": "environment-b",
|
||||
"remote_control_token": "token-b", "expires_at": "3026-05-22T12:34:56Z",
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
let (stream, _) = timeout(DEFAULT_TIMEOUT, listener.accept()).await??;
|
||||
let _websocket = timeout(DEFAULT_TIMEOUT, accept_async(stream)).await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn public_client_management_uses_runtime_auth() -> Result<()> {
|
||||
use base64::Engine;
|
||||
use core_test_support::runtime_auth::PROBE_SERVER;
|
||||
use core_test_support::runtime_auth::run_harness_through_proxy;
|
||||
use std::collections::BTreeSet;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
let claims =
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json!({
|
||||
"exp": 4102444800_i64, "session_id": "remote-public",
|
||||
"iss": "https://auth.openai.com",
|
||||
"https://api.openai.com/auth": {
|
||||
"chatgpt_user_id": "user-123", "chatgpt_account_id": "account-123"
|
||||
},
|
||||
}))?);
|
||||
let token = format!("e30.{claims}.c2ln");
|
||||
if std::env::var(PROBE_SERVER).is_ok() {
|
||||
for mode in ["dual_header", "assertion_only"] {
|
||||
let home = TempDir::new()?;
|
||||
write_chatgpt_auth(
|
||||
home.path(),
|
||||
ChatGptAuthFixture::new(&token)
|
||||
.account_id("account-123")
|
||||
.chatgpt_user_id("user-123")
|
||||
.plan_type("pro"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!(
|
||||
"chatgpt_base_url = \"https://chatgpt.com/backend-api\"\n[features.runtime_agent_instances]\nenabled = true\nmode = {mode:?}\n"
|
||||
),
|
||||
)?;
|
||||
let mut app = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.without_auto_env()
|
||||
.with_env_overrides(&[("OPENAI_API_KEY", None)])
|
||||
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
|
||||
.await?;
|
||||
for _ in 0..2 {
|
||||
let id = app
|
||||
.send_remote_control_clients_list_request(RemoteControlClientsListParams {
|
||||
environment_id: "environment".into(),
|
||||
cursor: None,
|
||||
limit: None,
|
||||
order: None,
|
||||
})
|
||||
.await?;
|
||||
let response: RemoteControlClientsListResponse =
|
||||
timeout(DEFAULT_TIMEOUT, app.read_response(id)).await??;
|
||||
assert!(response.data.is_empty());
|
||||
}
|
||||
let id = app
|
||||
.send_remote_control_clients_revoke_request(RemoteControlClientsRevokeParams {
|
||||
environment_id: "environment".into(),
|
||||
client_id: "client".into(),
|
||||
})
|
||||
.await?;
|
||||
let _: RemoteControlClientsRevokeResponse =
|
||||
timeout(DEFAULT_TIMEOUT, app.read_response(id)).await??;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let server = MockServer::start().await;
|
||||
app_test_support::mount_workspace_routing(&server).await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/agent/register"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-remote-public", "agent_host_id": "host",
|
||||
"actor": {"kind": "chatgpt", "user_id": "user-123", "account_id": "account-123"}
|
||||
})))
|
||||
.expect(/*r*/ 2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path(
|
||||
"/backend-api/wham/remote/control/environments/environment/clients",
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"items": [], "cursor": null
|
||||
})))
|
||||
.expect(/*r*/ 4)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("DELETE"))
|
||||
.and(path(
|
||||
"/backend-api/wham/remote/control/environments/environment/clients/client",
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 204))
|
||||
.expect(/*r*/ 2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
run_harness_through_proxy(
|
||||
&server,
|
||||
"suite::v2::remote_control::auth_tests::public_client_management_uses_runtime_auth",
|
||||
/*realtime_target*/ None,
|
||||
)
|
||||
.await?;
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let mut proofs = BTreeSet::new();
|
||||
let mut dual = 0;
|
||||
for request in requests
|
||||
.iter()
|
||||
.filter(|r| r.url.path().contains("/wham/remote/control/"))
|
||||
{
|
||||
assert_eq!(request.headers["host"], "chatgpt.com");
|
||||
assert_eq!(request.headers["chatgpt-account-id"], "account-123");
|
||||
let authorization = request.headers["authorization"].to_str()?;
|
||||
let proof = if let Some(proof) = request.headers.get("x-openai-agent-assertion") {
|
||||
dual += 1;
|
||||
assert_eq!(authorization, format!("Bearer {token}"));
|
||||
proof.to_str()?
|
||||
} else {
|
||||
authorization
|
||||
.strip_prefix("AgentAssertion ")
|
||||
.expect("assertion-only auth")
|
||||
};
|
||||
let payload: Value = serde_json::from_slice(
|
||||
&base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(proof.split('.').nth(/*n*/ 2).unwrap())?,
|
||||
)?;
|
||||
assert_eq!(payload["runtime_agent_instance"], "runtime-remote-public");
|
||||
assert!(
|
||||
proofs.insert(proof.to_owned()),
|
||||
"each request gets a fresh assertion"
|
||||
);
|
||||
}
|
||||
assert_eq!((dual, proofs.len()), (3, 6));
|
||||
server.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "chatgpt",
|
||||
crate_name = "codex_chatgpt",
|
||||
)
|
||||
@@ -1,37 +0,0 @@
|
||||
[package]
|
||||
name = "codex-chatgpt"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
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"] }
|
||||
tokio = { workspace = true, features = ["full"] }
|
||||
|
||||
[dev-dependencies]
|
||||
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 }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
@@ -1,5 +0,0 @@
|
||||
# ChatGPT
|
||||
|
||||
This crate pertains to first party ChatGPT APIs and products such as Codex agent.
|
||||
|
||||
This crate is built and maintained by OpenAI employees. External code contributions are not accepted; please report bugs and request features in the [Codex issue tracker](https://github.com/openai/codex/issues).
|
||||
@@ -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<PathBuf>,
|
||||
) -> 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<PathBuf>,
|
||||
) -> 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<PathBuf>) -> 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(())
|
||||
}
|
||||
@@ -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<AssistantTurn>,
|
||||
}
|
||||
|
||||
// Only relevant fields for our extraction
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct AssistantTurn {
|
||||
pub output_items: Vec<OutputItem>,
|
||||
}
|
||||
|
||||
#[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<GetTaskResponse> {
|
||||
let path = format!("/wham/tasks/{task_id}");
|
||||
chatgpt_get_request(config, path).await
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
#![recursion_limit = "256"]
|
||||
|
||||
pub mod apply_command;
|
||||
mod chatgpt_client;
|
||||
pub mod connectors;
|
||||
pub mod get_task;
|
||||
@@ -1,3 +0,0 @@
|
||||
// Single integration test binary that aggregates all test modules.
|
||||
// The submodules live in `tests/suite/`.
|
||||
mod suite;
|
||||
@@ -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<TempDir> {
|
||||
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<GetTaskResponse> {
|
||||
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}",
|
||||
);
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
// Aggregates all former standalone integration tests as modules.
|
||||
mod apply_command_e2e;
|
||||
@@ -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+\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."
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -39,9 +39,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 }
|
||||
@@ -66,7 +64,6 @@ codex-model-provider = { workspace = true }
|
||||
codex-models-manager = { workspace = true }
|
||||
codex-plugin = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
codex-responses-api-proxy = { workspace = true }
|
||||
codex-tcp-tunnel = { workspace = true }
|
||||
codex-rmcp-client = { workspace = true }
|
||||
codex-rollout = { workspace = true }
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
use clap::Parser;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
pub struct AppCommand {
|
||||
/// Workspace path to open in the Desktop app.
|
||||
#[arg(value_name = "PATH", default_value = ".")]
|
||||
pub path: PathBuf,
|
||||
|
||||
/// Override the app installer download URL (advanced).
|
||||
#[arg(long = "download-url")]
|
||||
pub download_url_override: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn run_app(cmd: AppCommand) -> anyhow::Result<()> {
|
||||
let workspace = std::fs::canonicalize(&cmd.path).unwrap_or(cmd.path);
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
crate::desktop_app::run_app_open_or_install(workspace, cmd.download_url_override).await
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
crate::desktop_app::run_app_open_or_install(workspace, cmd.download_url_override).await
|
||||
}
|
||||
}
|
||||
@@ -1,513 +0,0 @@
|
||||
use anyhow::Context as _;
|
||||
use std::ffi::CString;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tempfile::Builder;
|
||||
use tokio::process::Command;
|
||||
|
||||
const CODEX_BUNDLE_IDENTIFIER: &str = "com.openai.codex";
|
||||
const OPENAI_APPLE_TEAM_IDENTIFIER: &str = "2DC432GLL2";
|
||||
const CODEX_DMG_URL_ARM64: &str = "https://persistent.oaistatic.com/codex-app-prod/Codex.dmg";
|
||||
const CODEX_DMG_URL_X64: &str =
|
||||
"https://persistent.oaistatic.com/codex-app-prod/Codex-latest-x64.dmg";
|
||||
|
||||
pub async fn run_mac_app_open_or_install(
|
||||
workspace: PathBuf,
|
||||
download_url_override: Option<String>,
|
||||
) -> anyhow::Result<()> {
|
||||
if let Some(app_path) = find_existing_codex_app_path(&codex_app_search_dirs()) {
|
||||
eprintln!(
|
||||
"Opening Desktop app at {app_path}...",
|
||||
app_path = app_path.display()
|
||||
);
|
||||
open_codex_app(&app_path, &workspace).await?;
|
||||
return Ok(());
|
||||
}
|
||||
eprintln!("Desktop app not found; downloading installer...");
|
||||
let download_url = download_url_override.unwrap_or_else(|| {
|
||||
let default_url = if is_apple_silicon_mac() {
|
||||
CODEX_DMG_URL_ARM64
|
||||
} else {
|
||||
CODEX_DMG_URL_X64
|
||||
};
|
||||
default_url.to_string()
|
||||
});
|
||||
let installed_app = download_and_install_codex_to_user_applications(&download_url)
|
||||
.await
|
||||
.context("failed to download/install Desktop app")?;
|
||||
eprintln!(
|
||||
"Launching Desktop app from {installed_app}...",
|
||||
installed_app = installed_app.display()
|
||||
);
|
||||
open_codex_app(&installed_app, &workspace).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_apple_silicon_mac() -> bool {
|
||||
fn macos_sysctl_flag(name: &str) -> Option<bool> {
|
||||
let name = CString::new(name).ok()?;
|
||||
let mut value: libc::c_int = 0;
|
||||
let mut size = std::mem::size_of_val(&value);
|
||||
let result = unsafe {
|
||||
libc::sysctlbyname(
|
||||
name.as_ptr(),
|
||||
(&mut value as *mut libc::c_int).cast::<libc::c_void>(),
|
||||
&mut size,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
)
|
||||
};
|
||||
(result == 0).then_some(value != 0)
|
||||
}
|
||||
|
||||
std::env::consts::ARCH == "aarch64"
|
||||
|| macos_sysctl_flag("sysctl.proc_translated").unwrap_or(false)
|
||||
|| macos_sysctl_flag("hw.optional.arm64").unwrap_or(false)
|
||||
}
|
||||
|
||||
fn find_existing_codex_app_path(applications_dirs: &[PathBuf]) -> Option<PathBuf> {
|
||||
applications_dirs
|
||||
.iter()
|
||||
.flat_map(|dir| ["ChatGPT.app", "Codex.app"].map(|app_name| dir.join(app_name)))
|
||||
.find(|candidate| is_codex_app_bundle(candidate))
|
||||
}
|
||||
|
||||
fn codex_app_search_dirs() -> Vec<PathBuf> {
|
||||
let mut paths = vec![PathBuf::from("/Applications")];
|
||||
if let Some(home) = std::env::var_os("HOME") {
|
||||
paths.push(PathBuf::from(home).join("Applications"));
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
fn is_codex_app_bundle(app_path: &Path) -> bool {
|
||||
if !app_path.is_dir() {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::process::Command::new("/usr/bin/plutil")
|
||||
.arg("-extract")
|
||||
.arg("CFBundleIdentifier")
|
||||
.arg("raw")
|
||||
.arg("-o")
|
||||
.arg("-")
|
||||
.arg(app_path.join("Contents/Info.plist"))
|
||||
.output()
|
||||
.is_ok_and(|output| {
|
||||
output.status.success()
|
||||
&& String::from_utf8_lossy(&output.stdout).trim() == CODEX_BUNDLE_IDENTIFIER
|
||||
})
|
||||
}
|
||||
|
||||
async fn open_codex_app(app_path: &Path, workspace: &Path) -> anyhow::Result<()> {
|
||||
verify_codex_app_bundle(app_path).await?;
|
||||
eprintln!(
|
||||
"Opening workspace {workspace}...",
|
||||
workspace = workspace.display()
|
||||
);
|
||||
let url = codex_new_thread_url(workspace);
|
||||
let status = Command::new("open")
|
||||
.arg("-a")
|
||||
.arg(app_path)
|
||||
.arg(&url)
|
||||
.status()
|
||||
.await
|
||||
.context("failed to invoke `open`")?;
|
||||
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
anyhow::bail!(
|
||||
"`open -a {app_path} {url}` exited with {status}",
|
||||
app_path = app_path.display(),
|
||||
url = url
|
||||
);
|
||||
}
|
||||
|
||||
async fn verify_codex_app_bundle(app_path: &Path) -> anyhow::Result<()> {
|
||||
let requirement = format!(
|
||||
"identifier \"{CODEX_BUNDLE_IDENTIFIER}\" and anchor apple generic and certificate leaf[subject.OU] = \"{OPENAI_APPLE_TEAM_IDENTIFIER}\""
|
||||
);
|
||||
let output = Command::new("/usr/bin/codesign")
|
||||
.args(["--verify", "--deep", "--strict"])
|
||||
.arg(format!("-R={requirement}"))
|
||||
.arg(app_path)
|
||||
.output()
|
||||
.await
|
||||
.context("failed to verify Desktop app signature")?;
|
||||
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
anyhow::bail!(
|
||||
"Desktop app at {} failed OpenAI signature verification (team {OPENAI_APPLE_TEAM_IDENTIFIER}, bundle {CODEX_BUNDLE_IDENTIFIER}): {}",
|
||||
app_path.display(),
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
);
|
||||
}
|
||||
|
||||
fn codex_new_thread_url(workspace: &Path) -> String {
|
||||
let workspace = workspace.as_os_str().to_string_lossy();
|
||||
let mut serializer = url::form_urlencoded::Serializer::new(String::new());
|
||||
serializer.append_pair("path", workspace.as_ref());
|
||||
let query = serializer.finish();
|
||||
format!("codex://threads/new?{query}")
|
||||
}
|
||||
|
||||
async fn download_and_install_codex_to_user_applications(dmg_url: &str) -> anyhow::Result<PathBuf> {
|
||||
let temp_dir = Builder::new()
|
||||
.prefix("codex-app-installer-")
|
||||
.tempdir()
|
||||
.context("failed to create temp dir")?;
|
||||
let tmp_root = temp_dir.path().to_path_buf();
|
||||
let _temp_dir = temp_dir;
|
||||
|
||||
let dmg_path = tmp_root.join("Codex.dmg");
|
||||
download_dmg(dmg_url, &dmg_path).await?;
|
||||
|
||||
eprintln!("Mounting Desktop app installer...");
|
||||
let mount_point = mount_dmg(&dmg_path).await?;
|
||||
eprintln!(
|
||||
"Installer mounted at {mount_point}.",
|
||||
mount_point = mount_point.display()
|
||||
);
|
||||
let result = async {
|
||||
let app_in_volume = find_codex_app_in_mount(&mount_point)
|
||||
.context("failed to locate Codex.app in mounted dmg")?;
|
||||
verify_codex_app_bundle(&app_in_volume)
|
||||
.await
|
||||
.context("refusing to install an unverified Desktop app")?;
|
||||
install_codex_app_bundle(&app_in_volume).await
|
||||
}
|
||||
.await;
|
||||
|
||||
let detach_result = detach_dmg(&mount_point).await;
|
||||
if let Err(err) = detach_result {
|
||||
eprintln!(
|
||||
"warning: failed to detach dmg at {mount_point}: {err}",
|
||||
mount_point = mount_point.display()
|
||||
);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
async fn install_codex_app_bundle(app_in_volume: &Path) -> anyhow::Result<PathBuf> {
|
||||
for applications_dir in candidate_applications_dirs()? {
|
||||
eprintln!(
|
||||
"Installing Desktop app into {applications_dir}...",
|
||||
applications_dir = applications_dir.display()
|
||||
);
|
||||
std::fs::create_dir_all(&applications_dir).with_context(|| {
|
||||
format!(
|
||||
"failed to create applications dir {applications_dir}",
|
||||
applications_dir = applications_dir.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
let dest_app = applications_dir.join("Codex.app");
|
||||
if dest_app.is_dir() {
|
||||
return Ok(dest_app);
|
||||
}
|
||||
|
||||
match copy_app_bundle(app_in_volume, &dest_app).await {
|
||||
Ok(()) => return Ok(dest_app),
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"warning: failed to install Codex.app to {applications_dir}: {err}",
|
||||
applications_dir = applications_dir.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
anyhow::bail!("failed to install Codex.app to any applications directory");
|
||||
}
|
||||
|
||||
fn candidate_applications_dirs() -> anyhow::Result<Vec<PathBuf>> {
|
||||
let mut dirs = vec![PathBuf::from("/Applications")];
|
||||
dirs.push(user_applications_dir()?);
|
||||
Ok(dirs)
|
||||
}
|
||||
|
||||
async fn download_dmg(url: &str, dest: &Path) -> anyhow::Result<()> {
|
||||
eprintln!("Downloading installer...");
|
||||
let status = Command::new("curl")
|
||||
.arg("-fL")
|
||||
.arg("--retry")
|
||||
.arg("3")
|
||||
.arg("--retry-delay")
|
||||
.arg("1")
|
||||
.arg("-o")
|
||||
.arg(dest)
|
||||
.arg(url)
|
||||
.status()
|
||||
.await
|
||||
.context("failed to invoke `curl`")?;
|
||||
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
anyhow::bail!("curl download failed with {status}");
|
||||
}
|
||||
|
||||
async fn mount_dmg(dmg_path: &Path) -> anyhow::Result<PathBuf> {
|
||||
let output = Command::new("hdiutil")
|
||||
.arg("attach")
|
||||
.arg("-nobrowse")
|
||||
.arg("-readonly")
|
||||
.arg(dmg_path)
|
||||
.output()
|
||||
.await
|
||||
.context("failed to invoke `hdiutil attach`")?;
|
||||
|
||||
if !output.status.success() {
|
||||
anyhow::bail!(
|
||||
"`hdiutil attach` failed with {status}: {stderr}",
|
||||
status = output.status,
|
||||
stderr = String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
parse_hdiutil_attach_mount_point(&stdout)
|
||||
.map(PathBuf::from)
|
||||
.with_context(|| format!("failed to parse mount point from hdiutil output:\n{stdout}"))
|
||||
}
|
||||
|
||||
async fn detach_dmg(mount_point: &Path) -> anyhow::Result<()> {
|
||||
let status = Command::new("hdiutil")
|
||||
.arg("detach")
|
||||
.arg(mount_point)
|
||||
.status()
|
||||
.await
|
||||
.context("failed to invoke `hdiutil detach`")?;
|
||||
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
anyhow::bail!("hdiutil detach failed with {status}");
|
||||
}
|
||||
|
||||
fn find_codex_app_in_mount(mount_point: &Path) -> anyhow::Result<PathBuf> {
|
||||
let direct = mount_point.join("Codex.app");
|
||||
if direct.is_dir() {
|
||||
return Ok(direct);
|
||||
}
|
||||
|
||||
for entry in std::fs::read_dir(mount_point).with_context(|| {
|
||||
format!(
|
||||
"failed to read {mount_point}",
|
||||
mount_point = mount_point.display()
|
||||
)
|
||||
})? {
|
||||
let entry = entry.context("failed to read mount directory entry")?;
|
||||
let path = entry.path();
|
||||
if path.extension().is_some_and(|ext| ext == "app") && path.is_dir() {
|
||||
return Ok(path);
|
||||
}
|
||||
}
|
||||
|
||||
anyhow::bail!(
|
||||
"no .app bundle found at {mount_point}",
|
||||
mount_point = mount_point.display()
|
||||
);
|
||||
}
|
||||
|
||||
async fn copy_app_bundle(src_app: &Path, dest_app: &Path) -> anyhow::Result<()> {
|
||||
let status = Command::new("ditto")
|
||||
.arg(src_app)
|
||||
.arg(dest_app)
|
||||
.status()
|
||||
.await
|
||||
.context("failed to invoke `ditto`")?;
|
||||
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
anyhow::bail!("ditto copy failed with {status}");
|
||||
}
|
||||
|
||||
fn user_applications_dir() -> anyhow::Result<PathBuf> {
|
||||
let home = std::env::var_os("HOME").context("HOME is not set")?;
|
||||
Ok(PathBuf::from(home).join("Applications"))
|
||||
}
|
||||
|
||||
fn parse_hdiutil_attach_mount_point(output: &str) -> Option<String> {
|
||||
output.lines().find_map(|line| {
|
||||
if !line.contains("/Volumes/") {
|
||||
return None;
|
||||
}
|
||||
if let Some((_, mount)) = line.rsplit_once('\t') {
|
||||
return Some(mount.trim().to_string());
|
||||
}
|
||||
line.split_whitespace()
|
||||
.find(|field| field.starts_with("/Volumes/"))
|
||||
.map(str::to_string)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::codex_new_thread_url;
|
||||
use super::find_existing_codex_app_path;
|
||||
use super::open_codex_app;
|
||||
use super::parse_hdiutil_attach_mount_point;
|
||||
use super::verify_codex_app_bundle;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
fn write_app_bundle(app_path: &Path, bundle_identifier: &str) {
|
||||
let contents_path = app_path.join("Contents");
|
||||
fs::create_dir_all(&contents_path).expect("create app bundle");
|
||||
fs::write(
|
||||
contents_path.join("Info.plist"),
|
||||
format!(
|
||||
r#"<?xml version="1.0"?><plist version="1.0"><dict><key>CFBundleIdentifier</key><string>{bundle_identifier}</string></dict></plist>"#
|
||||
),
|
||||
)
|
||||
.expect("write Info.plist");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_chatgpt_app_with_codex_bundle_identifier() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let app_path = temp_dir.path().join("ChatGPT.app");
|
||||
write_app_bundle(&app_path, "com.openai.codex");
|
||||
|
||||
assert_eq!(
|
||||
find_existing_codex_app_path(&[temp_dir.path().to_path_buf()]),
|
||||
Some(app_path)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_classic_chatgpt_app() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
write_app_bundle(&temp_dir.path().join("ChatGPT.app"), "com.openai.chat");
|
||||
let codex_app_path = temp_dir.path().join("Codex.app");
|
||||
write_app_bundle(&codex_app_path, "com.openai.codex");
|
||||
|
||||
assert_eq!(
|
||||
find_existing_codex_app_path(&[temp_dir.path().to_path_buf()]),
|
||||
Some(codex_app_path)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_unsigned_app_with_codex_bundle_identifier() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let app_path = temp_dir.path().join("Codex.app");
|
||||
write_app_bundle(&app_path, "com.openai.codex");
|
||||
|
||||
let err = verify_codex_app_bundle(&app_path)
|
||||
.await
|
||||
.expect_err("unsigned app should not satisfy the OpenAI signing requirement");
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("failed OpenAI signature verification"),
|
||||
"unexpected verification error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_valid_signature_without_openai_signing_identity() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let app_path = temp_dir.path().join("Codex.app");
|
||||
let contents_path = app_path.join("Contents");
|
||||
let executable_path = contents_path.join("MacOS/Codex");
|
||||
fs::create_dir_all(executable_path.parent().expect("executable parent"))
|
||||
.expect("create executable directory");
|
||||
codex_utils_cargo_bin::copy_executable(Path::new("/usr/bin/true"), &executable_path)
|
||||
.expect("copy executable into app bundle");
|
||||
fs::write(
|
||||
contents_path.join("Info.plist"),
|
||||
r#"<?xml version="1.0"?><plist version="1.0"><dict><key>CFBundleIdentifier</key><string>com.openai.codex</string><key>CFBundleExecutable</key><string>Codex</string></dict></plist>"#,
|
||||
)
|
||||
.expect("write Info.plist");
|
||||
|
||||
let sign_status = std::process::Command::new("/usr/bin/codesign")
|
||||
.args(["--force", "--sign", "-"])
|
||||
.arg(&app_path)
|
||||
.status()
|
||||
.expect("sign app bundle");
|
||||
assert!(sign_status.success(), "failed to ad-hoc sign app bundle");
|
||||
|
||||
let verify_status = std::process::Command::new("/usr/bin/codesign")
|
||||
.args(["--verify", "--deep", "--strict"])
|
||||
.arg(&app_path)
|
||||
.status()
|
||||
.expect("verify app bundle signature");
|
||||
assert!(verify_status.success(), "ad-hoc signature should be valid");
|
||||
|
||||
let err = verify_codex_app_bundle(&app_path)
|
||||
.await
|
||||
.expect_err("valid signature without the OpenAI team should not be trusted");
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("failed OpenAI signature verification"),
|
||||
"unexpected verification error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refuses_to_launch_unsigned_existing_codex_app() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let app_path = temp_dir.path().join("Codex.app");
|
||||
write_app_bundle(&app_path, "com.openai.codex");
|
||||
|
||||
let err = open_codex_app(&app_path, temp_dir.path())
|
||||
.await
|
||||
.expect_err("unsigned existing app should not be launched");
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("failed OpenAI signature verification"),
|
||||
"unexpected launch error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_mount_point_from_tab_separated_hdiutil_output() {
|
||||
let output = "/dev/disk2s1\tApple_HFS\tCodex\t/Volumes/Codex\n";
|
||||
assert_eq!(
|
||||
parse_hdiutil_attach_mount_point(output).as_deref(),
|
||||
Some("/Volumes/Codex")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_mount_point_with_spaces() {
|
||||
let output = "/dev/disk2s1\tApple_HFS\tCodex Installer\t/Volumes/Codex Installer\n";
|
||||
assert_eq!(
|
||||
parse_hdiutil_attach_mount_point(output).as_deref(),
|
||||
Some("/Volumes/Codex Installer")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_new_thread_url_encodes_workspace_path() {
|
||||
let url = url::Url::parse(&codex_new_thread_url(Path::new("/tmp/codex workspace/#1")))
|
||||
.expect("deep link should parse");
|
||||
|
||||
assert_eq!(
|
||||
(
|
||||
url.scheme().to_string(),
|
||||
url.host_str().map(str::to_string),
|
||||
url.path().to_string(),
|
||||
url.query_pairs().into_owned().collect::<Vec<_>>(),
|
||||
),
|
||||
(
|
||||
"codex".to_string(),
|
||||
Some("threads".to_string()),
|
||||
"/new".to_string(),
|
||||
vec![("path".to_string(), "/tmp/codex workspace/#1".to_string())],
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows;
|
||||
|
||||
/// Run the app install/open logic for the current OS.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub async fn run_app_open_or_install(
|
||||
workspace: std::path::PathBuf,
|
||||
download_url_override: Option<String>,
|
||||
) -> anyhow::Result<()> {
|
||||
mac::run_mac_app_open_or_install(workspace, download_url_override).await
|
||||
}
|
||||
|
||||
/// Run the app install/open logic for the current OS.
|
||||
#[cfg(target_os = "windows")]
|
||||
pub async fn run_app_open_or_install(
|
||||
workspace: std::path::PathBuf,
|
||||
download_url_override: Option<String>,
|
||||
) -> anyhow::Result<()> {
|
||||
windows::run_windows_app_open_or_install(workspace, download_url_override).await
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
use anyhow::Context as _;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tokio::process::Command;
|
||||
|
||||
const CODEX_WINDOWS_INSTALLER_URL: &str =
|
||||
"https://get.microsoft.com/installer/download/9PLM9XGG6VKS?cid=website_cta_psi";
|
||||
const CODEX_MICROSOFT_STORE_WEB_URL: &str = "https://apps.microsoft.com/detail/9plm9xgg6vks";
|
||||
|
||||
pub async fn run_windows_app_open_or_install(
|
||||
workspace: PathBuf,
|
||||
download_url_override: Option<String>,
|
||||
) -> anyhow::Result<()> {
|
||||
let workspace_path = workspace.display().to_string();
|
||||
let display_workspace = display_workspace_path(&workspace);
|
||||
if codex_app_is_installed().await? {
|
||||
eprintln!("Opening workspace {display_workspace} in the Desktop app...");
|
||||
open_url(&codex_new_thread_url(&workspace_path)).await?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
eprintln!("Desktop app not found; opening Windows installer...");
|
||||
let download_url = download_url_override
|
||||
.as_deref()
|
||||
.unwrap_or(CODEX_WINDOWS_INSTALLER_URL);
|
||||
if open_url(download_url).await.is_err() && download_url_override.is_none() {
|
||||
open_url(CODEX_MICROSOFT_STORE_WEB_URL).await?;
|
||||
}
|
||||
eprintln!("After installing the Desktop app, open workspace {display_workspace}.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn codex_app_is_installed() -> anyhow::Result<bool> {
|
||||
// This package identity is stable across Codex- and ChatGPT-branded builds.
|
||||
let output = Command::new("powershell.exe")
|
||||
.arg("-NoProfile")
|
||||
.arg("-Command")
|
||||
.arg(
|
||||
"Get-StartApps | Where-Object AppID -Like 'OpenAI.Codex_*!App' | Select-Object -First 1 -ExpandProperty AppID",
|
||||
)
|
||||
.output()
|
||||
.await
|
||||
.context("failed to invoke `powershell.exe`")?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
Ok(!String::from_utf8_lossy(&output.stdout).trim().is_empty())
|
||||
}
|
||||
|
||||
async fn open_url(url: &str) -> anyhow::Result<()> {
|
||||
let status = Command::new("powershell.exe")
|
||||
.arg("-NoProfile")
|
||||
.arg("-Command")
|
||||
.arg("& { param($target) Start-Process -FilePath $target }")
|
||||
.arg(url)
|
||||
.status()
|
||||
.await
|
||||
.with_context(|| format!("failed to open {url}"))?;
|
||||
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
anyhow::bail!("failed to open {url} with {status}");
|
||||
}
|
||||
}
|
||||
|
||||
fn codex_new_thread_url(workspace: &str) -> String {
|
||||
let mut serializer = url::form_urlencoded::Serializer::new(String::new());
|
||||
serializer.append_pair("path", workspace);
|
||||
let query = serializer.finish();
|
||||
format!("codex://threads/new?{query}")
|
||||
}
|
||||
|
||||
fn display_workspace_path(workspace: &Path) -> String {
|
||||
let path = workspace.display().to_string();
|
||||
if let Some(path) = path.strip_prefix(r"\\?\UNC\") {
|
||||
format!(r"\\{path}")
|
||||
} else if let Some(path) = path.strip_prefix(r"\\?\") {
|
||||
path.to_string()
|
||||
} else {
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::codex_new_thread_url;
|
||||
use super::display_workspace_path;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn display_workspace_path_removes_windows_extended_prefix() {
|
||||
assert_eq!(
|
||||
display_workspace_path(Path::new(r"\\?\C:\Users\fcoury\code\codex")),
|
||||
r"C:\Users\fcoury\code\codex"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_workspace_path_preserves_unc_prefix() {
|
||||
assert_eq!(
|
||||
display_workspace_path(Path::new(r"\\?\UNC\server\share\codex")),
|
||||
r"\\server\share\codex"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_workspace_path_leaves_regular_paths_unchanged() {
|
||||
assert_eq!(
|
||||
display_workspace_path(Path::new(r"C:\Users\fcoury\code\codex")),
|
||||
r"C:\Users\fcoury\code\codex"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_new_thread_url_encodes_windows_workspace_path() {
|
||||
assert_eq!(
|
||||
codex_new_thread_url(r"C:\Users\akuma\repos\koba"),
|
||||
r"codex://threads/new?path=C%3A%5CUsers%5Cakuma%5Crepos%5Ckoba"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_new_thread_url_preserves_verbatim_workspace_path() {
|
||||
assert_eq!(
|
||||
codex_new_thread_url(r"\\?\C:\Users\akuma\repos\koba"),
|
||||
r"codex://threads/new?path=%5C%5C%3F%5CC%3A%5CUsers%5Cakuma%5Crepos%5Ckoba"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -44,8 +44,10 @@ use codex_features::FEATURES;
|
||||
use codex_features::Feature;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OpenAiDestination;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use codex_http_client::classify_openai_api_url;
|
||||
use codex_install_context::CodexPackageLayout;
|
||||
use codex_install_context::InstallContext;
|
||||
use codex_install_context::InstallMethod;
|
||||
@@ -569,11 +571,6 @@ async fn build_report(
|
||||
|
||||
progress.begin("desktop");
|
||||
if let Some(desktop) = desktop::collect().await {
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
if let Some(application) = desktop.application.as_ref() {
|
||||
updates::append_desktop_update(&mut checks, config_result.as_ref().ok(), application)
|
||||
.await;
|
||||
}
|
||||
progress.finish("desktop", overall_status(&desktop.checks));
|
||||
checks.extend(desktop.checks);
|
||||
}
|
||||
@@ -2339,6 +2336,21 @@ async fn websocket_reachability_check(
|
||||
.details(details);
|
||||
}
|
||||
|
||||
// aKode: never open a probe connection to OpenAI/ChatGPT, including the implicit default.
|
||||
if provider
|
||||
.base_url
|
||||
.as_deref()
|
||||
.is_none_or(|url| classify_openai_api_url(url) != OpenAiDestination::Other)
|
||||
{
|
||||
return DoctorCheck::new(
|
||||
"network.websocket_reachability",
|
||||
"websocket",
|
||||
CheckStatus::Ok,
|
||||
"Responses WebSocket probe skipped: no explicit non-OpenAI provider base URL",
|
||||
)
|
||||
.details(details);
|
||||
}
|
||||
|
||||
details.push(format!(
|
||||
"connect timeout: {} ms",
|
||||
provider.websocket_connect_timeout().as_millis()
|
||||
@@ -2670,21 +2682,20 @@ fn provider_reachability_plan(config: &Config) -> ReachabilityPlan {
|
||||
config.model_provider.base_url.as_deref(),
|
||||
query_params.as_ref(),
|
||||
config.model_provider.is_amazon_bedrock(),
|
||||
&config.chatgpt_base_url,
|
||||
);
|
||||
plan.http_client_factory = config.http_client_factory();
|
||||
plan
|
||||
}
|
||||
|
||||
/// aKode: without a loaded config there is no explicit provider endpoint, so nothing is probed.
|
||||
fn default_reachability_plan() -> ReachabilityPlan {
|
||||
provider_reachability_plan_from_parts(
|
||||
ProviderAuthReachabilityMode::Chatgpt,
|
||||
"openai",
|
||||
"OpenAI",
|
||||
ProviderAuthReachabilityMode::NotRequired,
|
||||
"unknown",
|
||||
"unknown",
|
||||
/*provider_base_url*/ None,
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ false,
|
||||
"https://chatgpt.com/backend-api/",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2730,35 +2741,20 @@ fn provider_reachability_plan_from_parts(
|
||||
provider_base_url: Option<&str>,
|
||||
provider_query_params: Option<&HashMap<String, String>>,
|
||||
is_amazon_bedrock: bool,
|
||||
chatgpt_base_url: &str,
|
||||
) -> ReachabilityPlan {
|
||||
let provider_route_probe_url = provider_base_url
|
||||
.or_else(|| {
|
||||
(mode == ProviderAuthReachabilityMode::ApiKey).then_some("https://api.openai.com/v1")
|
||||
})
|
||||
.and_then(|url| {
|
||||
should_probe_models_route(provider_name, url, is_amazon_bedrock)
|
||||
.then(|| provider_url_for_path(url, "models", provider_query_params))
|
||||
});
|
||||
let endpoints = match (mode, provider_base_url) {
|
||||
(ProviderAuthReachabilityMode::ApiKey, _) | (_, Some(_)) => vec![ReachabilityEndpoint {
|
||||
// aKode: only an explicitly configured base URL outside OpenAI/ChatGPT is probed. The
|
||||
// implicit chatgpt.com and api.openai.com endpoints are never contacted.
|
||||
let endpoints = provider_base_url
|
||||
.filter(|url| classify_openai_api_url(url) == OpenAiDestination::Other)
|
||||
.map(|base_url| ReachabilityEndpoint {
|
||||
label: format!("{provider_id} API"),
|
||||
url: provider_url_for_path(
|
||||
provider_base_url.unwrap_or("https://api.openai.com/v1"),
|
||||
"responses",
|
||||
provider_query_params,
|
||||
),
|
||||
url: provider_url_for_path(base_url, "responses", provider_query_params),
|
||||
required: true,
|
||||
route_probe_url: provider_route_probe_url,
|
||||
}],
|
||||
(ProviderAuthReachabilityMode::Chatgpt, None) => vec![ReachabilityEndpoint {
|
||||
label: "ChatGPT".to_string(),
|
||||
url: provider_url_for_path(chatgpt_base_url, "codex/responses", provider_query_params),
|
||||
required: true,
|
||||
route_probe_url: None,
|
||||
}],
|
||||
(ProviderAuthReachabilityMode::NotRequired, None) => Vec::new(),
|
||||
};
|
||||
route_probe_url: should_probe_models_route(provider_name, base_url, is_amazon_bedrock)
|
||||
.then(|| provider_url_for_path(base_url, "models", provider_query_params)),
|
||||
})
|
||||
.into_iter()
|
||||
.collect();
|
||||
ReachabilityPlan {
|
||||
description: mode.description().to_string(),
|
||||
endpoints,
|
||||
@@ -2878,7 +2874,7 @@ async fn provider_reachability_check(plan: ReachabilityPlan) -> DoctorCheck {
|
||||
)
|
||||
.measured(format!("{route_probe_url} returned {status}"))
|
||||
.expected("GET /models returns 2xx, 401, or 403")
|
||||
.remedy("Set base_url to the provider API root, for example https://api.openai.com/v1")
|
||||
.remedy("Set base_url to the provider API root, for example http://localhost:8080/v1")
|
||||
.field("route probe"),
|
||||
);
|
||||
}
|
||||
@@ -3922,7 +3918,6 @@ mod tests {
|
||||
Some("https://example.openai.azure.com/openai/v1"),
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ false,
|
||||
"https://chatgpt.com/backend-api/",
|
||||
),
|
||||
ReachabilityPlan {
|
||||
description: "provider auth".to_string(),
|
||||
@@ -3953,7 +3948,6 @@ mod tests {
|
||||
Some("https://example.com/openai/v1/"),
|
||||
Some(&query_params),
|
||||
/*is_amazon_bedrock*/ false,
|
||||
"https://chatgpt.com/backend-api/",
|
||||
),
|
||||
ReachabilityPlan {
|
||||
description: description.to_string(),
|
||||
@@ -3984,14 +3978,13 @@ mod tests {
|
||||
Some("https://bedrock-runtime.us-east-1.amazonaws.com/openai/v1"),
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ true,
|
||||
"https://chatgpt.com/backend-api/",
|
||||
);
|
||||
|
||||
assert_eq!(plan.endpoints[0].route_probe_url, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_reachability_api_key_does_not_require_chatgpt() {
|
||||
fn provider_reachability_never_infers_openai_endpoints() {
|
||||
let plan = provider_reachability_plan_from_parts(
|
||||
ProviderAuthReachabilityMode::ApiKey,
|
||||
"openai",
|
||||
@@ -3999,31 +3992,28 @@ mod tests {
|
||||
/*provider_base_url*/ None,
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ false,
|
||||
"https://chatgpt.com/backend-api/",
|
||||
);
|
||||
assert_eq!(plan.endpoints, Vec::new());
|
||||
|
||||
assert_eq!(
|
||||
plan.endpoints,
|
||||
vec![ReachabilityEndpoint {
|
||||
label: "openai API".to_string(),
|
||||
url: "https://api.openai.com/v1/responses".to_string(),
|
||||
required: true,
|
||||
route_probe_url: Some("https://api.openai.com/v1/models".to_string()),
|
||||
}]
|
||||
);
|
||||
for base_url in [
|
||||
"https://api.openai.com/v1",
|
||||
"https://chatgpt.com/backend-api/",
|
||||
] {
|
||||
let plan = provider_reachability_plan_from_parts(
|
||||
ProviderAuthReachabilityMode::Chatgpt,
|
||||
"openai",
|
||||
"OpenAI",
|
||||
Some(base_url),
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ false,
|
||||
);
|
||||
assert_eq!(plan.endpoints, Vec::new(), "{base_url}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_reachability_chatgpt_uses_inference_endpoint() {
|
||||
assert_eq!(
|
||||
default_reachability_plan().endpoints,
|
||||
vec![ReachabilityEndpoint {
|
||||
label: "ChatGPT".to_string(),
|
||||
url: "https://chatgpt.com/backend-api/codex/responses".to_string(),
|
||||
required: true,
|
||||
route_probe_url: None,
|
||||
}]
|
||||
);
|
||||
fn provider_reachability_default_plan_probes_nothing() {
|
||||
assert_eq!(default_reachability_plan().endpoints, Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -4065,7 +4055,6 @@ mod tests {
|
||||
Some(&format!("http://{addr}/xxxx")),
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ false,
|
||||
"https://chatgpt.com/backend-api/",
|
||||
);
|
||||
|
||||
let check = provider_reachability_check(plan).await;
|
||||
@@ -4081,7 +4070,7 @@ mod tests {
|
||||
assert_eq!(check.issues.len(), 1);
|
||||
assert_eq!(
|
||||
check.issues[0].remedy.as_deref(),
|
||||
Some("Set base_url to the provider API root, for example https://api.openai.com/v1")
|
||||
Some("Set base_url to the provider API root, for example http://localhost:8080/v1")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4106,7 +4095,6 @@ mod tests {
|
||||
Some(&format!("http://{addr}/v1")),
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ false,
|
||||
"https://chatgpt.com/backend-api/",
|
||||
);
|
||||
|
||||
let check = provider_reachability_check(plan).await;
|
||||
|
||||
@@ -28,8 +28,6 @@ const HANDSHAKE_CHECK_ID: &str = "desktop.app_server.handshake";
|
||||
|
||||
pub(super) struct DesktopDiagnostics {
|
||||
pub(super) checks: Vec<DoctorCheck>,
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
pub(super) application: Option<platform::InstalledApp>,
|
||||
}
|
||||
|
||||
struct DesktopLog {
|
||||
@@ -69,8 +67,6 @@ pub(super) async fn collect() -> Option<DesktopDiagnostics> {
|
||||
#[cfg(target_os = "windows")]
|
||||
windows_security::collect().await,
|
||||
],
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
application: None,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -104,8 +100,6 @@ pub(super) async fn collect() -> Option<DesktopDiagnostics> {
|
||||
#[cfg(target_os = "windows")]
|
||||
windows_security::collect().await,
|
||||
],
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
application: Some(application),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -52,8 +52,6 @@ pub(in crate::doctor) struct InstalledApp {
|
||||
package_family: &'static str,
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(in crate::doctor) bundle: PathBuf,
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(in crate::doctor) build: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -268,16 +266,10 @@ pub(in crate::doctor) async fn inspect_macos_bundle(
|
||||
.or_else(|| metadata.get("CFBundleVersion"))
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(DiscoveryError)?;
|
||||
let build = metadata
|
||||
.get("CFBundleVersion")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|value| value.parse().ok())
|
||||
.ok_or(DiscoveryError)?;
|
||||
|
||||
Ok(Some(InstalledApp {
|
||||
identity: "com.openai.codex",
|
||||
version: version.to_string(),
|
||||
bundle: bundle.to_path_buf(),
|
||||
build,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -17,13 +17,12 @@ async fn provider_reachability_rejects_proxy_authentication_challenges() {
|
||||
.mount(&proxy)
|
||||
.await;
|
||||
let plan = provider_reachability_plan_from_parts(
|
||||
ProviderAuthReachabilityMode::Chatgpt,
|
||||
"openai",
|
||||
"OpenAI",
|
||||
/*provider_base_url*/ None,
|
||||
ProviderAuthReachabilityMode::NotRequired,
|
||||
"local",
|
||||
"Local",
|
||||
Some(&format!("{}/v1", proxy.uri())),
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ false,
|
||||
&format!("{}/backend-api/", proxy.uri()),
|
||||
);
|
||||
|
||||
let check = provider_reachability_check(plan).await;
|
||||
|
||||
@@ -1,55 +1,23 @@
|
||||
//! Diagnoses whether Codex update paths target the running installation.
|
||||
//!
|
||||
//! Update diagnostics combine cached version metadata, install-channel hints,
|
||||
//! and bounded latest-version HTTP probes. It never executes package managers or
|
||||
//! other helpers selected by PATH; npm update targets are not verified.
|
||||
//! aKode: diagnostics are local only (cached version metadata and install-channel hints).
|
||||
//! There are no latest-version probes (GitHub, Homebrew) and no desktop appcast probes.
|
||||
|
||||
use std::path::Path;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_core::config::Config;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use codex_install_context::InstallContext;
|
||||
use codex_install_context::InstallMethod;
|
||||
use http::Method;
|
||||
use serde::Deserialize;
|
||||
#[cfg(target_os = "macos")]
|
||||
use url::Url;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
use super::DoctorIssue;
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
use super::desktop::platform::InstalledApp;
|
||||
use super::doctor_install_context;
|
||||
use super::doctor_managed_by_npm;
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
use super::network;
|
||||
|
||||
const MAX_VERSION_RESPONSE_BYTES: usize = 1024 * 1024;
|
||||
|
||||
const VERSION_FILE_NAME: &str = "version.json";
|
||||
const GITHUB_LATEST_RELEASE_URL: &str = "https://api.github.com/repos/openai/codex/releases/latest";
|
||||
const HOMEBREW_CASK_API_URL: &str = "https://formulae.brew.sh/api/cask/codex.json";
|
||||
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
|
||||
const DESKTOP_UPDATE_URL: &str = "https://persistent.oaistatic.com/codex-app-prod/appcast-x64.xml";
|
||||
#[cfg(all(target_os = "macos", not(target_arch = "x86_64")))]
|
||||
const DESKTOP_UPDATE_URL: &str = "https://persistent.oaistatic.com/codex-app-prod/appcast.xml";
|
||||
#[cfg(target_os = "macos")]
|
||||
const BACKEND_DESKTOP_UPDATE_URL: &str = "https://chatgpt.com/backend-api/wham/app/appcast";
|
||||
#[cfg(target_os = "windows")]
|
||||
const DESKTOP_UPDATE_URL: &str =
|
||||
"https://persistent.oaistatic.com/codex-app-prod/windows-store-update.json";
|
||||
|
||||
/// Builds the update-health row for the current installation.
|
||||
///
|
||||
/// Network failures while fetching latest-version metadata degrade the row to a
|
||||
/// warning instead of failing doctor outright; update freshness is useful
|
||||
/// support context but should not mask more direct install/config failures.
|
||||
/// Builds the update-health row for the current installation from local state only.
|
||||
pub(super) async fn updates_check(config: &Config) -> DoctorCheck {
|
||||
let current_exe = std::env::current_exe().ok();
|
||||
let install_context = doctor_install_context(current_exe.as_deref());
|
||||
@@ -63,306 +31,19 @@ pub(super) async fn updates_check(config: &Config) -> DoctorCheck {
|
||||
let version_file = config.codex_home.join(VERSION_FILE_NAME);
|
||||
push_cached_version_details(&mut details, &version_file);
|
||||
|
||||
let mut status = CheckStatus::Ok;
|
||||
let summary = "update configuration is locally consistent".to_string();
|
||||
|
||||
if doctor_managed_by_npm(current_exe.as_deref()) {
|
||||
details
|
||||
.push("npm update target: not inspected (PATH helpers are not executed)".to_string());
|
||||
}
|
||||
let client = RouteAwareClientPool::new_without_request_logging(
|
||||
config.http_client_factory(),
|
||||
ClientRouteClass::Other,
|
||||
);
|
||||
details.push("latest version probe: disabled (no network update checks)".to_string());
|
||||
|
||||
match fetch_latest_version(&client, &install_context).await {
|
||||
Ok(latest_version) => {
|
||||
details.push(format!("latest version: {latest_version}"));
|
||||
if is_newer(&latest_version, env!("CARGO_PKG_VERSION")) == Some(true) {
|
||||
details.push("latest version status: newer version is available".to_string());
|
||||
} else {
|
||||
details.push("latest version status: current version is not older".to_string());
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
status = status.max(CheckStatus::Warning);
|
||||
details.push(format!("latest version probe: {err}"));
|
||||
}
|
||||
}
|
||||
|
||||
DoctorCheck::new("updates.status", "updates", status, summary).details(details)
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
pub(super) async fn append_desktop_update(
|
||||
checks: &mut [DoctorCheck],
|
||||
config: Option<&Config>,
|
||||
application: &InstalledApp,
|
||||
) {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(home) = std::env::var_os("HOME").map(PathBuf::from)
|
||||
&& let Some(build) = latest_macos_staged_build(
|
||||
&home
|
||||
.join("Library/Caches")
|
||||
.join(application.identity)
|
||||
.join("org.sparkle-project.Sparkle/Installation"),
|
||||
application.build,
|
||||
)
|
||||
.await
|
||||
&& let Some(update) = checks.iter_mut().find(|check| check.id == "updates.status")
|
||||
{
|
||||
update.details.extend([
|
||||
"desktop update status: ready to install".to_string(),
|
||||
format!("desktop latest build: {build}"),
|
||||
format!("desktop application: {}", application.identity),
|
||||
]);
|
||||
}
|
||||
|
||||
let Some(config) = config else {
|
||||
return;
|
||||
};
|
||||
let Some(reachability_index) = checks
|
||||
.iter()
|
||||
.position(|check| check.id == "network.provider_reachability")
|
||||
else {
|
||||
return;
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
let desktop_update_url = std::env::var_os("HOME")
|
||||
.map(PathBuf::from)
|
||||
.map(|home| {
|
||||
macos_desktop_update_url(&home, application, &os_info::get().version().to_string())
|
||||
})
|
||||
.unwrap_or_else(|| DESKTOP_UPDATE_URL.to_string());
|
||||
#[cfg(target_os = "windows")]
|
||||
let desktop_update_url = DESKTOP_UPDATE_URL;
|
||||
#[cfg(target_os = "macos")]
|
||||
let desktop_update_url = desktop_update_url.as_str();
|
||||
let desktop_update_display_url = desktop_update_url
|
||||
.split_once('?')
|
||||
.map_or(desktop_update_url, |(endpoint, _)| endpoint);
|
||||
let client = RouteAwareClientPool::new_without_request_logging(
|
||||
config.http_client_factory(),
|
||||
ClientRouteClass::Other,
|
||||
);
|
||||
let outcome = match client
|
||||
.request(Method::GET, desktop_update_url)
|
||||
.timeout(deadline.saturating_duration_since(tokio::time::Instant::now()))
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
let status = response.status().as_u16();
|
||||
#[cfg(target_os = "windows")]
|
||||
if status == 404 && response.url().scheme() == "https" {
|
||||
checks[reachability_index].details.push(format!(
|
||||
"desktop assets CDN: {desktop_update_display_url} reachable (HTTP 404; no update available)"
|
||||
));
|
||||
return;
|
||||
}
|
||||
if cfg!(target_os = "windows") && response.url().scheme() != "https" {
|
||||
Err("update manifest redirected to a non-HTTPS URL".to_string())
|
||||
} else if status == 407 {
|
||||
Err("proxy authentication required (HTTP 407)".to_string())
|
||||
} else if !(200..=299).contains(&status) {
|
||||
Err(format!("HTTP {status}"))
|
||||
} else {
|
||||
checks[reachability_index].details.push(format!(
|
||||
"desktop assets CDN: {desktop_update_display_url} reachable (HTTP {status})"
|
||||
));
|
||||
#[cfg(target_os = "windows")]
|
||||
if let Some(update) = checks.iter_mut().find(|check| check.id == "updates.status") {
|
||||
match response.bytes().await {
|
||||
Ok(body) => match windows_store_update(&body, &application.version) {
|
||||
Ok(Some(build)) => update.details.extend([
|
||||
"desktop update status: available".to_string(),
|
||||
format!("desktop latest build: {build}"),
|
||||
format!("desktop application: {}", application.identity),
|
||||
]),
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
update.status = update.status.max(CheckStatus::Warning);
|
||||
update
|
||||
.details
|
||||
.push(format!("desktop update manifest: {error}"));
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
update.status = update.status.max(CheckStatus::Warning);
|
||||
update
|
||||
.details
|
||||
.push("desktop update manifest: response could not be read".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Err(error) => Err(network::request_error(error)),
|
||||
};
|
||||
|
||||
if let Err(error) = outcome {
|
||||
let reachability = &mut checks[reachability_index];
|
||||
reachability.details.push(format!(
|
||||
"desktop assets CDN: {desktop_update_display_url} {error} (optional)"
|
||||
));
|
||||
if reachability.status == CheckStatus::Ok {
|
||||
reachability.status = CheckStatus::Warning;
|
||||
reachability.summary = "desktop update and runtime CDN is unreachable".to_string();
|
||||
}
|
||||
reachability.issues.push(
|
||||
DoctorIssue::new(
|
||||
CheckStatus::Warning,
|
||||
"desktop update and runtime CDN is unreachable",
|
||||
)
|
||||
.measured(format!("{desktop_update_display_url} {error}"))
|
||||
.expected("desktop update and runtime CDN reachable over HTTPS")
|
||||
.remedy(
|
||||
if desktop_update_display_url.starts_with("https://chatgpt.com/") {
|
||||
"check proxy, firewall, DNS, and certificate access to chatgpt.com"
|
||||
} else {
|
||||
"check proxy, firewall, DNS, and certificate access to persistent.oaistatic.com"
|
||||
},
|
||||
)
|
||||
.field("desktop assets CDN"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn macos_desktop_update_url(home: &Path, application: &InstalledApp, os_version: &str) -> String {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ProductionAppcastState {
|
||||
#[serde(default)]
|
||||
backend_appcast_enabled: bool,
|
||||
installation_id: Option<String>,
|
||||
}
|
||||
|
||||
let state_path = home
|
||||
.join("Library/Application Support")
|
||||
.join(application.identity)
|
||||
.join("production-appcast-bootstrap.json");
|
||||
let Some(state) = std::fs::read(state_path)
|
||||
.ok()
|
||||
.and_then(|contents| serde_json::from_slice::<ProductionAppcastState>(&contents).ok())
|
||||
else {
|
||||
return DESKTOP_UPDATE_URL.to_string();
|
||||
};
|
||||
let Some(installation_id) = state
|
||||
.backend_appcast_enabled
|
||||
.then_some(state.installation_id)
|
||||
.flatten()
|
||||
else {
|
||||
return DESKTOP_UPDATE_URL.to_string();
|
||||
};
|
||||
|
||||
let Ok(mut url) = Url::parse(BACKEND_DESKTOP_UPDATE_URL) else {
|
||||
return DESKTOP_UPDATE_URL.to_string();
|
||||
};
|
||||
url.query_pairs_mut().extend_pairs([
|
||||
("installation_id", installation_id.as_str()),
|
||||
(
|
||||
"arch",
|
||||
if cfg!(target_arch = "x86_64") {
|
||||
"x64"
|
||||
} else {
|
||||
"arm64"
|
||||
},
|
||||
),
|
||||
("app_version", application.version.as_str()),
|
||||
("beta", "false"),
|
||||
("os-version", os_version),
|
||||
("plan_type", "unknown"),
|
||||
]);
|
||||
url.to_string()
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
fn windows_store_update(
|
||||
manifest: &[u8],
|
||||
installed_version: &str,
|
||||
) -> Result<Option<String>, &'static str> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct StoreManifest {
|
||||
schema_version: u64,
|
||||
build_version: String,
|
||||
store_product_id: String,
|
||||
package_identity: String,
|
||||
}
|
||||
|
||||
let manifest: StoreManifest =
|
||||
serde_json::from_slice(manifest).map_err(|_| "invalid Windows Store update manifest")?;
|
||||
if manifest.schema_version == 0
|
||||
|| manifest.store_product_id != "9PLM9XGG6VKS"
|
||||
|| manifest.package_identity != "OpenAI.Codex"
|
||||
{
|
||||
return Err("Windows Store update manifest does not target the production application");
|
||||
}
|
||||
let version = |value: &str| -> Option<[u64; 4]> {
|
||||
value
|
||||
.split('.')
|
||||
.map(str::parse::<u64>)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.ok()?
|
||||
.try_into()
|
||||
.ok()
|
||||
};
|
||||
let latest = version(&manifest.build_version)
|
||||
.ok_or("Windows Store update manifest contains an invalid build version")?;
|
||||
let installed =
|
||||
version(installed_version).ok_or("installed Windows application has an invalid version")?;
|
||||
Ok((latest > installed).then_some(manifest.build_version))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
async fn latest_macos_staged_build(root: &Path, installed_build: u64) -> Option<u64> {
|
||||
const MAX_STAGED_BUNDLES: usize = 64;
|
||||
|
||||
if !std::fs::symlink_metadata(root).ok()?.is_dir() {
|
||||
return None;
|
||||
}
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
|
||||
let mut inspected = 0;
|
||||
let mut latest = None;
|
||||
for entry in std::fs::read_dir(root).ok()? {
|
||||
if inspected == MAX_STAGED_BUNDLES || tokio::time::Instant::now() >= deadline {
|
||||
break;
|
||||
}
|
||||
let Ok(entry) = entry else {
|
||||
continue;
|
||||
};
|
||||
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let extracted = entry.path().join("extracted");
|
||||
if !std::fs::symlink_metadata(&extracted).is_ok_and(|metadata| metadata.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let bundle = extracted.join("ChatGPT.app");
|
||||
if !std::fs::symlink_metadata(&bundle).is_ok_and(|metadata| metadata.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
inspected += 1;
|
||||
let Ok(result) = tokio::time::timeout_at(
|
||||
deadline,
|
||||
super::desktop::platform::inspect_macos_bundle(&bundle),
|
||||
)
|
||||
.await
|
||||
else {
|
||||
break;
|
||||
};
|
||||
if let Ok(Some(application)) = result
|
||||
&& application.build > installed_build
|
||||
{
|
||||
latest = Some(latest.map_or(application.build, |latest: u64| {
|
||||
latest.max(application.build)
|
||||
}));
|
||||
}
|
||||
}
|
||||
latest
|
||||
DoctorCheck::new(
|
||||
"updates.status",
|
||||
"updates",
|
||||
CheckStatus::Ok,
|
||||
"update configuration is locally consistent",
|
||||
)
|
||||
.details(details)
|
||||
}
|
||||
|
||||
fn push_cached_version_details(details: &mut Vec<String>, version_file: &Path) {
|
||||
@@ -399,92 +80,6 @@ fn update_action_label(context: &InstallContext) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
async fn fetch_latest_version(
|
||||
client: &RouteAwareClientPool,
|
||||
context: &InstallContext,
|
||||
) -> Result<String, String> {
|
||||
match &context.method {
|
||||
InstallMethod::Brew => fetch_homebrew_cask_version(client).await,
|
||||
InstallMethod::Npm
|
||||
| InstallMethod::Bun
|
||||
| InstallMethod::VitePlus
|
||||
| InstallMethod::Pnpm
|
||||
| InstallMethod::Standalone { .. }
|
||||
| InstallMethod::Other => fetch_latest_github_release_version(client).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn fetch_latest_github_release_version(
|
||||
client: &RouteAwareClientPool,
|
||||
) -> Result<String, String> {
|
||||
#[derive(Deserialize)]
|
||||
struct ReleaseInfo {
|
||||
tag_name: String,
|
||||
}
|
||||
|
||||
let info = http_get_json::<ReleaseInfo>(client, GITHUB_LATEST_RELEASE_URL).await?;
|
||||
info.tag_name
|
||||
.strip_prefix("rust-v")
|
||||
.map(str::to_string)
|
||||
.ok_or_else(|| format!("failed to parse latest tag {}", info.tag_name))
|
||||
}
|
||||
|
||||
async fn fetch_homebrew_cask_version(client: &RouteAwareClientPool) -> Result<String, String> {
|
||||
#[derive(Deserialize)]
|
||||
struct HomebrewCaskInfo {
|
||||
version: String,
|
||||
}
|
||||
|
||||
http_get_json::<HomebrewCaskInfo>(client, HOMEBREW_CASK_API_URL)
|
||||
.await
|
||||
.map(|info| info.version)
|
||||
}
|
||||
|
||||
async fn http_get_json<T>(client: &RouteAwareClientPool, url: &str) -> Result<T, String>
|
||||
where
|
||||
T: for<'de> Deserialize<'de>,
|
||||
{
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 5), async {
|
||||
let mut response = client
|
||||
.request(Method::GET, url)
|
||||
.header(
|
||||
http::header::USER_AGENT,
|
||||
concat!("codex-doctor/", env!("CARGO_PKG_VERSION")),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|err| err.to_string())?;
|
||||
if !response.status().is_success() {
|
||||
return Err(format!("HTTP {}", response.status()));
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = response.chunk().await.map_err(|err| err.to_string())? {
|
||||
if chunk.len() > MAX_VERSION_RESPONSE_BYTES.saturating_sub(body.len()) {
|
||||
return Err("version response exceeds size limit".to_string());
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
serde_json::from_slice(&body).map_err(|err| err.to_string())
|
||||
})
|
||||
.await
|
||||
.map_err(|_| "version request timed out".to_string())?
|
||||
}
|
||||
|
||||
fn is_newer(latest: &str, current: &str) -> Option<bool> {
|
||||
match (parse_version(latest), parse_version(current)) {
|
||||
(Some(latest), Some(current)) => Some(latest > current),
|
||||
(Some(_), None) | (None, Some(_)) | (None, None) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_version(value: &str) -> Option<(u64, u64, u64)> {
|
||||
let mut parts = value.trim().split('.');
|
||||
let major = parts.next()?.parse::<u64>().ok()?;
|
||||
let minor = parts.next()?.parse::<u64>().ok()?;
|
||||
let patch = parts.next()?.parse::<u64>().ok()?;
|
||||
Some((major, minor, patch))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct VersionInfo {
|
||||
latest_version: String,
|
||||
@@ -499,191 +94,6 @@ mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_http_probe_decodes_json_and_rejects_invalid_responses() {
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
let server = MockServer::start().await;
|
||||
let client = RouteAwareClientPool::new_without_request_logging(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
ClientRouteClass::Other,
|
||||
);
|
||||
for (endpoint, response) in [
|
||||
(
|
||||
"valid",
|
||||
ResponseTemplate::new(/*s*/ 200)
|
||||
.set_body_json(serde_json::json!({"version": "1.2.3"})),
|
||||
),
|
||||
(
|
||||
"invalid",
|
||||
ResponseTemplate::new(/*s*/ 200).set_body_string("not JSON"),
|
||||
),
|
||||
("unavailable", ResponseTemplate::new(/*s*/ 503)),
|
||||
("proxy_auth_required", ResponseTemplate::new(/*s*/ 407)),
|
||||
(
|
||||
"redirect",
|
||||
ResponseTemplate::new(/*s*/ 302)
|
||||
.insert_header("Location", format!("{}/valid", server.uri())),
|
||||
),
|
||||
(
|
||||
"timeout",
|
||||
ResponseTemplate::new(/*s*/ 200).set_delay(Duration::from_secs(/*secs*/ 6)),
|
||||
),
|
||||
(
|
||||
"oversized",
|
||||
ResponseTemplate::new(/*s*/ 200)
|
||||
.set_body_bytes(vec![b' '; MAX_VERSION_RESPONSE_BYTES + 1]),
|
||||
),
|
||||
] {
|
||||
Mock::given(method("GET"))
|
||||
.and(path(format!("/{endpoint}")))
|
||||
.respond_with(response)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let result = http_get_json::<serde_json::Value>(
|
||||
&client,
|
||||
&format!("{}/{endpoint}", server.uri()),
|
||||
)
|
||||
.await;
|
||||
if matches!(endpoint, "valid" | "redirect") {
|
||||
assert_eq!(result, Ok(serde_json::json!({"version": "1.2.3"})));
|
||||
} else if endpoint == "timeout" {
|
||||
assert_eq!(result, Err("version request timed out".to_string()));
|
||||
} else if endpoint == "proxy_auth_required" {
|
||||
assert_eq!(
|
||||
result,
|
||||
Err("HTTP 407 Proxy Authentication Required".to_string())
|
||||
);
|
||||
} else {
|
||||
assert!(result.is_err(), "{endpoint} must not be accepted");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn macos_update_probe_uses_the_persisted_production_appcast_feed() {
|
||||
let home = tempfile::tempdir().expect("temporary home should be created");
|
||||
let application = InstalledApp {
|
||||
identity: "com.openai.codex",
|
||||
version: "26.623.10000".to_string(),
|
||||
bundle: PathBuf::new(),
|
||||
build: 6139,
|
||||
};
|
||||
assert_eq!(
|
||||
macos_desktop_update_url(home.path(), &application, "26.6.0"),
|
||||
DESKTOP_UPDATE_URL
|
||||
);
|
||||
|
||||
let state_directory = home
|
||||
.path()
|
||||
.join("Library/Application Support/com.openai.codex");
|
||||
std::fs::create_dir_all(&state_directory)
|
||||
.expect("production appcast state directory should be created");
|
||||
std::fs::write(
|
||||
state_directory.join("production-appcast-bootstrap.json"),
|
||||
r#"{"backendAppcastEnabled":true,"installationId":"028e90f8-5f2a-47db-a05c-6a48f548d728"}"#,
|
||||
)
|
||||
.expect("production appcast state should be created");
|
||||
|
||||
let arch = if cfg!(target_arch = "x86_64") {
|
||||
"x64"
|
||||
} else {
|
||||
"arm64"
|
||||
};
|
||||
assert_eq!(
|
||||
macos_desktop_update_url(home.path(), &application, "26.6.0"),
|
||||
format!(
|
||||
"{BACKEND_DESKTOP_UPDATE_URL}?installation_id=028e90f8-5f2a-47db-a05c-6a48f548d728&arch={arch}&app_version=26.623.10000&beta=false&os-version=26.6.0&plan_type=unknown"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[tokio::test]
|
||||
async fn macos_staged_updates_require_a_newer_matching_extracted_bundle() {
|
||||
let root = tempfile::tempdir().expect("temporary Sparkle cache should be created");
|
||||
for index in 0..320 {
|
||||
std::fs::create_dir(root.path().join(format!("unrelated-{index}")))
|
||||
.expect("unrelated Sparkle cache directory should be created");
|
||||
}
|
||||
for (name, identity, build) in [
|
||||
("newest", "com.openai.codex", "6268"),
|
||||
("newer", "com.openai.codex", "6168"),
|
||||
("older", "com.openai.codex", "6138"),
|
||||
("different", "com.example.other", "9999"),
|
||||
("invalid", "com.openai.codex", "invalid"),
|
||||
] {
|
||||
let bundle = root.path().join(name).join("extracted/ChatGPT.app");
|
||||
write_macos_bundle(&bundle, identity, build);
|
||||
}
|
||||
let outside = tempfile::tempdir().expect("external fixture should be created");
|
||||
let linked = outside.path().join("ChatGPT.app");
|
||||
write_macos_bundle(&linked, "com.openai.codex", "9999");
|
||||
std::os::unix::fs::symlink(&linked, root.path().join("ChatGPT.app"))
|
||||
.expect("symlinked staged app fixture should be created");
|
||||
|
||||
assert_eq!(
|
||||
latest_macos_staged_build(root.path(), /*installed_build*/ 6139).await,
|
||||
Some(6268)
|
||||
);
|
||||
assert_eq!(
|
||||
latest_macos_staged_build(root.path(), /*installed_build*/ 6268).await,
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_store_updates_compare_all_four_production_build_components() {
|
||||
let mut manifest = serde_json::json!({
|
||||
"schemaVersion": 1,
|
||||
"buildVersion": "26.803.5235.1",
|
||||
"storeProductId": "9PLM9XGG6VKS",
|
||||
"packageIdentity": "OpenAI.Codex",
|
||||
});
|
||||
assert_eq!(
|
||||
windows_store_update(&serde_json::to_vec(&manifest).unwrap(), "26.803.5235.0"),
|
||||
Ok(Some("26.803.5235.1".to_string()))
|
||||
);
|
||||
assert_eq!(
|
||||
windows_store_update(&serde_json::to_vec(&manifest).unwrap(), "26.803.5235.1"),
|
||||
Ok(None)
|
||||
);
|
||||
manifest["storeProductId"] = "other".into();
|
||||
assert!(
|
||||
windows_store_update(&serde_json::to_vec(&manifest).unwrap(), "26.803.5235.0").is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn write_macos_bundle(path: &Path, identity: &str, build: &str) {
|
||||
let contents = path.join("Contents");
|
||||
std::fs::create_dir_all(&contents).expect("staged app fixture should be created");
|
||||
std::fs::write(
|
||||
contents.join("Info.plist"),
|
||||
format!(
|
||||
"<?xml version=\"1.0\"?><plist version=\"1.0\"><dict>\
|
||||
<key>CFBundleIdentifier</key><string>{identity}</string>\
|
||||
<key>CFBundleVersion</key><string>{build}</string>\
|
||||
</dict></plist>"
|
||||
),
|
||||
)
|
||||
.expect("staged app metadata should be created");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_newer_compares_plain_semver() {
|
||||
assert_eq!(is_newer("1.2.4", "1.2.3"), Some(true));
|
||||
assert_eq!(is_newer("1.2.3", "1.2.4"), Some(false));
|
||||
assert_eq!(is_newer("1.2.3-beta.1", "1.2.2"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_action_labels_install_contexts() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -5,11 +5,8 @@ use clap_complete::Shell;
|
||||
use clap_complete::generate;
|
||||
use codex_app_server_daemon::BootstrapOptions as AppServerBootstrapOptions;
|
||||
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,12 +16,10 @@ 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;
|
||||
use codex_execpolicy::ExecPolicyCheckCommand;
|
||||
use codex_responses_api_proxy::Args as ResponsesApiProxyArgs;
|
||||
use codex_rollout_trace::REDUCED_STATE_FILE_NAME;
|
||||
use codex_rollout_trace::replay_bundle;
|
||||
use codex_state::StateRuntime;
|
||||
@@ -51,13 +46,9 @@ use supports_color::Stream;
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
mod app_cmd;
|
||||
mod config_override_args;
|
||||
mod daemon_install;
|
||||
mod daemon_telemetry;
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
mod desktop_app;
|
||||
mod doctor;
|
||||
#[cfg(test)]
|
||||
#[path = "exec_args_tests.rs"]
|
||||
@@ -72,7 +63,6 @@ mod migrate_nfs_db;
|
||||
mod migrate_rollouts;
|
||||
mod plugin_cmd;
|
||||
mod queue_cmd;
|
||||
mod remote_control_cmd;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod sandbox_setup;
|
||||
mod sandbox_uninstall;
|
||||
@@ -84,7 +74,6 @@ use crate::mcp_cmd::McpCli;
|
||||
use crate::plugin_cmd::PluginCli;
|
||||
use crate::plugin_cmd::PluginSubcommand;
|
||||
use crate::queue_cmd::QueueCommand;
|
||||
use crate::remote_control_cmd::RemoteControlCommand;
|
||||
use codex_exec_server_cli::ExecServerCommand;
|
||||
use doctor::DoctorCommand;
|
||||
use state_db_recovery as local_state_db;
|
||||
@@ -171,13 +160,6 @@ enum Subcommand {
|
||||
/// [experimental] Run the app server or related tooling.
|
||||
AppServer(AppServerCommand),
|
||||
|
||||
/// [experimental] Manage the app-server daemon with remote control enabled.
|
||||
RemoteControl(RemoteControlCommand),
|
||||
|
||||
/// Launch the Desktop app (opens the app installer if missing).
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
App(app_cmd::AppCommand),
|
||||
|
||||
/// Generate shell completion scripts.
|
||||
Completion(CompletionCommand),
|
||||
|
||||
@@ -197,10 +179,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),
|
||||
|
||||
@@ -225,14 +203,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),
|
||||
|
||||
/// Internal: relay stdio to a Unix domain socket.
|
||||
#[clap(hide = true, name = "stdio-to-uds")]
|
||||
StdioToUds(StdioToUdsCommand),
|
||||
@@ -605,10 +575,6 @@ struct AppServerCommand {
|
||||
#[arg(long = "stdio", conflicts_with = "listen")]
|
||||
stdio: bool,
|
||||
|
||||
/// Enable remote control for this app-server process without changing persistence.
|
||||
#[arg(long = "remote-control", hide = true)]
|
||||
remote_control: bool,
|
||||
|
||||
/// Save loaded threads during managed daemon shutdown.
|
||||
#[arg(long, hide = true)]
|
||||
managed_daemon: bool,
|
||||
@@ -682,12 +648,6 @@ enum AppServerDaemonSubcommand {
|
||||
yes: bool,
|
||||
},
|
||||
|
||||
/// Enable remote control for future starts and a currently running managed daemon.
|
||||
EnableRemoteControl,
|
||||
|
||||
/// Disable remote control for future starts and a currently running managed daemon.
|
||||
DisableRemoteControl,
|
||||
|
||||
/// Stop the local app server daemon.
|
||||
Stop,
|
||||
|
||||
@@ -714,11 +674,7 @@ struct AppServerProxyCommand {
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
struct AppServerBootstrapCommand {
|
||||
/// Launch the managed app-server with remote control enabled.
|
||||
#[arg(long = "remote-control")]
|
||||
remote_control: bool,
|
||||
}
|
||||
struct AppServerBootstrapCommand {}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
struct GenerateTsCommand {
|
||||
@@ -1041,10 +997,11 @@ fn stage_str(stage: Stage) -> &'static str {
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
codex_build_info::initialize!();
|
||||
let remote_control_disabled = codex_app_server::take_remote_control_disabled_env();
|
||||
// aKode: remote control is not available; still consume the daemon's internal marker.
|
||||
let _ = codex_app_server::take_remote_control_disabled_env();
|
||||
arg0_dispatch_or_else(move |arg0_paths: Arg0DispatchPaths| async move {
|
||||
// Finish polling the large subcommand dispatcher before polling interactive TUI events.
|
||||
if let Some(tui) = Box::pin(dispatch_cli(arg0_paths, remote_control_disabled)).await? {
|
||||
if let Some(tui) = Box::pin(dispatch_cli(arg0_paths)).await? {
|
||||
tui.await?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -1053,7 +1010,6 @@ fn main() -> anyhow::Result<()> {
|
||||
|
||||
async fn dispatch_cli(
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
remote_control_disabled: bool,
|
||||
) -> anyhow::Result<Option<impl Future<Output = anyhow::Result<()>>>> {
|
||||
let MultitoolCli {
|
||||
config_overrides: mut root_config_overrides,
|
||||
@@ -1250,7 +1206,6 @@ async fn dispatch_cli(
|
||||
strict_config: app_server_strict_config,
|
||||
listen,
|
||||
stdio,
|
||||
remote_control,
|
||||
managed_daemon,
|
||||
analytics_default_enabled,
|
||||
auth,
|
||||
@@ -1297,18 +1252,9 @@ async fn dispatch_cli(
|
||||
cloud_skills_snapshot,
|
||||
code_mode_host_transport: code_mode_host.into(),
|
||||
managed_daemon,
|
||||
remote_control_startup_mode: match (remote_control, remote_control_disabled)
|
||||
{
|
||||
(true, _) => {
|
||||
codex_app_server::RemoteControlStartupMode::EnabledEphemeral
|
||||
}
|
||||
(false, true) => {
|
||||
codex_app_server::RemoteControlStartupMode::DisabledEphemeral
|
||||
}
|
||||
(false, false) => {
|
||||
codex_app_server::RemoteControlStartupMode::ResolvePersisted
|
||||
}
|
||||
},
|
||||
// aKode: remote control (chatgpt.com relay) is never started.
|
||||
remote_control_startup_mode:
|
||||
codex_app_server::RemoteControlStartupMode::DisabledEphemeral,
|
||||
..Default::default()
|
||||
};
|
||||
let exit = codex_app_server::run_main_with_transport_options(
|
||||
@@ -1332,10 +1278,10 @@ async fn dispatch_cli(
|
||||
AppServerDaemonSubcommand::Start => {
|
||||
print_app_server_daemon_output(AppServerLifecycleCommand::Start).await?;
|
||||
}
|
||||
AppServerDaemonSubcommand::Bootstrap(bootstrap_cli) => {
|
||||
AppServerDaemonSubcommand::Bootstrap(AppServerBootstrapCommand {}) => {
|
||||
let output =
|
||||
codex_app_server_daemon::bootstrap(AppServerBootstrapOptions {
|
||||
remote_control_enabled: bootstrap_cli.remote_control,
|
||||
remote_control_enabled: false,
|
||||
})
|
||||
.await?;
|
||||
println!("{}", serde_json::to_string(&output)?);
|
||||
@@ -1401,16 +1347,6 @@ async fn dispatch_cli(
|
||||
println!("{}", serde_json::to_string(&output)?);
|
||||
}
|
||||
}
|
||||
AppServerDaemonSubcommand::EnableRemoteControl => {
|
||||
print_app_server_remote_control_output(AppServerRemoteControlMode::Enabled)
|
||||
.await?;
|
||||
}
|
||||
AppServerDaemonSubcommand::DisableRemoteControl => {
|
||||
print_app_server_remote_control_output(
|
||||
AppServerRemoteControlMode::Disabled,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
AppServerDaemonSubcommand::Stop => {
|
||||
print_app_server_daemon_output(AppServerLifecycleCommand::Stop).await?;
|
||||
}
|
||||
@@ -1501,30 +1437,6 @@ async fn dispatch_cli(
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Subcommand::RemoteControl(mut remote_control_cli)) => {
|
||||
remote_control_cli.no_daemon |= interactive.no_daemon;
|
||||
let subcommand_name = remote_control_cli.subcommand_name();
|
||||
reject_remote_mode_for_subcommand(
|
||||
root_remote.as_deref(),
|
||||
root_remote_auth_token_env.as_deref(),
|
||||
subcommand_name,
|
||||
)?;
|
||||
remote_control_cmd::run(
|
||||
remote_control_cli,
|
||||
arg0_paths.clone(),
|
||||
root_config_overrides,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
Some(Subcommand::App(app_cli)) => {
|
||||
reject_remote_mode_for_subcommand(
|
||||
root_remote.as_deref(),
|
||||
root_remote_auth_token_env.as_deref(),
|
||||
"app",
|
||||
)?;
|
||||
app_cmd::run_app(app_cli).await?;
|
||||
}
|
||||
Some(Subcommand::Resume(ResumeCommand {
|
||||
session_id,
|
||||
last,
|
||||
@@ -1732,19 +1644,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,
|
||||
@@ -1866,27 +1765,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(),
|
||||
root_remote_auth_token_env.as_deref(),
|
||||
"responses-api-proxy",
|
||||
)?;
|
||||
tokio::task::spawn_blocking(move || codex_responses_api_proxy::run_main(args))
|
||||
.await??;
|
||||
}
|
||||
Some(Subcommand::StdioToUds(cmd)) => {
|
||||
reject_remote_mode_for_subcommand(
|
||||
root_remote.as_deref(),
|
||||
@@ -2375,23 +2253,17 @@ fn unsupported_subcommand_name_for_strict_config(
|
||||
Some(Subcommand::AppServer(app_server)) => {
|
||||
Some(app_server_subcommand_name(app_server.subcommand.as_ref()))
|
||||
}
|
||||
Some(Subcommand::RemoteControl(remote_control)) => Some(remote_control.subcommand_name()),
|
||||
Some(Subcommand::Mcp(_)) => Some("mcp"),
|
||||
Some(Subcommand::Plugin(_)) => Some("plugin"),
|
||||
Some(Subcommand::MigrateRollouts(_)) => Some("migrate-rollouts"),
|
||||
Some(Subcommand::MigrateNfsDb(_)) => Some("migrate-nfs-db"),
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
Some(Subcommand::App(_)) => Some("app"),
|
||||
Some(Subcommand::Login(_)) => Some("login"),
|
||||
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::StdioToUds(_)) => Some("stdio-to-uds"),
|
||||
Some(Subcommand::Features(_)) => Some("features"),
|
||||
Some(Subcommand::TcpTunnel(_)) => Some("tcp-tunnel"),
|
||||
@@ -2438,12 +2310,6 @@ fn app_server_subcommand_name(subcommand: Option<&AppServerSubcommand>) -> &'sta
|
||||
AppServerDaemonSubcommand::Start => "app-server daemon start",
|
||||
AppServerDaemonSubcommand::Restart => "app-server daemon restart",
|
||||
AppServerDaemonSubcommand::Update { .. } => "app-server daemon update",
|
||||
AppServerDaemonSubcommand::EnableRemoteControl => {
|
||||
"app-server daemon enable-remote-control"
|
||||
}
|
||||
AppServerDaemonSubcommand::DisableRemoteControl => {
|
||||
"app-server daemon disable-remote-control"
|
||||
}
|
||||
AppServerDaemonSubcommand::Stop => "app-server daemon stop",
|
||||
AppServerDaemonSubcommand::Version => "app-server daemon version",
|
||||
AppServerDaemonSubcommand::PidUpdateLoop { .. } => "app-server daemon pid-update-loop",
|
||||
@@ -2471,14 +2337,6 @@ fn updater_http_client_factory(
|
||||
Ok(config.http_client_factory())
|
||||
}
|
||||
|
||||
async fn print_app_server_remote_control_output(
|
||||
mode: AppServerRemoteControlMode,
|
||||
) -> anyhow::Result<()> {
|
||||
let output = codex_app_server_daemon::set_remote_control(mode).await?;
|
||||
println!("{}", serde_json::to_string(&output)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_remote_auth_token_from_env_var_with<F>(
|
||||
env_var_name: &str,
|
||||
get_var: F,
|
||||
@@ -4263,7 +4121,6 @@ enabled = true
|
||||
fn app_server_analytics_default_disabled_without_flag() {
|
||||
let app_server = app_server_from_args(["codex", "app-server"].as_ref());
|
||||
assert!(!app_server.analytics_default_enabled);
|
||||
assert!(!app_server.remote_control);
|
||||
assert_eq!(
|
||||
app_server.listen,
|
||||
codex_app_server::AppServerTransport::Stdio
|
||||
@@ -4271,9 +4128,13 @@ enabled = true
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_server_remote_control_startup_flag_enables_remote_control() {
|
||||
let enabled = app_server_from_args(["codex", "app-server", "--remote-control"].as_ref());
|
||||
assert!(enabled.remote_control);
|
||||
fn removed_remote_control_flags_do_not_parse() {
|
||||
for args in [
|
||||
["codex", "app-server", "--remote-control"].as_slice(),
|
||||
["codex", "app-server", "daemon", "enable-remote-control"].as_slice(),
|
||||
] {
|
||||
assert!(MultitoolCli::try_parse_from(args).is_err(), "{args:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -4394,19 +4255,6 @@ enabled = true
|
||||
err.to_string(),
|
||||
"`--strict-config` is not supported for `codex mcp`"
|
||||
);
|
||||
|
||||
let cli = MultitoolCli::try_parse_from(["codex", "--strict-config", "remote-control"])
|
||||
.expect("parse");
|
||||
let err = reject_root_strict_config_for_subcommand(
|
||||
cli.interactive.strict_config,
|
||||
&cli.subcommand,
|
||||
)
|
||||
.expect_err("remote-control should not support root --strict-config");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"`--strict-config` is not supported for `codex remote-control`"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -4425,34 +4273,6 @@ enabled = true
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reject_remote_flag_for_remote_control() {
|
||||
let cli = MultitoolCli::try_parse_from(["codex", "--remote", "unix://", "remote-control"])
|
||||
.expect("parse");
|
||||
let Some(Subcommand::RemoteControl(remote_control)) = &cli.subcommand else {
|
||||
panic!("expected remote-control subcommand");
|
||||
};
|
||||
assert_eq!(remote_control.subcommand_name(), "remote-control");
|
||||
|
||||
let err = reject_remote_mode_for_subcommand(
|
||||
cli.remote.remote.as_deref(),
|
||||
cli.remote.remote_auth_token_env.as_deref(),
|
||||
"remote-control",
|
||||
)
|
||||
.expect_err("remote-control should reject root --remote");
|
||||
|
||||
assert!(err.to_string().contains("remote-control"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_pair_parses() {
|
||||
let cli = MultitoolCli::try_parse_from(["codex", "remote-control", "pair"]).expect("parse");
|
||||
let Some(Subcommand::RemoteControl(remote_control)) = &cli.subcommand else {
|
||||
panic!("expected remote-control subcommand");
|
||||
};
|
||||
assert_eq!(remote_control.subcommand_name(), "remote-control pair");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_flag_parses_for_interactive_root() {
|
||||
let cli = MultitoolCli::try_parse_from(["codex", "--remote", "unix://codex.sock"])
|
||||
@@ -4736,21 +4556,10 @@ enabled = true
|
||||
#[test]
|
||||
fn app_server_daemon_subcommands_parse() {
|
||||
assert!(matches!(
|
||||
app_server_from_args(
|
||||
[
|
||||
"codex",
|
||||
"app-server",
|
||||
"daemon",
|
||||
"bootstrap",
|
||||
"--remote-control"
|
||||
]
|
||||
.as_ref()
|
||||
)
|
||||
.subcommand,
|
||||
app_server_from_args(["codex", "app-server", "daemon", "bootstrap"].as_ref())
|
||||
.subcommand,
|
||||
Some(AppServerSubcommand::Daemon(AppServerDaemonCommand {
|
||||
subcommand: AppServerDaemonSubcommand::Bootstrap(AppServerBootstrapCommand {
|
||||
remote_control: true
|
||||
})
|
||||
subcommand: AppServerDaemonSubcommand::Bootstrap(AppServerBootstrapCommand {})
|
||||
}))
|
||||
));
|
||||
assert!(matches!(
|
||||
@@ -4765,24 +4574,6 @@ enabled = true
|
||||
subcommand: AppServerDaemonSubcommand::Restart
|
||||
}))
|
||||
));
|
||||
assert!(matches!(
|
||||
app_server_from_args(
|
||||
["codex", "app-server", "daemon", "enable-remote-control"].as_ref()
|
||||
)
|
||||
.subcommand,
|
||||
Some(AppServerSubcommand::Daemon(AppServerDaemonCommand {
|
||||
subcommand: AppServerDaemonSubcommand::EnableRemoteControl
|
||||
}))
|
||||
));
|
||||
assert!(matches!(
|
||||
app_server_from_args(
|
||||
["codex", "app-server", "daemon", "disable-remote-control"].as_ref()
|
||||
)
|
||||
.subcommand,
|
||||
Some(AppServerSubcommand::Daemon(AppServerDaemonCommand {
|
||||
subcommand: AppServerDaemonSubcommand::DisableRemoteControl
|
||||
}))
|
||||
));
|
||||
assert!(matches!(
|
||||
app_server_from_args(["codex", "app-server", "daemon", "stop"].as_ref()).subcommand,
|
||||
Some(AppServerSubcommand::Daemon(AppServerDaemonCommand {
|
||||
|
||||
@@ -1,859 +0,0 @@
|
||||
use std::io::Write;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use clap::Args;
|
||||
use codex_app_server::AppServerRuntimeOptions;
|
||||
use codex_app_server::AppServerTransport;
|
||||
use codex_app_server_daemon::LifecycleCommand as AppServerLifecycleCommand;
|
||||
use codex_app_server_daemon::LifecycleOutput as AppServerLifecycleOutput;
|
||||
use codex_app_server_daemon::LifecycleStatus as AppServerLifecycleStatus;
|
||||
use codex_app_server_daemon::RemoteControlReadyOutput as AppServerRemoteControlReadyOutput;
|
||||
use codex_app_server_daemon::RemoteControlReadyStatus as AppServerRemoteControlReadyStatus;
|
||||
use codex_app_server_daemon::RemoteControlStartOutput as AppServerRemoteControlStartOutput;
|
||||
use codex_app_server_protocol::RemoteControlConnectionStatus;
|
||||
use codex_app_server_protocol::RemoteControlPairingStartResponse;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_cli::CliConfigOverrides;
|
||||
use codex_websocket_auth::WebsocketAuthSettings;
|
||||
use serde::Serialize;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const FOREGROUND_SOCKET_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const FOREGROUND_SOCKET_CONNECT_RETRY_DELAY: Duration = Duration::from_millis(50);
|
||||
const FOREGROUND_APP_SERVER_ABORT_TIMEOUT: Duration = Duration::from_secs(1);
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
pub(crate) struct RemoteControlCommand {
|
||||
/// Emit machine-readable JSON.
|
||||
#[arg(long = "json", global = true)]
|
||||
json: bool,
|
||||
|
||||
/// Run an embedded app-server in the foreground until Ctrl-C.
|
||||
#[arg(long = "no-daemon")]
|
||||
pub(super) no_daemon: bool,
|
||||
|
||||
#[command(subcommand)]
|
||||
pub(super) subcommand: Option<RemoteControlSubcommand>,
|
||||
}
|
||||
|
||||
impl RemoteControlCommand {
|
||||
pub(crate) fn subcommand_name(&self) -> &'static str {
|
||||
match self.subcommand {
|
||||
None => "remote-control",
|
||||
Some(RemoteControlSubcommand::Start) => "remote-control start",
|
||||
Some(RemoteControlSubcommand::Stop) => "remote-control stop",
|
||||
Some(RemoteControlSubcommand::Pair) => "remote-control pair",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, clap::Subcommand)]
|
||||
pub(super) enum RemoteControlSubcommand {
|
||||
/// Start the app-server daemon with remote control enabled.
|
||||
Start,
|
||||
|
||||
/// Stop the app-server daemon.
|
||||
Stop,
|
||||
|
||||
/// Create and print a short-lived manual pairing code.
|
||||
Pair,
|
||||
}
|
||||
|
||||
pub(crate) async fn run(
|
||||
command: RemoteControlCommand,
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
root_config_overrides: CliConfigOverrides,
|
||||
) -> anyhow::Result<()> {
|
||||
if command.no_daemon && command.subcommand.is_some() {
|
||||
anyhow::bail!("`--no-daemon` cannot be used with a remote-control subcommand");
|
||||
}
|
||||
|
||||
if command.subcommand.is_none() {
|
||||
if command.no_daemon || command.json || !daemon_eligible(&root_config_overrides).await? {
|
||||
run_foreground_remote_control(command.json, arg0_paths, root_config_overrides).await?;
|
||||
} else {
|
||||
print_remote_control_progress(
|
||||
command.json,
|
||||
"Starting app-server daemon with remote control enabled...",
|
||||
)?;
|
||||
let daemon = match codex_app_server_daemon::start_with_features(&Default::default())
|
||||
.await
|
||||
{
|
||||
Ok(daemon) => daemon,
|
||||
#[cfg(windows)]
|
||||
Err(error) if error.is::<codex_app_server_daemon::DetachedLaunchRestricted>() => {
|
||||
return run_foreground_remote_control(
|
||||
command.json,
|
||||
arg0_paths,
|
||||
root_config_overrides,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
if daemon.backend.is_none() {
|
||||
return run_foreground_remote_control(
|
||||
command.json,
|
||||
arg0_paths,
|
||||
root_config_overrides,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let remote_control = codex_app_server_daemon::enable_remote_control_on_socket(
|
||||
&daemon.socket_path,
|
||||
FOREGROUND_SOCKET_CONNECT_TIMEOUT,
|
||||
FOREGROUND_SOCKET_CONNECT_RETRY_DELAY,
|
||||
)
|
||||
.await?;
|
||||
let output = AppServerRemoteControlReadyOutput {
|
||||
daemon: AppServerRemoteControlStartOutput::Start(daemon),
|
||||
remote_control,
|
||||
};
|
||||
print_remote_control_start_output(&output, command.json)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
match command.subcommand {
|
||||
Some(RemoteControlSubcommand::Start) => {
|
||||
print_remote_control_progress(
|
||||
command.json,
|
||||
"Starting app-server daemon with remote control enabled...",
|
||||
)?;
|
||||
let output = codex_app_server_daemon::ensure_remote_control_ready().await?;
|
||||
print_remote_control_start_output(&output, command.json)?;
|
||||
}
|
||||
Some(RemoteControlSubcommand::Stop) => {
|
||||
print_remote_control_progress(command.json, "Stopping remote control...")?;
|
||||
let output = codex_app_server_daemon::run(AppServerLifecycleCommand::Stop).await?;
|
||||
print_remote_control_stop_output(&output, command.json)?;
|
||||
}
|
||||
Some(RemoteControlSubcommand::Pair) => {
|
||||
let output = codex_app_server_daemon::start_remote_control_pairing().await?;
|
||||
print_remote_control_pairing_output(&output, command.json)?;
|
||||
}
|
||||
None => unreachable!("bare remote-control returned before explicit subcommand dispatch"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn daemon_eligible(root_config_overrides: &CliConfigOverrides) -> anyhow::Result<bool> {
|
||||
if !root_config_overrides.raw_overrides.is_empty()
|
||||
|| codex_login::is_workload_identity_selected()
|
||||
|| std::env::var_os(codex_exec_server::CODEX_EXEC_SERVER_URL_ENV_VAR).is_some()
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
if codex_app_server_daemon::is_elevated()? {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let Ok(config) = ConfigBuilder::default().build().await else {
|
||||
return Ok(false);
|
||||
};
|
||||
Ok(config.features.enabled(Feature::DaemonAutoStart)
|
||||
&& !codex_tui::uses_wsl_drvfs(&config.codex_home))
|
||||
}
|
||||
|
||||
fn print_remote_control_progress(json: bool, message: &str) -> anyhow::Result<()> {
|
||||
if json {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
println!("{message}");
|
||||
std::io::stdout()
|
||||
.flush()
|
||||
.context("failed to flush remote-control progress message")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_foreground_remote_control(
|
||||
json: bool,
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
root_config_overrides: CliConfigOverrides,
|
||||
) -> anyhow::Result<()> {
|
||||
print_remote_control_progress(json, "Starting app-server with remote control enabled...")?;
|
||||
#[cfg(not(windows))]
|
||||
let socket_dir = tempfile::Builder::new()
|
||||
.prefix("codex-rc-")
|
||||
.tempdir_in("/tmp")
|
||||
.or_else(|_| tempfile::tempdir())
|
||||
.context("failed to create private app-server socket directory")?;
|
||||
#[cfg(not(windows))]
|
||||
let socket_path = socket_dir.path().join("rc.sock");
|
||||
// Let the transport create this parent with a protected DACL instead of
|
||||
// inheriting the broader ACL from a directory created under `%TEMP%`.
|
||||
#[cfg(windows)]
|
||||
let socket_path = std::env::temp_dir()
|
||||
.join("codex-remote-control")
|
||||
.join(format!("rc-{}.sock", std::process::id()));
|
||||
let socket_path = AbsolutePathBuf::from_absolute_path(&socket_path)
|
||||
.context("private app-server socket path was not absolute")?;
|
||||
let transport = AppServerTransport::UnixSocket {
|
||||
socket_path: socket_path.clone(),
|
||||
};
|
||||
let runtime_options = AppServerRuntimeOptions {
|
||||
remote_control_startup_mode: codex_app_server::RemoteControlStartupMode::EnabledEphemeral,
|
||||
install_shutdown_signal_handler: false,
|
||||
..Default::default()
|
||||
};
|
||||
let (stop_rx, stop_signal_task) = foreground_stop_signal();
|
||||
let app_server = codex_app_server::run_main_with_transport_options(
|
||||
arg0_paths,
|
||||
root_config_overrides,
|
||||
LoaderOverrides::default(),
|
||||
/*strict_config*/ false,
|
||||
/*default_analytics_enabled*/ false,
|
||||
transport,
|
||||
SessionSource::VSCode,
|
||||
WebsocketAuthSettings::default(),
|
||||
runtime_options,
|
||||
);
|
||||
let mut app_server_task = tokio::spawn(async move { app_server.await.map(|_| ()) });
|
||||
|
||||
let summary = match wait_for_foreground_remote_control_start(
|
||||
&mut app_server_task,
|
||||
wait_for_foreground_remote_control_ready(socket_path),
|
||||
stop_rx.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
ForegroundStartupResult::Ready(summary) => summary,
|
||||
ForegroundStartupResult::Stopped => {
|
||||
abort_foreground_app_server(app_server_task).await;
|
||||
stop_signal_task.abort();
|
||||
return Ok(());
|
||||
}
|
||||
ForegroundStartupResult::ReadyFailed(error) => {
|
||||
abort_foreground_app_server(app_server_task).await;
|
||||
stop_signal_task.abort();
|
||||
return Err(error);
|
||||
}
|
||||
ForegroundStartupResult::AppServerExited(error) => {
|
||||
stop_signal_task.abort();
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
|
||||
if *stop_rx.borrow() {
|
||||
abort_foreground_app_server(app_server_task).await;
|
||||
stop_signal_task.abort();
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Err(error) = print_foreground_ready_output(&summary, json) {
|
||||
abort_foreground_app_server(app_server_task).await;
|
||||
stop_signal_task.abort();
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
let result = wait_for_foreground_app_server(app_server_task, stop_rx).await;
|
||||
stop_signal_task.abort();
|
||||
result
|
||||
}
|
||||
|
||||
fn foreground_stop_signal() -> (watch::Receiver<bool>, JoinHandle<()>) {
|
||||
let (stop_tx, stop_rx) = watch::channel(false);
|
||||
let task = tokio::spawn(async move {
|
||||
if let Err(err) = tokio::signal::ctrl_c().await {
|
||||
eprintln!("failed to listen for Ctrl-C: {err}");
|
||||
}
|
||||
let _ = stop_tx.send(true);
|
||||
});
|
||||
(stop_rx, task)
|
||||
}
|
||||
|
||||
enum ForegroundStartupResult {
|
||||
Ready(AppServerRemoteControlReadyStatus),
|
||||
Stopped,
|
||||
ReadyFailed(anyhow::Error),
|
||||
AppServerExited(anyhow::Error),
|
||||
}
|
||||
|
||||
async fn wait_for_foreground_remote_control_start(
|
||||
app_server_task: &mut JoinHandle<std::io::Result<()>>,
|
||||
ready: impl std::future::Future<Output = anyhow::Result<AppServerRemoteControlReadyStatus>>,
|
||||
mut stop_rx: watch::Receiver<bool>,
|
||||
) -> ForegroundStartupResult {
|
||||
tokio::pin!(ready);
|
||||
|
||||
tokio::select! {
|
||||
ready_result = &mut ready => match ready_result {
|
||||
Ok(summary) => ForegroundStartupResult::Ready(summary),
|
||||
Err(error) => ForegroundStartupResult::ReadyFailed(error),
|
||||
},
|
||||
app_server_result = app_server_task => {
|
||||
ForegroundStartupResult::AppServerExited(
|
||||
foreground_app_server_exited_before_ready(app_server_result)
|
||||
)
|
||||
}
|
||||
_ = wait_for_stop_signal(&mut stop_rx) => ForegroundStartupResult::Stopped,
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_foreground_app_server(
|
||||
mut app_server_task: JoinHandle<std::io::Result<()>>,
|
||||
mut stop_rx: watch::Receiver<bool>,
|
||||
) -> anyhow::Result<()> {
|
||||
tokio::select! {
|
||||
app_server_result = &mut app_server_task => {
|
||||
app_server_result
|
||||
.context("foreground app-server task failed to join")?
|
||||
.context("foreground app-server exited with an error")?;
|
||||
}
|
||||
_ = wait_for_stop_signal(&mut stop_rx) => {
|
||||
abort_foreground_app_server(app_server_task).await;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn wait_for_stop_signal(stop_rx: &mut watch::Receiver<bool>) {
|
||||
if *stop_rx.borrow() {
|
||||
return;
|
||||
}
|
||||
let _ = stop_rx.wait_for(|stopped| *stopped).await;
|
||||
}
|
||||
|
||||
fn foreground_app_server_exited_before_ready(
|
||||
result: Result<std::io::Result<()>, tokio::task::JoinError>,
|
||||
) -> anyhow::Error {
|
||||
match result {
|
||||
Ok(Ok(())) => {
|
||||
anyhow::anyhow!("foreground app-server exited before remote control became ready")
|
||||
}
|
||||
Ok(Err(error)) => anyhow::Error::new(error)
|
||||
.context("foreground app-server exited before remote control became ready"),
|
||||
Err(error) => anyhow::Error::new(error)
|
||||
.context("foreground app-server task failed before remote control became ready"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn abort_foreground_app_server(app_server_task: JoinHandle<std::io::Result<()>>) {
|
||||
app_server_task.abort();
|
||||
let _ = timeout(FOREGROUND_APP_SERVER_ABORT_TIMEOUT, app_server_task).await;
|
||||
}
|
||||
|
||||
async fn wait_for_foreground_remote_control_ready(
|
||||
socket_path: AbsolutePathBuf,
|
||||
) -> anyhow::Result<AppServerRemoteControlReadyStatus> {
|
||||
codex_app_server_daemon::enable_remote_control_on_socket(
|
||||
socket_path.as_path(),
|
||||
FOREGROUND_SOCKET_CONNECT_TIMEOUT,
|
||||
FOREGROUND_SOCKET_CONNECT_RETRY_DELAY,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn print_remote_control_start_output(
|
||||
output: &AppServerRemoteControlReadyOutput,
|
||||
json: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
ensure_remote_control_startable(&output.remote_control)?;
|
||||
if json {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string(&RemoteControlStartJsonOutput::daemon(output))?
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for line in remote_control_start_human_lines(
|
||||
&output.remote_control,
|
||||
RemoteControlHumanOutputMode::Daemon,
|
||||
)? {
|
||||
println!("{line}");
|
||||
}
|
||||
for line in daemon_app_server_human_lines(&output.daemon) {
|
||||
println!("{line}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_foreground_ready_output(
|
||||
summary: &AppServerRemoteControlReadyStatus,
|
||||
json: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
if json {
|
||||
ensure_remote_control_startable(summary)?;
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string(&RemoteControlStartJsonOutput::foreground(summary))?
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for line in remote_control_start_human_lines(summary, RemoteControlHumanOutputMode::Foreground)?
|
||||
{
|
||||
println!("{line}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RemoteControlStartJsonOutput<'a> {
|
||||
mode: RemoteControlModeJson,
|
||||
status: RemoteControlConnectionStatus,
|
||||
server_name: &'a str,
|
||||
environment_id: Option<&'a str>,
|
||||
timed_out: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
daemon: Option<&'a AppServerRemoteControlStartOutput>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
enum RemoteControlModeJson {
|
||||
Foreground,
|
||||
Daemon,
|
||||
}
|
||||
|
||||
impl<'a> RemoteControlStartJsonOutput<'a> {
|
||||
fn foreground(summary: &'a AppServerRemoteControlReadyStatus) -> Self {
|
||||
Self {
|
||||
mode: RemoteControlModeJson::Foreground,
|
||||
status: summary.status,
|
||||
server_name: &summary.server_name,
|
||||
environment_id: summary.environment_id.as_deref(),
|
||||
timed_out: summary.timed_out,
|
||||
daemon: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn daemon(output: &'a AppServerRemoteControlReadyOutput) -> Self {
|
||||
let remote_control = &output.remote_control;
|
||||
Self {
|
||||
mode: RemoteControlModeJson::Daemon,
|
||||
status: remote_control.status,
|
||||
server_name: &remote_control.server_name,
|
||||
environment_id: remote_control.environment_id.as_deref(),
|
||||
timed_out: remote_control.timed_out,
|
||||
daemon: Some(&output.daemon),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remote_control_start_human_message(
|
||||
output: &AppServerRemoteControlReadyStatus,
|
||||
) -> anyhow::Result<String> {
|
||||
ensure_remote_control_startable(output)?;
|
||||
match output.status {
|
||||
RemoteControlConnectionStatus::Connected => Ok(format!(
|
||||
"This machine is available for remote control as {}.",
|
||||
output.server_name
|
||||
)),
|
||||
RemoteControlConnectionStatus::Connecting => Ok(format!(
|
||||
"Remote control is enabled on {} and still connecting.",
|
||||
output.server_name
|
||||
)),
|
||||
RemoteControlConnectionStatus::Errored | RemoteControlConnectionStatus::Disabled => {
|
||||
unreachable!("errored and disabled statuses are rejected before formatting")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_remote_control_startable(
|
||||
output: &AppServerRemoteControlReadyStatus,
|
||||
) -> anyhow::Result<()> {
|
||||
match output.status {
|
||||
RemoteControlConnectionStatus::Connected | RemoteControlConnectionStatus::Connecting => {
|
||||
Ok(())
|
||||
}
|
||||
RemoteControlConnectionStatus::Errored => {
|
||||
anyhow::bail!(
|
||||
"Remote control is enabled on {} but the connection is errored.",
|
||||
output.server_name
|
||||
);
|
||||
}
|
||||
RemoteControlConnectionStatus::Disabled => {
|
||||
anyhow::bail!("Remote control is disabled on {}.", output.server_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum RemoteControlHumanOutputMode {
|
||||
Foreground,
|
||||
Daemon,
|
||||
}
|
||||
|
||||
fn remote_control_start_human_lines(
|
||||
summary: &AppServerRemoteControlReadyStatus,
|
||||
mode: RemoteControlHumanOutputMode,
|
||||
) -> anyhow::Result<Vec<String>> {
|
||||
let mut lines = vec![remote_control_start_human_message(summary)?];
|
||||
match mode {
|
||||
RemoteControlHumanOutputMode::Foreground => {
|
||||
lines.push("Press Ctrl-C to stop.".to_string());
|
||||
}
|
||||
RemoteControlHumanOutputMode::Daemon => {}
|
||||
}
|
||||
Ok(lines)
|
||||
}
|
||||
|
||||
fn daemon_app_server_human_lines(output: &AppServerRemoteControlStartOutput) -> Vec<String> {
|
||||
let (managed_codex_path, managed_codex_version) = daemon_app_server_identity(output);
|
||||
vec![
|
||||
"Daemon used app-server:".to_string(),
|
||||
format!(" path: {}", managed_codex_path.display()),
|
||||
format!(" version: {}", managed_codex_version.unwrap_or("unknown")),
|
||||
]
|
||||
}
|
||||
|
||||
fn daemon_app_server_identity(
|
||||
output: &AppServerRemoteControlStartOutput,
|
||||
) -> (&std::path::Path, Option<&str>) {
|
||||
match output {
|
||||
AppServerRemoteControlStartOutput::Bootstrap(output) => (
|
||||
&output.managed_codex_path,
|
||||
output.managed_codex_version.as_deref(),
|
||||
),
|
||||
AppServerRemoteControlStartOutput::Start(output) => (
|
||||
&output.managed_codex_path,
|
||||
output.managed_codex_version.as_deref(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn print_remote_control_stop_output(
|
||||
output: &AppServerLifecycleOutput,
|
||||
json: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
if json {
|
||||
println!("{}", serde_json::to_string(output)?);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
println!("{}", remote_control_stop_human_message(output));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_remote_control_pairing_output(
|
||||
output: &RemoteControlPairingStartResponse,
|
||||
json: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
println!("{}", format_remote_control_pairing_output(output, json)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn format_remote_control_pairing_output(
|
||||
output: &RemoteControlPairingStartResponse,
|
||||
json: bool,
|
||||
) -> anyhow::Result<String> {
|
||||
if json {
|
||||
return Ok(serde_json::to_string(output)?);
|
||||
}
|
||||
|
||||
let manual_pairing_code = output
|
||||
.manual_pairing_code
|
||||
.as_deref()
|
||||
.context("remote-control pairing response did not include a manual pairing code")?;
|
||||
Ok(format!("Pairing code: {manual_pairing_code}"))
|
||||
}
|
||||
|
||||
fn remote_control_stop_human_message(output: &AppServerLifecycleOutput) -> String {
|
||||
match output.status {
|
||||
AppServerLifecycleStatus::Stopped => "Remote control stopped.".to_string(),
|
||||
AppServerLifecycleStatus::NotRunning => "Remote control is not running.".to_string(),
|
||||
AppServerLifecycleStatus::Started
|
||||
| AppServerLifecycleStatus::Restarted
|
||||
| AppServerLifecycleStatus::AlreadyRunning
|
||||
| AppServerLifecycleStatus::Running => {
|
||||
format!(
|
||||
"Remote control stop completed with status {:?}.",
|
||||
output.status
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn remote_control_status(
|
||||
status: RemoteControlConnectionStatus,
|
||||
) -> AppServerRemoteControlReadyStatus {
|
||||
AppServerRemoteControlReadyStatus {
|
||||
status,
|
||||
server_name: "owen-mbp".to_string(),
|
||||
environment_id: Some("env_test".to_string()),
|
||||
timed_out: status == RemoteControlConnectionStatus::Connecting,
|
||||
}
|
||||
}
|
||||
|
||||
fn daemon_ready_output(
|
||||
status: RemoteControlConnectionStatus,
|
||||
) -> AppServerRemoteControlReadyOutput {
|
||||
AppServerRemoteControlReadyOutput {
|
||||
daemon: AppServerRemoteControlStartOutput::Start(AppServerLifecycleOutput {
|
||||
status: AppServerLifecycleStatus::Started,
|
||||
backend: None,
|
||||
pid: Some(42),
|
||||
managed_codex_path: PathBuf::from("/opt/codex/bin/codex"),
|
||||
managed_codex_version: Some("1.0.0".to_string()),
|
||||
socket_path: PathBuf::from("/tmp/app-server-control.sock"),
|
||||
cli_version: Some("1.0.0".to_string()),
|
||||
app_server_version: Some("2.0.0".to_string()),
|
||||
}),
|
||||
remote_control: AppServerRemoteControlReadyStatus {
|
||||
status,
|
||||
server_name: "owen-mbp".to_string(),
|
||||
environment_id: Some("env_test".to_string()),
|
||||
timed_out: status == RemoteControlConnectionStatus::Connecting,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn pairing_response(manual_pairing_code: Option<&str>) -> RemoteControlPairingStartResponse {
|
||||
RemoteControlPairingStartResponse {
|
||||
pairing_code: "pairing-code".to_string(),
|
||||
manual_pairing_code: manual_pairing_code.map(str::to_string),
|
||||
environment_id: "env_test".to_string(),
|
||||
expires_at: 1_700_000_000,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_human_start_messages_use_server_name() {
|
||||
assert_eq!(
|
||||
remote_control_start_human_message(&remote_control_status(
|
||||
RemoteControlConnectionStatus::Connected
|
||||
))
|
||||
.expect("connected message"),
|
||||
"This machine is available for remote control as owen-mbp."
|
||||
);
|
||||
assert_eq!(
|
||||
remote_control_start_human_message(&remote_control_status(
|
||||
RemoteControlConnectionStatus::Connecting
|
||||
))
|
||||
.expect("connecting message"),
|
||||
"Remote control is enabled on owen-mbp and still connecting."
|
||||
);
|
||||
assert_eq!(
|
||||
remote_control_start_human_message(&remote_control_status(
|
||||
RemoteControlConnectionStatus::Errored
|
||||
))
|
||||
.expect_err("errored status should fail")
|
||||
.to_string(),
|
||||
"Remote control is enabled on owen-mbp but the connection is errored."
|
||||
);
|
||||
assert_eq!(
|
||||
remote_control_start_human_message(&remote_control_status(
|
||||
RemoteControlConnectionStatus::Disabled
|
||||
))
|
||||
.expect_err("disabled status should fail")
|
||||
.to_string(),
|
||||
"Remote control is disabled on owen-mbp."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_human_lines_include_foreground_stop_hint_only() {
|
||||
let summary = remote_control_status(RemoteControlConnectionStatus::Connected);
|
||||
|
||||
assert_eq!(
|
||||
remote_control_start_human_lines(&summary, RemoteControlHumanOutputMode::Foreground)
|
||||
.expect("foreground lines"),
|
||||
vec![
|
||||
"This machine is available for remote control as owen-mbp.".to_string(),
|
||||
"Press Ctrl-C to stop.".to_string(),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
remote_control_start_human_lines(&summary, RemoteControlHumanOutputMode::Daemon)
|
||||
.expect("daemon lines"),
|
||||
vec!["This machine is available for remote control as owen-mbp.".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daemon_app_server_human_lines_include_path_and_version() {
|
||||
assert_eq!(
|
||||
daemon_app_server_human_lines(
|
||||
&daemon_ready_output(RemoteControlConnectionStatus::Connected).daemon
|
||||
),
|
||||
vec![
|
||||
"Daemon used app-server:".to_string(),
|
||||
" path: /opt/codex/bin/codex".to_string(),
|
||||
" version: 1.0.0".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_json_output_marks_foreground_or_daemon() {
|
||||
let foreground_summary = remote_control_status(RemoteControlConnectionStatus::Connected);
|
||||
assert_eq!(
|
||||
serde_json::to_value(RemoteControlStartJsonOutput::foreground(
|
||||
&foreground_summary
|
||||
))
|
||||
.expect("foreground JSON"),
|
||||
json!({
|
||||
"mode": "foreground",
|
||||
"status": "connected",
|
||||
"serverName": "owen-mbp",
|
||||
"environmentId": "env_test",
|
||||
"timedOut": false,
|
||||
})
|
||||
);
|
||||
|
||||
let daemon_output = daemon_ready_output(RemoteControlConnectionStatus::Connected);
|
||||
assert_eq!(
|
||||
serde_json::to_value(RemoteControlStartJsonOutput::daemon(&daemon_output))
|
||||
.expect("daemon JSON"),
|
||||
json!({
|
||||
"mode": "daemon",
|
||||
"status": "connected",
|
||||
"serverName": "owen-mbp",
|
||||
"environmentId": "env_test",
|
||||
"timedOut": false,
|
||||
"daemon": {
|
||||
"status": "started",
|
||||
"pid": 42,
|
||||
"managedCodexPath": "/opt/codex/bin/codex",
|
||||
"managedCodexVersion": "1.0.0",
|
||||
"socketPath": "/tmp/app-server-control.sock",
|
||||
"cliVersion": "1.0.0",
|
||||
"appServerVersion": "2.0.0",
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_daemon_json_rejects_unstartable_status() {
|
||||
assert_eq!(
|
||||
print_remote_control_start_output(
|
||||
&daemon_ready_output(RemoteControlConnectionStatus::Errored),
|
||||
/*json*/ true
|
||||
)
|
||||
.expect_err("errored daemon status should fail")
|
||||
.to_string(),
|
||||
"Remote control is enabled on owen-mbp but the connection is errored."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_pairing_human_output_labels_the_manual_code() {
|
||||
assert_eq!(
|
||||
format_remote_control_pairing_output(
|
||||
&pairing_response(Some("ABCD-EFGH")),
|
||||
/*json*/ false,
|
||||
)
|
||||
.expect("manual pairing output"),
|
||||
"Pairing code: ABCD-EFGH"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_pairing_json_output_preserves_pairing_artifacts() {
|
||||
let output = format_remote_control_pairing_output(
|
||||
&pairing_response(Some("ABCD-EFGH")),
|
||||
/*json*/ true,
|
||||
)
|
||||
.expect("pairing JSON output");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&output).expect("valid JSON"),
|
||||
json!({
|
||||
"pairingCode": "pairing-code",
|
||||
"manualPairingCode": "ABCD-EFGH",
|
||||
"environmentId": "env_test",
|
||||
"expiresAt": 1_700_000_000,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_pairing_human_output_requires_manual_code() {
|
||||
assert_eq!(
|
||||
format_remote_control_pairing_output(
|
||||
&pairing_response(/*manual_pairing_code*/ None),
|
||||
/*json*/ false,
|
||||
)
|
||||
.expect_err("missing manual pairing code should fail")
|
||||
.to_string(),
|
||||
"remote-control pairing response did not include a manual pairing code"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn foreground_wait_aborts_app_server_on_stop_signal() {
|
||||
let app_server_task = tokio::spawn(std::future::pending::<std::io::Result<()>>());
|
||||
let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
|
||||
stop_tx.send(true).expect("send stop signal");
|
||||
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(1),
|
||||
wait_for_foreground_app_server(app_server_task, stop_rx),
|
||||
)
|
||||
.await
|
||||
.expect("foreground wait should return after stop signal")
|
||||
.expect("stop signal should shut down cleanly");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn foreground_start_wait_stops_before_ready() {
|
||||
let mut app_server_task = tokio::spawn(std::future::pending::<std::io::Result<()>>());
|
||||
let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
|
||||
stop_tx.send(true).expect("send stop signal");
|
||||
|
||||
let startup = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(1),
|
||||
wait_for_foreground_remote_control_start(
|
||||
&mut app_server_task,
|
||||
std::future::pending::<anyhow::Result<AppServerRemoteControlReadyStatus>>(),
|
||||
stop_rx,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("foreground startup wait should return after stop signal");
|
||||
|
||||
assert!(matches!(startup, ForegroundStartupResult::Stopped));
|
||||
app_server_task.abort();
|
||||
let _ = app_server_task.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn foreground_start_wait_reports_app_server_exit_before_ready() {
|
||||
let mut app_server_task =
|
||||
tokio::spawn(async { Err(std::io::Error::other("startup failed before socket bind")) });
|
||||
let (_stop_tx, stop_rx) = tokio::sync::watch::channel(false);
|
||||
|
||||
let startup = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(1),
|
||||
wait_for_foreground_remote_control_start(
|
||||
&mut app_server_task,
|
||||
std::future::pending::<anyhow::Result<AppServerRemoteControlReadyStatus>>(),
|
||||
stop_rx,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("foreground startup wait should return after app-server exits");
|
||||
|
||||
let ForegroundStartupResult::AppServerExited(error) = startup else {
|
||||
panic!("expected app-server exit before ready");
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"foreground app-server exited before remote control became ready"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<assert_cmd::Command> {
|
||||
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(())
|
||||
}
|
||||
@@ -151,21 +151,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()?;
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "cloud-client",
|
||||
crate_name = "codex_cloud_client",
|
||||
)
|
||||
@@ -1,37 +0,0 @@
|
||||
[package]
|
||||
name = "codex-cloud-client"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
async-stream = { workspace = true }
|
||||
bytes = { workspace = true }
|
||||
codex-http-client = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
http = { workspace = true }
|
||||
http-body-util = "0.1.3"
|
||||
prost = "0.14.3"
|
||||
tonic = { workspace = true }
|
||||
tonic-prost = { workspace = true }
|
||||
tower = { version = "0.5.3", features = ["util"] }
|
||||
thiserror = { workspace = true }
|
||||
tokio = { workspace = true, features = ["time"] }
|
||||
url = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
|
||||
hyper = { version = "1.8.1", features = ["server", "http2"] }
|
||||
hyper-util = { version = "0.1.20", features = ["tokio"] }
|
||||
tokio-rustls = { workspace = true }
|
||||
@@ -1,109 +0,0 @@
|
||||
# Codex cloud client
|
||||
|
||||
Reusable Rust client for native ThreadService gRPC over HTTP/2, with no TUI,
|
||||
conventional app-server or private monorepo dependency. This slice supports
|
||||
`Resume` and live `Attach`. It does not use the HTTP `/grpc` JSON gateway.
|
||||
|
||||
The caller supplies a trusted native gRPC origin (scheme/host/port, no path),
|
||||
ChatGPT bearer token, selected account ID and configured `HttpClientFactory`.
|
||||
HTTPS is required except for direct loopback HTTP with an unrestricted, unmanaged
|
||||
factory. This exception bypasses proxies to keep plaintext credentials local.
|
||||
For HTTPS, the shared HTTP client supplies proxy,
|
||||
custom CA and network policy handling; redirects are rejected. Tonic supplies
|
||||
gRPC framing, protobuf encoding, message bounds (64 MiB) and status/trailer handling.
|
||||
Bind factory policy before loading credentials; rebuild on login/account changes.
|
||||
|
||||
`ResumeRequest.wait = false` acknowledges admission, not readiness. Requests are
|
||||
never retried by this crate: a timeout or disconnect can leave work admitted.
|
||||
`Attach` has no history snapshot or replay guarantee. Dropping it detaches without
|
||||
stopping the thread or answering approvals. Streams end after their first error.
|
||||
Resume and Attach setup have a 150-second local deadline; live streams have no idle
|
||||
deadline. Setup does not send a gRPC deadline that would expire a healthy stream.
|
||||
|
||||
`Event::Transcript` decodes selected text, command output, patch, and turn updates.
|
||||
It validates the thread ID and exposes the decoded fields. Turn updates include
|
||||
start time, completion time, and duration when the server provides them.
|
||||
Other notifications and server requests remain opaque protobuf payloads, preserving
|
||||
unknown fields. These are not ProtoJSON or app-server JSON-RPC. Native status
|
||||
code, message and binary details are available explicitly; credentials, event
|
||||
and error diagnostics are redacted. Item lifecycle updates report supported
|
||||
message, command, and file-change summaries. Agent message summaries retain
|
||||
structured questions even when their text is empty. Unsupported item kinds stay opaque.
|
||||
Approval replies and reconnect are subsequent slices.
|
||||
The minimal envelopes in `wire.rs` and `ResumeRequest` mirror ThreadService field
|
||||
numbers; no monorepo checkout or protobuf compiler is required to build this crate.
|
||||
|
||||
Provide `CODEX_CLOUD_ACCESS_TOKEN` and `CODEX_CLOUD_ACCOUNT_ID` through your environment, then run
|
||||
this standalone consumer from `codex-rs`:
|
||||
|
||||
```sh
|
||||
cargo run -p codex-cloud-client --example attach -- "$CODEX_CLOUD_GRPC_ENDPOINT" "$CODEX_CLOUD_THREAD_ID"
|
||||
```
|
||||
|
||||
Use an existing authorized thread and native gRPC origin. No production URL is
|
||||
assumed. Public native ingress is a rollout assumption, not proved by fixture
|
||||
tests. This change does not publish a package to a registry.
|
||||
|
||||
History reads use native `ListTurns` (stored turn metadata) and `ListItems` (one
|
||||
turn or the whole thread). Calls return one page with forward/backward opaque
|
||||
cursors, preserve server order and retain raw responses and rows. Reuse a cursor
|
||||
with the same account, thread and filters. Keep the sort order for `next_cursor`
|
||||
and reverse it for `backwards_cursor`. Calls never paginate or retry automatically.
|
||||
Items with an unknown variant or command source remain in the page with no typed summary.
|
||||
|
||||
History pages and Attach have no shared revision or replay cursor. A page is not
|
||||
an atomic history/live boundary, and timestamps are not event offsets. Do not
|
||||
append buffered deltas to a fetched snapshot: it may already include that text.
|
||||
Full item snapshots can replace matching account/host/thread/turn/item identities;
|
||||
they must not create duplicate transcript rows. Disconnects, untyped recovery
|
||||
notifications and uncertain overlap require authoritative history reload. This
|
||||
crate exposes the read primitives; a coordinated resync/display state machine is
|
||||
still required before claiming lossless resume or live/history reconciliation.
|
||||
|
||||
`add_user_message` submits ordered text and image parts using the thread's existing
|
||||
configuration. Use `UserMessageInput::Text` or `UserMessageInput::Image` with an
|
||||
`ImageReference::Url` (inline data URLs only) or `ImageReference::FileId` and optional
|
||||
`ImageDetail`. Image-only input is supported; local paths must be converted by the
|
||||
caller before submission. URL prefixes are case-insensitive and must contain
|
||||
nonempty data; HTTP image URLs are rejected locally because the backend would
|
||||
omit them. File IDs must be nonblank. Requests containing images have a 3.75 MiB
|
||||
encoded-envelope cap, reserving 256 KiB below CCA's 4 MiB forwarding limit. Plain
|
||||
text retains the 64 MiB encoded-message limit. Text parts carry optional UTF-8
|
||||
byte spans through `UserMessageTextElement`; empty span lists preserve the plain
|
||||
text wire encoding. User-message summaries retain ordered content and client IDs
|
||||
for both text and image echoes.
|
||||
|
||||
Choose `StartIfIdle`, `Steer`, or `Queue` explicitly; admission distinguishes
|
||||
started, steered, duplicate and queued results. Persist a unique client message ID
|
||||
with each logical input and keep it unchanged when reconciling an uncertain
|
||||
submission. Success means admission, not completion. `interrupt_turn` addresses
|
||||
one thread/turn and does not stop the thread or delete queued input. Duplicate
|
||||
admission exposes only the original turn ID when supplied. Its wire turn status
|
||||
is synthesized by the backend and does not describe current lifecycle state;
|
||||
reload history or observe Attach instead of treating the receipt as an active turn.
|
||||
|
||||
`MutationError::InvalidRequest` means local validation rejected the request before
|
||||
sending. `OutcomeUnknown` retains the source error: even a server error can follow
|
||||
admission, so status codes alone do not prove rejection. Malformed success replies
|
||||
and mismatched response IDs are also uncertain. No automatic retry is performed;
|
||||
dropping a pending call does not undo remote work. Reconcile with server state
|
||||
before deciding whether another attempt is safe. Other input kinds, configuration
|
||||
overrides and automated outcome reconciliation are not implemented.
|
||||
|
||||
The attach example accepts two optional additional arguments to explicitly send
|
||||
one message after attaching: a persisted client message ID and the text. It uses
|
||||
`StartIfIdle`, drains events during admission, and prints only redacted event kinds:
|
||||
|
||||
```sh
|
||||
cargo run -p codex-cloud-client --example attach -- "$CODEX_CLOUD_GRPC_ENDPOINT" "$CODEX_CLOUD_THREAD_ID" "$CODEX_CLOUD_MESSAGE_ID" 'Explain this project'
|
||||
```
|
||||
|
||||
`prewarm_default_thread` prepares an ordinary coding thread in the default managed
|
||||
cloud environment, with optional model/provider selection. It returns the native
|
||||
thread identity and resolved settings without a separate activation RPC. The
|
||||
service makes the thread discoverable when it admits the first user message.
|
||||
The service owns executor selection and paths; the caller supplies no local cwd,
|
||||
workspace roots, custom configuration, or Aeon mode. This API does not request an
|
||||
ephemeral thread. Prewarm is sent once; a timeout, disconnect or malformed response
|
||||
can leave a prepared thread whose identity the caller did not receive. No retry
|
||||
or cleanup is automatic.
|
||||
@@ -1,99 +0,0 @@
|
||||
//! Standalone consumer; prints event kinds without logging payloads.
|
||||
use codex_cloud_client::AddUserMessageRequest;
|
||||
use codex_cloud_client::AdmissionOutcome;
|
||||
use codex_cloud_client::Client;
|
||||
use codex_cloud_client::Credentials;
|
||||
use codex_cloud_client::ResumeRequest;
|
||||
use codex_cloud_client::SubmissionMode;
|
||||
use codex_cloud_client::UserMessageInput;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use futures::StreamExt;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let endpoint = args
|
||||
.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("expected native gRPC origin"))?;
|
||||
let thread_id = args
|
||||
.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("expected existing thread ID"))?;
|
||||
// Supplying both extra arguments explicitly opts into sending one message.
|
||||
let submission = match (args.next(), args.next()) {
|
||||
(None, None) => None,
|
||||
(Some(client_user_message_id), Some(text)) => Some(AddUserMessageRequest {
|
||||
thread_id: thread_id.clone(),
|
||||
client_user_message_id,
|
||||
input: vec![UserMessageInput::Text {
|
||||
text: text,
|
||||
text_elements: vec![],
|
||||
}],
|
||||
turn_trigger: None,
|
||||
mode: SubmissionMode::StartIfIdle,
|
||||
shared_access: false,
|
||||
}),
|
||||
_ => anyhow::bail!("expected both client message ID and text, or neither"),
|
||||
};
|
||||
if args.next().is_some() {
|
||||
anyhow::bail!("unexpected argument");
|
||||
}
|
||||
let credentials = Credentials::new(
|
||||
&std::env::var("CODEX_CLOUD_ACCESS_TOKEN")?,
|
||||
&std::env::var("CODEX_CLOUD_ACCOUNT_ID")?,
|
||||
)?;
|
||||
let client = Client::new(
|
||||
&HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
|
||||
&endpoint,
|
||||
credentials,
|
||||
)?;
|
||||
client
|
||||
.resume(&ResumeRequest {
|
||||
thread_id: thread_id.clone(),
|
||||
wait: false,
|
||||
shared_access: false,
|
||||
})
|
||||
.await?;
|
||||
let mut events = client.attach(&thread_id).await?;
|
||||
if let Some(request) = submission {
|
||||
// Drain Attach while admission is pending; events can precede its response.
|
||||
let admission = client.add_user_message(&request);
|
||||
tokio::pin!(admission);
|
||||
let (result, stream_error) = loop {
|
||||
tokio::select! {
|
||||
result = &mut admission => {
|
||||
break (result, None);
|
||||
}
|
||||
event = events.next() => match event {
|
||||
Some(Ok(event)) => println!("{event:?}"),
|
||||
Some(Err(error)) => break (admission.await, Some(anyhow::Error::new(error))),
|
||||
None => break (admission.await, Some(anyhow::anyhow!("attachment ended"))),
|
||||
}
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(admission) => println!(
|
||||
"admission: {}",
|
||||
match admission.outcome {
|
||||
AdmissionOutcome::Started(_) => "started",
|
||||
AdmissionOutcome::Steered(_) => "steered",
|
||||
AdmissionOutcome::Duplicate { .. } => "duplicate",
|
||||
AdmissionOutcome::Queued { .. } => "queued",
|
||||
}
|
||||
),
|
||||
Err(error) => match stream_error {
|
||||
Some(stream_error) => {
|
||||
anyhow::bail!("attachment failed: {stream_error}; admission failed: {error}");
|
||||
}
|
||||
None => return Err(error.into()),
|
||||
},
|
||||
}
|
||||
if let Some(error) = stream_error {
|
||||
return Err(error.context("attachment failed"));
|
||||
}
|
||||
}
|
||||
while let Some(event) = events.next().await {
|
||||
println!("{:?}", event?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,536 +0,0 @@
|
||||
//! Authoritative cloud thread settings returned by deliberate native activation.
|
||||
|
||||
use crate::Client;
|
||||
use crate::Error;
|
||||
use crate::MutationError;
|
||||
use crate::activation_wire as wire;
|
||||
use bytes::Bytes;
|
||||
use prost::Message;
|
||||
use serde::Serialize;
|
||||
use std::fmt;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "activation_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
/// Resolved settings and metadata returned after loading a cloud thread.
|
||||
#[derive(Clone, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ThreadActivation {
|
||||
pub thread: ThreadSnapshot,
|
||||
pub collaboration_mode: Option<CollaborationMode>,
|
||||
pub model: String,
|
||||
pub model_provider: String,
|
||||
pub service_tier: Option<String>,
|
||||
pub cwd: String,
|
||||
pub instruction_sources: Vec<String>,
|
||||
pub runtime_workspace_roots: Vec<String>,
|
||||
pub approval_policy: ApprovalPolicy,
|
||||
pub approvals_reviewer: ApprovalsReviewer,
|
||||
pub sandbox: SandboxPolicy,
|
||||
pub active_permission_profile: Option<ActivePermissionProfile>,
|
||||
pub reasoning_effort: Option<String>,
|
||||
pub turns_backwards_cursor: Option<String>,
|
||||
pub items_backwards_cursor: Option<String>,
|
||||
}
|
||||
|
||||
/// Effective collaboration mode and its backend-resolved settings.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(tag = "mode", content = "settings", rename_all = "lowercase")]
|
||||
pub enum CollaborationMode {
|
||||
Plan(CollaborationSettings),
|
||||
Default(CollaborationSettings),
|
||||
}
|
||||
|
||||
/// The resume protocol uses snake_case for these nested settings.
|
||||
#[derive(Clone, PartialEq, Eq, Serialize)]
|
||||
pub struct CollaborationSettings {
|
||||
pub model: String,
|
||||
pub reasoning_effort: Option<String>,
|
||||
pub developer_instructions: Option<String>,
|
||||
}
|
||||
|
||||
/// Metadata needed to reconstruct a turn-free app-server thread snapshot.
|
||||
#[derive(Clone, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ThreadSnapshot {
|
||||
pub id: String,
|
||||
pub session_id: String,
|
||||
pub forked_from_id: Option<String>,
|
||||
pub parent_thread_id: Option<String>,
|
||||
pub preview: String,
|
||||
pub ephemeral: bool,
|
||||
pub daybreak_enabled: Option<bool>,
|
||||
pub project_id: Option<String>,
|
||||
pub history_mode: ThreadHistoryMode,
|
||||
pub model_provider: String,
|
||||
pub model: Option<String>,
|
||||
pub reasoning_effort: Option<String>,
|
||||
pub created_at: i64,
|
||||
pub updated_at: i64,
|
||||
pub recency_at: Option<i64>,
|
||||
pub status: ThreadStatus,
|
||||
pub path: Option<String>,
|
||||
pub cwd: String,
|
||||
pub cli_version: String,
|
||||
pub originator: Option<String>,
|
||||
pub source: SessionSource,
|
||||
pub can_accept_direct_input: Option<bool>,
|
||||
pub thread_source: Option<String>,
|
||||
pub agent_nickname: Option<String>,
|
||||
pub agent_role: Option<String>,
|
||||
pub git_info: Option<GitInfo>,
|
||||
pub name: Option<String>,
|
||||
pub environments: Option<Vec<ThreadEnvironment>>,
|
||||
/// Activation deliberately excludes turns; callers page history separately.
|
||||
pub turns: [(); 0],
|
||||
#[serde(skip)]
|
||||
raw_protobuf: Bytes,
|
||||
}
|
||||
|
||||
/// Optional repository metadata associated with a cloud conversation.
|
||||
#[derive(Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GitInfo {
|
||||
pub branch: Option<String>,
|
||||
pub origin_url: Option<String>,
|
||||
pub sha: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ThreadHistoryMode {
|
||||
Legacy,
|
||||
Paginated,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ThreadEnvironment {
|
||||
pub environment_id: String,
|
||||
pub cwd: String,
|
||||
pub runtime_workspace_roots: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SessionSource {
|
||||
Cli,
|
||||
#[serde(rename = "vscode")]
|
||||
VsCode,
|
||||
Exec,
|
||||
AppServer,
|
||||
Unknown,
|
||||
Custom(String),
|
||||
SubAgent(SubAgentSource),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SubAgentSource {
|
||||
Review,
|
||||
Compact,
|
||||
MemoryConsolidation,
|
||||
ThreadSpawn {
|
||||
parent_thread_id: String,
|
||||
depth: i32,
|
||||
agent_path: Option<String>,
|
||||
agent_nickname: Option<String>,
|
||||
agent_role: Option<String>,
|
||||
},
|
||||
Other(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(
|
||||
tag = "type",
|
||||
rename_all = "camelCase",
|
||||
rename_all_fields = "camelCase"
|
||||
)]
|
||||
pub enum ThreadStatus {
|
||||
NotLoaded,
|
||||
Idle,
|
||||
SystemError,
|
||||
Active { active_flags: Vec<ThreadActiveFlag> },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ThreadActiveFlag {
|
||||
WaitingOnApproval,
|
||||
WaitingOnUserInput,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum ApprovalPolicy {
|
||||
#[serde(rename = "untrusted")]
|
||||
UnlessTrusted,
|
||||
OnRequest,
|
||||
Never,
|
||||
Granular {
|
||||
sandbox_approval: bool,
|
||||
rules: bool,
|
||||
skill_approval: bool,
|
||||
request_permissions: bool,
|
||||
mcp_elicitations: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
pub enum ApprovalsReviewer {
|
||||
#[serde(rename = "user")]
|
||||
User,
|
||||
#[serde(rename = "auto_review")]
|
||||
AutoReview,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ActivePermissionProfile {
|
||||
pub id: String,
|
||||
pub extends: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum NetworkAccess {
|
||||
Restricted,
|
||||
Enabled,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(
|
||||
tag = "type",
|
||||
rename_all = "camelCase",
|
||||
rename_all_fields = "camelCase"
|
||||
)]
|
||||
pub enum SandboxPolicy {
|
||||
DangerFullAccess,
|
||||
ReadOnly {
|
||||
network_access: bool,
|
||||
},
|
||||
ExternalSandbox {
|
||||
network_access: NetworkAccess,
|
||||
},
|
||||
WorkspaceWrite {
|
||||
writable_roots: Vec<String>,
|
||||
network_access: bool,
|
||||
exclude_tmpdir_env_var: bool,
|
||||
exclude_slash_tmp: bool,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Debug for CollaborationSettings {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("CollaborationSettings([redacted])")
|
||||
}
|
||||
}
|
||||
impl fmt::Debug for ThreadActivation {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("ThreadActivation([redacted])")
|
||||
}
|
||||
}
|
||||
impl fmt::Debug for ThreadSnapshot {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("ThreadSnapshot([redacted])")
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadSnapshot {
|
||||
/// Complete bounded native Thread payload, including fields this client does not interpret.
|
||||
pub fn protobuf(&self) -> &Bytes {
|
||||
&self.raw_protobuf
|
||||
}
|
||||
}
|
||||
|
||||
impl Client {
|
||||
/// Loads a thread and returns its resolved settings without hydrating turns.
|
||||
///
|
||||
/// This is a mutation-capable RPC and is never retried. A timeout or disconnect
|
||||
/// can leave the thread loaded even though the caller did not receive settings.
|
||||
/// Local rejection sends nothing; errors after dispatch leave the outcome unknown.
|
||||
pub async fn activate(&self, thread_id: &str) -> Result<ThreadActivation, MutationError> {
|
||||
if thread_id.trim().is_empty() {
|
||||
return Err(MutationError::InvalidRequest);
|
||||
}
|
||||
let bytes = self
|
||||
.mutate(
|
||||
wire::UpdateConfigRequest {
|
||||
exclude_turns: Some(true),
|
||||
thread_id: Some(thread_id.to_owned()),
|
||||
},
|
||||
"/oaiproto.codex_app_server_backend.ThreadService/UpdateConfig",
|
||||
)
|
||||
.await?;
|
||||
let response = wire::UpdateConfigResponse::decode(bytes)
|
||||
.map_err(|_| MutationError::OutcomeUnknown(Error::InvalidResponse))?;
|
||||
let settings =
|
||||
ThreadActivation::from_settings(response).map_err(MutationError::OutcomeUnknown)?;
|
||||
if settings.thread.id != thread_id {
|
||||
return Err(MutationError::OutcomeUnknown(Error::InvalidResponse));
|
||||
}
|
||||
Ok(settings)
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadActivation {
|
||||
pub(crate) fn from_settings(response: wire::UpdateConfigResponse) -> Result<Self, Error> {
|
||||
let raw_thread = required(response.thread)?;
|
||||
let thread = ThreadSnapshot::decode(raw_thread)?;
|
||||
if thread.session_id.is_empty() || thread.model_provider.is_empty() {
|
||||
return Err(Error::InvalidResponse);
|
||||
}
|
||||
Ok(Self {
|
||||
thread,
|
||||
collaboration_mode: response
|
||||
.collaboration_mode
|
||||
.map(parse_collaboration_mode)
|
||||
.transpose()?,
|
||||
model: nonempty(response.model)?,
|
||||
model_provider: nonempty(response.model_provider)?,
|
||||
service_tier: response.service_tier.and_then(|value| match value.value {
|
||||
Some(wire::nullable_string::Value::String(value)) => Some(value),
|
||||
Some(wire::nullable_string::Value::Null(_)) | None => None,
|
||||
}),
|
||||
cwd: nonempty(response.cwd)?,
|
||||
instruction_sources: response
|
||||
.instruction_sources
|
||||
.map_or_else(Vec::new, |sources| sources.values),
|
||||
runtime_workspace_roots: response
|
||||
.runtime_workspace_roots
|
||||
.map_or_else(Vec::new, |roots| roots.values),
|
||||
approval_policy: parse_approval(required(response.approval_policy)?)?,
|
||||
approvals_reviewer: parse_reviewer(required(response.approvals_reviewer)?)?,
|
||||
sandbox: parse_sandbox(required(response.sandbox)?)?,
|
||||
active_permission_profile: response
|
||||
.active_permission_profile
|
||||
.map(|profile| -> Result<_, Error> {
|
||||
Ok(ActivePermissionProfile {
|
||||
id: nonempty(profile.id)?,
|
||||
extends: profile.extends,
|
||||
})
|
||||
})
|
||||
.transpose()?,
|
||||
reasoning_effort: response.reasoning_effort,
|
||||
turns_backwards_cursor: response.turns_backwards_cursor,
|
||||
items_backwards_cursor: response.items_backwards_cursor,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadSnapshot {
|
||||
pub(crate) fn decode(raw_protobuf: Bytes) -> Result<Self, Error> {
|
||||
let thread =
|
||||
wire::Thread::decode(raw_protobuf.clone()).map_err(|_| Error::InvalidResponse)?;
|
||||
Self::try_from_wire(thread, raw_protobuf)
|
||||
}
|
||||
|
||||
fn try_from_wire(thread: wire::Thread, raw_protobuf: Bytes) -> Result<Self, Error> {
|
||||
Ok(Self {
|
||||
id: nonempty(thread.id)?,
|
||||
session_id: required(thread.session_id)?,
|
||||
forked_from_id: thread.forked_from_id,
|
||||
parent_thread_id: thread.parent_thread_id,
|
||||
preview: required(thread.preview)?,
|
||||
ephemeral: required(thread.ephemeral)?,
|
||||
daybreak_enabled: thread.daybreak_enabled,
|
||||
project_id: thread.project_id,
|
||||
history_mode: parse_history_mode(thread.history_mode)?,
|
||||
model_provider: required(thread.model_provider)?,
|
||||
model: thread.model,
|
||||
reasoning_effort: thread.reasoning_effort,
|
||||
created_at: required(thread.created_at)?,
|
||||
updated_at: required(thread.updated_at)?,
|
||||
recency_at: thread.recency_at,
|
||||
status: parse_status(required(thread.status)?)?,
|
||||
path: thread.path,
|
||||
cwd: nonempty(thread.cwd)?,
|
||||
cli_version: required(thread.cli_version)?,
|
||||
originator: thread.originator,
|
||||
source: parse_source(required(thread.source)?)?,
|
||||
can_accept_direct_input: thread.can_accept_direct_input,
|
||||
thread_source: thread.thread_source,
|
||||
agent_nickname: thread.agent_nickname,
|
||||
agent_role: thread.agent_role,
|
||||
git_info: thread.git_info.map(|git_info| GitInfo {
|
||||
branch: git_info.branch,
|
||||
origin_url: git_info.origin_url,
|
||||
sha: git_info.sha,
|
||||
}),
|
||||
name: thread.name,
|
||||
environments: thread
|
||||
.environments
|
||||
.map(|environments| {
|
||||
environments
|
||||
.values
|
||||
.into_iter()
|
||||
.map(|environment| -> Result<_, Error> {
|
||||
Ok(ThreadEnvironment {
|
||||
environment_id: nonempty(environment.environment_id)?,
|
||||
cwd: nonempty(environment.cwd)?,
|
||||
runtime_workspace_roots: required(
|
||||
environment.runtime_workspace_roots,
|
||||
)?
|
||||
.values,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.transpose()?,
|
||||
turns: [],
|
||||
raw_protobuf,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_collaboration_mode(value: wire::CollaborationMode) -> Result<CollaborationMode, Error> {
|
||||
let settings = required(value.settings)?;
|
||||
let settings = CollaborationSettings {
|
||||
model: nonempty(settings.model)?,
|
||||
reasoning_effort: settings.reasoning_effort,
|
||||
developer_instructions: settings.developer_instructions,
|
||||
};
|
||||
match required(value.mode)? {
|
||||
1 => Ok(CollaborationMode::Plan(settings)),
|
||||
2 => Ok(CollaborationMode::Default(settings)),
|
||||
_ => Err(Error::UnsupportedResponse("collaboration mode")),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_history_mode(value: Option<i32>) -> Result<ThreadHistoryMode, Error> {
|
||||
match value {
|
||||
None | Some(1) => Ok(ThreadHistoryMode::Legacy),
|
||||
Some(2) => Ok(ThreadHistoryMode::Paginated),
|
||||
Some(_) => Err(Error::UnsupportedResponse("thread history mode")),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_approval(value: wire::ApprovalPolicy) -> Result<ApprovalPolicy, Error> {
|
||||
match required(value.value)? {
|
||||
wire::approval_policy::Value::Simple(1) => Ok(ApprovalPolicy::UnlessTrusted),
|
||||
wire::approval_policy::Value::Simple(2) => Ok(ApprovalPolicy::OnRequest),
|
||||
wire::approval_policy::Value::Simple(3) => Ok(ApprovalPolicy::Never),
|
||||
wire::approval_policy::Value::Simple(_) => {
|
||||
Err(Error::UnsupportedResponse("approval policy"))
|
||||
}
|
||||
wire::approval_policy::Value::Granular(wrapper) => {
|
||||
let granular = required(wrapper.granular)?;
|
||||
Ok(ApprovalPolicy::Granular {
|
||||
sandbox_approval: required(granular.sandbox_approval)?,
|
||||
rules: required(granular.rules)?,
|
||||
skill_approval: granular.skill_approval.unwrap_or(false),
|
||||
request_permissions: granular.request_permissions.unwrap_or(false),
|
||||
mcp_elicitations: required(granular.mcp_elicitations)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_reviewer(value: i32) -> Result<ApprovalsReviewer, Error> {
|
||||
match value {
|
||||
1 => Ok(ApprovalsReviewer::User),
|
||||
2 | 3 => Ok(ApprovalsReviewer::AutoReview),
|
||||
_ => Err(Error::UnsupportedResponse("approvals reviewer")),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_sandbox(value: wire::SandboxPolicy) -> Result<SandboxPolicy, Error> {
|
||||
match required(value.value)? {
|
||||
wire::sandbox_policy::Value::DangerFullAccess(_) => Ok(SandboxPolicy::DangerFullAccess),
|
||||
wire::sandbox_policy::Value::ReadOnly(policy) => Ok(SandboxPolicy::ReadOnly {
|
||||
network_access: policy.network_access.unwrap_or(false),
|
||||
}),
|
||||
wire::sandbox_policy::Value::ExternalSandbox(policy) => {
|
||||
Ok(SandboxPolicy::ExternalSandbox {
|
||||
network_access: match policy.network_access {
|
||||
None | Some(1) => NetworkAccess::Restricted,
|
||||
Some(2) => NetworkAccess::Enabled,
|
||||
Some(_) => return Err(Error::UnsupportedResponse("external network policy")),
|
||||
},
|
||||
})
|
||||
}
|
||||
wire::sandbox_policy::Value::WorkspaceWrite(policy) => Ok(SandboxPolicy::WorkspaceWrite {
|
||||
writable_roots: policy
|
||||
.writable_roots
|
||||
.map_or_else(Vec::new, |roots| roots.values),
|
||||
network_access: policy.network_access.unwrap_or(false),
|
||||
exclude_tmpdir_env_var: policy.exclude_tmpdir_env_var.unwrap_or(false),
|
||||
exclude_slash_tmp: policy.exclude_slash_tmp.unwrap_or(false),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_source(value: wire::SessionSource) -> Result<SessionSource, Error> {
|
||||
match required(value.value)? {
|
||||
wire::session_source::Value::Simple(1) => Ok(SessionSource::Cli),
|
||||
wire::session_source::Value::Simple(2) => Ok(SessionSource::VsCode),
|
||||
wire::session_source::Value::Simple(3) => Ok(SessionSource::Exec),
|
||||
wire::session_source::Value::Simple(4) => Ok(SessionSource::AppServer),
|
||||
wire::session_source::Value::Simple(0) => Err(Error::UnsupportedResponse("session source")),
|
||||
wire::session_source::Value::Simple(_) => Ok(SessionSource::Unknown),
|
||||
wire::session_source::Value::Custom(source) => {
|
||||
Ok(SessionSource::Custom(nonempty(source.custom)?))
|
||||
}
|
||||
wire::session_source::Value::SubAgent(wrapper) => Ok(SessionSource::SubAgent(
|
||||
parse_subagent_source(required(wrapper.sub_agent)?)?,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_subagent_source(value: wire::SubAgentSource) -> Result<SubAgentSource, Error> {
|
||||
match required(value.value)? {
|
||||
wire::sub_agent_source::Value::Simple(1) => Ok(SubAgentSource::Review),
|
||||
wire::sub_agent_source::Value::Simple(2) => Ok(SubAgentSource::Compact),
|
||||
wire::sub_agent_source::Value::Simple(3) => Ok(SubAgentSource::MemoryConsolidation),
|
||||
wire::sub_agent_source::Value::Simple(_) => {
|
||||
Err(Error::UnsupportedResponse("sub-agent source"))
|
||||
}
|
||||
wire::sub_agent_source::Value::ThreadSpawn(wrapper) => {
|
||||
let source = required(wrapper.thread_spawn)?;
|
||||
Ok(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id: nonempty(source.parent_thread_id)?,
|
||||
depth: i32::try_from(required(source.depth)?)
|
||||
.map_err(|_| Error::InvalidResponse)?,
|
||||
agent_path: source.agent_path,
|
||||
agent_nickname: source.agent_nickname,
|
||||
agent_role: source.agent_role,
|
||||
})
|
||||
}
|
||||
wire::sub_agent_source::Value::Other(source) => {
|
||||
Ok(SubAgentSource::Other(nonempty(source.other)?))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn parse_status(value: wire::ThreadStatus) -> Result<ThreadStatus, Error> {
|
||||
match required(value.value)? {
|
||||
wire::thread_status::Value::NotLoaded(_) => Ok(ThreadStatus::NotLoaded),
|
||||
wire::thread_status::Value::Idle(_) => Ok(ThreadStatus::Idle),
|
||||
wire::thread_status::Value::SystemError(_) => Ok(ThreadStatus::SystemError),
|
||||
wire::thread_status::Value::Active(active) => Ok(ThreadStatus::Active {
|
||||
active_flags: required(active.active_flags)?
|
||||
.values
|
||||
.into_iter()
|
||||
.map(|flag| match flag {
|
||||
1 => Ok(ThreadActiveFlag::WaitingOnApproval),
|
||||
2 => Ok(ThreadActiveFlag::WaitingOnUserInput),
|
||||
_ => Err(Error::UnsupportedResponse("thread active flag")),
|
||||
})
|
||||
.collect::<Result<_, _>>()?,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn required<T>(value: Option<T>) -> Result<T, Error> {
|
||||
value.ok_or(Error::InvalidResponse)
|
||||
}
|
||||
|
||||
fn nonempty(value: Option<String>) -> Result<String, Error> {
|
||||
let value = required(value)?;
|
||||
if value.is_empty() {
|
||||
Err(Error::InvalidResponse)
|
||||
} else {
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn wire_debug_redacts_thread_preview_and_raw_bytes() {
|
||||
let thread = wire::Thread {
|
||||
preview: Some("synthetic private preview".to_owned()),
|
||||
..Default::default()
|
||||
};
|
||||
let response = wire::UpdateConfigResponse {
|
||||
thread: Some(Bytes::from(thread.encode_to_vec())),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert_eq!(format!("{thread:?}"), "Thread([redacted])");
|
||||
assert_eq!(format!("{response:?}"), "UpdateConfigResponse([redacted])");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_history_mode_uses_legacy_compatibility_default() {
|
||||
assert_eq!(
|
||||
parse_history_mode(/*value*/ None).unwrap(),
|
||||
ThreadHistoryMode::Legacy
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_sandbox_network_access_defaults_only_when_omitted() {
|
||||
let decode = |network_access| {
|
||||
parse_sandbox(wire::SandboxPolicy {
|
||||
value: Some(wire::sandbox_policy::Value::ExternalSandbox(
|
||||
wire::ExternalSandbox { network_access },
|
||||
)),
|
||||
})
|
||||
};
|
||||
for (value, network_access) in [
|
||||
(None, NetworkAccess::Restricted),
|
||||
(Some(1), NetworkAccess::Restricted),
|
||||
(Some(2), NetworkAccess::Enabled),
|
||||
] {
|
||||
assert_eq!(
|
||||
decode(value).unwrap(),
|
||||
SandboxPolicy::ExternalSandbox { network_access }
|
||||
);
|
||||
}
|
||||
for value in [0, 99] {
|
||||
assert!(matches!(
|
||||
decode(Some(value)),
|
||||
Err(Error::UnsupportedResponse("external network policy"))
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,373 +0,0 @@
|
||||
//! Minimal protobuf envelopes for authoritative thread activation.
|
||||
|
||||
use bytes::Bytes;
|
||||
use prost::Message;
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct UpdateConfigRequest {
|
||||
#[prost(bool, optional, tag = "7")]
|
||||
pub exclude_turns: Option<bool>,
|
||||
#[prost(string, optional, tag = "18")]
|
||||
pub thread_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Message)]
|
||||
#[prost(skip_debug)]
|
||||
pub(super) struct UpdateConfigResponse {
|
||||
#[prost(message, optional, tag = "1")]
|
||||
pub active_permission_profile: Option<ActivePermissionProfile>,
|
||||
#[prost(message, optional, tag = "2")]
|
||||
pub approval_policy: Option<ApprovalPolicy>,
|
||||
#[prost(int32, optional, tag = "3")]
|
||||
pub approvals_reviewer: Option<i32>,
|
||||
#[prost(message, optional, tag = "4")]
|
||||
pub collaboration_mode: Option<CollaborationMode>,
|
||||
#[prost(string, optional, tag = "5")]
|
||||
pub cwd: Option<String>,
|
||||
#[prost(message, optional, tag = "8")]
|
||||
pub instruction_sources: Option<StringList>,
|
||||
#[prost(string, optional, tag = "9")]
|
||||
pub items_backwards_cursor: Option<String>,
|
||||
#[prost(string, optional, tag = "10")]
|
||||
pub model: Option<String>,
|
||||
#[prost(string, optional, tag = "11")]
|
||||
pub model_provider: Option<String>,
|
||||
#[prost(string, optional, tag = "13")]
|
||||
pub reasoning_effort: Option<String>,
|
||||
#[prost(message, optional, tag = "14")]
|
||||
pub runtime_workspace_roots: Option<StringList>,
|
||||
#[prost(message, optional, tag = "15")]
|
||||
pub sandbox: Option<SandboxPolicy>,
|
||||
#[prost(message, optional, tag = "16")]
|
||||
pub service_tier: Option<NullableString>,
|
||||
#[prost(bytes = "bytes", optional, tag = "17")]
|
||||
pub thread: Option<Bytes>,
|
||||
#[prost(string, optional, tag = "18")]
|
||||
pub turns_backwards_cursor: Option<String>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for UpdateConfigResponse {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("UpdateConfigResponse([redacted])")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct CollaborationMode {
|
||||
#[prost(int32, optional, tag = "1")]
|
||||
pub mode: Option<i32>,
|
||||
#[prost(message, optional, tag = "2")]
|
||||
pub settings: Option<Settings>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Message)]
|
||||
#[prost(skip_debug)]
|
||||
pub(super) struct Settings {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub developer_instructions: Option<String>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub model: Option<String>,
|
||||
#[prost(string, optional, tag = "3")]
|
||||
pub reasoning_effort: Option<String>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Settings {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("Settings([redacted])")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ActivePermissionProfile {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub extends: Option<String>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ApprovalPolicy {
|
||||
#[prost(oneof = "approval_policy::Value", tags = "1, 2")]
|
||||
pub value: Option<approval_policy::Value>,
|
||||
}
|
||||
pub(super) mod approval_policy {
|
||||
#[derive(Clone, prost::Oneof)]
|
||||
pub enum Value {
|
||||
#[prost(int32, tag = "1")]
|
||||
Simple(i32),
|
||||
#[prost(message, tag = "2")]
|
||||
Granular(super::GranularApprovalWrapper),
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct GranularApprovalWrapper {
|
||||
#[prost(message, optional, tag = "1")]
|
||||
pub granular: Option<GranularApproval>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct GranularApproval {
|
||||
#[prost(bool, optional, tag = "1")]
|
||||
pub mcp_elicitations: Option<bool>,
|
||||
#[prost(bool, optional, tag = "2")]
|
||||
pub request_permissions: Option<bool>,
|
||||
#[prost(bool, optional, tag = "3")]
|
||||
pub rules: Option<bool>,
|
||||
#[prost(bool, optional, tag = "4")]
|
||||
pub sandbox_approval: Option<bool>,
|
||||
#[prost(bool, optional, tag = "5")]
|
||||
pub skill_approval: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct SandboxPolicy {
|
||||
#[prost(oneof = "sandbox_policy::Value", tags = "1, 2, 3, 4")]
|
||||
pub value: Option<sandbox_policy::Value>,
|
||||
}
|
||||
pub(super) mod sandbox_policy {
|
||||
#[derive(Clone, prost::Oneof)]
|
||||
pub enum Value {
|
||||
#[prost(message, tag = "1")]
|
||||
DangerFullAccess(super::Empty),
|
||||
#[prost(message, tag = "2")]
|
||||
ReadOnly(super::ReadOnlySandbox),
|
||||
#[prost(message, tag = "3")]
|
||||
ExternalSandbox(super::ExternalSandbox),
|
||||
#[prost(message, tag = "4")]
|
||||
WorkspaceWrite(super::WorkspaceWriteSandbox),
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct Empty {}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ReadOnlySandbox {
|
||||
#[prost(bool, optional, tag = "1")]
|
||||
pub network_access: Option<bool>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ExternalSandbox {
|
||||
#[prost(int32, optional, tag = "1")]
|
||||
pub network_access: Option<i32>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct WorkspaceWriteSandbox {
|
||||
#[prost(bool, optional, tag = "1")]
|
||||
pub exclude_slash_tmp: Option<bool>,
|
||||
#[prost(bool, optional, tag = "2")]
|
||||
pub exclude_tmpdir_env_var: Option<bool>,
|
||||
#[prost(bool, optional, tag = "3")]
|
||||
pub network_access: Option<bool>,
|
||||
#[prost(message, optional, tag = "4")]
|
||||
pub writable_roots: Option<StringList>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct StringList {
|
||||
#[prost(string, repeated, tag = "1")]
|
||||
pub values: Vec<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct NullableString {
|
||||
#[prost(oneof = "nullable_string::Value", tags = "1, 2")]
|
||||
pub value: Option<nullable_string::Value>,
|
||||
}
|
||||
pub(super) mod nullable_string {
|
||||
#[derive(Clone, prost::Oneof)]
|
||||
pub enum Value {
|
||||
#[prost(string, tag = "1")]
|
||||
String(String),
|
||||
#[prost(message, tag = "2")]
|
||||
Null(super::Empty),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Message)]
|
||||
#[prost(skip_debug)]
|
||||
pub(super) struct Thread {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub agent_nickname: Option<String>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub agent_role: Option<String>,
|
||||
#[prost(bool, optional, tag = "3")]
|
||||
pub can_accept_direct_input: Option<bool>,
|
||||
#[prost(string, optional, tag = "4")]
|
||||
pub cli_version: Option<String>,
|
||||
#[prost(int64, optional, tag = "5")]
|
||||
pub created_at: Option<i64>,
|
||||
#[prost(string, optional, tag = "6")]
|
||||
pub cwd: Option<String>,
|
||||
#[prost(bool, optional, tag = "7")]
|
||||
pub daybreak_enabled: Option<bool>,
|
||||
#[prost(message, optional, tag = "8")]
|
||||
pub environments: Option<Environments>,
|
||||
#[prost(bool, optional, tag = "9")]
|
||||
pub ephemeral: Option<bool>,
|
||||
#[prost(string, optional, tag = "11")]
|
||||
pub forked_from_id: Option<String>,
|
||||
#[prost(message, optional, tag = "12")]
|
||||
pub git_info: Option<GitInfo>,
|
||||
#[prost(int32, optional, tag = "13")]
|
||||
pub history_mode: Option<i32>,
|
||||
#[prost(string, optional, tag = "14")]
|
||||
pub id: Option<String>,
|
||||
#[prost(string, optional, tag = "15")]
|
||||
pub model: Option<String>,
|
||||
#[prost(string, optional, tag = "16")]
|
||||
pub model_provider: Option<String>,
|
||||
#[prost(string, optional, tag = "17")]
|
||||
pub name: Option<String>,
|
||||
#[prost(string, optional, tag = "18")]
|
||||
pub originator: Option<String>,
|
||||
#[prost(string, optional, tag = "19")]
|
||||
pub parent_thread_id: Option<String>,
|
||||
#[prost(string, optional, tag = "20")]
|
||||
pub path: Option<String>,
|
||||
#[prost(string, optional, tag = "21")]
|
||||
pub preview: Option<String>,
|
||||
#[prost(string, optional, tag = "22")]
|
||||
pub project_id: Option<String>,
|
||||
#[prost(string, optional, tag = "23")]
|
||||
pub reasoning_effort: Option<String>,
|
||||
#[prost(int64, optional, tag = "24")]
|
||||
pub recency_at: Option<i64>,
|
||||
#[prost(string, optional, tag = "27")]
|
||||
pub session_id: Option<String>,
|
||||
#[prost(message, optional, tag = "28")]
|
||||
pub source: Option<SessionSource>,
|
||||
#[prost(message, optional, tag = "29")]
|
||||
pub status: Option<ThreadStatus>,
|
||||
#[prost(string, optional, tag = "30")]
|
||||
pub thread_source: Option<String>,
|
||||
#[prost(int64, optional, tag = "32")]
|
||||
pub updated_at: Option<i64>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Thread {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("Thread([redacted])")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Message)]
|
||||
#[prost(skip_debug)]
|
||||
pub(super) struct GitInfo {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub branch: Option<String>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub origin_url: Option<String>,
|
||||
#[prost(string, optional, tag = "3")]
|
||||
pub sha: Option<String>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for GitInfo {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("GitInfo([redacted])")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct Environments {
|
||||
#[prost(message, repeated, tag = "1")]
|
||||
pub values: Vec<Environment>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct Environment {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub cwd: Option<String>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub environment_id: Option<String>,
|
||||
#[prost(message, optional, tag = "3")]
|
||||
pub runtime_workspace_roots: Option<StringList>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct SessionSource {
|
||||
#[prost(oneof = "session_source::Value", tags = "1, 2, 3")]
|
||||
pub value: Option<session_source::Value>,
|
||||
}
|
||||
pub(super) mod session_source {
|
||||
#[derive(Clone, prost::Oneof)]
|
||||
pub enum Value {
|
||||
#[prost(int32, tag = "1")]
|
||||
Simple(i32),
|
||||
#[prost(message, tag = "2")]
|
||||
Custom(super::CustomSource),
|
||||
#[prost(message, tag = "3")]
|
||||
SubAgent(super::SubAgentSourceWrapper),
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct SubAgentSourceWrapper {
|
||||
#[prost(message, optional, tag = "1")]
|
||||
pub sub_agent: Option<SubAgentSource>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct SubAgentSource {
|
||||
#[prost(oneof = "sub_agent_source::Value", tags = "1, 2, 3")]
|
||||
pub value: Option<sub_agent_source::Value>,
|
||||
}
|
||||
pub(super) mod sub_agent_source {
|
||||
#[derive(Clone, prost::Oneof)]
|
||||
pub enum Value {
|
||||
#[prost(int32, tag = "1")]
|
||||
Simple(i32),
|
||||
#[prost(message, tag = "2")]
|
||||
ThreadSpawn(super::ThreadSpawnWrapper),
|
||||
#[prost(message, tag = "3")]
|
||||
Other(super::OtherSubAgentSource),
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct OtherSubAgentSource {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub other: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ThreadSpawnWrapper {
|
||||
#[prost(message, optional, tag = "1")]
|
||||
pub thread_spawn: Option<ThreadSpawnSource>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ThreadSpawnSource {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub agent_nickname: Option<String>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub agent_path: Option<String>,
|
||||
#[prost(string, optional, tag = "3")]
|
||||
pub agent_role: Option<String>,
|
||||
#[prost(int64, optional, tag = "4")]
|
||||
pub depth: Option<i64>,
|
||||
#[prost(string, optional, tag = "5")]
|
||||
pub parent_thread_id: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct CustomSource {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub custom: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ThreadStatus {
|
||||
#[prost(oneof = "thread_status::Value", tags = "1, 2, 3, 4")]
|
||||
pub value: Option<thread_status::Value>,
|
||||
}
|
||||
pub(super) mod thread_status {
|
||||
#[derive(Clone, prost::Oneof)]
|
||||
pub enum Value {
|
||||
#[prost(message, tag = "1")]
|
||||
NotLoaded(super::Empty),
|
||||
#[prost(message, tag = "2")]
|
||||
Idle(super::Empty),
|
||||
#[prost(message, tag = "3")]
|
||||
SystemError(super::Empty),
|
||||
#[prost(message, tag = "4")]
|
||||
Active(super::ActiveStatus),
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ActiveStatus {
|
||||
#[prost(message, optional, tag = "1")]
|
||||
pub active_flags: Option<IntList>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct IntList {
|
||||
#[prost(int32, repeated, tag = "1")]
|
||||
pub values: Vec<i32>,
|
||||
}
|
||||
@@ -1,634 +0,0 @@
|
||||
//! Exercises native HTTP/2 framing, metadata, trailers and cancellation with synthetic data.
|
||||
use super::*;
|
||||
use bytes::Bytes;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use http_body_util::StreamBody;
|
||||
use hyper::body::Frame;
|
||||
use hyper::service::service_fn;
|
||||
use hyper_util::rt::TokioExecutor;
|
||||
use hyper_util::rt::TokioIo;
|
||||
use pretty_assertions::assert_eq;
|
||||
use prost::Message;
|
||||
use std::convert::Infallible;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
struct Fixture {
|
||||
client: Client,
|
||||
requests: mpsc::UnboundedReceiver<(http::request::Parts, Bytes)>,
|
||||
task: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
async fn fixture(response: http::Response<Body>) -> Fixture {
|
||||
fixture_responses(vec![response]).await
|
||||
}
|
||||
async fn fixture_responses(responses: Vec<http::Response<Body>>) -> Fixture {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let endpoint = format!("http://{}", listener.local_addr().unwrap());
|
||||
let (sender, requests) = mpsc::unbounded_channel();
|
||||
let responses = std::sync::Arc::new(std::sync::Mutex::new(std::collections::VecDeque::from(
|
||||
responses,
|
||||
)));
|
||||
let task = tokio::spawn(async move {
|
||||
let (socket, _) = listener.accept().await.unwrap();
|
||||
let service = service_fn(move |request: http::Request<hyper::body::Incoming>| {
|
||||
let sender = sender.clone();
|
||||
let response = responses.lock().unwrap().pop_front().unwrap();
|
||||
async move {
|
||||
let (parts, body) = request.into_parts();
|
||||
sender
|
||||
.send((parts, body.collect().await.unwrap().to_bytes()))
|
||||
.unwrap();
|
||||
Ok::<_, Infallible>(response)
|
||||
}
|
||||
});
|
||||
let _ = hyper::server::conn::http2::Builder::new(TokioExecutor::new())
|
||||
.serve_connection(TokioIo::new(socket), service)
|
||||
.await;
|
||||
});
|
||||
let client = Client::new(
|
||||
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
&endpoint,
|
||||
Credentials::new("synthetic-token", "synthetic-account").unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
Fixture {
|
||||
client,
|
||||
requests,
|
||||
task,
|
||||
}
|
||||
}
|
||||
fn frame(payload: &[u8]) -> Bytes {
|
||||
let mut bytes = vec![0];
|
||||
bytes.extend_from_slice(&(payload.len() as u32).to_be_bytes());
|
||||
bytes.extend_from_slice(payload);
|
||||
bytes.into()
|
||||
}
|
||||
fn response(messages: Vec<Bytes>, status: tonic::Status) -> http::Response<Body> {
|
||||
let frames = messages
|
||||
.into_iter()
|
||||
.map(Frame::data)
|
||||
.chain([Frame::trailers(
|
||||
status.into_http::<Body>().into_parts().0.headers,
|
||||
)]);
|
||||
http::Response::builder()
|
||||
.header("content-type", "application/grpc")
|
||||
.body(Body::new(StreamBody::new(futures::stream::iter(
|
||||
frames.map(Ok::<_, Infallible>),
|
||||
))))
|
||||
.unwrap()
|
||||
}
|
||||
async fn assert_request(fixture: &mut Fixture, method: &str, expected: &[u8]) {
|
||||
let (parts, body) = tokio::time::timeout(Duration::from_secs(5), fixture.requests.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(parts.method, http::Method::POST);
|
||||
assert_eq!(parts.version, http::Version::HTTP_2);
|
||||
assert_eq!(
|
||||
parts.uri.path(),
|
||||
format!("/oaiproto.codex_app_server_backend.ThreadService/{method}")
|
||||
);
|
||||
assert_eq!(parts.headers["authorization"], "Bearer synthetic-token");
|
||||
assert_eq!(parts.headers["chatgpt-account-id"], "synthetic-account");
|
||||
assert_eq!(parts.headers["content-type"], "application/grpc");
|
||||
assert!(!parts.headers.contains_key("grpc-timeout"));
|
||||
assert_eq!(body, frame(expected));
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn activation_sends_only_identity_and_excludes_turns() {
|
||||
let mut fixture = fixture(response(vec![frame(&[])], tonic::Status::ok(""))).await;
|
||||
assert!(matches!(
|
||||
fixture.client.activate("t").await,
|
||||
Err(MutationError::OutcomeUnknown(Error::InvalidResponse))
|
||||
));
|
||||
// exclude_turns=true (field 7), thread_id="t" (field 18).
|
||||
assert_request(&mut fixture, "UpdateConfig", &[56, 1, 0x92, 1, 1, b't']).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn activation_preserves_native_settings_and_thread_metadata() {
|
||||
// Native Thread fields encoded independently of the client's wire types.
|
||||
let thread_base: &[u8] = &[
|
||||
0x22, 1, b'v', // cli_version (4)
|
||||
0x28, 1, // created_at (5)
|
||||
0x32, 1, b'/', // cwd (6)
|
||||
0x48, 0, // ephemeral (9)
|
||||
0x72, 1, b't', // id (14)
|
||||
0x82, 1, 1, b'p', // model_provider (16)
|
||||
0xaa, 1, 0, // preview (21)
|
||||
0xda, 1, 1, b's', // session_id (27)
|
||||
0xe2, 1, 2, 8, 99, // source (28): future simple value
|
||||
0xea, 1, 2, 0x12, 0, // status (29): idle
|
||||
0xfa, 1, 0, // turns (31): empty
|
||||
0x80, 2, 2, // updated_at (32)
|
||||
];
|
||||
let encode_response = |mode: u8, daybreak: Option<bool>, approval: u8| {
|
||||
let mut thread = thread_base.to_vec();
|
||||
if let Some(enabled) = daybreak {
|
||||
thread.extend_from_slice(&[0x38, u8::from(enabled)]); // daybreak_enabled (7)
|
||||
}
|
||||
// Settings has developer_instructions (1), model (2), and reasoning_effort (3).
|
||||
let settings = Bytes::from_static(if mode == 1 {
|
||||
b"\x0a\x01d\x12\x01m\x1a\x04high"
|
||||
} else {
|
||||
b"\x12\x01m"
|
||||
});
|
||||
let mut collaboration_mode = vec![8, mode];
|
||||
prost::encoding::bytes::encode(/* settings */ 2, &settings, &mut collaboration_mode);
|
||||
let mut response_bytes = vec![0x12, 2, 8, approval, 0x18, 1]; // approval and reviewer
|
||||
prost::encoding::bytes::encode(
|
||||
/* collaboration_mode */ 4,
|
||||
&collaboration_mode,
|
||||
&mut response_bytes,
|
||||
);
|
||||
// instruction_sources (8) wraps repeated string values (1).
|
||||
response_bytes.extend_from_slice(b"\x42\x0c\x0a\x0a/AGENTS.md");
|
||||
response_bytes.extend_from_slice(&[
|
||||
0x2a, 1, b'/', // cwd (5)
|
||||
0x52, 1, b'm', // model (10)
|
||||
0x5a, 1, b'p', // model_provider (11)
|
||||
0x7a, 4, 0x12, 2, 8, 1, // sandbox (15): read-only with network access
|
||||
]);
|
||||
prost::encoding::bytes::encode(/* thread */ 17, &thread, &mut response_bytes);
|
||||
(response_bytes, thread)
|
||||
};
|
||||
|
||||
// Activation retains stricter runtime requirements than stored list metadata.
|
||||
for (session_id, model_provider) in [("", "p"), ("s", "")] {
|
||||
let (response_bytes, _) = encode_response(1, Some(true), 2);
|
||||
let mut settings =
|
||||
crate::activation_wire::UpdateConfigResponse::decode(Bytes::from(response_bytes))
|
||||
.unwrap();
|
||||
let mut thread =
|
||||
crate::activation_wire::Thread::decode(settings.thread.take().unwrap()).unwrap();
|
||||
thread.session_id = Some(session_id.into());
|
||||
thread.model_provider = Some(model_provider.into());
|
||||
settings.thread = Some(thread.encode_to_vec().into());
|
||||
assert!(matches!(
|
||||
ThreadActivation::from_settings(settings),
|
||||
Err(Error::InvalidResponse)
|
||||
));
|
||||
}
|
||||
|
||||
for (mode, daybreak) in [(1, Some(true)), (2, Some(false)), (2, None)] {
|
||||
let (response_bytes, thread) = encode_response(mode, daybreak, 2);
|
||||
let mut server = fixture(response(
|
||||
vec![frame(&response_bytes)],
|
||||
tonic::Status::ok(""),
|
||||
))
|
||||
.await;
|
||||
let activation = server.client.activate("t").await.unwrap();
|
||||
assert_eq!(activation.thread.protobuf().as_ref(), thread.as_slice());
|
||||
let json = serde_json::to_value(&activation).unwrap();
|
||||
assert_eq!(json["thread"]["source"], "unknown");
|
||||
assert_eq!(
|
||||
json["thread"].get("daybreakEnabled"),
|
||||
Some(&serde_json::json!(daybreak))
|
||||
);
|
||||
assert_eq!(
|
||||
json["instructionSources"],
|
||||
serde_json::json!(["/AGENTS.md"])
|
||||
);
|
||||
assert_eq!(json["approvalPolicy"], "on-request");
|
||||
assert_eq!(json["approvalsReviewer"], "user");
|
||||
assert_eq!(
|
||||
json["sandbox"],
|
||||
serde_json::json!({"type": "readOnly", "networkAccess": true})
|
||||
);
|
||||
assert_eq!(
|
||||
json["collaborationMode"],
|
||||
serde_json::json!({
|
||||
"mode": if mode == 1 { "plan" } else { "default" },
|
||||
"settings": {
|
||||
"model": "m",
|
||||
"developer_instructions": if mode == 1 { Some("d") } else { None },
|
||||
"reasoning_effort": if mode == 1 { Some("high") } else { None }
|
||||
}
|
||||
})
|
||||
);
|
||||
assert_request(&mut server, "UpdateConfig", &[56, 1, 0x92, 1, 1, b't']).await;
|
||||
assert!(server.requests.try_recv().is_err());
|
||||
}
|
||||
|
||||
// Unknown security policy must remain an error, never a default.
|
||||
let (response_bytes, _) = encode_response(1, Some(true), 99);
|
||||
let mut server = fixture(response(
|
||||
vec![frame(&response_bytes)],
|
||||
tonic::Status::ok(""),
|
||||
))
|
||||
.await;
|
||||
assert!(matches!(
|
||||
server.client.activate("t").await,
|
||||
Err(MutationError::OutcomeUnknown(Error::UnsupportedResponse(
|
||||
"approval policy"
|
||||
)))
|
||||
));
|
||||
assert_request(&mut server, "UpdateConfig", &[56, 1, 0x92, 1, 1, b't']).await;
|
||||
assert!(server.requests.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prewarm_defers_readiness_only_for_selected_projects() {
|
||||
let mut fixture = fixture_responses(vec![
|
||||
response(vec![frame(&[])], tonic::Status::ok("")),
|
||||
response(vec![frame(&[])], tonic::Status::ok("")),
|
||||
])
|
||||
.await;
|
||||
|
||||
assert!(matches!(
|
||||
fixture
|
||||
.client
|
||||
.prewarm_default_thread(/*model*/ None, /*model_provider*/ None)
|
||||
.await,
|
||||
Err(Error::InvalidResponse)
|
||||
));
|
||||
assert_request(&mut fixture, "Prewarm", b"\x52\x04\x0a\x02\x0a\x00").await;
|
||||
|
||||
assert!(matches!(
|
||||
fixture
|
||||
.client
|
||||
.prewarm_thread(
|
||||
/*model*/ None,
|
||||
/*model_provider*/ None,
|
||||
Some(ProjectEnvironment {
|
||||
name: "App".to_owned(),
|
||||
cwd: Some("/workspace/acme/app".to_owned()),
|
||||
origin_urls: vec![
|
||||
"git@github.com:acme/app.git".to_owned(),
|
||||
"https://github.com/acme/lib.git".to_owned(),
|
||||
],
|
||||
}),
|
||||
)
|
||||
.await,
|
||||
Err(Error::InvalidResponse)
|
||||
));
|
||||
let expected = [
|
||||
b"\x52\x73\x0a\x71\x0a\x6f\x0a\x0d" as &[u8],
|
||||
b"asenvcfg_base",
|
||||
b"\x12\x13/workspace/acme/app",
|
||||
b"\x1a\x49\x0a\x42\x0a\x1d\x2a\x1b",
|
||||
b"git@github.com:acme/app.git",
|
||||
b"\x0a\x21\x2a\x1f",
|
||||
b"https://github.com/acme/lib.git",
|
||||
b"\x12\x03App\xe8\x01\x01",
|
||||
]
|
||||
.concat();
|
||||
assert_request(&mut fixture, "Prewarm", &expected).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prewarm_uses_managed_defaults_and_preserves_resolved_settings() {
|
||||
// PrewarmThread uses Thread field numbers but omits turns entirely.
|
||||
let thread = Bytes::from_static(&[
|
||||
0x22, 1, b'v', // cli_version (4)
|
||||
0x28, 1, // created_at (5)
|
||||
0x32, 1, b'/', // cwd (6)
|
||||
0x48, 0, // ephemeral (9)
|
||||
0x72, 1, b't', // id (14)
|
||||
0x82, 1, 1, b'p', // model_provider (16)
|
||||
0xaa, 1, 0, // preview (21)
|
||||
0xda, 1, 1, b's', // session_id (27)
|
||||
0xe2, 1, 2, 8, 1, // source (28): cli
|
||||
0xea, 1, 2, 0x12, 0, // status (29): idle
|
||||
0x80, 2, 2, // updated_at (32)
|
||||
0xa0, 6, 7, // unknown field (100)
|
||||
]);
|
||||
let native_thread = [b"\xfa\x01\x00".as_slice(), thread.as_ref()].concat(); // empty turns (31)
|
||||
// The settings use different field numbers in Prewarm and UpdateConfig.
|
||||
let fields = [
|
||||
(1, 1, b"\x0a\x01e\x12\x01i".as_slice()), // active permission profile
|
||||
(2, 2, b"\x08\x02".as_slice()), // on-request approval
|
||||
(4, 5, b"/".as_slice()), // cwd
|
||||
(7, 10, b"m".as_slice()), // model
|
||||
(8, 11, b"p".as_slice()), // provider
|
||||
(10, 13, b"high".as_slice()), // reasoning effort
|
||||
(11, 14, b"\x0a\x01/".as_slice()), // workspace roots
|
||||
(12, 15, b"\x12\x02\x08\x01".as_slice()), // read-only sandbox
|
||||
(13, 16, b"\x0a\x04fast".as_slice()), // service tier
|
||||
];
|
||||
let mut prewarm = vec![0x18, 1]; // approvals reviewer (3): user
|
||||
let mut activation = prewarm.clone();
|
||||
for (prewarm_tag, activation_tag, bytes) in fields {
|
||||
prost::encoding::bytes::encode(prewarm_tag, &bytes.to_vec(), &mut prewarm);
|
||||
prost::encoding::bytes::encode(activation_tag, &bytes.to_vec(), &mut activation);
|
||||
}
|
||||
prost::encoding::bytes::encode(/* tag */ 14, &thread, &mut prewarm);
|
||||
prost::encoding::bytes::encode(/* tag */ 17, &native_thread, &mut activation);
|
||||
let mut server = fixture_responses(vec![
|
||||
response(vec![frame(&activation)], tonic::Status::ok("")),
|
||||
response(vec![frame(&prewarm)], tonic::Status::ok("")),
|
||||
response(vec![frame(&prewarm)], tonic::Status::ok("")),
|
||||
])
|
||||
.await;
|
||||
let expected = server.client.activate("t").await.unwrap();
|
||||
assert_request(&mut server, "UpdateConfig", &[56, 1, 0x92, 1, 1, b't']).await;
|
||||
for (model, model_provider, request) in [
|
||||
(None, None, vec![0x52, 4, 0x0a, 2, 0x0a, 0]),
|
||||
(
|
||||
Some("m".to_owned()),
|
||||
Some("p".to_owned()),
|
||||
vec![0x52, 4, 0x0a, 2, 0x0a, 0, 0x7a, 1, b'm', 0x82, 1, 1, b'p'],
|
||||
),
|
||||
] {
|
||||
let actual = server
|
||||
.client
|
||||
.prewarm_default_thread(model, model_provider)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
serde_json::to_value(&actual).unwrap(),
|
||||
serde_json::to_value(&expected).unwrap()
|
||||
);
|
||||
assert_eq!(actual.thread.protobuf().as_ref(), native_thread.as_slice());
|
||||
// Exactly one default managed selection; no custom settings or Aeon mode.
|
||||
assert_request(&mut server, "Prewarm", &request).await;
|
||||
assert!(server.requests.try_recv().is_err());
|
||||
}
|
||||
|
||||
// Missing authoritative policy must fail rather than supplying local defaults.
|
||||
let mut missing_sandbox = vec![0x18, 1];
|
||||
for (tag, _, bytes) in fields {
|
||||
if tag != 12 {
|
||||
prost::encoding::bytes::encode(tag, &bytes.to_vec(), &mut missing_sandbox);
|
||||
}
|
||||
}
|
||||
prost::encoding::bytes::encode(/* tag */ 14, &thread, &mut missing_sandbox);
|
||||
let mut server = fixture(response(
|
||||
vec![frame(&missing_sandbox)],
|
||||
tonic::Status::ok(""),
|
||||
))
|
||||
.await;
|
||||
assert!(matches!(
|
||||
server
|
||||
.client
|
||||
.prewarm_default_thread(/*model*/ None, /*model_provider*/ None)
|
||||
.await,
|
||||
Err(Error::InvalidResponse)
|
||||
));
|
||||
assert_request(&mut server, "Prewarm", &[0x52, 4, 0x0a, 2, 0x0a, 0]).await;
|
||||
assert!(server.requests.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resume_sends_protobuf_and_preserves_admission_flags() {
|
||||
for wait in [false, true] {
|
||||
let mut fixture = fixture(response(vec![frame(&[])], tonic::Status::ok(""))).await;
|
||||
fixture
|
||||
.client
|
||||
.resume(&ResumeRequest {
|
||||
thread_id: "t".into(),
|
||||
wait,
|
||||
shared_access: true,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// Independent protobuf wire fixtures, not the client's encoder.
|
||||
let expected: &[u8] = if wait {
|
||||
&[10, 1, b't', 16, 1, 24, 1]
|
||||
} else {
|
||||
&[10, 1, b't', 24, 1]
|
||||
};
|
||||
assert_request(&mut fixture, "Resume", expected).await;
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn attach_preserves_opaque_events_and_native_error_details() {
|
||||
let secret = Bytes::from_static(b"private-error-details");
|
||||
let status = tonic::Status::with_details(
|
||||
tonic::Code::PermissionDenied,
|
||||
"private-message",
|
||||
secret.clone(),
|
||||
);
|
||||
let data = [frame(&[10, 3, 10, 1, b'n']), frame(&[18, 3, 10, 1, b'r'])].concat();
|
||||
let mut fixture = fixture(response(
|
||||
data.iter().map(|b| Bytes::from(vec![*b])).collect(),
|
||||
status,
|
||||
))
|
||||
.await;
|
||||
let mut events = fixture.client.attach("t").await.unwrap();
|
||||
assert_request(&mut fixture, "Attach", &[10, 1, b't']).await;
|
||||
let notification = events.next().await.unwrap().unwrap();
|
||||
assert_eq!(format!("{notification:?}"), "Notification([redacted])");
|
||||
let Event::Notification(bytes) = notification else {
|
||||
panic!("notification expected")
|
||||
};
|
||||
assert_eq!(bytes.as_ref(), &[10, 1, b'n']);
|
||||
let Event::ServerRequest(bytes) = events.next().await.unwrap().unwrap() else {
|
||||
panic!("server request expected")
|
||||
};
|
||||
assert_eq!(bytes.as_ref(), &[10, 1, b'r']);
|
||||
let error = events.next().await.unwrap().unwrap_err();
|
||||
assert!(!format!("{error:?} {error}").contains("private"));
|
||||
let Error::Rpc(status) = error else {
|
||||
panic!("native status expected")
|
||||
};
|
||||
assert_eq!(
|
||||
(status.code, status.message, status.details),
|
||||
(7, "private-message".into(), secret)
|
||||
);
|
||||
assert!(events.next().await.is_none());
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn successful_stream_ends_and_bad_frames_terminate() {
|
||||
let fixture = fixture(response(vec![], tonic::Status::ok(""))).await;
|
||||
assert!(
|
||||
fixture
|
||||
.client
|
||||
.attach("t")
|
||||
.await
|
||||
.unwrap()
|
||||
.next()
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
for message in [
|
||||
frame(&[]),
|
||||
frame(&[10, 99]),
|
||||
Bytes::from_static(&[0, 4, 0, 0, 1]),
|
||||
] {
|
||||
let fixture = self::fixture(response(vec![message], tonic::Status::ok(""))).await;
|
||||
let mut stream = fixture.client.attach("t").await.unwrap();
|
||||
assert!(stream.next().await.unwrap().is_err());
|
||||
assert!(stream.next().await.is_none());
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn unary_checks_status_trailers_and_preserves_details() {
|
||||
let fixture = fixture(response(
|
||||
vec![frame(&[])],
|
||||
tonic::Status::with_details(
|
||||
tonic::Code::Unavailable,
|
||||
"secret",
|
||||
Bytes::from_static(b"details"),
|
||||
),
|
||||
))
|
||||
.await;
|
||||
let error = fixture
|
||||
.client
|
||||
.resume(&ResumeRequest {
|
||||
thread_id: "t".into(),
|
||||
wait: false,
|
||||
shared_access: false,
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
let Error::Rpc(status) = error else {
|
||||
panic!("RPC status expected")
|
||||
};
|
||||
assert_eq!(
|
||||
(status.code, status.details),
|
||||
(14, Bytes::from_static(b"details"))
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn dropping_attachment_cancels_idle_response() {
|
||||
let (sender, dropped) = tokio::sync::oneshot::channel::<()>();
|
||||
let stream = async_stream::stream! {
|
||||
let _sender = sender;
|
||||
yield Ok::<_, Infallible>(Frame::data(frame(&[10, 0])));
|
||||
std::future::pending::<()>().await;
|
||||
};
|
||||
let fixture = fixture(
|
||||
http::Response::builder()
|
||||
.header("content-type", "application/grpc")
|
||||
.body(Body::new(StreamBody::new(stream)))
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
let mut events = fixture.client.attach("t").await.unwrap();
|
||||
events.next().await.unwrap().unwrap();
|
||||
drop(events);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(5), dropped)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn redirects_and_http_failures_are_not_followed() {
|
||||
for status in [307, 403] {
|
||||
let fixture = fixture(
|
||||
http::Response::builder()
|
||||
.status(status)
|
||||
.header("location", "http://127.0.0.1:1/private")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
let error = match fixture.client.attach("t").await {
|
||||
Ok(mut stream) => stream.next().await.unwrap().unwrap_err(),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(matches!(error, Error::Rpc(_)));
|
||||
assert!(!format!("{error:?} {error}").contains("private"));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn rejects_unsafe_origins_and_redacts_credentials() {
|
||||
for endpoint in [
|
||||
"http://example.com",
|
||||
"https://user:secret@example.com",
|
||||
"https://example.com?token=secret",
|
||||
"https://example.com#secret",
|
||||
"https://example.com/grpc",
|
||||
] {
|
||||
assert!(matches!(
|
||||
Client::new(
|
||||
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
endpoint,
|
||||
Credentials::new("token", "account").unwrap(),
|
||||
),
|
||||
Err(Error::InvalidEndpoint)
|
||||
));
|
||||
}
|
||||
assert!(Credentials::new("secret\nvalue", "account").is_err());
|
||||
assert!(
|
||||
!format!(
|
||||
"{:?}",
|
||||
Credentials::new("synthetic-token", "synthetic-account").unwrap()
|
||||
)
|
||||
.contains("synthetic")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loopback_http_rejects_managed_and_endpoint_restricted_policies() {
|
||||
for policy in [
|
||||
codex_http_client::NetworkPolicyController::default().policy(),
|
||||
codex_http_client::NetworkPolicy::unmanaged().restrict_to_endpoints(Default::default()),
|
||||
] {
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy)
|
||||
.with_network_policy(policy);
|
||||
assert!(matches!(
|
||||
Client::new(
|
||||
&factory,
|
||||
"http://127.0.0.1:1234",
|
||||
Credentials::new("token", "account").unwrap(),
|
||||
),
|
||||
Err(Error::InvalidEndpoint)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn https_advertises_h2_in_tls_client_hello() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let client = HttpClientBuilder::new()
|
||||
.http2_prior_knowledge()
|
||||
.build_direct()
|
||||
.unwrap();
|
||||
let request = client.get(format!("https://{}", listener.local_addr().unwrap()));
|
||||
let handshake = async {
|
||||
let (socket, _) = listener.accept().await.unwrap();
|
||||
let hello = tokio_rustls::LazyConfigAcceptor::new(Default::default(), socket)
|
||||
.await
|
||||
.unwrap();
|
||||
let protocols: Vec<_> = hello
|
||||
.client_hello()
|
||||
.alpn()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(<[u8]>::to_vec)
|
||||
.collect();
|
||||
assert_eq!(protocols, vec![b"h2".to_vec()]);
|
||||
// Inspect negotiation without trusting a test CA or completing the TLS handshake.
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
let (_, result) = tokio::join!(handshake, request.send());
|
||||
assert!(result.is_err());
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn https_enforces_unmanaged_endpoint_restrictions_before_connecting() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault).with_network_policy(
|
||||
codex_http_client::NetworkPolicy::unmanaged().restrict_to_endpoints(Default::default()),
|
||||
);
|
||||
let client = Client::new(
|
||||
&factory,
|
||||
&format!("https://{}", listener.local_addr().unwrap()),
|
||||
Credentials::new("token", "account").unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
tokio::select! {
|
||||
result = client.attach("t") => assert!(result.is_err()),
|
||||
_ = listener.accept() => panic!("denied destination was contacted"),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
#[path = "transcript_tests.rs"]
|
||||
mod transcript;
|
||||
|
||||
#[path = "discovery_tests.rs"]
|
||||
mod discovery;
|
||||
@@ -1,226 +0,0 @@
|
||||
//! Typed, paginated cloud thread discovery over the native ThreadService.
|
||||
|
||||
use crate::Client;
|
||||
use crate::Error;
|
||||
use crate::ThreadSnapshot;
|
||||
use bytes::Bytes;
|
||||
use prost::Message;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub enum ThreadSortKey {
|
||||
#[default]
|
||||
CreatedAt,
|
||||
UpdatedAt,
|
||||
RecencyAt,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub enum ThreadSortDirection {
|
||||
Asc,
|
||||
#[default]
|
||||
Desc,
|
||||
}
|
||||
|
||||
/// Lists unarchived threads with the server's default source selection.
|
||||
/// Reuse the same originators and order when continuing with an opaque cursor.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct ThreadListQuery {
|
||||
pub cursor: Option<String>,
|
||||
pub limit: Option<u32>,
|
||||
pub sort_key: ThreadSortKey,
|
||||
pub sort_direction: ThreadSortDirection,
|
||||
/// Empty means all originators, including conversations created by other clients.
|
||||
pub originators: Vec<String>,
|
||||
}
|
||||
|
||||
/// One bounded page in server order; no automatic pagination or deduplication.
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ThreadPage {
|
||||
pub data: Vec<ThreadSnapshot>,
|
||||
pub read_states: Option<HashMap<String, ThreadReadState>>,
|
||||
pub next_cursor: Option<String>,
|
||||
pub backwards_cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ThreadReadState {
|
||||
pub first_unread: Option<ThreadUnreadPosition>,
|
||||
pub revision: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum ThreadUnreadPosition {
|
||||
ThreadStart,
|
||||
Turn {
|
||||
#[serde(rename = "turnId")]
|
||||
turn_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
macro_rules! redacted_debug {
|
||||
($($ty:ty),*) => {$(impl fmt::Debug for $ty {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(concat!(stringify!($ty), "([redacted])"))
|
||||
}
|
||||
})*};
|
||||
}
|
||||
redacted_debug!(ThreadListQuery, ThreadPage);
|
||||
|
||||
impl Client {
|
||||
/// Returns one bounded native page. Read failures are not retried automatically.
|
||||
pub async fn list_threads(&self, query: &ThreadListQuery) -> Result<ThreadPage, Error> {
|
||||
let bytes = self
|
||||
.raw_unary(
|
||||
wire::ListThreadsRequest {
|
||||
cursor: query.cursor.clone(),
|
||||
limit: query.limit,
|
||||
sort_key: Some(match query.sort_key {
|
||||
ThreadSortKey::CreatedAt => 1,
|
||||
ThreadSortKey::UpdatedAt => 2,
|
||||
ThreadSortKey::RecencyAt => 3,
|
||||
}),
|
||||
sort_direction: Some(match query.sort_direction {
|
||||
ThreadSortDirection::Asc => 1,
|
||||
ThreadSortDirection::Desc => 2,
|
||||
}),
|
||||
archived: Some(false),
|
||||
originators: Some(wire::StringList {
|
||||
values: query.originators.clone(),
|
||||
}),
|
||||
},
|
||||
"/oaiproto.codex_app_server_backend.ThreadService/ListThreads",
|
||||
)
|
||||
.await?;
|
||||
let response =
|
||||
wire::ListThreadsResponse::decode(bytes).map_err(|_| Error::InvalidResponse)?;
|
||||
Ok(ThreadPage {
|
||||
data: response
|
||||
.data
|
||||
.ok_or(Error::InvalidResponse)?
|
||||
.values
|
||||
.into_iter()
|
||||
.map(ThreadSnapshot::decode)
|
||||
.collect::<Result<_, _>>()?,
|
||||
read_states: response
|
||||
.read_states
|
||||
.map(|states| {
|
||||
states
|
||||
.values
|
||||
.into_iter()
|
||||
.map(|(thread_id, state)| {
|
||||
let revision = state.revision.ok_or(Error::InvalidResponse)?;
|
||||
if revision.is_empty() {
|
||||
return Err(Error::InvalidResponse);
|
||||
}
|
||||
let first_unread = state
|
||||
.first_unread
|
||||
.map(|position| match position.value {
|
||||
Some(wire::thread_unread_position::Value::ThreadStart(_)) => {
|
||||
Ok(ThreadUnreadPosition::ThreadStart)
|
||||
}
|
||||
Some(wire::thread_unread_position::Value::Turn(turn)) => {
|
||||
let turn_id = turn.turn_id.ok_or(Error::InvalidResponse)?;
|
||||
if turn_id.is_empty() {
|
||||
Err(Error::InvalidResponse)
|
||||
} else {
|
||||
Ok(ThreadUnreadPosition::Turn { turn_id })
|
||||
}
|
||||
}
|
||||
None => Err(Error::InvalidResponse),
|
||||
})
|
||||
.transpose()?;
|
||||
Ok((
|
||||
thread_id,
|
||||
ThreadReadState {
|
||||
first_unread,
|
||||
revision,
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect::<Result<_, _>>()
|
||||
})
|
||||
.transpose()?,
|
||||
next_cursor: response.next_cursor,
|
||||
backwards_cursor: response.backwards_cursor,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
mod wire {
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ListThreadsRequest {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub cursor: Option<String>,
|
||||
#[prost(uint32, optional, tag = "2")]
|
||||
pub limit: Option<u32>,
|
||||
#[prost(int32, optional, tag = "3")]
|
||||
pub sort_key: Option<i32>,
|
||||
#[prost(int32, optional, tag = "4")]
|
||||
pub sort_direction: Option<i32>,
|
||||
#[prost(bool, optional, tag = "5")]
|
||||
pub archived: Option<bool>,
|
||||
#[prost(message, optional, tag = "6")]
|
||||
pub originators: Option<StringList>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct StringList {
|
||||
#[prost(string, repeated, tag = "1")]
|
||||
pub values: Vec<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ListThreadsResponse {
|
||||
#[prost(message, optional, tag = "1")]
|
||||
pub data: Option<ThreadList>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub next_cursor: Option<String>,
|
||||
#[prost(string, optional, tag = "3")]
|
||||
pub backwards_cursor: Option<String>,
|
||||
#[prost(message, optional, tag = "4")]
|
||||
pub read_states: Option<ThreadReadStateMap>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ThreadList {
|
||||
#[prost(bytes = "bytes", repeated, tag = "1")]
|
||||
pub values: Vec<Bytes>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ThreadReadStateMap {
|
||||
#[prost(map = "string, message", tag = "1")]
|
||||
pub values: HashMap<String, ThreadReadState>,
|
||||
}
|
||||
#[derive(Clone, Message, PartialEq)]
|
||||
pub(super) struct ThreadReadState {
|
||||
#[prost(message, optional, tag = "1")]
|
||||
pub first_unread: Option<ThreadUnreadPosition>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub revision: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Message, PartialEq)]
|
||||
pub(super) struct ThreadUnreadPosition {
|
||||
#[prost(oneof = "thread_unread_position::Value", tags = "1, 2")]
|
||||
pub value: Option<thread_unread_position::Value>,
|
||||
}
|
||||
pub(super) mod thread_unread_position {
|
||||
#[derive(Clone, prost::Oneof, PartialEq)]
|
||||
pub enum Value {
|
||||
#[prost(message, tag = "1")]
|
||||
ThreadStart(super::ThreadUnreadPositionThreadStart),
|
||||
#[prost(message, tag = "2")]
|
||||
Turn(super::ThreadUnreadPositionTurn),
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Message, PartialEq)]
|
||||
pub(super) struct ThreadUnreadPositionThreadStart {}
|
||||
#[derive(Clone, Message, PartialEq)]
|
||||
pub(super) struct ThreadUnreadPositionTurn {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub turn_id: Option<String>,
|
||||
}
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovery_preserves_pagination_and_order_on_each_request() {
|
||||
let payload = b"\x0a\x00\x12\x04next\x1a\x04back";
|
||||
let mut fixture = fixture_responses(vec![
|
||||
response(vec![frame(payload)], tonic::Status::ok("")),
|
||||
response(vec![frame(b"\x0a\x00")], tonic::Status::ok("")),
|
||||
])
|
||||
.await;
|
||||
let mut query = ThreadListQuery {
|
||||
cursor: Some("cursor".into()),
|
||||
limit: Some(7),
|
||||
sort_key: ThreadSortKey::UpdatedAt,
|
||||
sort_direction: ThreadSortDirection::Asc,
|
||||
originators: vec!["tui".into()],
|
||||
};
|
||||
let page = fixture.client.list_threads(&query).await.unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
page.data,
|
||||
page.next_cursor.clone(),
|
||||
page.backwards_cursor,
|
||||
page.read_states
|
||||
),
|
||||
(Vec::new(), Some("next".into()), Some("back".into()), None)
|
||||
);
|
||||
assert_request(
|
||||
&mut fixture,
|
||||
"ListThreads",
|
||||
b"\x0a\x06cursor\x10\x07\x18\x02\x20\x01\x28\x00\x32\x05\x0a\x03tui",
|
||||
)
|
||||
.await;
|
||||
query.cursor = page.next_cursor;
|
||||
let last = fixture.client.list_threads(&query).await.unwrap();
|
||||
assert_eq!((last.data, last.next_cursor), (Vec::new(), None));
|
||||
assert_request(
|
||||
&mut fixture,
|
||||
"ListThreads",
|
||||
b"\x0a\x04next\x10\x07\x18\x02\x20\x01\x28\x00\x32\x05\x0a\x03tui",
|
||||
)
|
||||
.await;
|
||||
assert!(fixture.requests.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovery_preserves_native_snapshots_and_read_state() {
|
||||
// Independent native Thread encodings: Git metadata and future field (99), and a legacy row.
|
||||
let thread = Bytes::from_static(
|
||||
b"\x22\x01v\x28\x01\x32\x01/\x48\x00\x62\x28\x0a\x04main\x12\x18https://example.com/repo\x1a\x06abc123\
|
||||
\x72\x01t\x82\x01\x01p\xaa\x01\x00\xda\x01\x01s\xe2\x01\x02\x08\x63\xea\x01\x02\x12\x00\xfa\x01\x00\x80\x02\x02\x98\x06\x01",
|
||||
);
|
||||
let legacy = Bytes::from_static(b"\x22\x00\x28\x00\x32\x01/\x48\x00\x72\x06legacy\x82\x01\x00\xaa\x01\x00\xda\x01\x00\xe2\x01\x02\x08\x01\xea\x01\x02\x12\x00\xfa\x01\x00\x80\x02\x00");
|
||||
let mut data = Vec::new();
|
||||
for row in [&thread, &legacy, &thread] {
|
||||
prost::encoding::bytes::encode(1, row, &mut data);
|
||||
}
|
||||
let mut payload = Vec::new();
|
||||
prost::encoding::bytes::encode(1, &Bytes::from(data), &mut payload);
|
||||
// Read state map: t -> {first_unread: thread_start, revision: r}.
|
||||
payload.extend_from_slice(b"\x22\x0e\x0a\x0c\x0a\x01t\x12\x07\x0a\x02\x0a\x00\x12\x01r");
|
||||
let mut fixture = fixture(response(vec![frame(&payload)], tonic::Status::ok(""))).await;
|
||||
let page = fixture
|
||||
.client
|
||||
.list_threads(&ThreadListQuery::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
page.data
|
||||
.iter()
|
||||
.map(ThreadSnapshot::protobuf)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![&thread, &legacy, &thread]
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
page.data[1].id.as_str(),
|
||||
page.data[1].session_id.as_str(),
|
||||
page.data[1].model_provider.as_str(),
|
||||
page.data[1].cli_version.as_str()
|
||||
),
|
||||
("legacy", "", "", "")
|
||||
);
|
||||
let page_json = serde_json::to_value(&page).unwrap();
|
||||
assert_eq!(
|
||||
page_json["data"][0]["gitInfo"],
|
||||
serde_json::json!({"branch": "main", "originUrl": "https://example.com/repo", "sha": "abc123"})
|
||||
);
|
||||
assert!(page.data[1].git_info.is_none());
|
||||
assert_eq!(page.data[0].status, ThreadStatus::Idle);
|
||||
assert_eq!(
|
||||
page.read_states,
|
||||
Some(std::collections::HashMap::from([(
|
||||
"t".into(),
|
||||
ThreadReadState {
|
||||
first_unread: Some(ThreadUnreadPosition::ThreadStart),
|
||||
revision: "r".into(),
|
||||
}
|
||||
)]))
|
||||
);
|
||||
assert_request(
|
||||
&mut fixture,
|
||||
"ListThreads",
|
||||
b"\x18\x01\x20\x02\x28\x00\x32\x00",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovery_rejects_missing_data_invalid_snapshot_and_empty_revision() {
|
||||
for payload in [
|
||||
&b""[..],
|
||||
&b"\x0a\x02\x0a\x00"[..],
|
||||
&b"\x0a\x00\x22\x07\x0a\x05\x0a\x01t\x12\x00"[..],
|
||||
] {
|
||||
let mut fixture = fixture(response(vec![frame(payload)], tonic::Status::ok(""))).await;
|
||||
assert!(matches!(
|
||||
fixture
|
||||
.client
|
||||
.list_threads(&ThreadListQuery::default())
|
||||
.await,
|
||||
Err(Error::InvalidResponse)
|
||||
));
|
||||
assert_request(
|
||||
&mut fixture,
|
||||
"ListThreads",
|
||||
b"\x18\x01\x20\x02\x28\x00\x32\x00",
|
||||
)
|
||||
.await;
|
||||
assert!(fixture.requests.try_recv().is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,198 +0,0 @@
|
||||
//! Bounded history page reads. Pagination cursors are not live-event replay offsets.
|
||||
use crate::Client;
|
||||
use crate::Error;
|
||||
use crate::ItemSummary;
|
||||
use crate::TurnSummary;
|
||||
use crate::history_wire as wire;
|
||||
use crate::transcript::DecodeFailure;
|
||||
use crate::transcript::required;
|
||||
use bytes::Bytes;
|
||||
use prost::Message;
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum HistoryOrder {
|
||||
Ascending,
|
||||
#[default]
|
||||
Descending,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum HistoryAccess {
|
||||
#[default]
|
||||
Default,
|
||||
Shared,
|
||||
}
|
||||
/// A cursor belongs to its original thread and filters. Keep the order for
|
||||
/// `next_cursor` and reverse it for `backwards_cursor`.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct HistoryQuery {
|
||||
pub cursor: Option<String>,
|
||||
pub limit: Option<u32>,
|
||||
pub order: HistoryOrder,
|
||||
pub access: HistoryAccess,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct ListTurnsRequest {
|
||||
pub thread_id: String,
|
||||
pub page: HistoryQuery,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct ListItemsRequest {
|
||||
pub thread_id: String,
|
||||
pub turn_id: Option<String>,
|
||||
pub page: HistoryQuery,
|
||||
}
|
||||
/// One server page in server order. No automatic pagination, deduplication or retries.
|
||||
pub struct HistoryPage<T> {
|
||||
pub thread_id: String,
|
||||
pub data: Vec<T>,
|
||||
pub next_cursor: Option<String>,
|
||||
pub backwards_cursor: Option<String>,
|
||||
payload: Bytes,
|
||||
}
|
||||
impl<T> HistoryPage<T> {
|
||||
pub fn payload(&self) -> &Bytes {
|
||||
&self.payload
|
||||
}
|
||||
}
|
||||
pub struct HistoryTurn {
|
||||
pub summary: TurnSummary,
|
||||
payload: Bytes,
|
||||
}
|
||||
impl HistoryTurn {
|
||||
/// Original Turn protobuf; includes metadata omitted from the summary.
|
||||
pub fn payload(&self) -> &Bytes {
|
||||
&self.payload
|
||||
}
|
||||
}
|
||||
pub struct HistoryItem {
|
||||
pub turn_id: String,
|
||||
/// Unsupported items and command sources have no summary and retain their original entry.
|
||||
pub summary: Option<ItemSummary>,
|
||||
pub started_at_ms: Option<i64>,
|
||||
pub completed_at_ms: Option<i64>,
|
||||
payload: Bytes,
|
||||
}
|
||||
impl HistoryItem {
|
||||
/// Original ThreadItemEntry protobuf, including the item and untyped metadata.
|
||||
pub fn payload(&self) -> &Bytes {
|
||||
&self.payload
|
||||
}
|
||||
}
|
||||
macro_rules! redacted_debug {
|
||||
($($ty:ty),*) => {$(impl fmt::Debug for $ty {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(concat!(stringify!($ty), "([redacted])")) }
|
||||
})*};
|
||||
}
|
||||
redacted_debug!(
|
||||
HistoryQuery,
|
||||
ListTurnsRequest,
|
||||
ListItemsRequest,
|
||||
HistoryTurn,
|
||||
HistoryItem
|
||||
);
|
||||
impl<T> fmt::Debug for HistoryPage<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("HistoryPage([redacted])")
|
||||
}
|
||||
}
|
||||
impl HistoryQuery {
|
||||
fn order(&self) -> Option<i32> {
|
||||
Some(match self.order {
|
||||
HistoryOrder::Ascending => 1,
|
||||
HistoryOrder::Descending => 2,
|
||||
})
|
||||
}
|
||||
fn access(&self) -> Option<i32> {
|
||||
match self.access {
|
||||
HistoryAccess::Default => None,
|
||||
HistoryAccess::Shared => Some(1),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Client {
|
||||
/// Reads stored turn metadata; use `list_items` for paginated item content.
|
||||
pub async fn list_turns(
|
||||
&self,
|
||||
request: &ListTurnsRequest,
|
||||
) -> Result<HistoryPage<HistoryTurn>, Error> {
|
||||
let payload = self
|
||||
.raw_unary(
|
||||
wire::TurnsRequest {
|
||||
thread_id: request.thread_id.clone(),
|
||||
cursor: request.page.cursor.clone(),
|
||||
limit: request.page.limit,
|
||||
order: request.page.order(),
|
||||
access: request.page.access(),
|
||||
},
|
||||
"/oaiproto.codex_app_server_backend.ThreadService/ListTurns",
|
||||
)
|
||||
.await?;
|
||||
decode_page(&request.thread_id, payload, |payload| {
|
||||
let turn = crate::transcript_wire::Turn::decode(payload.clone())?;
|
||||
Ok(HistoryTurn {
|
||||
summary: turn.try_into()?,
|
||||
payload,
|
||||
})
|
||||
})
|
||||
.map_err(|_| Error::InvalidResponse)
|
||||
}
|
||||
/// Reads one page, across the thread or restricted to one turn. This is not an
|
||||
/// atomic snapshot synchronized with Attach; do not append buffered deltas to it.
|
||||
pub async fn list_items(
|
||||
&self,
|
||||
request: &ListItemsRequest,
|
||||
) -> Result<HistoryPage<HistoryItem>, Error> {
|
||||
let payload = self
|
||||
.raw_unary(
|
||||
wire::ItemsRequest {
|
||||
thread_id: request.thread_id.clone(),
|
||||
turn_id: request.turn_id.clone(),
|
||||
cursor: request.page.cursor.clone(),
|
||||
limit: request.page.limit,
|
||||
order: request.page.order(),
|
||||
access: request.page.access(),
|
||||
},
|
||||
"/oaiproto.codex_app_server_backend.ThreadService/ListItems",
|
||||
)
|
||||
.await?;
|
||||
decode_page(&request.thread_id, payload, |payload| {
|
||||
let entry = wire::ItemEntry::decode(payload.clone())?;
|
||||
let turn_id = required(entry.turn_id)?;
|
||||
if request
|
||||
.turn_id
|
||||
.as_ref()
|
||||
.is_some_and(|expected| expected != &turn_id)
|
||||
{
|
||||
return Err(DecodeFailure::InvalidResponse);
|
||||
}
|
||||
Ok(HistoryItem {
|
||||
turn_id,
|
||||
summary: crate::items::summary(required(entry.item)?)?,
|
||||
started_at_ms: entry.started_at_ms,
|
||||
completed_at_ms: entry.completed_at_ms,
|
||||
payload,
|
||||
})
|
||||
})
|
||||
.map_err(|_| Error::InvalidResponse)
|
||||
}
|
||||
}
|
||||
fn decode_page<T>(
|
||||
thread_id: &str,
|
||||
payload: Bytes,
|
||||
decode: impl Fn(Bytes) -> Result<T, DecodeFailure>,
|
||||
) -> Result<HistoryPage<T>, DecodeFailure> {
|
||||
let page = wire::Page::decode(payload.clone())?;
|
||||
let data = required(page.data)?
|
||||
.values
|
||||
.into_iter()
|
||||
.map(decode)
|
||||
.collect::<Result<_, _>>()?;
|
||||
Ok(HistoryPage {
|
||||
thread_id: thread_id.to_owned(),
|
||||
data,
|
||||
next_cursor: page.next_cursor,
|
||||
backwards_cursor: page.backwards_cursor,
|
||||
payload,
|
||||
})
|
||||
}
|
||||
@@ -1,245 +0,0 @@
|
||||
//! Independent wire fixtures cover page requests, presence, provenance and unknown data.
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn page(rows: &[&[u8]]) -> Vec<u8> {
|
||||
message(
|
||||
/*tag*/ 1,
|
||||
&rows
|
||||
.iter()
|
||||
.flat_map(|row| message(/*tag*/ 1, row))
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn item_history_paginates_with_explicit_filters_and_preserves_rows() {
|
||||
let entry =
|
||||
b"\x0a\x01u\x12\x0f\x1a\x0d\x12\x01i\x32\x01d\x2a\x05\x0a\x03\x12\x01Q\x18\x65\x20\x67";
|
||||
// A future command source alongside a known agent message.
|
||||
let command = b"\x12\x01c\x1a\x00\x22\x01w\x3a\x01i\x58\x63\x60\x03";
|
||||
let item = message(/*tag*/ 7, command);
|
||||
let opaque = [message(/*tag*/ 1, b"u"), message(/*tag*/ 2, &item)].concat();
|
||||
let mut first = page(&[entry, &opaque]);
|
||||
first.extend(b"\x12\x01n\x1a\x01b\xa0\x06\x01");
|
||||
let unknown = b"\x0a\x01u\x12\x03\xa2\x01\x00";
|
||||
let second = page(&[unknown]);
|
||||
let mut fixture = fixture_responses(vec![
|
||||
response(vec![frame(&first)], tonic::Status::ok("")),
|
||||
response(vec![frame(&second)], tonic::Status::ok("")),
|
||||
])
|
||||
.await;
|
||||
let mut request = ListItemsRequest {
|
||||
thread_id: "t".into(),
|
||||
turn_id: Some("u".into()),
|
||||
page: HistoryQuery {
|
||||
cursor: None,
|
||||
limit: Some(2),
|
||||
order: HistoryOrder::Ascending,
|
||||
access: HistoryAccess::Shared,
|
||||
},
|
||||
};
|
||||
let first_page = fixture.client.list_items(&request).await.unwrap();
|
||||
assert_request(
|
||||
&mut fixture,
|
||||
"ListItems",
|
||||
b"\x0a\x01t\x12\x01u\x20\x02\x28\x01\x30\x01",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
(
|
||||
&first_page.thread_id,
|
||||
&first_page.next_cursor,
|
||||
&first_page.backwards_cursor,
|
||||
first_page.payload()
|
||||
),
|
||||
(
|
||||
&"t".to_owned(),
|
||||
&Some("n".into()),
|
||||
&Some("b".into()),
|
||||
&Bytes::from(first)
|
||||
)
|
||||
);
|
||||
let [item, unknown_source] = first_page.data.as_slice() else {
|
||||
panic!("expected two items")
|
||||
};
|
||||
assert_eq!(unknown_source.summary, None);
|
||||
assert_eq!(unknown_source.payload().as_ref(), opaque.as_slice());
|
||||
assert_eq!(
|
||||
(
|
||||
&item.turn_id,
|
||||
&item.summary,
|
||||
item.started_at_ms,
|
||||
item.completed_at_ms,
|
||||
item.payload()
|
||||
),
|
||||
(
|
||||
&"u".to_owned(),
|
||||
&Some(ItemSummary::AgentMessage {
|
||||
id: "i".into(),
|
||||
text: "d".into(),
|
||||
questions: Some(vec![AgentQuestion {
|
||||
title: "Q".into(),
|
||||
options: None
|
||||
}]),
|
||||
}),
|
||||
Some(101),
|
||||
Some(103),
|
||||
&Bytes::from_static(entry)
|
||||
)
|
||||
);
|
||||
request.page.cursor = first_page.next_cursor;
|
||||
let second_page = fixture.client.list_items(&request).await.unwrap();
|
||||
assert_request(
|
||||
&mut fixture,
|
||||
"ListItems",
|
||||
b"\x0a\x01t\x12\x01u\x1a\x01n\x20\x02\x28\x01\x30\x01",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
(second_page.next_cursor, second_page.backwards_cursor),
|
||||
(None, None)
|
||||
);
|
||||
assert_eq!(second_page.data.len(), 1);
|
||||
assert_eq!(
|
||||
(
|
||||
&second_page.data[0].summary,
|
||||
second_page.data[0].started_at_ms,
|
||||
second_page.data[0].payload()
|
||||
),
|
||||
(&None, None, &Bytes::from_static(unknown))
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn turn_history_reuses_summary_and_retains_omitted_metadata() {
|
||||
let turn = b"\x08\x65\x10\x02\x22\x01u\x2a\x00\x38\x63\x40\x03";
|
||||
let payload = page(&[turn]);
|
||||
let mut fixture = fixture(response(vec![frame(&payload)], tonic::Status::ok(""))).await;
|
||||
let result = fixture
|
||||
.client
|
||||
.list_turns(&ListTurnsRequest {
|
||||
thread_id: "t".into(),
|
||||
page: HistoryQuery {
|
||||
cursor: Some("c".into()),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_request(&mut fixture, "ListTurns", b"\x0a\x01t\x12\x01c\x20\x02").await;
|
||||
assert_eq!(result.data.len(), 1);
|
||||
assert_eq!(
|
||||
(
|
||||
&result.thread_id,
|
||||
&result.data[0].summary,
|
||||
result.data[0].payload(),
|
||||
result.payload()
|
||||
),
|
||||
(
|
||||
&"t".to_owned(),
|
||||
&TurnSummary {
|
||||
id: "u".into(),
|
||||
status: TurnStatus::Failed,
|
||||
started_at: Some(99),
|
||||
completed_at: Some(101),
|
||||
duration_ms: Some(2),
|
||||
error: None
|
||||
},
|
||||
&Bytes::from_static(turn),
|
||||
&Bytes::from(payload)
|
||||
)
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn history_distinguishes_empty_pages_from_missing_wrappers_and_bad_rows() {
|
||||
let valid_empty = page(&[]);
|
||||
let fixture = fixture(response(vec![frame(&valid_empty)], tonic::Status::ok(""))).await;
|
||||
let request = ListItemsRequest {
|
||||
thread_id: "t".into(),
|
||||
turn_id: Some("u".into()),
|
||||
page: HistoryQuery::default(),
|
||||
};
|
||||
assert!(
|
||||
fixture
|
||||
.client
|
||||
.list_items(&request)
|
||||
.await
|
||||
.unwrap()
|
||||
.data
|
||||
.is_empty()
|
||||
);
|
||||
for payload in [
|
||||
vec![],
|
||||
page(&[b"\x0a\x01u"]),
|
||||
page(&[b"\x12\x00"]),
|
||||
page(&[b"\x0a\x01u\x12\x05\x1a\x03\x12\x01i"]), // Agent message without text.
|
||||
page(&[b"\x0a\x01x\x12\x00"]),
|
||||
// Unknown command source and missing required status.
|
||||
page(&[b"\x0a\x01u\x12\x0f\x3a\x0d\x12\x01c\x1a\x00\x22\x01w\x3a\x01i\x58\x63"]),
|
||||
vec![10, 127],
|
||||
] {
|
||||
let server = super::fixture(response(vec![frame(&payload)], tonic::Status::ok(""))).await;
|
||||
assert!(matches!(
|
||||
server.client.list_items(&request).await,
|
||||
Err(Error::InvalidResponse)
|
||||
));
|
||||
}
|
||||
for turn in [b"\x22\x01u".as_slice(), b"\x40\x01"] {
|
||||
let server =
|
||||
super::fixture(response(vec![frame(&page(&[turn]))], tonic::Status::ok(""))).await;
|
||||
assert!(matches!(
|
||||
server
|
||||
.client
|
||||
.list_turns(&ListTurnsRequest {
|
||||
thread_id: "t".into(),
|
||||
page: HistoryQuery::default()
|
||||
})
|
||||
.await,
|
||||
Err(Error::InvalidResponse)
|
||||
));
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn history_errors_preserve_status_without_retrying() {
|
||||
let mut fixture = fixture(response(
|
||||
vec![],
|
||||
tonic::Status::permission_denied("private error"),
|
||||
))
|
||||
.await;
|
||||
let error = fixture
|
||||
.client
|
||||
.list_items(&ListItemsRequest {
|
||||
thread_id: "t".into(),
|
||||
turn_id: None,
|
||||
page: HistoryQuery::default(),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(!format!("{error:?}").contains("private error"));
|
||||
assert!(matches!(error, Error::Rpc(status) if status.code == 7));
|
||||
assert_request(&mut fixture, "ListItems", b"\x0a\x01t\x28\x02").await;
|
||||
assert!(fixture.requests.try_recv().is_err());
|
||||
}
|
||||
#[test]
|
||||
fn history_diagnostics_redact_each_public_payload_type() {
|
||||
let query = HistoryQuery {
|
||||
cursor: Some("secret".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let items = ListItemsRequest {
|
||||
thread_id: "secret".into(),
|
||||
turn_id: Some("secret".into()),
|
||||
page: query.clone(),
|
||||
};
|
||||
let turns = ListTurnsRequest {
|
||||
thread_id: "secret".into(),
|
||||
page: query.clone(),
|
||||
};
|
||||
for value in [
|
||||
format!("{query:?}"),
|
||||
format!("{items:?}"),
|
||||
format!("{turns:?}"),
|
||||
] {
|
||||
assert!(value.ends_with("([redacted])"));
|
||||
assert!(!value.contains("secret"));
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
//! Native paginated history envelopes. Raw rows and unary responses retain unknown fields.
|
||||
use bytes::Bytes;
|
||||
use prost::Message;
|
||||
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct TurnsRequest {
|
||||
#[prost(string, tag = "1")]
|
||||
pub thread_id: String,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub cursor: Option<String>,
|
||||
#[prost(uint32, optional, tag = "3")]
|
||||
pub limit: Option<u32>,
|
||||
#[prost(int32, optional, tag = "4")]
|
||||
pub order: Option<i32>,
|
||||
#[prost(int32, optional, tag = "6")]
|
||||
pub access: Option<i32>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ItemsRequest {
|
||||
#[prost(string, tag = "1")]
|
||||
pub thread_id: String,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub turn_id: Option<String>,
|
||||
#[prost(string, optional, tag = "3")]
|
||||
pub cursor: Option<String>,
|
||||
#[prost(uint32, optional, tag = "4")]
|
||||
pub limit: Option<u32>,
|
||||
#[prost(int32, optional, tag = "5")]
|
||||
pub order: Option<i32>,
|
||||
#[prost(int32, optional, tag = "6")]
|
||||
pub access: Option<i32>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct Page {
|
||||
#[prost(message, optional, tag = "1")]
|
||||
pub data: Option<Rows>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub next_cursor: Option<String>,
|
||||
#[prost(string, optional, tag = "3")]
|
||||
pub backwards_cursor: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct Rows {
|
||||
#[prost(bytes = "bytes", repeated, tag = "1")]
|
||||
pub values: Vec<Bytes>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ItemEntry {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub turn_id: Option<String>,
|
||||
#[prost(message, optional, tag = "2")]
|
||||
pub item: Option<crate::item_wire::Item>,
|
||||
#[prost(int64, optional, tag = "3")]
|
||||
pub started_at_ms: Option<i64>,
|
||||
#[prost(int64, optional, tag = "4")]
|
||||
pub completed_at_ms: Option<i64>,
|
||||
}
|
||||
@@ -1,399 +0,0 @@
|
||||
//! Item fixtures cover lifecycle order, outcomes, presence, and opaque fallback.
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use prost::Message;
|
||||
|
||||
const AGENT: &[u8] = b"\x1a\x06\x12\x01i\x32\x01d";
|
||||
|
||||
const COMMAND: &[u8] =
|
||||
b"\x0a\x00\x12\x01c\x1a\x07\x0a\x05\x22\x03\x0a\x01c\x22\x01w\x28\x00\x30\x00\x3a\x01i\x60\x03";
|
||||
|
||||
fn lifecycle(tag: u32, item: &[u8]) -> Vec<u8> {
|
||||
let (at_ms, emitted_at_ms) = if tag == 27 { (3, 7) } else { (5, 11) };
|
||||
let params = if tag == 27 {
|
||||
[
|
||||
message(/*tag*/ 1, item),
|
||||
vec![16, at_ms as u8],
|
||||
b"\x1a\x01t\x22\x01u".to_vec(),
|
||||
]
|
||||
.concat()
|
||||
} else {
|
||||
[
|
||||
vec![8, at_ms as u8],
|
||||
message(/*tag*/ 2, item),
|
||||
b"\x1a\x01t\x22\x01u".to_vec(),
|
||||
]
|
||||
.concat()
|
||||
};
|
||||
message(
|
||||
tag,
|
||||
&[vec![8, emitted_at_ms as u8], message(/*tag*/ 2, ¶ms)].concat(),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn item_lifecycle_keeps_identity_and_timestamps() {
|
||||
let payloads = [
|
||||
lifecycle(/*tag*/ 27, AGENT),
|
||||
notification(/*tag*/ 32, DELTA),
|
||||
lifecycle(/*tag*/ 31, AGENT),
|
||||
];
|
||||
let fixture = fixture(response(
|
||||
payloads
|
||||
.iter()
|
||||
.map(|payload| frame(&message(/*tag*/ 1, payload)))
|
||||
.collect(),
|
||||
tonic::Status::ok(""),
|
||||
))
|
||||
.await;
|
||||
let mut stream = fixture.client.attach("t").await.unwrap();
|
||||
let item = |at_ms| ItemLifecycle {
|
||||
turn_id: "u".into(),
|
||||
at_ms,
|
||||
item: ItemSummary::AgentMessage {
|
||||
id: "i".into(),
|
||||
text: "d".into(),
|
||||
questions: None,
|
||||
},
|
||||
};
|
||||
let expected = [
|
||||
(Some(7), TranscriptUpdate::ItemStarted(item(3))),
|
||||
(
|
||||
None,
|
||||
TranscriptUpdate::AgentMessageDelta(ItemDelta {
|
||||
item_id: "i".into(),
|
||||
turn_id: "u".into(),
|
||||
delta: "d".into(),
|
||||
}),
|
||||
),
|
||||
(Some(11), TranscriptUpdate::ItemCompleted(item(5))),
|
||||
];
|
||||
for (emitted_at_ms, update) in expected {
|
||||
let Event::Transcript(event) = stream.next().await.unwrap().unwrap() else {
|
||||
panic!("expected transcript event")
|
||||
};
|
||||
assert_eq!(
|
||||
(&event.thread_id, event.emitted_at_ms, &event.update),
|
||||
(&"t".to_owned(), emitted_at_ms, &update)
|
||||
);
|
||||
}
|
||||
assert!(stream.next().await.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_message_preserves_client_id_and_text() {
|
||||
let user = b"\x0a\x23\x0a\x09client-id\x12\x0b\x0a\x09\x0a\x07\x0a\x05hello\x1a\x09user-item";
|
||||
assert_eq!(
|
||||
summary(user),
|
||||
Some(ItemSummary::UserMessage {
|
||||
id: "user-item".into(),
|
||||
client_id: Some("client-id".into()),
|
||||
content: vec![UserMessageInput::Text {
|
||||
text: "hello".into(),
|
||||
text_elements: vec![]
|
||||
}],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_message_preserves_images_spans_and_client_id() {
|
||||
let url = "data:image/png;base64,AA==";
|
||||
let label = "[Image #1]";
|
||||
let element = [
|
||||
message(/*tag*/ 1, b"\x08\x0d\x10\x03"),
|
||||
message(/*tag*/ 2, label.as_bytes()),
|
||||
]
|
||||
.concat();
|
||||
let text = [
|
||||
message(/*tag*/ 1, "é [Image #1]".as_bytes()),
|
||||
message(/*tag*/ 2, &message(/*tag*/ 1, &element)),
|
||||
]
|
||||
.concat();
|
||||
let image_bytes = [vec![0x08, 99], message(/*tag*/ 2, url.as_bytes())].concat();
|
||||
let content = [
|
||||
message(/*tag*/ 1, &message(/*tag*/ 1, &text)),
|
||||
message(
|
||||
/*tag*/ 1,
|
||||
&message(/*tag*/ 2, &message(/*tag*/ 1, &image_bytes)),
|
||||
),
|
||||
]
|
||||
.concat();
|
||||
let user = message(
|
||||
/*tag*/ 1,
|
||||
&[
|
||||
message(/*tag*/ 1, b"client-id"),
|
||||
message(/*tag*/ 2, &content),
|
||||
message(/*tag*/ 3, b"user-item"),
|
||||
]
|
||||
.concat(),
|
||||
);
|
||||
let expected = ItemSummary::UserMessage {
|
||||
id: "user-item".into(),
|
||||
client_id: Some("client-id".into()),
|
||||
content: vec![
|
||||
UserMessageInput::Text {
|
||||
text: "é [Image #1]".into(),
|
||||
text_elements: vec![UserMessageTextElement {
|
||||
start: 3,
|
||||
end: 13,
|
||||
placeholder: Some(label.into()),
|
||||
}],
|
||||
},
|
||||
UserMessageInput::Image {
|
||||
image: ImageReference::Url(url.into()),
|
||||
detail: None,
|
||||
},
|
||||
],
|
||||
};
|
||||
assert_eq!(summary(&user), Some(expected.clone()));
|
||||
assert_eq!(format!("{expected:?}"), "ItemSummary([redacted])");
|
||||
let event = TranscriptEvent::decode("t", &lifecycle(/*tag*/ 31, &user))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
event.update,
|
||||
TranscriptUpdate::ItemCompleted(ItemLifecycle {
|
||||
turn_id: "u".into(),
|
||||
at_ms: 5,
|
||||
item: expected,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
fn summary(bytes: &[u8]) -> Option<ItemSummary> {
|
||||
crate::items::summary(crate::item_wire::Item::decode(bytes).unwrap())
|
||||
.unwrap_or_else(|_| panic!("expected supported item fields"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_and_patch_summaries_preserve_status_and_presence() {
|
||||
let command = CommandSummary {
|
||||
id: "i".into(),
|
||||
command: "c".into(),
|
||||
cwd: "w".into(),
|
||||
actions: vec![CommandAction::Unknown {
|
||||
command: "c".into(),
|
||||
}],
|
||||
source: CommandExecutionSource::Agent,
|
||||
aggregated_output: Some(String::new()),
|
||||
duration_ms: Some(0),
|
||||
exit_code: Some(0),
|
||||
status: ItemStatus::Failed,
|
||||
};
|
||||
assert_eq!(
|
||||
summary(&message(/*tag*/ 7, &[COMMAND, b"\x58\x02"].concat())),
|
||||
Some(ItemSummary::CommandExecution(CommandSummary {
|
||||
source: CommandExecutionSource::UserShell,
|
||||
..command.clone()
|
||||
}))
|
||||
);
|
||||
let change = b"\x0a\x01d\x12\x02\x0a\x00\x1a\x01p";
|
||||
for (wire_status, status) in [
|
||||
(1, ItemStatus::InProgress),
|
||||
(2, ItemStatus::Completed),
|
||||
(3, ItemStatus::Failed),
|
||||
(4, ItemStatus::Declined),
|
||||
(99, ItemStatus::Unknown(99)),
|
||||
] {
|
||||
assert_eq!(
|
||||
summary(&message(
|
||||
/*tag*/ 7,
|
||||
&[COMMAND, &[96, wire_status]].concat()
|
||||
)),
|
||||
Some(ItemSummary::CommandExecution(CommandSummary {
|
||||
status,
|
||||
..command.clone()
|
||||
}))
|
||||
);
|
||||
let patch = [
|
||||
message(/*tag*/ 1, &message(/*tag*/ 1, change)),
|
||||
b"\x12\x01i".to_vec(),
|
||||
vec![24, wire_status],
|
||||
]
|
||||
.concat();
|
||||
assert_eq!(
|
||||
summary(&message(/*tag*/ 8, &patch)),
|
||||
Some(ItemSummary::FileChange {
|
||||
id: "i".into(),
|
||||
changes: vec![FileUpdate {
|
||||
path: "p".into(),
|
||||
diff: "d".into(),
|
||||
kind: PatchKind::Add
|
||||
}],
|
||||
status,
|
||||
})
|
||||
);
|
||||
}
|
||||
// Lifecycle completion must not rewrite a failed command's outcome.
|
||||
for tag in [27, 31] {
|
||||
let event = TranscriptEvent::decode("t", &lifecycle(tag, &message(/*tag*/ 7, COMMAND)))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let (TranscriptUpdate::ItemStarted(item) | TranscriptUpdate::ItemCompleted(item)) =
|
||||
event.update
|
||||
else {
|
||||
panic!("expected item lifecycle");
|
||||
};
|
||||
assert_eq!(item.item, ItemSummary::CommandExecution(command.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reasoning_preserves_summary_and_content() {
|
||||
let reasoning = [
|
||||
message(/*tag*/ 1, &message(/*tag*/ 1, b"detail")),
|
||||
b"\x12\x01i".to_vec(),
|
||||
message(/*tag*/ 3, &message(/*tag*/ 1, b"summary")),
|
||||
]
|
||||
.concat();
|
||||
assert_eq!(
|
||||
summary(&message(/*tag*/ 6, &reasoning)),
|
||||
Some(ItemSummary::Reasoning {
|
||||
id: "i".into(),
|
||||
summary: vec!["summary".into()],
|
||||
content: vec!["detail".into()],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_messages_keep_questions_with_empty_text() {
|
||||
let choices = message(/*tag*/ 1, b"Continue");
|
||||
let questions = [
|
||||
message(/*tag*/ 1, &message(/*tag*/ 2, b"Freeform")),
|
||||
message(/*tag*/ 1, b"\x0a\x00\x12\x05Empty"),
|
||||
message(
|
||||
/*tag*/ 1,
|
||||
&[
|
||||
message(/*tag*/ 1, &choices),
|
||||
message(/*tag*/ 2, b"Proceed?"),
|
||||
]
|
||||
.concat(),
|
||||
),
|
||||
]
|
||||
.concat();
|
||||
let expected = vec![
|
||||
AgentQuestion {
|
||||
title: "Freeform".into(),
|
||||
options: None,
|
||||
},
|
||||
AgentQuestion {
|
||||
title: "Empty".into(),
|
||||
options: Some(vec![]),
|
||||
},
|
||||
AgentQuestion {
|
||||
title: "Proceed?".into(),
|
||||
options: Some(vec!["Continue".into()]),
|
||||
},
|
||||
];
|
||||
for (questions, expected) in [(questions.as_slice(), expected), (&[], vec![])] {
|
||||
let item = message(
|
||||
/*tag*/ 3,
|
||||
&[b"\x12\x01i\x32\x00".to_vec(), message(/*tag*/ 5, questions)].concat(),
|
||||
);
|
||||
assert_eq!(
|
||||
summary(&item),
|
||||
Some(ItemSummary::AgentMessage {
|
||||
id: "i".into(),
|
||||
text: String::new(),
|
||||
questions: Some(expected),
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_and_incomplete_items_stay_opaque() {
|
||||
let absent_time = [message(/*tag*/ 1, AGENT), b"\x1a\x01t\x22\x01u".to_vec()].concat();
|
||||
// A later audio variant replaces text in the same native UserInput oneof.
|
||||
let text_then_audio = b"\x0a\x03\x0a\x01x\x22\x03\x0a\x01u";
|
||||
let user_content = message(/*tag*/ 2, &message(/*tag*/ 1, text_then_audio));
|
||||
let opaque = [
|
||||
message(
|
||||
/*tag*/ 1,
|
||||
&[user_content, message(/*tag*/ 3, b"i")].concat(),
|
||||
),
|
||||
message(/*tag*/ 7, &[COMMAND, b"\x58\x63"].concat()), // Future command source (99).
|
||||
message(/*tag*/ 9, b""),
|
||||
message(/*tag*/ 20, b""),
|
||||
[AGENT.to_vec(), message(/*tag*/ 19, b"")].concat(),
|
||||
message(/*tag*/ 3, b"\x12\x01i"),
|
||||
message(/*tag*/ 7, b"\x12\x01c\x22\x01w\x3a\x01i"),
|
||||
message(/*tag*/ 8, b"\x12\x01i\x18\x01"),
|
||||
];
|
||||
for item in opaque {
|
||||
assert!(
|
||||
TranscriptEvent::decode("t", &lifecycle(/*tag*/ 27, &item))
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
for input in [
|
||||
message(/*tag*/ 8, b""), // Future input variant.
|
||||
message(/*tag*/ 2, &message(/*tag*/ 3, b"")), // Future image reference.
|
||||
message(/*tag*/ 2, &message(/*tag*/ 1, b"\x08\x01")), // Missing URL.
|
||||
message(/*tag*/ 2, &message(/*tag*/ 2, b"")), // Missing file ID.
|
||||
message(
|
||||
/*tag*/ 1,
|
||||
&[
|
||||
message(/*tag*/ 1, b"hello"),
|
||||
message(/*tag*/ 2, &message(/*tag*/ 1, b"")), // Missing byte range.
|
||||
]
|
||||
.concat(),
|
||||
),
|
||||
message(
|
||||
/*tag*/ 1,
|
||||
&[
|
||||
message(/*tag*/ 1, b"hello"),
|
||||
message(
|
||||
/*tag*/ 2,
|
||||
&message(/*tag*/ 1, &message(/*tag*/ 1, b"\x08\x01")),
|
||||
), // Missing start.
|
||||
]
|
||||
.concat(),
|
||||
),
|
||||
] {
|
||||
let user = message(
|
||||
/*tag*/ 1,
|
||||
&[
|
||||
message(/*tag*/ 1, b"client-id"),
|
||||
message(/*tag*/ 2, &message(/*tag*/ 1, &input)),
|
||||
message(/*tag*/ 3, b"user-item"),
|
||||
]
|
||||
.concat(),
|
||||
);
|
||||
assert!(
|
||||
TranscriptEvent::decode("t", &lifecycle(/*tag*/ 27, &user))
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
TranscriptEvent::decode("t", ¬ification(/*tag*/ 27, &absent_time))
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn item_decoder_rejects_malformed_items_and_foreign_owners() {
|
||||
assert!(TranscriptEvent::decode("t", &lifecycle(/*tag*/ 27, &[0xff])).is_err());
|
||||
assert!(TranscriptEvent::decode("other", &lifecycle(/*tag*/ 31, AGENT)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn item_summaries_redact_sensitive_fields() {
|
||||
let item = ItemSummary::AgentMessage {
|
||||
questions: None,
|
||||
id: "secret".into(),
|
||||
text: "secret".into(),
|
||||
};
|
||||
let text = format!("{item:?}");
|
||||
assert_eq!(text, "ItemSummary([redacted])");
|
||||
assert!(!text.contains("secret"));
|
||||
let action = CommandAction::Unknown {
|
||||
command: "secret".into(),
|
||||
};
|
||||
assert_eq!(format!("{action:?}"), "CommandAction([redacted])");
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
//! Native item lifecycle envelopes and the item fields used by typed events.
|
||||
use prost::Message;
|
||||
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct Started {
|
||||
#[prost(message, optional, tag = "1")]
|
||||
pub item: Option<Item>,
|
||||
#[prost(int64, optional, tag = "2")]
|
||||
pub at_ms: Option<i64>,
|
||||
#[prost(string, optional, tag = "3")]
|
||||
pub thread_id: Option<String>,
|
||||
#[prost(string, optional, tag = "4")]
|
||||
pub turn_id: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct Completed {
|
||||
#[prost(int64, optional, tag = "1")]
|
||||
pub at_ms: Option<i64>,
|
||||
#[prost(message, optional, tag = "2")]
|
||||
pub item: Option<Item>,
|
||||
#[prost(string, optional, tag = "3")]
|
||||
pub thread_id: Option<String>,
|
||||
#[prost(string, optional, tag = "4")]
|
||||
pub turn_id: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct Item {
|
||||
#[prost(
|
||||
oneof = "Value",
|
||||
tags = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19"
|
||||
)]
|
||||
pub value: Option<Value>,
|
||||
}
|
||||
#[derive(Clone, prost::Oneof)]
|
||||
pub(super) enum Value {
|
||||
#[prost(message, tag = "1")]
|
||||
UserMessage(UserMessage),
|
||||
#[prost(bytes, tag = "2")]
|
||||
HookPrompt(Vec<u8>),
|
||||
#[prost(message, tag = "3")]
|
||||
AgentMessage(AgentMessage),
|
||||
#[prost(bytes, tag = "4")]
|
||||
FunctionCallOutput(Vec<u8>),
|
||||
#[prost(bytes, tag = "5")]
|
||||
Plan(Vec<u8>),
|
||||
#[prost(message, tag = "6")]
|
||||
Reasoning(Reasoning),
|
||||
#[prost(message, tag = "7")]
|
||||
Command(Command),
|
||||
#[prost(message, tag = "8")]
|
||||
FileChange(FileChange),
|
||||
#[prost(bytes, tag = "9")]
|
||||
Mcp(Vec<u8>),
|
||||
#[prost(bytes, tag = "10")]
|
||||
DynamicTool(Vec<u8>),
|
||||
#[prost(bytes, tag = "11")]
|
||||
CollabAgent(Vec<u8>),
|
||||
#[prost(bytes, tag = "12")]
|
||||
SubAgent(Vec<u8>),
|
||||
#[prost(bytes, tag = "13")]
|
||||
WebSearch(Vec<u8>),
|
||||
#[prost(bytes, tag = "14")]
|
||||
ImageView(Vec<u8>),
|
||||
#[prost(bytes, tag = "15")]
|
||||
Sleep(Vec<u8>),
|
||||
#[prost(bytes, tag = "16")]
|
||||
ImageGeneration(Vec<u8>),
|
||||
#[prost(bytes, tag = "17")]
|
||||
EnterReview(Vec<u8>),
|
||||
#[prost(bytes, tag = "18")]
|
||||
ExitReview(Vec<u8>),
|
||||
#[prost(bytes, tag = "19")]
|
||||
Compaction(Vec<u8>),
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct AgentMessage {
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub id: Option<String>,
|
||||
#[prost(message, optional, tag = "5")]
|
||||
pub questions: Option<AgentQuestionList>,
|
||||
#[prost(string, optional, tag = "6")]
|
||||
pub text: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct AgentQuestionList {
|
||||
#[prost(message, repeated, tag = "1")]
|
||||
pub values: Vec<AgentQuestion>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct AgentQuestion {
|
||||
#[prost(message, optional, tag = "1")]
|
||||
pub options: Option<StringList>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub title: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct Command {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub output: Option<String>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub command: Option<String>,
|
||||
#[prost(message, optional, tag = "3")]
|
||||
pub actions: Option<CommandActionList>,
|
||||
#[prost(string, optional, tag = "4")]
|
||||
pub cwd: Option<String>,
|
||||
#[prost(int64, optional, tag = "5")]
|
||||
pub duration_ms: Option<i64>,
|
||||
#[prost(int64, optional, tag = "6")]
|
||||
pub exit_code: Option<i64>,
|
||||
#[prost(string, optional, tag = "7")]
|
||||
pub id: Option<String>,
|
||||
#[prost(int32, optional, tag = "11")]
|
||||
pub source: Option<i32>,
|
||||
#[prost(int32, optional, tag = "12")]
|
||||
pub status: Option<i32>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct Reasoning {
|
||||
#[prost(message, optional, tag = "1")]
|
||||
pub content: Option<StringList>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub id: Option<String>,
|
||||
#[prost(message, optional, tag = "3")]
|
||||
pub summary: Option<StringList>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct StringList {
|
||||
#[prost(string, repeated, tag = "1")]
|
||||
pub values: Vec<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct CommandActionList {
|
||||
#[prost(message, repeated, tag = "1")]
|
||||
pub values: Vec<CommandAction>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct CommandAction {
|
||||
#[prost(oneof = "command_action::Value", tags = "1, 2, 3, 4")]
|
||||
pub value: Option<command_action::Value>,
|
||||
}
|
||||
pub(super) mod command_action {
|
||||
#[derive(Clone, prost::Oneof)]
|
||||
pub enum Value {
|
||||
#[prost(message, tag = "1")]
|
||||
Read(super::ReadAction),
|
||||
#[prost(message, tag = "2")]
|
||||
ListFiles(super::ListFilesAction),
|
||||
#[prost(message, tag = "3")]
|
||||
Search(super::SearchAction),
|
||||
#[prost(message, tag = "4")]
|
||||
Unknown(super::UnknownAction),
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ReadAction {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub command: Option<String>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub name: Option<String>,
|
||||
#[prost(string, optional, tag = "3")]
|
||||
pub path: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ListFilesAction {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub command: Option<String>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub path: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct SearchAction {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub command: Option<String>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub path: Option<String>,
|
||||
#[prost(string, optional, tag = "3")]
|
||||
pub query: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct UnknownAction {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub command: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct FileChange {
|
||||
#[prost(message, optional, tag = "1")]
|
||||
pub changes: Option<crate::transcript_wire::Changes>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub id: Option<String>,
|
||||
#[prost(int32, optional, tag = "3")]
|
||||
pub status: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct UserMessage {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub client_id: Option<String>,
|
||||
#[prost(message, optional, tag = "2")]
|
||||
pub content: Option<crate::turns_wire::Input>,
|
||||
#[prost(string, optional, tag = "3")]
|
||||
pub id: Option<String>,
|
||||
}
|
||||
@@ -1,313 +0,0 @@
|
||||
//! Selected item summaries for live start/completion events, without interpreting executor paths.
|
||||
use crate::FileUpdate;
|
||||
use crate::ImageDetail;
|
||||
use crate::ImageReference;
|
||||
use crate::TranscriptUpdate;
|
||||
use crate::UserMessageInput;
|
||||
use crate::UserMessageTextElement;
|
||||
use crate::item_wire as wire;
|
||||
use crate::transcript::DecodeFailure;
|
||||
use crate::transcript::ITEM_STARTED;
|
||||
use crate::transcript::required;
|
||||
use crate::transcript_wire::Envelope;
|
||||
use crate::transcript_wire::SelectedMessages;
|
||||
use crate::transcript_wire::merge_messages;
|
||||
use std::fmt;
|
||||
|
||||
/// Lifecycle identity and timestamp for a typed item event.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct ItemLifecycle {
|
||||
pub turn_id: String,
|
||||
/// Start or completion time in Unix milliseconds, according to the event variant.
|
||||
pub at_ms: i64,
|
||||
pub item: ItemSummary,
|
||||
}
|
||||
/// Selected fields only; this is not a complete display model.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub enum ItemSummary {
|
||||
UserMessage {
|
||||
id: String,
|
||||
client_id: Option<String>,
|
||||
content: Vec<UserMessageInput>,
|
||||
},
|
||||
AgentMessage {
|
||||
id: String,
|
||||
text: String,
|
||||
questions: Option<Vec<AgentQuestion>>,
|
||||
},
|
||||
Reasoning {
|
||||
id: String,
|
||||
summary: Vec<String>,
|
||||
content: Vec<String>,
|
||||
},
|
||||
CommandExecution(CommandSummary),
|
||||
FileChange {
|
||||
id: String,
|
||||
changes: Vec<FileUpdate>,
|
||||
status: ItemStatus,
|
||||
},
|
||||
}
|
||||
/// A structured question attached to an agent message.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct AgentQuestion {
|
||||
pub title: String,
|
||||
pub options: Option<Vec<String>>,
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct CommandSummary {
|
||||
pub id: String,
|
||||
pub command: String,
|
||||
/// Executor-native path. Do not interpret it as a path on the client machine.
|
||||
pub cwd: String,
|
||||
pub actions: Vec<CommandAction>,
|
||||
pub source: CommandExecutionSource,
|
||||
pub aggregated_output: Option<String>,
|
||||
pub duration_ms: Option<i64>,
|
||||
pub exit_code: Option<i64>,
|
||||
pub status: ItemStatus,
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub enum CommandAction {
|
||||
Read {
|
||||
command: String,
|
||||
name: String,
|
||||
path: String,
|
||||
},
|
||||
ListFiles {
|
||||
command: String,
|
||||
path: Option<String>,
|
||||
},
|
||||
Search {
|
||||
command: String,
|
||||
query: Option<String>,
|
||||
path: Option<String>,
|
||||
},
|
||||
Unknown {
|
||||
command: String,
|
||||
},
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CommandExecutionSource {
|
||||
Agent,
|
||||
UserShell,
|
||||
UnifiedExecStartup,
|
||||
UnifiedExecInteraction,
|
||||
}
|
||||
/// CommandExecutionStatus and PatchApplyStatus share these wire values.
|
||||
/// Completion of the item lifecycle does not imply the command or patch succeeded.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ItemStatus {
|
||||
InProgress,
|
||||
Completed,
|
||||
Failed,
|
||||
Declined,
|
||||
Unknown(i32),
|
||||
}
|
||||
impl From<i32> for ItemStatus {
|
||||
fn from(value: i32) -> Self {
|
||||
match value {
|
||||
1 => Self::InProgress,
|
||||
2 => Self::Completed,
|
||||
3 => Self::Failed,
|
||||
4 => Self::Declined,
|
||||
value => Self::Unknown(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
macro_rules! redacted_debug {
|
||||
($($ty:ty),*) => {$(impl fmt::Debug for $ty {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(concat!(stringify!($ty), "([redacted])"))
|
||||
}
|
||||
})*};
|
||||
}
|
||||
redacted_debug!(
|
||||
ItemLifecycle,
|
||||
ItemSummary,
|
||||
AgentQuestion,
|
||||
CommandSummary,
|
||||
CommandAction
|
||||
);
|
||||
|
||||
pub(crate) fn decode(
|
||||
tag: u32,
|
||||
values: SelectedMessages<'_>,
|
||||
) -> Result<Option<(String, Option<i64>, TranscriptUpdate)>, DecodeFailure> {
|
||||
let (thread_id, turn_id, at_ms, item, emitted_at_ms) = if tag == ITEM_STARTED {
|
||||
let envelope = merge_messages::<Envelope<wire::Started>>(values)?;
|
||||
let params = required(envelope.params)?;
|
||||
(
|
||||
params.thread_id,
|
||||
params.turn_id,
|
||||
params.at_ms,
|
||||
params.item,
|
||||
envelope.emitted_at_ms,
|
||||
)
|
||||
} else {
|
||||
let envelope = merge_messages::<Envelope<wire::Completed>>(values)?;
|
||||
let params = required(envelope.params)?;
|
||||
(
|
||||
params.thread_id,
|
||||
params.turn_id,
|
||||
params.at_ms,
|
||||
params.item,
|
||||
envelope.emitted_at_ms,
|
||||
)
|
||||
};
|
||||
let Some(item) = summary(required(item)?)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let lifecycle = ItemLifecycle {
|
||||
turn_id: required(turn_id)?,
|
||||
at_ms: required(at_ms)?,
|
||||
item,
|
||||
};
|
||||
let update = if tag == ITEM_STARTED {
|
||||
TranscriptUpdate::ItemStarted(lifecycle)
|
||||
} else {
|
||||
TranscriptUpdate::ItemCompleted(lifecycle)
|
||||
};
|
||||
Ok(Some((required(thread_id)?, emitted_at_ms, update)))
|
||||
}
|
||||
|
||||
pub(crate) fn summary(item: wire::Item) -> Result<Option<ItemSummary>, DecodeFailure> {
|
||||
let summary = match item.value {
|
||||
Some(wire::Value::UserMessage(value)) => {
|
||||
let mut content = Vec::new();
|
||||
for input in required(value.content)?.values {
|
||||
let input = match input.value {
|
||||
Some(crate::turns_wire::Value::Text(input)) => {
|
||||
let text = required(input.text)?;
|
||||
let text_elements = input
|
||||
.text_elements
|
||||
.map_or_else(Vec::new, |elements| elements.values)
|
||||
.into_iter()
|
||||
.map(|element| {
|
||||
let range = required(element.byte_range)?;
|
||||
let start = usize::try_from(required(range.start)?)
|
||||
.map_err(|_| DecodeFailure::MissingField)?;
|
||||
let end = usize::try_from(required(range.end)?)
|
||||
.map_err(|_| DecodeFailure::MissingField)?;
|
||||
text.get(start..end).ok_or(DecodeFailure::MissingField)?;
|
||||
Ok(UserMessageTextElement {
|
||||
start,
|
||||
end,
|
||||
placeholder: element.placeholder,
|
||||
})
|
||||
})
|
||||
.collect::<Result<_, DecodeFailure>>()?;
|
||||
UserMessageInput::Text {
|
||||
text,
|
||||
text_elements,
|
||||
}
|
||||
}
|
||||
Some(crate::turns_wire::Value::Image(input)) => {
|
||||
let (image, detail) = match input.value {
|
||||
Some(crate::turns_wire::ImageValue::Url(image)) => {
|
||||
(ImageReference::Url(required(image.value)?), image.detail)
|
||||
}
|
||||
Some(crate::turns_wire::ImageValue::FileId(image)) => {
|
||||
(ImageReference::FileId(required(image.value)?), image.detail)
|
||||
}
|
||||
None => return Ok(None),
|
||||
};
|
||||
let detail = match detail {
|
||||
Some(1) => Some(ImageDetail::Auto),
|
||||
Some(2) => Some(ImageDetail::Low),
|
||||
Some(3) => Some(ImageDetail::High),
|
||||
Some(4) => Some(ImageDetail::Original),
|
||||
// Detail is display metadata. Keep the receipt identity if it is newer.
|
||||
None | Some(_) => None,
|
||||
};
|
||||
UserMessageInput::Image { image, detail }
|
||||
}
|
||||
_ => return Ok(None),
|
||||
};
|
||||
content.push(input);
|
||||
}
|
||||
ItemSummary::UserMessage {
|
||||
id: required(value.id)?,
|
||||
client_id: value.client_id,
|
||||
content,
|
||||
}
|
||||
}
|
||||
Some(wire::Value::AgentMessage(value)) => ItemSummary::AgentMessage {
|
||||
id: required(value.id)?,
|
||||
text: required(value.text)?,
|
||||
questions: value
|
||||
.questions
|
||||
.map(|questions| {
|
||||
questions
|
||||
.values
|
||||
.into_iter()
|
||||
.map(|question| {
|
||||
Ok(AgentQuestion {
|
||||
title: required(question.title)?,
|
||||
options: question.options.map(|options| options.values),
|
||||
})
|
||||
})
|
||||
.collect::<Result<_, DecodeFailure>>()
|
||||
})
|
||||
.transpose()?,
|
||||
},
|
||||
Some(wire::Value::Reasoning(value)) => ItemSummary::Reasoning {
|
||||
id: required(value.id)?,
|
||||
summary: value.summary.map_or_else(Vec::new, |value| value.values),
|
||||
content: value.content.map_or_else(Vec::new, |value| value.values),
|
||||
},
|
||||
Some(wire::Value::Command(value)) => ItemSummary::CommandExecution(CommandSummary {
|
||||
id: required(value.id)?,
|
||||
command: required(value.command)?,
|
||||
cwd: required(value.cwd)?,
|
||||
actions: required(value.actions)?
|
||||
.values
|
||||
.into_iter()
|
||||
.map(command_action)
|
||||
.collect::<Result<_, _>>()?,
|
||||
status: required(value.status)?.into(),
|
||||
source: match value.source {
|
||||
None | Some(1) => CommandExecutionSource::Agent,
|
||||
Some(2) => CommandExecutionSource::UserShell,
|
||||
Some(3) => CommandExecutionSource::UnifiedExecStartup,
|
||||
Some(4) => CommandExecutionSource::UnifiedExecInteraction,
|
||||
Some(_) => return Ok(None),
|
||||
},
|
||||
aggregated_output: value.output,
|
||||
duration_ms: value.duration_ms,
|
||||
exit_code: value.exit_code,
|
||||
}),
|
||||
Some(wire::Value::FileChange(value)) => ItemSummary::FileChange {
|
||||
id: required(value.id)?,
|
||||
changes: required(value.changes)?
|
||||
.values
|
||||
.into_iter()
|
||||
.map(FileUpdate::try_from)
|
||||
.collect::<Result<_, _>>()?,
|
||||
status: required(value.status)?.into(),
|
||||
},
|
||||
_ => return Ok(None),
|
||||
};
|
||||
Ok(Some(summary))
|
||||
}
|
||||
|
||||
fn command_action(action: wire::CommandAction) -> Result<CommandAction, DecodeFailure> {
|
||||
Ok(match required(action.value)? {
|
||||
wire::command_action::Value::Read(value) => CommandAction::Read {
|
||||
command: required(value.command)?,
|
||||
name: required(value.name)?,
|
||||
path: required(value.path)?,
|
||||
},
|
||||
wire::command_action::Value::ListFiles(value) => CommandAction::ListFiles {
|
||||
command: required(value.command)?,
|
||||
path: value.path,
|
||||
},
|
||||
wire::command_action::Value::Search(value) => CommandAction::Search {
|
||||
command: required(value.command)?,
|
||||
query: value.query,
|
||||
path: value.path,
|
||||
},
|
||||
wire::command_action::Value::Unknown(value) => CommandAction::Unknown {
|
||||
command: required(value.command)?,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,275 +0,0 @@
|
||||
//! Native gRPC client for the Codex cloud ThreadService, using shared HTTP transport policy.
|
||||
//!
|
||||
//! Credentials and account selection belong to the caller. Requests are never retried:
|
||||
//! a timeout or disconnect can leave Resume admitted. Attach delivers live events only;
|
||||
//! dropping its stream detaches without interrupting the thread or answering approvals.
|
||||
|
||||
mod activation;
|
||||
mod activation_wire;
|
||||
mod discovery;
|
||||
mod history;
|
||||
mod history_wire;
|
||||
mod item_wire;
|
||||
mod items;
|
||||
mod prewarm;
|
||||
mod transcript;
|
||||
mod transcript_wire;
|
||||
mod turns;
|
||||
mod turns_wire;
|
||||
mod types;
|
||||
mod wire;
|
||||
|
||||
pub use activation::ActivePermissionProfile;
|
||||
pub use activation::ApprovalPolicy;
|
||||
pub use activation::ApprovalsReviewer;
|
||||
pub use activation::CollaborationMode;
|
||||
pub use activation::CollaborationSettings;
|
||||
pub use activation::GitInfo;
|
||||
pub use activation::NetworkAccess;
|
||||
pub use activation::SandboxPolicy;
|
||||
pub use activation::SessionSource;
|
||||
pub use activation::SubAgentSource;
|
||||
pub use activation::ThreadActivation;
|
||||
pub use activation::ThreadActiveFlag;
|
||||
pub use activation::ThreadEnvironment;
|
||||
pub use activation::ThreadHistoryMode;
|
||||
pub use activation::ThreadSnapshot;
|
||||
pub use activation::ThreadStatus;
|
||||
pub use discovery::ThreadListQuery;
|
||||
pub use discovery::ThreadPage;
|
||||
pub use discovery::ThreadReadState;
|
||||
pub use discovery::ThreadSortDirection;
|
||||
pub use discovery::ThreadSortKey;
|
||||
pub use discovery::ThreadUnreadPosition;
|
||||
pub use history::HistoryAccess;
|
||||
pub use history::HistoryItem;
|
||||
pub use history::HistoryOrder;
|
||||
pub use history::HistoryPage;
|
||||
pub use history::HistoryQuery;
|
||||
pub use history::HistoryTurn;
|
||||
pub use history::ListItemsRequest;
|
||||
pub use history::ListTurnsRequest;
|
||||
pub use items::AgentQuestion;
|
||||
pub use items::CommandAction;
|
||||
pub use items::CommandExecutionSource;
|
||||
pub use items::CommandSummary;
|
||||
pub use items::ItemLifecycle;
|
||||
pub use items::ItemStatus;
|
||||
pub use items::ItemSummary;
|
||||
pub use prewarm::ProjectEnvironment;
|
||||
pub use transcript::FileUpdate;
|
||||
pub use transcript::ItemDelta;
|
||||
pub use transcript::PatchKind;
|
||||
pub use transcript::PatchUpdate;
|
||||
pub use transcript::TranscriptEvent;
|
||||
pub use transcript::TranscriptUpdate;
|
||||
pub use transcript::TurnFailure;
|
||||
pub use transcript::TurnStatus;
|
||||
pub use transcript::TurnSummary;
|
||||
pub use turns::AddUserMessageRequest;
|
||||
pub use turns::Admission;
|
||||
pub use turns::AdmissionOutcome;
|
||||
pub use turns::ImageDetail;
|
||||
pub use turns::ImageReference;
|
||||
pub use turns::InterruptTurnRequest;
|
||||
pub use turns::MutationError;
|
||||
pub use turns::SubmissionMode;
|
||||
pub use turns::UserMessageInput;
|
||||
pub use turns::UserMessageTextElement;
|
||||
pub use types::Credentials;
|
||||
pub use types::Error;
|
||||
pub use types::Event;
|
||||
pub use types::ResumeRequest;
|
||||
pub use types::RpcStatus;
|
||||
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::HttpClientBuilder;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use futures::StreamExt;
|
||||
use futures::stream::BoxStream;
|
||||
use http_body_util::BodyExt;
|
||||
use std::io;
|
||||
use std::time::Duration;
|
||||
use tonic::body::Body;
|
||||
use tonic::client::Grpc;
|
||||
use tonic_prost::ProstCodec;
|
||||
use tower::service_fn;
|
||||
use tower::util::BoxCloneSyncService;
|
||||
use url::Url;
|
||||
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(150);
|
||||
const MAX_MESSAGE_BYTES: usize = 64 * 1024 * 1024;
|
||||
type Transport = BoxCloneSyncService<http::Request<Body>, http::Response<Body>, io::Error>;
|
||||
|
||||
/// One fixed origin and account. Construct a new client when credentials change.
|
||||
/// Supply a trusted native gRPC origin, without a path (not the HTTP `/grpc` gateway).
|
||||
pub struct Client {
|
||||
grpc: Grpc<Transport>,
|
||||
credentials: Credentials,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
async fn raw_unary<T: prost::Message + Send + 'static>(
|
||||
&self,
|
||||
value: T,
|
||||
path: &'static str,
|
||||
) -> Result<bytes::Bytes, Error> {
|
||||
let mut grpc = self.grpc.clone();
|
||||
let mut request = tonic::Request::new(value);
|
||||
*request.metadata_mut() =
|
||||
tonic::metadata::MetadataMap::from_headers(self.credentials.headers.clone());
|
||||
let response = tokio::time::timeout(
|
||||
REQUEST_TIMEOUT,
|
||||
grpc.unary(
|
||||
request,
|
||||
http::uri::PathAndQuery::from_static(path),
|
||||
wire::RawResponseCodec::<T>(std::marker::PhantomData),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| Error::Timeout)?
|
||||
.map_err(Error::from)?;
|
||||
Ok(response.into_inner())
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
factory: &HttpClientFactory,
|
||||
endpoint: &str,
|
||||
credentials: Credentials,
|
||||
) -> Result<Self, Error> {
|
||||
let endpoint = Url::parse(endpoint).map_err(|_| Error::InvalidEndpoint)?;
|
||||
let loopback = match endpoint.host() {
|
||||
Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
|
||||
Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
|
||||
Some(url::Host::Domain(name)) => name == "localhost",
|
||||
None => false,
|
||||
};
|
||||
if (endpoint.scheme() != "https" && !(endpoint.scheme() == "http" && loopback))
|
||||
|| !endpoint.username().is_empty()
|
||||
|| endpoint.password().is_some()
|
||||
|| endpoint.query().is_some()
|
||||
|| endpoint.fragment().is_some()
|
||||
|| endpoint.path() != "/"
|
||||
{
|
||||
return Err(Error::InvalidEndpoint);
|
||||
}
|
||||
let local_http = endpoint.scheme() == "http";
|
||||
if local_http
|
||||
&& (factory.network_policy().is_managed()
|
||||
|| factory
|
||||
.network_policy()
|
||||
.acquire_for_unsupported_sdk()
|
||||
.is_err())
|
||||
{
|
||||
return Err(Error::InvalidEndpoint);
|
||||
}
|
||||
let builder = HttpClientBuilder::new()
|
||||
.without_redirects()
|
||||
.without_request_logging()
|
||||
.http2_prior_knowledge()
|
||||
.connect_timeout(Duration::from_secs(30));
|
||||
let http = if local_http {
|
||||
// Plaintext credentials must never leave loopback through an outbound proxy.
|
||||
builder.build_direct().map_err(|_| Error::ClientBuild)?
|
||||
} else {
|
||||
RouteAwareClientPool::with_builder(factory.clone(), ClientRouteClass::Api, builder)
|
||||
.into_client()
|
||||
};
|
||||
let origin = endpoint
|
||||
.as_str()
|
||||
.parse()
|
||||
.map_err(|_| Error::InvalidEndpoint)?;
|
||||
let transport = service_fn(move |request: http::Request<Body>| {
|
||||
let http = http.clone();
|
||||
async move {
|
||||
let (parts, body) = request.into_parts();
|
||||
let response = http
|
||||
.request(parts.method, parts.uri.to_string())
|
||||
.version(parts.version)
|
||||
.headers(parts.headers)
|
||||
.body_stream(body.into_data_stream())
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| io::Error::other("gRPC transport failed"))?;
|
||||
Ok(response.into_http_response().map(Body::new))
|
||||
}
|
||||
});
|
||||
Ok(Self {
|
||||
grpc: Grpc::with_origin(BoxCloneSyncService::new(transport), origin)
|
||||
.max_decoding_message_size(MAX_MESSAGE_BYTES)
|
||||
.max_encoding_message_size(MAX_MESSAGE_BYTES),
|
||||
credentials,
|
||||
})
|
||||
}
|
||||
|
||||
/// With `wait: false`, success means admission only. Failures may leave work admitted.
|
||||
pub async fn resume(&self, request: &ResumeRequest) -> Result<(), Error> {
|
||||
let mut grpc = self.grpc.clone();
|
||||
let mut request = tonic::Request::new(request.clone());
|
||||
*request.metadata_mut() =
|
||||
tonic::metadata::MetadataMap::from_headers(self.credentials.headers.clone());
|
||||
// Bound the whole unary RPC, including its response body and trailers.
|
||||
tokio::time::timeout(
|
||||
REQUEST_TIMEOUT,
|
||||
grpc.unary(
|
||||
request,
|
||||
http::uri::PathAndQuery::from_static(
|
||||
"/oaiproto.codex_app_server_backend.ThreadService/Resume",
|
||||
),
|
||||
ProstCodec::<ResumeRequest, wire::ResumeResponse>::default(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| Error::Timeout)?
|
||||
.map_err(Error::from)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Live events only, without history or automatic reconnect. The stream terminates
|
||||
/// on its first error. Setup is bounded; there is no idle or total stream deadline.
|
||||
pub async fn attach(
|
||||
&self,
|
||||
thread_id: &str,
|
||||
) -> Result<BoxStream<'static, Result<Event, Error>>, Error> {
|
||||
let mut grpc = self.grpc.clone();
|
||||
let mut request = tonic::Request::new(wire::AttachRequest {
|
||||
thread_id: thread_id.to_owned(),
|
||||
});
|
||||
*request.metadata_mut() =
|
||||
tonic::metadata::MetadataMap::from_headers(self.credentials.headers.clone());
|
||||
let response = tokio::time::timeout(
|
||||
REQUEST_TIMEOUT,
|
||||
grpc.server_streaming(
|
||||
request,
|
||||
http::uri::PathAndQuery::from_static(
|
||||
"/oaiproto.codex_app_server_backend.ThreadService/Attach",
|
||||
),
|
||||
ProstCodec::<wire::AttachRequest, wire::AttachResponse>::default(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| Error::Timeout)?
|
||||
.map_err(Error::from)?;
|
||||
let mut stream = response.into_inner();
|
||||
let thread_id = thread_id.to_owned();
|
||||
Ok(async_stream::try_stream! {
|
||||
while let Some(message) = stream.message().await.map_err(Error::from)? {
|
||||
yield match message.event.ok_or(Error::InvalidResponse)? {
|
||||
wire::Payload::Notification(bytes) => {
|
||||
match TranscriptEvent::decode(&thread_id, &bytes)? {
|
||||
Some(event) => Event::Transcript(Box::new(event)),
|
||||
None => Event::Notification(bytes),
|
||||
}
|
||||
},
|
||||
wire::Payload::ServerRequest(bytes) => Event::ServerRequest(bytes),
|
||||
};
|
||||
}
|
||||
}
|
||||
.boxed())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "client_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,185 +0,0 @@
|
||||
//! Prepare an ordinary cloud coding thread with server-owned managed environment defaults.
|
||||
|
||||
use crate::Client;
|
||||
use crate::Error;
|
||||
use bytes::Bytes;
|
||||
use bytes::BytesMut;
|
||||
use prost::Message;
|
||||
|
||||
/// A local project's GitHub origins to provision in the default cloud environment.
|
||||
/// Callers must supply credential-free origin URLs; this client does not inspect local Git state.
|
||||
#[derive(Clone)]
|
||||
pub struct ProjectEnvironment {
|
||||
pub name: String,
|
||||
pub origin_urls: Vec<String>,
|
||||
/// Working directory inside the managed environment, when a project selects one.
|
||||
pub cwd: Option<String>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ProjectEnvironment {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("ProjectEnvironment([redacted])")
|
||||
}
|
||||
}
|
||||
|
||||
impl Client {
|
||||
/// Prewarm an ordinary coding thread in the default managed environment.
|
||||
/// The service makes it discoverable when it admits the first user message.
|
||||
/// This mutation is never retried. A timeout or disconnect can leave a thread
|
||||
/// prepared even if its identity and settings were not received. The caller
|
||||
/// must not use this ordinary-thread API for an ephemeral session.
|
||||
pub async fn prewarm_default_thread(
|
||||
&self,
|
||||
model: Option<String>,
|
||||
model_provider: Option<String>,
|
||||
) -> Result<crate::ThreadActivation, Error> {
|
||||
self.prewarm_thread(model, model_provider, /*project*/ None)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Prewarm a coding thread, deferring executor readiness for a selected project checkout.
|
||||
pub async fn prewarm_thread(
|
||||
&self,
|
||||
model: Option<String>,
|
||||
model_provider: Option<String>,
|
||||
project: Option<ProjectEnvironment>,
|
||||
) -> Result<crate::ThreadActivation, Error> {
|
||||
let deferred_environment = project.is_some().then_some(true);
|
||||
let managed = match project {
|
||||
Some(ProjectEnvironment {
|
||||
name,
|
||||
origin_urls,
|
||||
cwd,
|
||||
}) => wire::ManagedEnvironment {
|
||||
environment_config_id: Some("asenvcfg_base".to_owned()),
|
||||
cwd,
|
||||
overrides: Some(wire::EnvironmentOverrides {
|
||||
repositories: Some(wire::RepositoryOverrides {
|
||||
values: origin_urls
|
||||
.into_iter()
|
||||
.map(|origin_url| wire::RepositoryOverride {
|
||||
origin_url: Some(origin_url),
|
||||
})
|
||||
.collect(),
|
||||
}),
|
||||
name: Some(name),
|
||||
}),
|
||||
},
|
||||
None => wire::ManagedEnvironment::default(),
|
||||
};
|
||||
let response = self
|
||||
.raw_unary(
|
||||
wire::PrewarmRequest {
|
||||
model,
|
||||
model_provider,
|
||||
deferred_environment,
|
||||
environments: Some(wire::EnvironmentList {
|
||||
values: vec![wire::EnvironmentSelection {
|
||||
managed: Some(managed),
|
||||
}],
|
||||
}),
|
||||
},
|
||||
"/oaiproto.codex_app_server_backend.ThreadService/Prewarm",
|
||||
)
|
||||
.await?;
|
||||
let warm = wire::PrewarmResponse::decode(response).map_err(|_| Error::InvalidResponse)?;
|
||||
// PrewarmThread omits turns, but the native Thread requires an empty
|
||||
// ThreadTurns message. Prefix it so the original wire bytes, including
|
||||
// unknown fields, are preserved and malformed trailing data stays invalid.
|
||||
let mut thread = BytesMut::new();
|
||||
prost::encoding::bytes::encode(/* tag */ 31, &Bytes::new(), &mut thread);
|
||||
thread.extend_from_slice(&warm.thread.ok_or(Error::InvalidResponse)?);
|
||||
|
||||
crate::ThreadActivation::from_settings(crate::activation_wire::UpdateConfigResponse {
|
||||
active_permission_profile: warm.active_permission_profile,
|
||||
approval_policy: warm.approval_policy,
|
||||
approvals_reviewer: warm.approvals_reviewer,
|
||||
cwd: warm.cwd,
|
||||
model: warm.model,
|
||||
model_provider: warm.model_provider,
|
||||
reasoning_effort: warm.reasoning_effort,
|
||||
runtime_workspace_roots: warm.runtime_workspace_roots,
|
||||
sandbox: warm.sandbox,
|
||||
service_tier: warm.service_tier,
|
||||
thread: Some(thread.freeze()),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
mod wire {
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct PrewarmRequest {
|
||||
#[prost(message, optional, tag = "10")]
|
||||
pub environments: Option<EnvironmentList>,
|
||||
#[prost(string, optional, tag = "15")]
|
||||
pub model: Option<String>,
|
||||
#[prost(string, optional, tag = "16")]
|
||||
pub model_provider: Option<String>,
|
||||
#[prost(bool, optional, tag = "29")]
|
||||
pub deferred_environment: Option<bool>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct EnvironmentList {
|
||||
#[prost(message, repeated, tag = "1")]
|
||||
pub values: Vec<EnvironmentSelection>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct EnvironmentSelection {
|
||||
#[prost(message, optional, tag = "1")]
|
||||
pub managed: Option<ManagedEnvironment>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct ManagedEnvironment {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub environment_config_id: Option<String>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub cwd: Option<String>,
|
||||
#[prost(message, optional, tag = "3")]
|
||||
pub overrides: Option<EnvironmentOverrides>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct EnvironmentOverrides {
|
||||
#[prost(message, optional, tag = "1")]
|
||||
pub repositories: Option<RepositoryOverrides>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub name: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct RepositoryOverrides {
|
||||
#[prost(message, repeated, tag = "1")]
|
||||
pub values: Vec<RepositoryOverride>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct RepositoryOverride {
|
||||
#[prost(string, optional, tag = "5")]
|
||||
pub origin_url: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Message)]
|
||||
pub(super) struct PrewarmResponse {
|
||||
#[prost(message, optional, tag = "1")]
|
||||
pub active_permission_profile: Option<crate::activation_wire::ActivePermissionProfile>,
|
||||
#[prost(message, optional, tag = "2")]
|
||||
pub approval_policy: Option<crate::activation_wire::ApprovalPolicy>,
|
||||
#[prost(int32, optional, tag = "3")]
|
||||
pub approvals_reviewer: Option<i32>,
|
||||
#[prost(string, optional, tag = "4")]
|
||||
pub cwd: Option<String>,
|
||||
#[prost(string, optional, tag = "7")]
|
||||
pub model: Option<String>,
|
||||
#[prost(string, optional, tag = "8")]
|
||||
pub model_provider: Option<String>,
|
||||
#[prost(string, optional, tag = "10")]
|
||||
pub reasoning_effort: Option<String>,
|
||||
#[prost(message, optional, tag = "11")]
|
||||
pub runtime_workspace_roots: Option<crate::activation_wire::StringList>,
|
||||
#[prost(message, optional, tag = "12")]
|
||||
pub sandbox: Option<crate::activation_wire::SandboxPolicy>,
|
||||
#[prost(message, optional, tag = "13")]
|
||||
pub service_tier: Option<crate::activation_wire::NullableString>,
|
||||
#[prost(bytes = "bytes", optional, tag = "14")]
|
||||
pub thread: Option<Bytes>,
|
||||
}
|
||||
}
|
||||
@@ -1,284 +0,0 @@
|
||||
//! Typed live transcript updates for the attached thread.
|
||||
use crate::Error;
|
||||
use crate::Event;
|
||||
use crate::ThreadStatus;
|
||||
use crate::transcript_wire as wire;
|
||||
use std::fmt;
|
||||
|
||||
/// A live update, not a history snapshot or a replay guarantee.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct TranscriptEvent {
|
||||
pub thread_id: String,
|
||||
pub emitted_at_ms: Option<i64>,
|
||||
pub update: TranscriptUpdate,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub enum TranscriptUpdate {
|
||||
ItemStarted(crate::ItemLifecycle),
|
||||
ItemCompleted(crate::ItemLifecycle),
|
||||
AgentMessageDelta(ItemDelta),
|
||||
CommandOutputDelta(ItemDelta),
|
||||
FileChangeOutputDelta(ItemDelta),
|
||||
FileChangePatchUpdated(PatchUpdate),
|
||||
TurnStarted(TurnSummary),
|
||||
TurnCompleted(TurnSummary),
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct ItemDelta {
|
||||
pub item_id: String,
|
||||
pub turn_id: String,
|
||||
pub delta: String,
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct PatchUpdate {
|
||||
pub item_id: String,
|
||||
pub turn_id: String,
|
||||
pub changes: Vec<FileUpdate>,
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct FileUpdate {
|
||||
pub path: String,
|
||||
pub diff: String,
|
||||
pub kind: PatchKind,
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub enum PatchKind {
|
||||
Add,
|
||||
Delete,
|
||||
Update {
|
||||
move_path: Option<String>,
|
||||
},
|
||||
/// The server reported an unrecognized change kind.
|
||||
Unknown,
|
||||
}
|
||||
/// Status, timing, and failure details for a turn.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct TurnSummary {
|
||||
pub id: String,
|
||||
pub status: TurnStatus,
|
||||
/// Turn start time in Unix seconds, if reported by the server.
|
||||
pub started_at: Option<i64>,
|
||||
/// Turn completion time in Unix seconds, if reported by the server.
|
||||
pub completed_at: Option<i64>,
|
||||
/// Turn duration in milliseconds, if reported by the server.
|
||||
pub duration_ms: Option<i64>,
|
||||
pub error: Option<TurnFailure>,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TurnStatus {
|
||||
Completed,
|
||||
Interrupted,
|
||||
Failed,
|
||||
InProgress,
|
||||
Unknown(i32),
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct TurnFailure {
|
||||
pub message: String,
|
||||
pub additional_details: Option<String>,
|
||||
}
|
||||
// Each public payload type is safe to format independently, not just through Event.
|
||||
macro_rules! redacted_debug {
|
||||
($($ty:ty),* $(,)?) => {$(impl fmt::Debug for $ty {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(concat!(stringify!($ty), "([redacted])"))
|
||||
}
|
||||
})*};
|
||||
}
|
||||
redacted_debug!(
|
||||
TranscriptEvent,
|
||||
TranscriptUpdate,
|
||||
ItemDelta,
|
||||
PatchUpdate,
|
||||
FileUpdate,
|
||||
PatchKind,
|
||||
TurnSummary,
|
||||
TurnFailure
|
||||
);
|
||||
|
||||
// Field numbers in the ASB Notification.value oneof.
|
||||
const THREAD_STATUS_CHANGED: u32 = 3;
|
||||
const TURN_STARTED: u32 = 21;
|
||||
const TURN_COMPLETED: u32 = 23;
|
||||
pub(super) const ITEM_STARTED: u32 = 27;
|
||||
const ITEM_COMPLETED: u32 = 31;
|
||||
const ITEM_AGENT_MESSAGE_DELTA: u32 = 32;
|
||||
const ITEM_COMMAND_EXECUTION_OUTPUT_DELTA: u32 = 37;
|
||||
const ITEM_FILE_CHANGE_OUTPUT_DELTA: u32 = 39;
|
||||
const ITEM_FILE_CHANGE_PATCH_UPDATED: u32 = 40;
|
||||
|
||||
pub(super) enum DecodeFailure {
|
||||
MissingField,
|
||||
InvalidResponse,
|
||||
}
|
||||
|
||||
impl From<prost::DecodeError> for DecodeFailure {
|
||||
fn from(_: prost::DecodeError) -> Self {
|
||||
Self::InvalidResponse
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn required<T>(value: Option<T>) -> Result<T, DecodeFailure> {
|
||||
value.ok_or(DecodeFailure::MissingField)
|
||||
}
|
||||
impl Event {
|
||||
/// Returns a supported status update for this thread from an Attach notification.
|
||||
pub fn thread_status_for(&self, thread_id: &str) -> Option<ThreadStatus> {
|
||||
let Self::Notification(bytes) = self else {
|
||||
return None;
|
||||
};
|
||||
let (tag, values) = wire::notification(bytes).ok().flatten()?;
|
||||
if tag != THREAD_STATUS_CHANGED {
|
||||
return None;
|
||||
}
|
||||
let envelope = wire::merge_messages::<wire::Envelope<wire::StatusUpdate>>(values).ok()?;
|
||||
let params = envelope.params?;
|
||||
if params.thread_id.as_deref() != Some(thread_id) {
|
||||
return None;
|
||||
}
|
||||
crate::activation::parse_status(params.status?).ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl TranscriptEvent {
|
||||
pub(crate) fn decode(thread_id: &str, payload: &[u8]) -> Result<Option<Self>, Error> {
|
||||
match Self::decode_present_fields(thread_id, payload) {
|
||||
Ok(event) => Ok(event),
|
||||
Err(DecodeFailure::MissingField) => Ok(None),
|
||||
Err(DecodeFailure::InvalidResponse) => Err(Error::InvalidResponse),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_present_fields(
|
||||
thread_id: &str,
|
||||
payload: &[u8],
|
||||
) -> Result<Option<Self>, DecodeFailure> {
|
||||
let Some((tag, values)) = wire::notification(payload)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (owner, emitted_at_ms, update) = match tag {
|
||||
ITEM_STARTED | ITEM_COMPLETED => match crate::items::decode(tag, values)? {
|
||||
Some(decoded) => decoded,
|
||||
None => return Ok(None),
|
||||
},
|
||||
ITEM_AGENT_MESSAGE_DELTA
|
||||
| ITEM_COMMAND_EXECUTION_OUTPUT_DELTA
|
||||
| ITEM_FILE_CHANGE_OUTPUT_DELTA => {
|
||||
let envelope = wire::merge_messages::<wire::Envelope<wire::Delta>>(values)?;
|
||||
let params = required(envelope.params)?;
|
||||
let delta = ItemDelta {
|
||||
item_id: required(params.item_id)?,
|
||||
turn_id: required(params.turn_id)?,
|
||||
delta: required(params.delta)?,
|
||||
};
|
||||
let update = match tag {
|
||||
ITEM_AGENT_MESSAGE_DELTA => TranscriptUpdate::AgentMessageDelta(delta),
|
||||
ITEM_COMMAND_EXECUTION_OUTPUT_DELTA => {
|
||||
TranscriptUpdate::CommandOutputDelta(delta)
|
||||
}
|
||||
ITEM_FILE_CHANGE_OUTPUT_DELTA => TranscriptUpdate::FileChangeOutputDelta(delta),
|
||||
_ => return Ok(None),
|
||||
};
|
||||
(required(params.thread_id)?, envelope.emitted_at_ms, update)
|
||||
}
|
||||
ITEM_FILE_CHANGE_PATCH_UPDATED => {
|
||||
let envelope = wire::merge_messages::<wire::Envelope<wire::PatchUpdate>>(values)?;
|
||||
let params = required(envelope.params)?;
|
||||
let changes = required(params.changes)?
|
||||
.values
|
||||
.into_iter()
|
||||
.map(FileUpdate::try_from)
|
||||
.collect::<Result<_, DecodeFailure>>()?;
|
||||
|
||||
let update = PatchUpdate {
|
||||
item_id: required(params.item_id)?,
|
||||
turn_id: required(params.turn_id)?,
|
||||
changes,
|
||||
};
|
||||
(
|
||||
required(params.thread_id)?,
|
||||
envelope.emitted_at_ms,
|
||||
TranscriptUpdate::FileChangePatchUpdated(update),
|
||||
)
|
||||
}
|
||||
TURN_STARTED | TURN_COMPLETED => {
|
||||
let envelope = wire::merge_messages::<wire::Envelope<wire::TurnUpdate>>(values)?;
|
||||
let params = required(envelope.params)?;
|
||||
let summary = TurnSummary::try_from(required(params.turn)?)?;
|
||||
let update = if tag == TURN_STARTED {
|
||||
TranscriptUpdate::TurnStarted(summary)
|
||||
} else {
|
||||
TranscriptUpdate::TurnCompleted(summary)
|
||||
};
|
||||
(required(params.thread_id)?, envelope.emitted_at_ms, update)
|
||||
}
|
||||
_ => return Ok(None),
|
||||
};
|
||||
if owner != thread_id {
|
||||
// Attach also carries account-wide lifecycle notifications. Preserve them
|
||||
// as opaque events rather than ending this thread's transcript stream.
|
||||
return if matches!(tag, TURN_STARTED | TURN_COMPLETED) {
|
||||
Ok(None)
|
||||
} else {
|
||||
Err(DecodeFailure::InvalidResponse)
|
||||
};
|
||||
}
|
||||
Ok(Some(Self {
|
||||
thread_id: owner,
|
||||
emitted_at_ms,
|
||||
update,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<wire::Change> for FileUpdate {
|
||||
type Error = DecodeFailure;
|
||||
fn try_from(change: wire::Change) -> Result<Self, DecodeFailure> {
|
||||
let kind = match required(change.kind)?.value {
|
||||
Some(wire::Kind::Add(_)) => PatchKind::Add,
|
||||
Some(wire::Kind::Delete(_)) => PatchKind::Delete,
|
||||
Some(wire::Kind::Update(value)) => PatchKind::Update {
|
||||
move_path: value.move_path,
|
||||
},
|
||||
None => PatchKind::Unknown,
|
||||
};
|
||||
Ok(Self {
|
||||
path: required(change.path)?,
|
||||
diff: required(change.diff)?,
|
||||
kind,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<wire::Turn> for TurnSummary {
|
||||
type Error = DecodeFailure;
|
||||
|
||||
fn try_from(turn: wire::Turn) -> Result<Self, DecodeFailure> {
|
||||
let status = match required(turn.status)? {
|
||||
1 => TurnStatus::Completed,
|
||||
2 => TurnStatus::Interrupted,
|
||||
3 => TurnStatus::Failed,
|
||||
4 => TurnStatus::InProgress,
|
||||
value => TurnStatus::Unknown(value),
|
||||
};
|
||||
let error = turn
|
||||
.error
|
||||
.map(|error| {
|
||||
Ok::<_, DecodeFailure>(TurnFailure {
|
||||
message: required(error.message)?,
|
||||
additional_details: error.additional_details,
|
||||
})
|
||||
})
|
||||
.transpose()?;
|
||||
Ok(Self {
|
||||
id: required(turn.id)?,
|
||||
status,
|
||||
started_at: turn.started_at,
|
||||
completed_at: turn.completed_at,
|
||||
duration_ms: turn.duration_ms,
|
||||
error,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,303 +0,0 @@
|
||||
//! Independent protobuf fixtures cover the public transcript contract.
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn message(tag: u32, payload: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
prost::encoding::encode_key(tag, prost::encoding::WireType::LengthDelimited, &mut out);
|
||||
prost::encoding::encode_varint(payload.len() as u64, &mut out);
|
||||
out.extend_from_slice(payload);
|
||||
out
|
||||
}
|
||||
|
||||
fn notification(tag: u32, params: &[u8]) -> Vec<u8> {
|
||||
message(tag, &message(/*tag*/ 2, params))
|
||||
}
|
||||
|
||||
const DELTA: &[u8] = b"\x0a\x01d\x12\x01i\x1a\x01t\x22\x01u";
|
||||
|
||||
#[tokio::test]
|
||||
async fn attach_decodes_live_deltas_with_unknown_fields() {
|
||||
let fixture = fixture(response(
|
||||
[32, 37, 39]
|
||||
.into_iter()
|
||||
.map(|tag| {
|
||||
let mut payload = notification(tag, DELTA);
|
||||
payload.extend([0xa0, 0x06, 1]); // unknown field 100
|
||||
frame(&message(/*tag*/ 1, &payload))
|
||||
})
|
||||
.collect(),
|
||||
tonic::Status::ok(""),
|
||||
))
|
||||
.await;
|
||||
let mut stream = fixture.client.attach("t").await.unwrap();
|
||||
for expected in [
|
||||
TranscriptUpdate::AgentMessageDelta as fn(ItemDelta) -> TranscriptUpdate,
|
||||
TranscriptUpdate::CommandOutputDelta,
|
||||
TranscriptUpdate::FileChangeOutputDelta,
|
||||
] {
|
||||
let Event::Transcript(event) = stream.next().await.unwrap().unwrap() else {
|
||||
panic!("expected transcript event")
|
||||
};
|
||||
assert_eq!(format!("{event:?}"), "TranscriptEvent([redacted])");
|
||||
assert_eq!(event.thread_id, "t");
|
||||
assert_eq!(event.emitted_at_ms, None);
|
||||
assert_eq!(
|
||||
event.update,
|
||||
expected(ItemDelta {
|
||||
item_id: "i".into(),
|
||||
turn_id: "u".into(),
|
||||
delta: "d".into(),
|
||||
})
|
||||
);
|
||||
}
|
||||
assert!(stream.next().await.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patches_preserve_order_kinds_and_move_paths() {
|
||||
let mut changes = Vec::new();
|
||||
for kind in [
|
||||
b"\x0a\x00".as_slice(),
|
||||
b"\x12\x00",
|
||||
b"\x1a\x03\x0a\x01m",
|
||||
b"\x22\x00",
|
||||
] {
|
||||
changes.extend(message(
|
||||
/*tag*/ 1,
|
||||
&[
|
||||
b"\x0a\x01d".to_vec(),
|
||||
message(/*tag*/ 2, kind),
|
||||
b"\x1a\x01p".to_vec(),
|
||||
]
|
||||
.concat(),
|
||||
));
|
||||
}
|
||||
let params = [message(/*tag*/ 1, &changes), DELTA[3..].to_vec()].concat();
|
||||
let payload = notification(/*tag*/ 40, ¶ms);
|
||||
let event = TranscriptEvent::decode("t", &payload).unwrap().unwrap();
|
||||
assert_eq!(
|
||||
event.update,
|
||||
TranscriptUpdate::FileChangePatchUpdated(PatchUpdate {
|
||||
item_id: "i".into(),
|
||||
turn_id: "u".into(),
|
||||
changes: [
|
||||
PatchKind::Add,
|
||||
PatchKind::Delete,
|
||||
PatchKind::Update {
|
||||
move_path: Some("m".into())
|
||||
},
|
||||
PatchKind::Unknown,
|
||||
]
|
||||
.into_iter()
|
||||
.map(|kind| FileUpdate {
|
||||
path: "p".into(),
|
||||
diff: "d".into(),
|
||||
kind,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_events_preserve_status_failure_and_timing() {
|
||||
for (tag, status, expected) in [
|
||||
(23, 1, TurnStatus::Completed),
|
||||
(23, 2, TurnStatus::Interrupted),
|
||||
(21, 4, TurnStatus::InProgress),
|
||||
(23, 3, TurnStatus::Failed),
|
||||
(23, 99, TurnStatus::Unknown(99)),
|
||||
] {
|
||||
let (timing, started_at, completed_at, duration_ms) = match expected {
|
||||
TurnStatus::InProgress => (b"\x38\x00".as_slice(), Some(0), None, None),
|
||||
TurnStatus::Completed => (
|
||||
b"\x08\x0d\x10\xf4\x03\x38\x0b".as_slice(),
|
||||
Some(11),
|
||||
Some(13),
|
||||
Some(500),
|
||||
),
|
||||
_ => (&[][..], None, None, None),
|
||||
};
|
||||
let turn = [
|
||||
b"\x1a\x06\x0a\x01a\x1a\x01e\x22\x01u\x2a\x00\x40".to_vec(),
|
||||
vec![status],
|
||||
timing.to_vec(),
|
||||
]
|
||||
.concat();
|
||||
let params = [b"\x0a\x01t".to_vec(), message(/*tag*/ 2, &turn)].concat();
|
||||
let event = TranscriptEvent::decode(
|
||||
"t",
|
||||
&message(tag, &[vec![8, 7], message(/*tag*/ 2, ¶ms)].concat()),
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let turn = TurnSummary {
|
||||
id: "u".into(),
|
||||
status: expected,
|
||||
started_at,
|
||||
completed_at,
|
||||
duration_ms,
|
||||
error: Some(TurnFailure {
|
||||
message: "e".into(),
|
||||
additional_details: Some("a".into()),
|
||||
}),
|
||||
};
|
||||
assert_eq!(event.emitted_at_ms, Some(7));
|
||||
assert_eq!(
|
||||
event.update,
|
||||
if tag == 21 {
|
||||
TranscriptUpdate::TurnStarted(turn)
|
||||
} else {
|
||||
TranscriptUpdate::TurnCompleted(turn)
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attach_preserves_opaque_notifications_and_continues() {
|
||||
let foreign_turn = b"\x0a\x01x\x12\x05\x22\x01u\x40\x01";
|
||||
let opaque = [
|
||||
message(/*tag*/ 100, b"unknown notification"),
|
||||
notification(
|
||||
/*tag*/ 27,
|
||||
b"\x0a\x02\x4a\x00\x10\x03\x1a\x01t\x22\x01u",
|
||||
), // Unsupported MCP item.
|
||||
notification(/*tag*/ 21, foreign_turn),
|
||||
notification(/*tag*/ 23, foreign_turn),
|
||||
notification(/*tag*/ 32, &DELTA[..9]), // missing turn ID
|
||||
];
|
||||
let valid = notification(/*tag*/ 32, DELTA);
|
||||
let fixture = fixture(response(
|
||||
opaque
|
||||
.iter()
|
||||
.chain([&valid])
|
||||
.map(|payload| frame(&message(/*tag*/ 1, payload)))
|
||||
.collect(),
|
||||
tonic::Status::ok(""),
|
||||
))
|
||||
.await;
|
||||
let mut stream = fixture.client.attach("t").await.unwrap();
|
||||
for payload in opaque {
|
||||
let Some(Ok(Event::Notification(bytes))) = stream.next().await else {
|
||||
panic!("expected opaque notification");
|
||||
};
|
||||
assert_eq!(bytes.as_ref(), payload.as_slice());
|
||||
}
|
||||
let Some(Ok(Event::Transcript(event))) = stream.next().await else {
|
||||
panic!("expected transcript after opaque notifications");
|
||||
};
|
||||
assert_eq!(event.thread_id, "t");
|
||||
assert!(stream.next().await.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoder_keeps_incomplete_events_opaque_and_rejects_foreign_deltas() {
|
||||
let mut wrong_owner = DELTA.to_vec();
|
||||
wrong_owner[8] = b'x';
|
||||
for payload in [
|
||||
notification(/*tag*/ 32, &DELTA[3..]),
|
||||
notification(/*tag*/ 40, &DELTA[3..]),
|
||||
notification(/*tag*/ 23, b"\x0a\x01t"),
|
||||
] {
|
||||
assert!(TranscriptEvent::decode("t", &payload).unwrap().is_none());
|
||||
}
|
||||
assert!(TranscriptEvent::decode("t", ¬ification(/*tag*/ 32, &wrong_owner)).is_err());
|
||||
assert!(
|
||||
TranscriptEvent::decode("t", &message(/*tag*/ 100, b""))
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notification_selection_merges_only_repeated_variants() {
|
||||
let partial = notification(/*tag*/ 32, &DELTA[..6]);
|
||||
let tail = notification(/*tag*/ 32, &DELTA[6..]);
|
||||
assert!(
|
||||
TranscriptEvent::decode("t", &[partial.clone(), tail.clone()].concat())
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
TranscriptEvent::decode("t", &[partial, message(/*tag*/ 85, b""), tail].concat())
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
TranscriptEvent::decode(
|
||||
"t",
|
||||
&[notification(/*tag*/ 32, DELTA), message(/*tag*/ 89, b"")].concat()
|
||||
)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
|
||||
let envelope = message(/*tag*/ 2, DELTA);
|
||||
let split_inside_params = [
|
||||
message(/*tag*/ 32, &envelope[..4]),
|
||||
message(/*tag*/ 32, &envelope[4..]),
|
||||
]
|
||||
.concat();
|
||||
assert!(TranscriptEvent::decode("t", &split_inside_params).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_payload_debug_is_redacted() {
|
||||
for formatted in [
|
||||
format!(
|
||||
"{:?}",
|
||||
FileUpdate {
|
||||
path: "secret".into(),
|
||||
diff: "secret".into(),
|
||||
kind: PatchKind::Update {
|
||||
move_path: Some("secret".into()),
|
||||
},
|
||||
}
|
||||
),
|
||||
format!(
|
||||
"{:?}",
|
||||
TurnFailure {
|
||||
message: "secret".into(),
|
||||
additional_details: Some("secret".into()),
|
||||
}
|
||||
),
|
||||
] {
|
||||
assert!(formatted.ends_with("([redacted])"));
|
||||
assert!(!formatted.contains("secret"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notification_selection_handles_many_fragments_and_obsolete_malformed_messages() {
|
||||
let mut payload = message(/*tag*/ 32, b"\xff");
|
||||
payload.extend(message(/*tag*/ 85, b""));
|
||||
for _ in 0..100_000 {
|
||||
payload.extend(message(/*tag*/ 32, b""));
|
||||
}
|
||||
payload.extend(notification(/*tag*/ 32, &DELTA[..6]));
|
||||
payload.extend(message(/*tag*/ 100, b"\xff"));
|
||||
payload.extend(notification(/*tag*/ 32, &DELTA[6..]));
|
||||
let event = TranscriptEvent::decode("t", &payload).unwrap().unwrap();
|
||||
assert_eq!(
|
||||
event.update,
|
||||
TranscriptUpdate::AgentMessageDelta(ItemDelta {
|
||||
item_id: "i".into(),
|
||||
turn_id: "u".into(),
|
||||
delta: "d".into(),
|
||||
})
|
||||
);
|
||||
|
||||
payload.extend(message(/*tag*/ 89, b"\xff"));
|
||||
assert!(TranscriptEvent::decode("t", &payload).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[path = "item_tests.rs"]
|
||||
mod items;
|
||||
|
||||
#[path = "history_tests.rs"]
|
||||
mod history;
|
||||
|
||||
#[path = "turns_tests.rs"]
|
||||
mod turns_tests;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user