Store generated image items as attachment references (#54398)

## What changed

- Upload generated images to the attachment store and expose `fileId` in image-generation items when available, with inline `result` fallback on upload or decoding failure.
- Preserve file references through legacy events, persisted rollouts, thread history, and task output summaries. Keep model-facing image preparation separate.
- Add attachment request tags and mark generated-image uploads with `usage=image_gen`, preserving the thread's ephemeral setting.
- Update public schemas and SDK types to accept either image representation, retain the Python `ImageGenerationThreadItem` alias, and prefer `fileId` when reading records containing both fields.

## Testing

Add coverage for file-backed generation and rollout persistence, legacy history replay, inline and transitional serialization, task output visibility, and Python SDK alias compatibility.

GitOrigin-RevId: f7a2bb5707e2f277348a547a988bc33c8e96d891
This commit is contained in:
Krish Chainani
2026-10-15 19:51:22 +00:00
committed by copyberry
parent 1ef30bcbe7
commit aabf13307a
64 changed files with 1229 additions and 125 deletions
+3
View File
@@ -1,3 +1,5 @@
use std::collections::HashMap;
use crate::config::ManagedFeatures;
use crate::context::ContextualUserFragment;
use crate::context::ImageResizeNotice;
@@ -370,6 +372,7 @@ async fn prepare_image(
thread_id: origin.thread_id.to_owned(),
ephemeral: origin.ephemeral,
file_name: None,
tags: HashMap::new(),
data: prepared.encoded.bytes.to_vec(),
};
*image = match image_store.upload(request).await {
@@ -212,6 +212,8 @@ async fn to_extension_call<'a>(
session: Arc::downgrade(&invocation.session),
turn: Arc::downgrade(&invocation.turn),
}),
attachment_store: Arc::clone(&invocation.session.services.image_store),
ephemeral: invocation.turn.config.ephemeral,
environments,
payload: invocation.payload.clone(),
}
@@ -222,6 +224,7 @@ mod tests {
use std::sync::Arc;
use codex_extension_items::ExtensionItem;
use codex_extension_items::image_generation::GeneratedImageRef;
use codex_extension_items::image_generation::ImageGenerationItem;
use codex_extension_items::web_search::WebSearchItem;
use codex_protocol::items::TurnItem;
@@ -567,7 +570,9 @@ mod tests {
id: "call-image".to_string(),
status: "in_progress".to_string(),
revised_prompt: None,
result: String::new(),
image: GeneratedImageRef::Inline {
result: String::new(),
},
transparent_background: None,
failure: None,
saved_path: None,
@@ -578,7 +583,9 @@ mod tests {
id: "call-image".to_string(),
status: "completed".to_string(),
revised_prompt: Some("A tiny blue square".to_string()),
result: "cG5n".to_string(),
image: GeneratedImageRef::Inline {
result: "cG5n".to_string(),
},
transparent_background: Some(true),
failure: None,
saved_path: Some(expected_path.clone()),
@@ -603,7 +610,9 @@ mod tests {
call_id: "call-image".to_string(),
status: "completed".to_string(),
revised_prompt: Some("A tiny blue square".to_string()),
result: "cG5n".to_string(),
image: GeneratedImageRef::Inline {
result: "cG5n".to_string(),
},
transparent_background: Some(true),
failure: None,
saved_path: Some(expected_path.clone()),
@@ -1,5 +1,6 @@
use core_test_support::test_codex::local_requests;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Context;
@@ -9,7 +10,10 @@ use codex_core::config::Config;
use codex_core::config::Constrained;
use codex_extension_api::ExtensionRegistry;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_items::ExtensionItem;
use codex_extension_items::image_generation::GeneratedImageRef;
use codex_features::Feature;
use codex_history::RolloutItem;
use codex_http_client::DestinationPolicy;
use codex_http_client::NetworkPolicyController;
use codex_image_generation_extension::install as install_image_generation_extension;
@@ -20,7 +24,10 @@ use codex_protocol::config_types::ModeKind;
use codex_protocol::config_types::Settings;
use codex_protocol::config_types::WebSearchMode;
use codex_protocol::models::FileSystemPermissions;
use codex_protocol::models::FunctionCallOutputContentItem;
use codex_protocol::models::ImageReference;
use codex_protocol::models::PermissionProfile;
use codex_protocol::models::ResponseItem;
use codex_protocol::openai_models::InputModality;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
@@ -31,6 +38,7 @@ use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::ThreadHistoryMode;
use codex_protocol::protocol::ThreadSettingsOverrides;
use codex_protocol::request_permissions::PermissionGrantScope;
use codex_protocol::request_permissions::RequestPermissionProfile;
@@ -44,6 +52,7 @@ use core_test_support::skip_if_target_windows;
use core_test_support::test_codex::test_codex;
use core_test_support::test_codex::turn_permission_fields;
use core_test_support::wait_for_event;
use core_test_support::wait_for_event_match;
use pretty_assertions::assert_eq;
use serde_json::json;
use test_case::test_case;
@@ -52,6 +61,8 @@ use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::image_rollout::RecordingFileAttachmentStore;
const TINY_PNG_BYTES: &[u8] = &[
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0,
0, 0, 31, 21, 196, 137, 0, 0, 0, 13, 73, 68, 65, 84, 120, 156, 99, 248, 207, 192, 240, 31, 0,
@@ -70,6 +81,150 @@ fn image_generation_extensions(
Arc::new(extension_builder.build())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn generated_image_ui_item_is_file_backed_in_rollout() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
Mock::given(method("POST"))
.and(path("/v1/images/generations"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"created": 1,
"data": [{"b64_json": TINY_PNG_BASE64}],
})))
.expect(1)
.mount(&server)
.await;
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let extensions = image_generation_extensions(&auth, |_config| None);
let image_store = Arc::new(RecordingFileAttachmentStore::default());
let image_call_id = "image-generate-file-backed";
responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_function_call_with_namespace(
image_call_id,
"image_gen",
"imagegen",
&json!({"prompt": "paint a blue whale"}).to_string(),
),
responses::ev_completed("resp-1"),
]),
responses::sse(vec![
responses::ev_response_created("resp-2"),
responses::ev_assistant_message("msg-1", "done"),
responses::ev_completed("resp-2"),
]),
],
)
.await;
let test = test_codex()
.with_auth(auth)
.with_extensions(extensions)
.with_image_store(image_store.clone())
.with_history_mode(ThreadHistoryMode::Paginated)
.with_model_info_override("gpt-5.4", |model_info| {
model_info.use_responses_lite = true;
model_info.input_modalities = vec![InputModality::Text, InputModality::Image];
})
.build(&server)
.await?;
test.codex
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
text: "generate an image".to_string(),
text_elements: Vec::new(),
}]))
.await?;
let live_image =
wait_for_event_match(&test.codex, |event| match event {
EventMsg::ItemCompleted(event) => match &event.item {
codex_protocol::items::TurnItem::Extension(ExtensionItem::ImageGeneration(
image,
)) if image.id == image_call_id => Some(image.clone()),
_ => None,
},
_ => None,
})
.await;
assert_eq!(
live_image.image,
GeneratedImageRef::File {
file_id: "file_uploaded_image".to_string(),
}
);
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
test.codex.flush_rollout().await?;
{
let uploads = image_store.uploads.lock().expect("uploads lock");
let [item_upload, model_upload] = uploads.as_slice() else {
panic!("expected separate item and model uploads");
};
assert_eq!(
item_upload.thread_id,
test.session_configured.thread_id.to_string()
);
assert!(!item_upload.ephemeral);
assert_eq!(
item_upload.tags,
HashMap::from([("usage".to_string(), "image_gen".to_string())])
);
assert_eq!(item_upload.data, TINY_PNG_BYTES);
assert_eq!(model_upload.tags, HashMap::new());
}
let rollout_path = test.codex.rollout_path().context("rollout path")?;
let rollout = std::fs::read_to_string(rollout_path)?
.lines()
.filter_map(|line| codex_rollout::parse_rollout_line(line).ok())
.map(|line| line.item)
.collect::<Vec<_>>();
let image =
rollout.iter().find_map(|item| match item {
RolloutItem::EventMsg(EventMsg::ItemCompleted(event)) => match &event.item {
codex_protocol::items::TurnItem::Extension(ExtensionItem::ImageGeneration(
image,
)) if image.id == image_call_id => Some(image),
_ => None,
},
_ => None,
});
let image = image.context("persisted image-generation item")?;
assert_eq!(image, &live_image);
let output_image = rollout.iter().find_map(|item| match item {
RolloutItem::ResponseItem(envelope) => match &envelope.item {
ResponseItem::FunctionCallOutput {
call_id: Some(call_id),
output,
..
} if call_id == image_call_id => output.content_items().and_then(|items| {
items.iter().find_map(|item| match item {
FunctionCallOutputContentItem::InputImage { image, .. } => Some(image),
_ => None,
})
}),
_ => None,
},
_ => None,
});
assert_eq!(
output_image,
Some(&ImageReference::File {
file_id: "file_uploaded_image".to_string(),
})
);
Ok(())
}
#[test_case(false; "file_access")]
#[test_case(true; "application_network")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]