diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 11025d2..def30dd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/src-tauri/src/codex.rs b/src-tauri/src/codex.rs index f607b04..50c6db1 100644 --- a/src-tauri/src/codex.rs +++ b/src-tauri/src/codex.rs @@ -280,6 +280,10 @@ pub(crate) fn reset_codex_bin_cache() { } fn resolve_codex_bin() -> Option { + resolve_codex_bin_with(bundled_desktop_cli) +} + +fn resolve_codex_bin_with(desktop_cli: impl FnOnce() -> Option) -> Option { // 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") { @@ -288,7 +292,14 @@ fn resolve_codex_bin() -> Option { } } - // 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()); @@ -344,7 +355,7 @@ fn resolve_codex_bin() -> Option { } } - bundled_desktop_cli() + None } pub fn ensure_codex_cli() -> anyhow::Result<()> { @@ -431,7 +442,7 @@ fn login_shell_lookup() -> Option { /// The Codex desktop app ships a full CLI under /// `%LOCALAPPDATA%\OpenAI\Codex\bin\\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 { let bin_root = dirs::data_local_dir()? @@ -456,17 +467,31 @@ fn bundled_desktop_cli() -> Option { 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 { - 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() { @@ -484,6 +509,32 @@ fn bundled_desktop_cli() -> Option { 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 { + 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 diff --git a/src-tauri/src/codex/cli_lookup_tests.rs b/src-tauri/src/codex/cli_lookup_tests.rs index ecbab75..d13437c 100644 --- a/src-tauri/src/codex/cli_lookup_tests.rs +++ b/src-tauri/src/codex/cli_lookup_tests.rs @@ -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(); @@ -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); +} diff --git a/src-tauri/src/proxy.rs b/src-tauri/src/proxy.rs index 92f2e2c..5da03d0 100644 --- a/src-tauri/src/proxy.rs +++ b/src-tauri/src/proxy.rs @@ -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::*; @@ -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 @@ -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)) @@ -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( @@ -646,8 +661,7 @@ async fn handle_compact( ) -> Result { 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); @@ -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. @@ -682,9 +693,8 @@ async fn handle_native_image( headers: HeaderMap, body: Bytes, ) -> Result { - 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); @@ -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 { diff --git a/src-tauri/src/proxy/native_tools.rs b/src-tauri/src/proxy/native_tools.rs new file mode 100644 index 0000000..d54fdef --- /dev/null +++ b/src-tauri/src/proxy/native_tools.rs @@ -0,0 +1,54 @@ +use super::*; + +pub(super) async fn handle_native_search( + AxState(ctx): AxState, + headers: HeaderMap, + body: Bytes, +) -> Result { + 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; diff --git a/src-tauri/src/proxy/native_tools/tests.rs b/src-tauri/src/proxy/native_tools/tests.rs new file mode 100644 index 0000000..df752bd --- /dev/null +++ b/src-tauri/src/proxy/native_tools/tests.rs @@ -0,0 +1,161 @@ +use super::*; +use tower::ServiceExt; + +async fn mock_native( + status: StatusCode, + content_type: &'static str, +) -> (Router, Arc>>) { + let captured = Arc::new(Mutex::new(Vec::new())); + let seen = captured.clone(); + let upstream = Router::new().fallback( + move |uri: axum::http::Uri, headers: HeaderMap, body: Bytes| { + let seen = seen.clone(); + async move { + seen.lock().unwrap().push((uri.to_string(), headers, body)); + ( + status, + [ + ("content-type", content_type), + ("retry-after", "7"), + ("x-request-id", "native-fixture"), + ("set-cookie", "must-not-be-forwarded=1"), + ], + Bytes::from_static(b"native-response"), + ) + } + }, + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(listener, upstream).await.unwrap(); + }); + let mut ctx = super::super::tests_keys::test_ctx(KeyPools::new()); + ctx.native_base_url = format!("http://{addr}/backend-api/codex"); + ( + router_for_context(ctx, DEFAULT_MAX_REQUEST_BODY_BYTES), + captured, + ) +} + +fn request(path: &str, content_type: &str, body: &'static str) -> Request { + Request::builder() + .method("POST") + .uri(path) + .header("x-loomrouter-token", local_token()) + .header("authorization", "Bearer caller-chatgpt-token") + .header("chatgpt-account-id", "caller-account") + .header("session_id", "caller-session") + .header("content-type", content_type) + .body(Body::from(body)) + .unwrap() +} + +#[tokio::test] +async fn tooling_compat_search_preserves_native_auth_body_and_response_headers() { + let (app, captured) = mock_native(StatusCode::OK, "application/json").await; + let input = "{ \"search_query\": [{\"q\":\"Codex\"}] }"; + let response = app + .oneshot(request( + "/v1/alpha/search?token=local-only", + "application/json", + input, + )) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()["content-type"], "application/json"); + assert_eq!(response.headers()["x-request-id"], "native-fixture"); + assert!(!response.headers().contains_key("set-cookie")); + assert_eq!( + response.into_body().collect().await.unwrap().to_bytes(), + "native-response" + ); + let captured = captured.lock().unwrap(); + let (path, headers, body) = &captured[0]; + assert_eq!(path, "/backend-api/codex/alpha/search"); + assert_eq!(headers["authorization"], "Bearer caller-chatgpt-token"); + assert_eq!(headers["chatgpt-account-id"], "caller-account"); + assert_eq!(headers["session_id"], "caller-session"); + assert!(!headers.contains_key("x-loomrouter-token")); + assert_eq!(body.as_ref(), input.as_bytes()); +} + +#[tokio::test] +async fn tooling_compat_native_routes_preserve_errors_and_media_types() { + for (path, upstream_path, input_type, output_type) in [ + ( + "/v1/alpha/search", + "/alpha/search", + "application/json", + "application/json", + ), + ( + "/v1/responses/compact", + "/responses/compact", + "application/json", + "application/json", + ), + ( + "/v1/images/generations", + "/images/generations", + "application/json", + "text/event-stream", + ), + ( + "/images/edits", + "/images/edits", + "multipart/form-data; boundary=test", + "image/png", + ), + ] { + let (app, captured) = mock_native(StatusCode::TOO_MANY_REQUESTS, output_type).await; + let response = app.oneshot(request(path, input_type, "{}")).await.unwrap(); + assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS, "{path}"); + assert_eq!(response.headers()["retry-after"], "7"); + assert_eq!(response.headers()["content-type"], output_type); + assert_eq!( + response.into_body().collect().await.unwrap().to_bytes(), + "native-response" + ); + assert_eq!( + captured.lock().unwrap()[0].0, + format!("/backend-api/codex{upstream_path}") + ); + } +} + +#[tokio::test] +async fn tooling_compat_search_keeps_auth_json_and_route_boundaries() { + let (app, captured) = mock_native(StatusCode::OK, "application/json").await; + let mut unauthorized = request("/v1/alpha/search", "application/json", "{}"); + unauthorized.headers_mut().remove("x-loomrouter-token"); + assert_eq!( + app.clone().oneshot(unauthorized).await.unwrap().status(), + StatusCode::UNAUTHORIZED + ); + let mut cross_site = request("/v1/alpha/search", "application/json", "{}"); + cross_site + .headers_mut() + .insert("sec-fetch-site", "cross-site".parse().unwrap()); + assert_eq!( + app.clone().oneshot(cross_site).await.unwrap().status(), + StatusCode::FORBIDDEN + ); + assert_eq!( + app.clone() + .oneshot(request("/v1/alpha/search", "application/json", "{")) + .await + .unwrap() + .status(), + StatusCode::BAD_REQUEST + ); + assert_eq!( + app.oneshot(request("/v1/alpha/arbitrary", "application/json", "{}")) + .await + .unwrap() + .status(), + StatusCode::NOT_FOUND + ); + assert!(captured.lock().unwrap().is_empty()); +} diff --git a/src-tauri/src/proxy/realtime.rs b/src-tauri/src/proxy/realtime.rs index d59e43f..9657074 100644 --- a/src-tauri/src/proxy/realtime.rs +++ b/src-tauri/src/proxy/realtime.rs @@ -21,8 +21,7 @@ pub(super) async fn native_send( headers: &HeaderMap, payload: &Value, ) -> anyhow::Result { - 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 path = match wire { WireApi::Responses => "/responses", WireApi::ChatCompletions => "/chat/completions", @@ -463,21 +462,21 @@ pub(super) async fn clamp_routed_input( /// Rebuild the full input for an incremental follow-up turn. Codex sends /// `previous_response_id` + only the new items; the cached full list from -/// that response id is the conversation so far. A missing id (a fresh -/// conversation, or a cached entry already evicted) degrades to the delta -/// alone, matching the pre-cache behavior. +/// that response id is the conversation so far. Fresh conversations omit the +/// id. A referenced entry may have been evicted or lost on restart; accepting +/// its delta alone would silently erase context, so that continuation fails. pub(super) fn rebuild_input( history: &WsHistory, prev: Option<&str>, delta: Vec, -) -> Vec { - match prev.and_then(|id| history.get(id)) { - Some(base) => { - let mut v = base.clone(); +) -> Option> { + match prev { + Some(id) => { + let mut v = history.get(id)?.clone(); v.extend(delta); - v + Some(v) } - None => delta, + None => Some(delta), } } @@ -571,6 +570,29 @@ async fn ws_session(socket: WebSocket, ctx: ProxyCtx, headers: HeaderMap) { let history = ctx.history.lock().unwrap_or_else(|e| e.into_inner()); rebuild_input(&history, prev.as_deref(), delta) }; + let Some(items) = items else { + // A retry with a full transcript can recover; forwarding a delta + // would produce a successful answer that silently forgot the task. + let frame = json!({ + "type": "error", + "status": 400, + "error": { + "type": "invalid_request_error", + "code": "previous_response_not_found", + "param": "previous_response_id", + "message": "Conversation history is no longer cached. Retry with the full input and without previous_response_id." + } + }); + tracing::warn!("WS continuation rejected: conversation history is unavailable"); + if tx + .send(Message::Text(frame.to_string().into())) + .await + .is_err() + { + break; + } + continue; + }; replace_incremental_input(&mut payload, items.clone()); let mut full_input_items: Option> = Some(items.clone()); if let Some((provider, upstream_model)) = &routed { diff --git a/src-tauri/src/proxy/tests_keys.rs b/src-tauri/src/proxy/tests_keys.rs index 81a91f4..e046944 100644 --- a/src-tauri/src/proxy/tests_keys.rs +++ b/src-tauri/src/proxy/tests_keys.rs @@ -62,6 +62,7 @@ pub(super) fn test_ctx(key_pools: KeyPools) -> ProxyCtx { stats: Arc::new(tokio::sync::RwLock::new(crate::stats::Stats::in_memory())), key_pools, client: reqwest::Client::new(), + native_base_url: "http://127.0.0.1:1".into(), history: Arc::new(Mutex::new(WsHistory::new())), wake: crate::wake_lock::WakeController::disabled(), } diff --git a/src-tauri/src/proxy/tests_realtime.rs b/src-tauri/src/proxy/tests_realtime.rs index f9c7152..47733c8 100644 --- a/src-tauri/src/proxy/tests_realtime.rs +++ b/src-tauri/src/proxy/tests_realtime.rs @@ -228,7 +228,7 @@ fn follow_up_turn_appends_delta_to_the_cached_base() { vec![history_item("a"), history_item("b"), history_item("c")], None, ); - let rebuilt = rebuild_input(&history, Some("resp-1"), vec![history_item("d")]); + let rebuilt = rebuild_input(&history, Some("resp-1"), vec![history_item("d")]).unwrap(); assert_eq!( rebuilt .iter() @@ -239,13 +239,14 @@ fn follow_up_turn_appends_delta_to_the_cached_base() { } #[test] -fn unknown_previous_response_id_degrades_to_delta_alone() { - // A fresh conversation, or an id the cache already evicted: the old - // pre-cache behavior, delta-only. +fn unknown_previous_response_id_does_not_drop_the_conversation() { let history = WsHistory::new(); let rebuilt = rebuild_input(&history, Some("never-cached"), vec![history_item("d")]); - assert_eq!(rebuilt.len(), 1); - assert_eq!(rebuilt[0]["id"], "d"); + assert!(rebuilt.is_none()); + assert_eq!( + rebuild_input(&history, None, vec![history_item("d")]).unwrap(), + vec![history_item("d")] + ); } #[test] @@ -295,7 +296,7 @@ fn a_reconnect_rebuilds_input_from_the_shared_history() { // Session 2 (post-reconnect) sends only the delta + previous_response_id. let items = { let history = shared.lock().unwrap_or_else(|e| e.into_inner()); - rebuild_input(&history, Some("resp-1"), vec![history_item("c")]) + rebuild_input(&history, Some("resp-1"), vec![history_item("c")]).unwrap() }; assert_eq!( items diff --git a/src-tauri/tests/e2e/responses_http.rs b/src-tauri/tests/e2e/responses_http.rs index 9b777f6..474f474 100644 --- a/src-tauri/tests/e2e/responses_http.rs +++ b/src-tauri/tests/e2e/responses_http.rs @@ -4,6 +4,20 @@ use loom_router_lib::config::{AppConfig, ProviderProtocol}; use loom_router_lib::proxy; use std::collections::BTreeMap; +#[tokio::test] +async fn tooling_compat_web_search_reaches_json_validation_instead_of_404() { + let proxy_url = spawn_proxy(AppConfig::default()).await; + let response = reqwest::Client::new() + .post(format!("{proxy_url}/v1/alpha/search")) + .header("x-loomrouter-token", proxy::local_token()) + .header("content-type", "text/plain") + .body("{}") + .send() + .await + .unwrap(); + assert_eq!(response.status().as_u16(), 415); +} + #[tokio::test] async fn invalid_json_uses_the_structured_gateway_error_on_both_http_routes() { let proxy_url = spawn_proxy(AppConfig::default()).await; diff --git a/src-tauri/tests/e2e/responses_ws.rs b/src-tauri/tests/e2e/responses_ws.rs index 5be42b8..a3cc8c8 100644 --- a/src-tauri/tests/e2e/responses_ws.rs +++ b/src-tauri/tests/e2e/responses_ws.rs @@ -6,6 +6,82 @@ use std::collections::BTreeMap; use std::sync::{Arc, Mutex}; use tokio_tungstenite::tungstenite::Message; +#[tokio::test] +async fn tooling_compat_missing_history_rejects_delta_and_accepts_full_replay() { + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let counter = calls.clone(); + let upstream_url = spawn(Router::new().route( + "/v1/chat/completions", + post(move || { + counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + async { ([("content-type", "text/event-stream")], UPSTREAM_SSE) } + }), + )) + .await; + let mut config = AppConfig::default(); + config.providers.insert( + "test".into(), + provider( + "test", + "Test", + ProviderProtocol::OpenAI, + format!("{upstream_url}/v1"), + "sk-test", + "m", + None, + ), + ); + let proxy_url = spawn_proxy(config).await; + let (mut ws, _) = tokio_tungstenite::connect_async(ws_url(&proxy_url)) + .await + .unwrap(); + ws.send(Message::Text( + serde_json::json!({ + "type": "response.create", "model": "test/m", + "previous_response_id": "evicted-or-before-restart", + "input": [{"role":"user","content":"delta only"}] + }) + .to_string() + .into(), + )) + .await + .unwrap(); + let frame = tokio::time::timeout(std::time::Duration::from_secs(5), ws.next()) + .await + .unwrap() + .unwrap() + .unwrap(); + let error: serde_json::Value = serde_json::from_str(frame.to_text().unwrap()).unwrap(); + assert_eq!(error["type"], "error"); + assert_eq!(error["status"], 400); + assert_eq!(error["error"]["code"], "previous_response_not_found"); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0); + + ws.send(Message::Text( + serde_json::json!({ + "type": "response.create", "model": "test/m", + "input": [{"role":"user","content":"full original context and current question"}] + }) + .to_string() + .into(), + )) + .await + .unwrap(); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + let frame = ws.next().await.unwrap().unwrap(); + let event: serde_json::Value = serde_json::from_str(frame.to_text().unwrap()).unwrap(); + assert_ne!(event["type"], "error", "{event}"); + if event["type"] == "response.completed" { + break; + } + } + }) + .await + .unwrap(); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1); +} + #[tokio::test] async fn responses_websocket_end_to_end() { // 1. Fake upstream speaking chat.completion.chunk SSE.