Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,24 @@ jobs:

- name: cargo test
run: cargo test --manifest-path src-tauri/Cargo.toml

codex-compatibility:
# Linux runs the full suite above. CLI package paths and native HTTP/WS
# behavior must also be exercised on the other supported desktop OSes.
name: Codex compatibility (${{ matrix.os }})
strategy:
fail-fast: false
matrix:
os: [windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
timeout-minutes: 25
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@4360b52568e2003a75bf9bc1d59f33a8e3fc893c # stable
with:
toolchain: stable
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
workspaces: src-tauri
- name: Codex compatibility regressions
run: cargo test --manifest-path src-tauri/Cargo.toml tooling_compat
69 changes: 60 additions & 9 deletions src-tauri/src/codex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,10 @@ pub(crate) fn reset_codex_bin_cache() {
}

fn resolve_codex_bin() -> Option<String> {
resolve_codex_bin_with(bundled_desktop_cli)
}

fn resolve_codex_bin_with(desktop_cli: impl FnOnce() -> Option<String>) -> Option<String> {
// An explicit override always wins, and is the documented escape hatch
// when the heuristics below miss.
if let Ok(bin) = std::env::var("CODEX_BIN") {
Expand All @@ -288,7 +292,14 @@ fn resolve_codex_bin() -> Option<String> {
}
}

// 1. Whatever PATH this process has. Correct when launched from a shell.
// The catalog must match the desktop runtime. A separately updated PATH
// install can lag behind it; CODEX_BIN remains the explicit CLI-only opt-out.
if let Some(bin) = desktop_cli() {
tracing::info!(path = %bin, "using the desktop Codex CLI for catalog compatibility");
return Some(bin);
}

// 1. PATH is the fallback for CLI-only installations.
for name in path_candidates() {
if crate::cli_locator::find_in_path(name).is_some() && runs(Path::new(name)) {
return Some(name.to_string());
Expand Down Expand Up @@ -344,7 +355,7 @@ fn resolve_codex_bin() -> Option<String> {
}
}

bundled_desktop_cli()
None
}

pub fn ensure_codex_cli() -> anyhow::Result<()> {
Expand Down Expand Up @@ -431,7 +442,7 @@ fn login_shell_lookup() -> Option<String> {

/// The Codex desktop app ships a full CLI under
/// `%LOCALAPPDATA%\OpenAI\Codex\bin\<hash>\codex.exe` (Windows).
/// Use the most recently modified one when no PATH install exists.
/// Use the most recently modified executable package.
#[cfg(windows)]
fn bundled_desktop_cli() -> Option<String> {
let bin_root = dirs::data_local_dir()?
Expand All @@ -456,17 +467,31 @@ fn bundled_desktop_cli() -> Option<String> {
newest = Some((mtime, exe));
}
}
newest.map(|(_, path)| path.to_string_lossy().to_string())
newest.and_then(|(_, path)| runs(&path).then(|| path.to_string_lossy().to_string()))
}

/// The Codex desktop app ships a CLI inside the ChatGPT app bundle on macOS.
/// Check the known macOS locations for a bundled CLI binary when no PATH
/// install exists.
/// Prefer the versioned package entrypoint, with the legacy layout as fallback.
// why: macOS applications embed resources under Contents rather than a data directory.
#[cfg(target_os = "macos")]
fn bundled_desktop_cli() -> Option<String> {
let app_cli = PathBuf::from("/Applications/ChatGPT.app/Contents/Resources/codex");
if app_cli.is_file() && runs(&app_cli) {
return Some(app_cli.display().to_string());
let mut roots = vec![PathBuf::from("/Applications")];
if let Some(home) = dirs::home_dir() {
roots.push(home.join("Applications"));
}
for root in roots {
for app in ["ChatGPT.app", "Codex.app"] {
let resources = root.join(app).join("Contents/Resources");
let packaged = bundled_package_entrypoint(&resources.join("codex-cli"));
for bin in packaged
.into_iter()
.chain(std::iter::once(resources.join("codex")))
{
if bin.is_file() && runs(&bin) {
return Some(bin.display().to_string());
}
}
}
}

if let Some(data) = dirs::data_local_dir() {
Expand All @@ -484,6 +509,32 @@ fn bundled_desktop_cli() -> Option<String> {
None
}

// why: the macOS desktop package moved its executable behind a manifest.
// Fixtures remain portable so Unix and Windows path forms are both exercised.
#[cfg(any(target_os = "macos", test))]
fn bundled_package_entrypoint(package: &Path) -> Option<PathBuf> {
let metadata: Value =
serde_json::from_slice(&std::fs::read(package.join("codex-package.json")).ok()?).ok()?;
if metadata.get("layoutVersion")?.as_u64()? != 1 {
return None;
}
let entrypoint = metadata.get("entrypoint")?.as_str()?;
// A manifest must not select an executable outside its package. Check both
// separators even when inspecting a package authored on a different OS.
if entrypoint.is_empty() || entrypoint.contains(['\\', ':']) {
return None;
}
let relative = Path::new(entrypoint);
if !relative
.components()
.all(|part| matches!(part, std::path::Component::Normal(_)))
{
return None;
}
let candidate = package.join(relative);
candidate.is_file().then_some(candidate)
}

/// Desktop-app-style CLI installation on Linux: check `$XDG_DATA_HOME/codex/`
/// (typically `~/.local/share/codex/`). The well-known PATH-style locations
/// (`~/.local/bin/codex`, `/usr/local/bin/codex`) are already covered by the
Expand Down
80 changes: 80 additions & 0 deletions src-tauri/src/codex/cli_lookup_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,21 @@ impl Drop for RestoreEnv {

struct ResetCache;

// why: the regression was a macOS app bundle moving its CLI into a package.
#[cfg(target_os = "macos")]
#[test]
fn tooling_compat_prefers_the_installed_desktop_package_over_path() {
let package =
std::path::Path::new("/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex");
if !package.is_file() {
return;
}
let _guard = super::codex_home_guard();
let _restore = RestoreEnv::new("CODEX_BIN");
std::env::remove_var("CODEX_BIN");
assert_eq!(super::resolve_codex_bin().as_deref(), package.to_str());
}

impl Drop for ResetCache {
fn drop(&mut self) {
super::reset_codex_bin_cache();
Expand Down Expand Up @@ -121,3 +136,68 @@ fn cache_reset_picks_up_a_newly_available_cli() {
Some("loom-router-test-codex")
);
}

#[test]
fn tooling_compat_desktop_selection_keeps_the_explicit_override() {
let _guard = super::codex_home_guard();
let _restore = RestoreEnv::new("CODEX_BIN");
std::env::set_var("CODEX_BIN", "explicit-codex");
assert_eq!(
super::resolve_codex_bin_with(|| panic!("override must win")),
Some("explicit-codex".into())
);
std::env::remove_var("CODEX_BIN");
assert_eq!(
super::resolve_codex_bin_with(|| Some("desktop-codex".into())),
Some("desktop-codex".into())
);
}

#[test]
fn tooling_compat_package_metadata_accepts_unix_and_windows_entrypoints() {
let root = tempfile::tempdir().unwrap();
std::fs::create_dir(root.path().join("bin")).unwrap();
for entrypoint in ["bin/codex", "bin/codex.exe"] {
let bin = root.path().join(entrypoint);
std::fs::write(&bin, "fixture").unwrap();
std::fs::write(
root.path().join("codex-package.json"),
serde_json::json!({
"layoutVersion": 1, "entrypoint": entrypoint,
})
.to_string(),
)
.unwrap();
assert_eq!(super::bundled_package_entrypoint(root.path()), Some(bin));
}
}

#[test]
fn tooling_compat_package_metadata_rejects_missing_and_escaping_paths() {
let root = tempfile::tempdir().unwrap();
for entrypoint in [
"",
"/bin/sh",
"../codex",
"bin/../../codex",
"C:/codex.exe",
"..\\codex.exe",
"bin/missing",
] {
std::fs::write(
root.path().join("codex-package.json"),
serde_json::json!({
"layoutVersion": 1, "entrypoint": entrypoint,
})
.to_string(),
)
.unwrap();
assert_eq!(
super::bundled_package_entrypoint(root.path()),
None,
"{entrypoint}"
);
}
std::fs::write(root.path().join("codex-package.json"), "invalid").unwrap();
assert_eq!(super::bundled_package_entrypoint(root.path()), None);
}
33 changes: 20 additions & 13 deletions src-tauri/src/proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,14 @@ use std::sync::{Arc, Mutex};

mod auth;
mod dispatch;
mod native_tools;
mod realtime;
mod routing;
mod streaming;
mod upstream;
mod visuals;

use native_tools::{handle_native_search, native_response};
use realtime::*;
use streaming::*;
use visuals::*;
Expand Down Expand Up @@ -162,6 +164,7 @@ struct ProxyCtx {
stats: SharedStats,
key_pools: KeyPools,
client: reqwest::Client,
native_base_url: String,
/// Routed-turn history shared across WebSocket connections. Routed
/// providers are stateless, so each incremental follow-up turn replays
/// the full item list; the cache is what lets that rebuild happen. It is
Expand Down Expand Up @@ -235,9 +238,15 @@ pub(crate) fn router_with_pools_and_wake(
.timeout(std::time::Duration::from_secs(600))
.build()
.expect("reqwest client"),
native_base_url: std::env::var("CODEX_NATIVE_BASE_URL")
.unwrap_or_else(|_| "https://chatgpt.com/backend-api/codex".to_string()),
history: Arc::new(Mutex::new(WsHistory::new())),
wake,
};
router_for_context(ctx, max_responses_body_bytes)
}

fn router_for_context(ctx: ProxyCtx, max_responses_body_bytes: usize) -> Router {
let activity = ctx.wake.clone();
Router::new()
.route("/health", get(health))
Expand All @@ -252,6 +261,12 @@ pub(crate) fn router_with_pools_and_wake(
"/v1/responses/compact",
post(handle_compact).layer(DefaultBodyLimit::max(max_responses_body_bytes)),
)
.route(
"/v1/alpha/search",
post(handle_native_search).layer(DefaultBodyLimit::max(
CHAT_COMPLETIONS_MAX_REQUEST_BODY_BYTES,
)),
)
.route(
"/v1/chat/completions",
post(handle_chat_completions).layer(DefaultBodyLimit::max(
Expand Down Expand Up @@ -646,8 +661,7 @@ async fn handle_compact(
) -> Result<Response, (StatusCode, String)> {
enforce_json_post(&headers)?;
let payload = parse_body(&body, "/v1/responses/compact")?;
let base = std::env::var("CODEX_NATIVE_BASE_URL")
.unwrap_or_else(|_| "https://chatgpt.com/backend-api/codex".to_string());
let base = &ctx.native_base_url;
let url = format!("{}/responses/compact", base.trim_end_matches('/'));

let mut req = ctx.client.post(&url).json(&payload);
Expand All @@ -665,10 +679,7 @@ async fn handle_compact(
let status =
StatusCode::from_u16(upstream.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
tracing::info!(%url, %status, "compact passthrough");
Ok(Response::builder()
.status(status)
.body(Body::from_stream(upstream.bytes_stream()))
.unwrap())
Ok(native_response(upstream))
}

/// Forward Codex native image generation/edit requests to ChatGPT.
Expand All @@ -682,9 +693,8 @@ async fn handle_native_image(
headers: HeaderMap,
body: Bytes,
) -> Result<Response, (StatusCode, String)> {
let base = std::env::var("CODEX_NATIVE_BASE_URL")
.unwrap_or_else(|_| "https://chatgpt.com/backend-api/codex".to_string());
let target = native_image_target(Some(uri.path()), &base)
let base = &ctx.native_base_url;
let target = native_image_target(Some(uri.path()), base)
.ok_or_else(|| (StatusCode::NOT_FOUND, "unknown image route".to_string()))?;

let mut req = ctx.client.post(&target).body(body);
Expand All @@ -707,10 +717,7 @@ async fn handle_native_image(
let status =
StatusCode::from_u16(upstream.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
tracing::info!(%target, %status, "native image passthrough");
Ok(Response::builder()
.status(status)
.body(Body::from_stream(upstream.bytes_stream()))
.unwrap())
Ok(native_response(upstream))
}

fn native_image_target(path: Option<&str>, base: &str) -> Option<String> {
Expand Down
54 changes: 54 additions & 0 deletions src-tauri/src/proxy/native_tools.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use super::*;

pub(super) async fn handle_native_search(
AxState(ctx): AxState<ProxyCtx>,
headers: HeaderMap,
body: Bytes,
) -> Result<Response, (StatusCode, String)> {
enforce_json_post(&headers)?;
parse_body(&body, "/v1/alpha/search")?;
// This is a native Codex tool, not a model-provider request. Keep an exact
// route instead of exposing an unrestricted authenticated backend proxy.
let url = format!("{}/alpha/search", ctx.native_base_url.trim_end_matches('/'));
let mut request = ctx
.client
.post(&url)
.header("content-type", "application/json")
.body(body);
for name in NATIVE_FORWARD_HEADERS {
if let Some(value) = headers.get(*name) {
request = request.header(*name, value);
}
}
let upstream = request.send().await.map_err(|error| {
(
StatusCode::BAD_GATEWAY,
upstream_unreachable_error(&url, &error, "ChatGPT/OpenAI").to_string(),
)
})?;
tracing::info!(status = %upstream.status(), "native search passthrough");
Ok(native_response(upstream))
}

pub(super) fn native_response(upstream: reqwest::Response) -> Response {
// Native tools return JSON, SSE or binary data. Losing the media type or
// content encoding makes a successful response unusable by the client.
let mut response = Response::builder().status(upstream.status());
for name in [
"content-type",
"content-encoding",
"cache-control",
"retry-after",
"x-request-id",
] {
if let Some(value) = upstream.headers().get(name) {
response = response.header(name, value);
}
}
response
.body(Body::from_stream(upstream.bytes_stream()))
.unwrap()
}

#[cfg(test)]
mod tests;
Loading
Loading