From 83a83f78d9b610fbe30e0da8a1051132da31c72b Mon Sep 17 00:00:00 2001 From: kev1n77 Date: Thu, 5 Nov 2026 13:10:12 +0800 Subject: [PATCH] fix(images): use standalone Images requests for ChatGPT subscriptions --- src/crates/adapters/ai-adapters/AGENTS.md | 12 + .../src/client/image_generation.rs | 533 +++++++----------- src/crates/assembly/core/AGENTS.md | 1 + .../core/src/agentic/image_generation/mod.rs | 4 +- .../implementations/generate_image_tool.rs | 4 +- src/crates/contracts/core-types/AGENTS.md | 3 + src/crates/contracts/core-types/src/ai.rs | 29 +- .../image-generation/imageDialects.test.ts | 17 +- .../image-generation/imageDialects.ts | 11 +- .../src/infrastructure/config/types/index.ts | 4 +- .../src/locales/en-US/settings/media.json | 4 +- .../src/locales/zh-CN/settings/media.json | 4 +- .../src/locales/zh-TW/settings/media.json | 4 +- 13 files changed, 288 insertions(+), 342 deletions(-) diff --git a/src/crates/adapters/ai-adapters/AGENTS.md b/src/crates/adapters/ai-adapters/AGENTS.md index 4dfbcf4cbc..c3d146106a 100644 --- a/src/crates/adapters/ai-adapters/AGENTS.md +++ b/src/crates/adapters/ai-adapters/AGENTS.md @@ -376,3 +376,15 @@ and sends no inference request. This does not verify remote-host behavior. The image-generation filter uses synthetic HTTP credentials. The ignored Codex probe requires a real in-app subscription login and generates a billed image; run it explicitly only when live provider validation is needed. +Set `PROBE_CODEX_IMAGE_OUTPUT_DIR` to save the generated image for visual review. +Set `PROBE_CODEX_IMAGE_OUTPUT_FORMAT=gif` to request GIF output and +`PROBE_CODEX_IMAGE_PROMPT` to describe the subject and looping motion. The probe +checks the GIF signature; inspect frame count and timing in the saved file to +confirm animation. +The probe uses the production standalone subscription Images route and built-in +image model. It does not discover or invoke a chat model. Saved legacy +`/responses` endpoints are translated in memory to `/images/generations`. + +```bash +cargo test --locked -p openbitfun-ai-adapters --features image-generation,subscription-auth --lib client::image_generation::tests::probe_codex_subscription_image_generation -- --ignored --exact --nocapture +``` diff --git a/src/crates/adapters/ai-adapters/src/client/image_generation.rs b/src/crates/adapters/ai-adapters/src/client/image_generation.rs index 168397c07c..ad36ba2b19 100644 --- a/src/crates/adapters/ai-adapters/src/client/image_generation.rs +++ b/src/crates/adapters/ai-adapters/src/client/image_generation.rs @@ -24,14 +24,10 @@ const REQUEST_TIMEOUT_SECS: u64 = 180; /// Guard against a provider streaming an unbounded body. const MAX_BODY_BYTES: usize = 64 * 1024 * 1024; const DEFAULT_MIME: &str = "image/png"; -/// The Responses API has a separate image-tool model. Keep this independent -/// from the subscription's top-level chat model, which is only responsible for -/// orchestrating the tool call and revising the prompt. -const DEFAULT_CODEX_IMAGE_MODEL: &str = "gpt-image-2.5-sunburst"; -/// `high` is supported by the current GPT Image models and older GPT Image -/// models, so existing subscription configurations can opt into a quality -/// setting without a persisted-config migration. -const DEFAULT_CODEX_IMAGE_QUALITY: &str = "high"; +/// Model ID observed in Codex Desktop's standalone Images requests. Legacy +/// service model names described a chat orchestrator and must not be reinterpreted +/// as image model IDs. +const DEFAULT_CODEX_IMAGE_MODEL: &str = "gpt-image-2"; /// Substrings that mean the provider refused on safety grounds rather than /// failing. Reported separately so the UI can say "blocked" instead of "failed". @@ -62,6 +58,16 @@ pub struct ImageGenerationTarget<'a> { pub proxy: Option, } +impl ImageGenerationTarget<'_> { + /// Model ID sent to the image service, not an observed backend model. + pub fn requested_model(&self) -> &str { + match self.dialect { + ImageDialect::ChatgptCodex => DEFAULT_CODEX_IMAGE_MODEL, + _ => self.model, + } + } +} + /// One generation call. Unset fields fall back to the provider default. #[derive(Debug, Clone, Default)] pub struct ImageGenerationRequest { @@ -180,10 +186,11 @@ pub(crate) fn endpoint(target: &ImageGenerationTarget<'_>) -> Result) -> Result String { + if dialect == ImageDialect::ChatgptCodex { + if let Some(root) = url.trim_end_matches('/').strip_suffix("/responses") { + return format!("{root}{}", dialect.endpoint_path()); + } + } + url.to_string() +} + /// Rewrite a size expression to the requested separator. /// /// `size` stays a dialect-native string in config, so a user who typed the other @@ -279,47 +297,26 @@ fn build_body(target: &ImageGenerationTarget<'_>, request: &ImageGenerationReque match target.dialect { ImageDialect::OpenAiImages => openai_body(target, request), ImageDialect::DashScopeNative => dashscope_body(target, request), - ImageDialect::ChatgptCodex => chatgpt_codex_body(target.model, request), + ImageDialect::ChatgptCodex => chatgpt_codex_body(request), } } -/// ChatGPT subscription body. -/// -/// The image is not requested from an image endpoint: the model is asked to call -/// its built-in `image_generation` tool, and the picture arrives as a Responses -/// output item. `store: false` is required by the Codex backend, and `stream` -/// is what produces the SSE events the caller parses. -fn chatgpt_codex_body(model: &str, request: &ImageGenerationRequest) -> Value { - let mut tool = json!({ - "type": "image_generation", +/// Standalone Images JSON request, matching the Codex Desktop capture. +/// Explicit service parameters still win over the observed auto defaults. +/// The subscription endpoint generates one image; no chat model, tools, stream, +/// store, or n fields are sent. +fn chatgpt_codex_body(request: &ImageGenerationRequest) -> Value { + let mut body = json!({ "model": DEFAULT_CODEX_IMAGE_MODEL, - "quality": request - .quality - .as_deref() - .unwrap_or(DEFAULT_CODEX_IMAGE_QUALITY), + "prompt": request.prompt, + "background": request.background.as_deref().unwrap_or("opaque"), + "quality": request.quality.as_deref().unwrap_or("auto"), + "size": request.size.as_deref().map(|size| normalize_size(size, 'x')).unwrap_or_else(|| "auto".to_string()), }); - // The tool accepts the same knobs as the image API. Quality defaults to a - // high-quality setting above, while an explicit service setting wins. - if let Some(size) = request.size.as_deref() { - tool["size"] = json!(normalize_size(size, 'x')); - } - if let Some(quality) = request.quality.as_deref() { - tool["quality"] = json!(quality); - } - if let Some(background) = request.background.as_deref() { - tool["background"] = json!(background); + if let Some(output_format) = request.output_format.as_deref() { + body["output_format"] = json!(output_format); } - - json!({ - "model": model, - "stream": true, - "store": false, - "tools": [tool], - "input": [{ - "role": "user", - "content": [{ "type": "input_text", "text": request.prompt }], - }], - }) + body } /// Where a parsed image still has to come from. @@ -403,139 +400,14 @@ fn parse_images( match dialect { ImageDialect::OpenAiImages => parse_openai_images(value), ImageDialect::DashScopeNative => parse_dashscope_images(value), - // Streamed by `parse_chatgpt_codex_stream`; reaching here means the JSON - // path was taken for a dialect that never answers with one document. - ImageDialect::ChatgptCodex => Err(ImageGenerationError::new( - ImageGenerationErrorKind::Provider, - "the ChatGPT subscription dialect streams its result and cannot be read as JSON", - )), - } -} - -/// Reads the Responses SSE transcript and returns the image the model produced. -/// -/// The backend emits progress events while the tool runs, so only the terminal -/// `output_item.done` carries `result`. A response that completes without an -/// image item means the model declined to call the tool, which is a different -/// failure from an empty payload and is reported as such. -fn parse_chatgpt_codex_stream(raw: &[u8]) -> Result, ImageGenerationError> { - let text = String::from_utf8_lossy(raw); - let mut sources = Vec::new(); - let mut failure: Option<(Option, String)> = None; - let mut completed_without_image = false; - - for line in text.lines() { - let Some(payload) = line.strip_prefix("data:") else { - continue; - }; - let payload = payload.trim(); - if payload.is_empty() || payload == "[DONE]" { - continue; - } - let Ok(value) = serde_json::from_str::(payload) else { - continue; - }; - match value - .get("type") - .and_then(Value::as_str) - .unwrap_or_default() - { - "response.output_item.done" => { - let item = value.get("item"); - if item - .and_then(|item| item.get("type")) - .and_then(Value::as_str) - != Some("image_generation_call") - { - continue; - } - let Some(encoded) = item - .and_then(|item| item.get("result")) - .and_then(Value::as_str) - else { - continue; - }; - let bytes = BASE64_STANDARD.decode(encoded.trim()).map_err(|err| { - ImageGenerationError::new( - ImageGenerationErrorKind::Provider, - format!("image payload is not valid base64: {err}"), - ) - })?; - let mime = sniff_mime(&bytes).unwrap_or(DEFAULT_MIME).to_string(); - sources.push(ImageSource::Inline { bytes, mime }); - } - "response.failed" => { - let error = value.pointer("/response/error"); - failure = Some(( - error - .and_then(|error| error.get("code")) - .and_then(Value::as_str) - .map(str::to_string), - error - .and_then(|error| error.get("message")) - .and_then(Value::as_str) - .unwrap_or("the model reported a failed response") - .to_string(), - )); - } - "error" => { - let error = value.get("error"); - failure = Some(( - error - .and_then(|error| error.get("code")) - .and_then(Value::as_str) - .map(str::to_string), - error - .and_then(|error| error.get("message")) - .and_then(Value::as_str) - .unwrap_or("the provider streamed an error") - .to_string(), - )); - } - "response.completed" => completed_without_image = true, - _ => {} - } - } - - if let Some((code, message)) = failure { - return Err(ImageGenerationError::new( - codex_stream_error_kind(&message), - match code { - Some(code) => format!("provider failed the image request ({code}): {message}"), - None => format!("provider failed the image request: {message}"), - }, - )); - } - if sources.is_empty() { - return Err(ImageGenerationError::empty_result( - if completed_without_image { - "the response completed without calling the image tool; pick a model that can generate images" - } else { - "the provider streamed no image result" - }, - )); - } - Ok(sources) -} - -/// Map a streamed error message onto the guidance class the UI renders. -fn codex_stream_error_kind(message: &str) -> ImageGenerationErrorKind { - let lowered = message.to_ascii_lowercase(); - if looks_like_content_filter(message) { - ImageGenerationErrorKind::ContentFiltered - } else if lowered.contains("rate limit") || lowered.contains("usage limit") { - ImageGenerationErrorKind::RateLimited - } else if lowered.contains("timed out") || lowered.contains("timeout") { - ImageGenerationErrorKind::Timeout - } else { - ImageGenerationErrorKind::Provider + ImageDialect::ChatgptCodex => parse_openai_images(value), } } /// Error body of a rejected subscription request. /// /// The Codex backend answers JSON (`{"detail": ...}` for request problems, -/// `{"error": {...}}` for API errors) even though a successful call streams. +/// `{"error": {...}}` for API errors), just like a successful Images JSON response. fn chatgpt_codex_error(status: reqwest::StatusCode, raw: &[u8]) -> ImageGenerationError { let value: Value = serde_json::from_slice(raw).unwrap_or(Value::Null); if let Some(detail) = value.get("detail").and_then(Value::as_str) { @@ -556,71 +428,6 @@ fn chatgpt_codex_error(status: reqwest::StatusCode, raw: &[u8]) -> ImageGenerati ) } -/// Ask the account's own catalog which model to drive the image tool with. -async fn discover_chatgpt_codex_model( - client: &Client, - target: &ImageGenerationTarget<'_>, -) -> Result { - let base = match target.request_url { - Some(request_url) => request_url - .trim_end_matches('/') - .trim_end_matches("/responses") - .to_string(), - None => target.base_url.trim_end_matches('/').to_string(), - }; - let url = format!("{base}/models?client_version=1.0.0"); - - let mut builder = client - .get(&url) - .bearer_auth(target.api_key.trim()) - .timeout(Duration::from_secs(REQUEST_TIMEOUT_SECS)); - if let Some(headers) = target.custom_headers { - for (key, value) in headers { - builder = builder.header(key.as_str(), value.as_str()); - } - } - let response = builder.send().await.map_err(classify_transport)?; - let status = response.status(); - let raw = response.bytes().await.map_err(classify_transport)?; - let value: Value = serde_json::from_slice(&raw).map_err(|err| { - ImageGenerationError::new( - classify_status(status), - format!("could not read the subscription model catalog: {err}"), - ) - })?; - if !status.is_success() { - return Err(error_from_response(status, &value)); - } - - let model = value - .get("models") - .and_then(Value::as_array) - .and_then(|models| { - let mut entries: Vec<(u64, String)> = models - .iter() - .filter_map(|model| { - let slug = model.get("slug").and_then(Value::as_str)?.trim(); - if slug.is_empty() { - return None; - } - let priority = model - .get("priority") - .and_then(Value::as_u64) - .unwrap_or(10_000); - Some((priority, slug.to_string())) - }) - .collect(); - entries.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))); - entries.into_iter().next().map(|(_, slug)| slug) - }); - - model.ok_or_else(|| { - ImageGenerationError::config( - "the subscription login exposes no model to drive image generation; set a model name explicitly", - ) - }) -} - /// Extract a provider error from the shapes seen in the wild: /// `{error:{code,message}}`, `{code,message}` and DashScope's `{output:{code,message}}`. fn extract_error(value: &Value) -> Option<(Option, String)> { @@ -830,29 +637,28 @@ pub async fn generate( if request.prompt.trim().is_empty() { return Err(ImageGenerationError::config("prompt must not be empty")); } - // The subscription route asks a chat model to call its image tool, so the - // model is whatever the account's catalog offers. Discover it when the - // service left the field empty instead of guessing a slug. - let discover_model = - target.dialect == ImageDialect::ChatgptCodex && target.model.trim().is_empty(); - if target.model.trim().is_empty() && !discover_model { + if target.dialect != ImageDialect::ChatgptCodex && target.model.trim().is_empty() { return Err(ImageGenerationError::config("model name must not be empty")); } + if target.dialect == ImageDialect::ChatgptCodex { + if let Some(format) = request.output_format.as_deref() { + if !matches!(format, "png" | "jpeg" | "webp" | "gif") { + return Err(ImageGenerationError::config( + "subscription image output_format must be png, jpeg, webp, or gif", + )); + } + } + } let url = endpoint(target)?; let client = crate::client::http::create_http_client(target.proxy.clone(), target.skip_ssl_verify); - let model = if discover_model { - discover_chatgpt_codex_model(&client, target).await? - } else { - target.model.trim().to_string() - }; - let body = if target.dialect == ImageDialect::ChatgptCodex { - chatgpt_codex_body(&model, &request) - } else { - build_body(target, &request) - }; + let body = build_body(target, &request); + let model = body + .get("model") + .and_then(Value::as_str) + .unwrap_or_default(); debug!( "Image generation request: dialect={:?} model={} url={}", @@ -897,23 +703,8 @@ pub async fn generate( )); } - // The subscription route answers with an SSE transcript, not a JSON document. - if target.dialect == ImageDialect::ChatgptCodex { - if !status.is_success() { - return Err(chatgpt_codex_error(status, &raw)); - } - let sources = parse_chatgpt_codex_stream(&raw)?; - let mut images = Vec::with_capacity(sources.len()); - for source in sources { - match source { - ImageSource::Inline { bytes, mime } => images.push(GeneratedImage { bytes, mime }), - ImageSource::Remote(url) => { - let (bytes, mime) = download_image(&client, &url).await?; - images.push(GeneratedImage { bytes, mime }); - } - } - } - return Ok(ImageGenerationResponse { images }); + if target.dialect == ImageDialect::ChatgptCodex && !status.is_success() { + return Err(chatgpt_codex_error(status, &raw)); } let value: Value = serde_json::from_slice(&raw).map_err(|err| { @@ -1094,33 +885,49 @@ mod tests { } #[test] - fn codex_body_selects_explicit_high_quality_image_model() { - let body = chatgpt_codex_body( - "gpt-6-astra", - &ImageGenerationRequest { - prompt: "a red fox".to_string(), - ..ImageGenerationRequest::default() - }, + fn codex_body_matches_the_desktop_images_capture() { + let body = chatgpt_codex_body(&ImageGenerationRequest { + prompt: "a red fox".to_string(), + ..ImageGenerationRequest::default() + }); + assert_eq!( + body, + json!({ + "model": "gpt-image-2", "prompt": "a red fox", + "background": "opaque", "quality": "auto", "size": "auto" + }) ); - - assert_eq!(body["model"], "gpt-6-astra"); - assert_eq!(body["tools"][0]["type"], "image_generation"); - assert_eq!(body["tools"][0]["model"], "gpt-image-2.5-sunburst"); - assert_eq!(body["tools"][0]["quality"], "high"); } #[test] - fn codex_body_preserves_an_explicit_quality_override() { - let body = chatgpt_codex_body( - "gpt-6-astra", - &ImageGenerationRequest { - prompt: "a red fox".to_string(), - quality: Some("max".to_string()), - ..ImageGenerationRequest::default() - }, + fn codex_body_preserves_explicit_image_parameters() { + let body = chatgpt_codex_body(&ImageGenerationRequest { + prompt: "a red fox".to_string(), + quality: Some("high".to_string()), + background: Some("transparent".to_string()), + size: Some("1024*1536".to_string()), + n: Some(10), + ..ImageGenerationRequest::default() + }); + assert_eq!( + body, + json!({ + "model": "gpt-image-2", "prompt": "a red fox", + "background": "transparent", "quality": "high", "size": "1024x1536" + }) ); + } - assert_eq!(body["tools"][0]["quality"], "max"); + #[test] + fn codex_body_requests_gif_without_changing_the_image_model() { + let body = chatgpt_codex_body(&ImageGenerationRequest { + prompt: "a fox blinking in a seamless loop".to_string(), + output_format: Some("gif".to_string()), + ..ImageGenerationRequest::default() + }); + assert_eq!(body["output_format"], "gif"); + assert_eq!(body["model"], "gpt-image-2"); + assert_eq!(body["size"], "auto"); } #[test] @@ -1296,34 +1103,97 @@ mod tests { } #[tokio::test] - async fn subscription_catalog_sends_bearer_and_account_headers() { - use axum::{ - http::{HeaderMap, StatusCode}, - routing::get, - Json, Router, - }; + async fn subscription_posts_images_json_without_discovering_a_chat_model() { + use axum::{http::HeaderMap, routing::post, Json, Router}; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let base_url = format!("http://{}", listener.local_addr().unwrap()); let server = tokio::spawn(async move { - let app = Router::new().route("/models", get(|headers: HeaderMap| async move { - if headers.get("authorization").and_then(|value| value.to_str().ok()) != Some("Bearer sk-test") - || headers.get("chatgpt-account-id").and_then(|value| value.to_str().ok()) != Some("test-account") - { - return (StatusCode::UNAUTHORIZED, Json(json!({"error": {"message": "missing subscription authentication"}}))); - } - (StatusCode::OK, Json(json!({"models": [{"slug": "account-model", "priority": 0}]}))) + let app = Router::new().route("/images/generations", post(|headers: HeaderMap, Json(body): Json| async move { + assert_eq!(headers["authorization"], "Bearer sk-test"); + assert_eq!(headers["chatgpt-account-id"], "test-account"); + assert_eq!(headers["originator"], "openbitfun"); + assert_eq!(body, json!({"model":"gpt-image-2", "prompt":"a red fox", "background":"opaque", "quality":"auto", "size":"auto"})); + Json(json!({"created":1793849136_u64,"background":"opaque","quality":"medium","size":"1254x1254", + "data":[{"b64_json":"iVBORw0KGgo=", "generation_id":"test-generation"}], + "usage":{"total_tokens":2494}})) })); axum::serve(listener, app).await.unwrap(); }); - let headers = - HashMap::from([("ChatGPT-Account-ID".to_string(), "test-account".to_string())]); + let headers = HashMap::from([ + ("ChatGPT-Account-ID".to_string(), "test-account".to_string()), + ("originator".to_string(), "openbitfun".to_string()), + ]); let mut target = target(ImageDialect::ChatgptCodex, &base_url); + let legacy_url = format!("{base_url}/responses"); + target.request_url = Some(&legacy_url); + target.model = "legacy-chat-model"; target.custom_headers = Some(&headers); - openbitfun_services_core::tls_provider::ensure_ring_crypto_provider(); - let client = Client::builder().no_proxy().build().unwrap(); - let result = discover_chatgpt_codex_model(&client, &target).await; + let result = generate( + &target, + ImageGenerationRequest { + prompt: "a red fox".to_string(), + ..ImageGenerationRequest::default() + }, + ) + .await; server.abort(); - assert_eq!(result.unwrap(), "account-model"); + let response = result.unwrap(); + assert_eq!(response.images.len(), 1); + assert_eq!(response.images[0].mime, "image/png"); + assert_eq!( + response.images[0].bytes, + BASE64_STANDARD.decode("iVBORw0KGgo=").unwrap() + ); + } + + #[test] + fn subscription_legacy_endpoints_are_adapted_without_changing_api_key_routes() { + let root = "https://chatgpt.com/backend-api/codex"; + let expected = format!("{root}/images/generations"); + for base in [ + root.to_string(), + format!("{root}/responses/"), + expected.clone(), + ] { + assert_eq!( + endpoint(&target(ImageDialect::ChatgptCodex, &base)).unwrap(), + expected + ); + } + for old_model in ["", "gpt-6.1-sol", "gpt-6-astra", "gpt-image-2.6-sunburst"] { + let mut saved = target(ImageDialect::ChatgptCodex, root); + saved.model = old_model; + assert_eq!(saved.requested_model(), "gpt-image-2"); + assert_eq!( + build_body(&saved, &ImageGenerationRequest::default())["model"], + "gpt-image-2" + ); + } + let mut api = target(ImageDialect::OpenAiImages, root); + api.request_url = Some("https://gateway.example/responses"); + assert_eq!(endpoint(&api).unwrap(), "https://gateway.example/responses"); + } + + #[test] + fn subscription_json_errors_and_empty_images_are_reported() { + let error = chatgpt_codex_error( + reqwest::StatusCode::UNAUTHORIZED, + br#"{"detail":"login expired"}"#, + ); + assert_eq!(error.kind, ImageGenerationErrorKind::Auth); + assert!(error.message.contains("login expired")); + let error = chatgpt_codex_error(reqwest::StatusCode::BAD_REQUEST, br#"{"error":{"code":"content_policy_violation","message":"blocked by safety system"}}"#); + assert_eq!(error.kind, ImageGenerationErrorKind::ContentFiltered); + assert!( + parse_images(ImageDialect::ChatgptCodex, &json!({"data":[]})) + .unwrap() + .is_empty() + ); + assert!(parse_images( + ImageDialect::ChatgptCodex, + &json!({"data":[{"b64_json":"invalid-base64"}]}) + ) + .is_err()); } #[cfg(feature = "subscription-auth")] @@ -1337,37 +1207,66 @@ mod tests { ) .await .expect("codex credential"); - let model = std::env::var("PROBE_CODEX_MODEL").unwrap_or_default(); let target = ImageGenerationTarget { dialect: ImageDialect::ChatgptCodex, base_url: credential.base_url.as_deref().unwrap_or_default(), request_url: credential.request_url.as_deref(), - model: &model, + model: "", api_key: &credential.api_key, custom_headers: Some(&credential.extra_headers), custom_headers_mode: None, skip_ssl_verify: false, proxy: None, }; + println!( + "Testing subscription image generation: endpoint={} requested_model={}", + endpoint(&target).unwrap(), + DEFAULT_CODEX_IMAGE_MODEL + ); + let output_format = std::env::var("PROBE_CODEX_IMAGE_OUTPUT_FORMAT").ok(); + let prompt = std::env::var("PROBE_CODEX_IMAGE_PROMPT").unwrap_or_else(|_| "A cute minimalist mascot icon with a rounded-rectangle body, two small friendly oval eyes, and a short top antenna ending in a round joystick knob. Use a playful, harmonious color palette selected randomly for each generation, with no fixed colors. Centered composition, clean uncluttered background, polished product illustration.".to_string()); let response = generate( &target, ImageGenerationRequest { - prompt: "A cute minimalist mascot icon with a rounded-rectangle body, two small friendly oval eyes, and a short top antenna ending in a round joystick knob. Use a playful, harmonious color palette selected randomly for each generation, with no fixed colors. Centered composition, clean uncluttered background, polished product illustration.".to_string(), - size: Some("1024x1024".to_string()), - n: Some(1), + prompt, + output_format: output_format.clone(), ..ImageGenerationRequest::default() }, ) .await .expect("subscription image generation"); assert!(!response.images.is_empty()); - for image in response.images { + let output_dir = + std::env::var_os("PROBE_CODEX_IMAGE_OUTPUT_DIR").map(std::path::PathBuf::from); + if let Some(directory) = output_dir.as_ref() { + tokio::fs::create_dir_all(directory) + .await + .expect("image output directory"); + } + for (index, image) in response.images.into_iter().enumerate() { assert!(sniff_mime(&image.bytes).is_some()); println!( - "Generated image: mime={} bytes={}", + "Generated image: requested_model={} mime={} bytes={}", + DEFAULT_CODEX_IMAGE_MODEL, image.mime, image.bytes.len() ); + if let Some(directory) = output_dir.as_ref() { + let extension = match image.mime.as_str() { + "image/jpeg" => "jpg", + "image/webp" => "webp", + "image/gif" => "gif", + _ => "png", + }; + let path = directory.join(format!("codex-images-{}.{}", index + 1, extension)); + tokio::fs::write(&path, &image.bytes) + .await + .expect("generated image file"); + println!("Saved generated image: {}", path.display()); + } + if output_format.as_deref() == Some("gif") { + assert_eq!(image.mime, "image/gif", "provider must return a real GIF"); + } } } diff --git a/src/crates/assembly/core/AGENTS.md b/src/crates/assembly/core/AGENTS.md index 04ee00d919..7ef4678c64 100644 --- a/src/crates/assembly/core/AGENTS.md +++ b/src/crates/assembly/core/AGENTS.md @@ -256,6 +256,7 @@ For image-service selection and compatibility with saved subscription configurat ```bash cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git,tools-image-generation,subscription-auth --lib agentic::image_generation::tests +cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git,tools-image-generation --lib agentic::tools::implementations::generate_image_tool::tests cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git,tools-image-generation --lib agentic::tools::product_runtime::materialization::tests::image_tools_follow_independent_compiled_owners cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git,tools-image-analysis --lib agentic::tools::product_runtime::materialization::tests::image_tools_follow_independent_compiled_owners ``` diff --git a/src/crates/assembly/core/src/agentic/image_generation/mod.rs b/src/crates/assembly/core/src/agentic/image_generation/mod.rs index 027ea4eeae..8f138b736f 100644 --- a/src/crates/assembly/core/src/agentic/image_generation/mod.rs +++ b/src/crates/assembly/core/src/agentic/image_generation/mod.rs @@ -147,8 +147,8 @@ fn service_with_auth_route(service: &ImageServiceConfig) -> ImageServiceConfig { service.dialect = ImageDialect::ChatgptCodex; service.base_url.clear(); service.request_url = None; - // An image-model ID cannot drive a Responses tool call. Resolve a chat - // model from this subscription's live catalog instead. + // The subscription Images adapter owns the image model. Keep the legacy + // model slot empty in the resolved view without rewriting stored data. service.model_name.clear(); service.params.n = Some(1); } diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/generate_image_tool.rs b/src/crates/assembly/core/src/agentic/tools/implementations/generate_image_tool.rs index bd8cea018a..859ab833c0 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/generate_image_tool.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/generate_image_tool.rs @@ -267,7 +267,7 @@ impl Tool for GenerateImageTool { "service_id": {"type": "string"}, "service": {"type": "string"}, "dialect": {"type": "string"}, - "model": {"type": "string"}, + "model": {"type": "string", "description": "Model ID requested from the image service."}, "mime_type": {"type": "string"}, "bytes": {"type": "integer", "minimum": 0, "description": "Byte length of the first generated image."}, "summary": {"type": "string"} @@ -368,7 +368,7 @@ impl Tool for GenerateImageTool { "service_id": resolved.service.id, "service": resolved.service.name, "dialect": format!("{:?}", resolved.service.dialect), - "model": resolved.service.model_name, + "model": target.requested_model(), "mime_type": persisted[0].mime, "bytes": persisted[0].bytes, "summary": summary, diff --git a/src/crates/contracts/core-types/AGENTS.md b/src/crates/contracts/core-types/AGENTS.md index 6d8bddfa6e..04d2d37553 100644 --- a/src/crates/contracts/core-types/AGENTS.md +++ b/src/crates/contracts/core-types/AGENTS.md @@ -28,3 +28,6 @@ node scripts/check-core-boundaries.mjs ``` For documentation-only changes, run `git diff --check`. + +For persisted image dialect values and endpoint compatibility, run +`cargo test --locked -p openbitfun-core-types --lib ai::image_dialect_compatibility`. diff --git a/src/crates/contracts/core-types/src/ai.rs b/src/crates/contracts/core-types/src/ai.rs index 3721fbb607..d3c57136b2 100644 --- a/src/crates/contracts/core-types/src/ai.rs +++ b/src/crates/contracts/core-types/src/ai.rs @@ -920,11 +920,11 @@ pub enum ImageDialect { /// `POST {base}/services/aigc/multimodal-generation/generation`. #[serde(rename = "dashscope_native")] DashScopeNative, - /// ChatGPT subscription images, driven through Codex CLI's ChatGPT backend: - /// `POST {base}/responses` with an `image_generation` tool, streamed back as - /// SSE `response.output_item.done` items. This is a separate billing and - /// protocol path from [`Self::OpenAiImages`]: it takes the OAuth access token - /// from a Codex subscription login and never reaches the platform image API. + /// ChatGPT subscription images through the Codex subscription backend: + /// `POST {base}/images/generations` with a standalone Images JSON body. + /// This is a separate billing and protocol path from [`Self::OpenAiImages`]: + /// it takes the OAuth access token from a Codex subscription login and never + /// reaches the platform image API. #[serde(rename = "chatgpt_codex")] ChatgptCodex, } @@ -935,7 +935,7 @@ impl ImageDialect { match self { Self::OpenAiImages => "/images/generations", Self::DashScopeNative => "/services/aigc/multimodal-generation/generation", - Self::ChatgptCodex => "/responses", + Self::ChatgptCodex => "/images/generations", } } @@ -944,7 +944,7 @@ impl ImageDialect { match self { Self::OpenAiImages => MAX_IMAGES_PER_GENERATION_REQUEST, Self::DashScopeNative => 6, - // The subscription route returns one image per tool call. + // The subscription route generates one image per request. Self::ChatgptCodex => 1, } } @@ -956,6 +956,21 @@ impl ImageDialect { } } +#[cfg(test)] +mod image_dialect_compatibility { + use super::ImageDialect; + + #[test] + fn subscription_wire_value_survives_the_images_endpoint_upgrade() { + let legacy = r#""chatgpt_codex""#; + let dialect: ImageDialect = serde_json::from_str(legacy).unwrap(); + assert_eq!(serde_json::to_string(&dialect).unwrap(), legacy); + assert_eq!(dialect.endpoint_path(), "/images/generations"); + assert!(dialect.requires_subscription()); + assert_eq!(dialect.max_images_per_request(), 1); + } +} + #[cfg(test)] mod remote_model_routing_compatibility { #[test] diff --git a/src/web-ui/src/infrastructure/config/components/image-generation/imageDialects.test.ts b/src/web-ui/src/infrastructure/config/components/image-generation/imageDialects.test.ts index 3ab56c3d87..18e8d75137 100644 --- a/src/web-ui/src/infrastructure/config/components/image-generation/imageDialects.test.ts +++ b/src/web-ui/src/infrastructure/config/components/image-generation/imageDialects.test.ts @@ -19,7 +19,7 @@ describe('image service authentication routing', () => { const result = withImageServiceAuth(legacyService, { type: 'subscription', provider: 'codex' }); expect(result).toMatchObject({ id: 'saved-service', dialect: 'chatgpt_codex', model_name: '', params: { n: 1 } }); expect(resolveImageEndpoint(result.base_url, result.request_url, result.dialect)) - .toBe('https://chatgpt.com/backend-api/codex/responses'); + .toBe('https://chatgpt.com/backend-api/codex/images/generations'); expect(legacyService.request_url).toBe('https://api.openai.com/v1/images/generations'); }); @@ -36,10 +36,23 @@ describe('image service authentication routing', () => { expect(resolveImageEndpoint(result.base_url, result.request_url, result.dialect)).toBe('https://api.openai.com/v1/images/generations'); }); - it('preserves custom API-key gateways and explicitly chosen subscription models', () => { + it('preserves custom API-key gateways and legacy subscription model slots', () => { expect(withImageServiceAuth(legacyService, { type: 'api_key' })).toEqual(legacyService); const auth = { type: 'subscription' as const, provider: 'codex' as const }; const service = { ...withImageServiceAuth(legacyService, auth), model_name: 'account-model' }; expect(withImageServiceAuth(service, auth).model_name).toBe('account-model'); }); + + it('resolves old subscription endpoints without rewriting serialized settings', () => { + const root = 'https://chatgpt.com/backend-api/codex'; + const auth = { type: 'subscription' as const, provider: 'codex' as const }; + const saved = JSON.parse(JSON.stringify({ ...withImageServiceAuth(legacyService, auth), + request_url: `${root}/responses`, model_name: 'gpt-6.1-sol' })); + const snapshot = JSON.stringify(saved); + expect(resolveImageEndpoint(saved.base_url, saved.request_url, saved.dialect)).toBe(`${root}/images/generations`); + expect(resolveImageEndpoint(`${root}/responses/`, undefined, 'chatgpt_codex')).toBe(`${root}/images/generations`); + expect(resolveImageEndpoint(`${root}/images/generations`, undefined, 'chatgpt_codex')).toBe(`${root}/images/generations`); + expect(JSON.stringify(saved)).toBe(snapshot); + expect(resolveImageEndpoint(root, `${root}/responses`, 'openai_images')).toBe(`${root}/responses`); + }); }); diff --git a/src/web-ui/src/infrastructure/config/components/image-generation/imageDialects.ts b/src/web-ui/src/infrastructure/config/components/image-generation/imageDialects.ts index 245eef0146..290e130004 100644 --- a/src/web-ui/src/infrastructure/config/components/image-generation/imageDialects.ts +++ b/src/web-ui/src/infrastructure/config/components/image-generation/imageDialects.ts @@ -72,10 +72,10 @@ export const IMAGE_DIALECT_PRESETS: readonly ImageDialectPreset[] = [ id: 'chatgpt_codex', labelKey: 'dialect.chatgptCodex.name', descriptionKey: 'dialect.chatgptCodex.description', - endpointPath: '/responses', + endpointPath: '/images/generations', // The login supplies this address; the value here only seeds a new draft. defaultBaseUrl: 'https://chatgpt.com/backend-api/codex', - // Empty means "discover from the account catalog when sending". + // The subscription adapter owns the image model; legacy chat model IDs stay readable. defaultModel: '', sizes: ['1024x1024', '1536x1024', '1024x1536'], maxImagesPerRequest: 1, @@ -121,9 +121,12 @@ export function resolveImageEndpoint( dialect: ImageDialect, ): string { const override = requestUrl?.trim(); - if (override) return override; + const subscriptionUrl = (url: string) => dialect === 'chatgpt_codex' + ? url.replace(/\/responses\/?$/, '/images/generations') + : url; + if (override) return subscriptionUrl(override); - const root = baseUrl.trim().replace(/\/+$/, ''); + const root = subscriptionUrl(baseUrl.trim().replace(/\/+$/, '')); if (!root) return ''; const path = findImageDialectPreset(dialect).endpointPath; return root.endsWith(path) ? root : `${root}${path}`; diff --git a/src/web-ui/src/infrastructure/config/types/index.ts b/src/web-ui/src/infrastructure/config/types/index.ts index db407394a7..7a73fe85eb 100644 --- a/src/web-ui/src/infrastructure/config/types/index.ts +++ b/src/web-ui/src/infrastructure/config/types/index.ts @@ -386,8 +386,8 @@ export interface DefaultModelsConfig { /** * Image request protocol. * - * `chatgpt_codex` is the subscription route: it drives a chat model's - * `image_generation` tool over the provider's own backend and never touches the + * `chatgpt_codex` sends standalone Images JSON requests using the subscription + * login over the provider's own backend and never touches the * API-key image endpoint. */ export type ImageDialect = 'openai_images' | 'dashscope_native' | 'chatgpt_codex'; diff --git a/src/web-ui/src/locales/en-US/settings/media.json b/src/web-ui/src/locales/en-US/settings/media.json index 597f0808a0..a84d62748d 100644 --- a/src/web-ui/src/locales/en-US/settings/media.json +++ b/src/web-ui/src/locales/en-US/settings/media.json @@ -124,8 +124,8 @@ "modelName": { "label": "Image model id", "hint": "The exact model id the provider expects for image generation, not a chat model.", - "subscriptionPlaceholder": "Empty uses any model the account offers", - "subscriptionHint": "This is the chat model that drives the image tool, not an image model name. Leave it empty to pick one from the account's catalog automatically." + "subscriptionPlaceholder": "Uses the built-in image model", + "subscriptionHint": "Subscription image generation uses a built-in image model. No chat model is needed." }, "name": { "label": "Display name", diff --git a/src/web-ui/src/locales/zh-CN/settings/media.json b/src/web-ui/src/locales/zh-CN/settings/media.json index cae8964562..bae96be79a 100644 --- a/src/web-ui/src/locales/zh-CN/settings/media.json +++ b/src/web-ui/src/locales/zh-CN/settings/media.json @@ -124,8 +124,8 @@ "modelName": { "label": "图像模型 ID", "hint": "填服务商用于图像生成的确切模型 ID,不是对话模型。", - "subscriptionPlaceholder": "留空则使用账号可用的模型", - "subscriptionHint": "这里填的是驱动图像工具的对话模型,不是图像模型名;留空会按账号可用模型自动选择。" + "subscriptionPlaceholder": "使用内置图像模型", + "subscriptionHint": "订阅生图使用内置图像模型,无需配置对话模型。" }, "name": { "label": "显示名称", diff --git a/src/web-ui/src/locales/zh-TW/settings/media.json b/src/web-ui/src/locales/zh-TW/settings/media.json index eb74807b2c..837a02af2d 100644 --- a/src/web-ui/src/locales/zh-TW/settings/media.json +++ b/src/web-ui/src/locales/zh-TW/settings/media.json @@ -124,8 +124,8 @@ "modelName": { "label": "圖像模型 ID", "hint": "填服務商用於圖像生成的正確模型 ID,不是對話模型。", - "subscriptionPlaceholder": "留空則使用帳號可用的模型", - "subscriptionHint": "這裡填的是驅動圖像工具的對話模型,不是圖像模型名稱;留空會依帳號可用模型自動選擇。" + "subscriptionPlaceholder": "使用內建圖像模型", + "subscriptionHint": "訂閱生圖使用內建圖像模型,無需設定對話模型。" }, "name": { "label": "顯示名稱",