Refactor exec to use the shared app-server client (#61706)

## What changed

- Use `AppServerClient` throughout exec and extract turn completion into `finish_turn`, including handling for server and thread-stream disconnections.
- Move remote address parsing and auth-token resolution into `codex-app-server-client`, with re-exports from the TUI.
- Allow human-readable exec output to be initialized without a local `Config`.

## Testing

Move remote address and auth-token tests into `codex-app-server-client`, retaining coverage for WebSocket and Unix socket addresses, invalid addresses, and missing, empty, or whitespace-padded tokens.

GitOrigin-RevId: 465b17a1c03392a7d4e7700d83ce67c2cf5ef021
This commit is contained in:
Eric Traut
2026-11-15 23:50:49 +00:00
committed by copyberry
parent a394ff9cf6
commit 598df2d015
10 changed files with 325 additions and 273 deletions
+3
View File
@@ -25,6 +25,7 @@ pub mod cloud_backend;
pub use codex_cloud_client::ProjectEnvironment;
mod path;
mod remote;
mod remote_addr;
mod remote_websocket;
pub use cloud::CloudClient;
pub use cloud::CloudCommand;
@@ -83,6 +84,8 @@ pub use crate::path::AppServerPath;
pub use crate::remote::RemoteAppServerClient;
pub use crate::remote::RemoteAppServerConnectArgs;
pub use crate::remote::RemoteAppServerEndpoint;
pub use crate::remote_addr::resolve_remote_addr;
pub use crate::remote_addr::resolve_remote_endpoint;
/// Transitional access to core-only embedded app-server types.
///
@@ -0,0 +1,138 @@
//! Parse CLI remote app-server endpoints and determine whether they can carry bearer tokens.
use crate::RemoteAppServerEndpoint;
use crate::remote::websocket_url_supports_auth_token;
use codex_core::config::find_codex_home;
use codex_utils_absolute_path::AbsolutePathBuf;
use color_eyre::eyre::WrapErr;
use url::Url;
fn remote_addr_has_explicit_port(addr: &str, parsed: &Url) -> bool {
let Some(host) = parsed.host_str() else {
return false;
};
if parsed.port().is_some() {
return true;
}
let Some((_, rest)) = addr.split_once("://") else {
return false;
};
let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
let authority = &rest[..authority_end];
let host_and_port = authority
.rsplit_once('@')
.map_or(authority, |(_, host_and_port)| host_and_port);
let explicit_default_port = match parsed.scheme() {
"ws" => 80,
"wss" => 443,
_ => return false,
};
let expected_host = if host.contains(':') {
format!("[{host}]")
} else {
host.to_string()
};
host_and_port == format!("{expected_host}:{explicit_default_port}")
}
pub fn resolve_remote_addr(addr: &str) -> color_eyre::Result<RemoteAppServerEndpoint> {
if let Some(socket_path) = addr.strip_prefix("unix://") {
let socket_path = if socket_path.is_empty() {
let codex_home = find_codex_home().wrap_err("failed to resolve CODEX_HOME")?;
crate::app_server_control_socket_path(&codex_home).map_err(color_eyre::Report::new)?
} else {
AbsolutePathBuf::relative_to_current_dir(socket_path)
.map_err(color_eyre::Report::new)?
};
return Ok(RemoteAppServerEndpoint::UnixSocket { socket_path });
}
let parsed = match Url::parse(addr) {
Ok(parsed) => parsed,
Err(_) => {
color_eyre::eyre::bail!(
"invalid remote address `{addr}`; expected `ws://host:port`, `wss://host:port`, `unix://`, or `unix://PATH`"
);
}
};
if matches!(parsed.scheme(), "ws" | "wss")
&& parsed.host_str().is_some()
&& remote_addr_has_explicit_port(addr, &parsed)
&& parsed.path() == "/"
&& parsed.query().is_none()
&& parsed.fragment().is_none()
{
return Ok(RemoteAppServerEndpoint::WebSocket {
websocket_url: parsed.to_string(),
auth_token: None,
});
}
color_eyre::eyre::bail!(
"invalid remote address `{addr}`; expected `ws://host:port`, `wss://host:port`, `unix://`, or `unix://PATH`"
);
}
pub fn resolve_remote_endpoint(
remote: Option<String>,
remote_auth_token_env: Option<String>,
) -> std::io::Result<Option<RemoteAppServerEndpoint>> {
let mut remote_endpoint = remote
.as_deref()
.map(resolve_remote_addr)
.transpose()
.map_err(std::io::Error::other)?;
if let Some(remote_auth_token_env) = remote_auth_token_env {
let Some(endpoint) = remote_endpoint.as_mut() else {
return Err(std::io::Error::other(
"`--remote-auth-token-env` requires `--remote`.",
));
};
let slot = match endpoint {
RemoteAppServerEndpoint::WebSocket {
websocket_url,
auth_token,
} if Url::parse(websocket_url)
.is_ok_and(|parsed| websocket_url_supports_auth_token(&parsed)) =>
{
auth_token
}
RemoteAppServerEndpoint::WebSocket { .. }
| RemoteAppServerEndpoint::UnixSocket { .. } => {
return Err(std::io::Error::other(
"`--remote-auth-token-env` requires a `wss://` or loopback `ws://` remote.",
));
}
};
*slot = Some(read_remote_auth_token_from_env_var(&remote_auth_token_env)?);
}
Ok(remote_endpoint)
}
fn read_remote_auth_token_from_env_var_with<F>(
env_var_name: &str,
get_var: F,
) -> std::io::Result<String>
where
F: FnOnce(&str) -> Result<String, std::env::VarError>,
{
let auth_token = get_var(env_var_name).map_err(|_| {
std::io::Error::other(format!("environment variable `{env_var_name}` is not set"))
})?;
let auth_token = auth_token.trim().to_string();
if auth_token.is_empty() {
return Err(std::io::Error::other(format!(
"environment variable `{env_var_name}` is empty"
)));
}
Ok(auth_token)
}
fn read_remote_auth_token_from_env_var(env_var_name: &str) -> std::io::Result<String> {
read_remote_auth_token_from_env_var_with(env_var_name, |name| std::env::var(name))
}
#[cfg(test)]
#[path = "remote_addr_tests.rs"]
mod tests;
@@ -0,0 +1,106 @@
#![cfg(test)]
use super::*;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
#[test]
fn resolve_remote_addr_accepts_websocket_url() {
assert_eq!(
resolve_remote_addr("ws://127.0.0.1:4500").expect("ws URL should normalize"),
RemoteAppServerEndpoint::WebSocket {
websocket_url: "ws://127.0.0.1:4500/".to_string(),
auth_token: None,
}
);
}
#[test]
fn resolve_remote_addr_accepts_secure_websocket_url() {
assert_eq!(
resolve_remote_addr("wss://example.com:443").expect("wss URL should normalize"),
RemoteAppServerEndpoint::WebSocket {
websocket_url: "wss://example.com/".to_string(),
auth_token: None,
}
);
}
#[test]
fn resolve_remote_addr_accepts_default_socket() -> color_eyre::Result<()> {
let codex_home = find_codex_home().wrap_err("failed to resolve CODEX_HOME")?;
assert_eq!(
resolve_remote_addr("unix://")?,
RemoteAppServerEndpoint::UnixSocket {
socket_path: crate::app_server_control_socket_path(&codex_home)?,
}
);
Ok(())
}
#[test]
fn resolve_remote_addr_accepts_relative_socket_path() -> color_eyre::Result<()> {
assert_eq!(
resolve_remote_addr("unix://codex.sock")?,
RemoteAppServerEndpoint::UnixSocket {
socket_path: AbsolutePathBuf::relative_to_current_dir("codex.sock")?,
}
);
Ok(())
}
#[test]
fn resolve_remote_addr_accepts_absolute_socket_path() -> color_eyre::Result<()> {
let temp_dir = TempDir::new()?;
let socket_path = temp_dir.path().join("codex.sock");
assert_eq!(
resolve_remote_addr(&format!("unix://{}", socket_path.display()))?,
RemoteAppServerEndpoint::UnixSocket {
socket_path: AbsolutePathBuf::from_absolute_path(&socket_path)?,
}
);
Ok(())
}
#[test]
fn resolve_remote_addr_rejects_invalid_remote_addresses() {
for addr in [
"ws://127.0.0.1",
"wss://example.com",
"127.0.0.1:4500",
"https://127.0.0.1:4500",
] {
let err = resolve_remote_addr(addr).expect_err("invalid remote addresses should fail");
assert!(
err.to_string().contains(
"expected `ws://host:port`, `wss://host:port`, `unix://`, or `unix://PATH`"
)
);
}
}
#[test]
fn read_remote_auth_token_from_env_var_reports_missing_values() {
let err = read_remote_auth_token_from_env_var_with("CODEX_REMOTE_AUTH_TOKEN", |_| {
Err(std::env::VarError::NotPresent)
})
.expect_err("missing env vars should be rejected");
assert!(err.to_string().contains("is not set"));
}
#[test]
fn read_remote_auth_token_from_env_var_trims_values() {
let auth_token = read_remote_auth_token_from_env_var_with("CODEX_REMOTE_AUTH_TOKEN", |_| {
Ok(" bearer-token ".to_string())
})
.expect("env var should parse");
assert_eq!(auth_token, "bearer-token");
}
#[test]
fn read_remote_auth_token_from_env_var_rejects_empty_values() {
let err = read_remote_auth_token_from_env_var_with("CODEX_REMOTE_AUTH_TOKEN", |_| {
Ok(" \n\t ".to_string())
})
.expect_err("empty env vars should be rejected");
assert!(err.to_string().contains("is empty"));
}