mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Support image references by file ID in inputs and tool outputs (#45794)
## What changed - Accept `fileId` alongside the existing `url` form for app-server image inputs, and forward file references to the Responses API as `file_id`. Update generated schemas and client types. - Preserve file references, image detail hints, and mixed inline/file image ordering through user-message events, thread history, and rollout migration. Retain file images when truncating tool output. - Pass file references through image preparation without resolving them, while keeping resize-notice numbering correct. Omit them from unsupported TUI display and Guardian image context. - Reject image-edit requests whose recent-image window includes a file reference, preventing selection of an older inline image instead. ## Testing Add coverage for serialization, request and rollout preservation, mixed-image history ordering, incomplete ordering metadata, tool-output truncation, and rejection of unsupported image-edit selections. GitOrigin-RevId: 6ca20a8577155cc934b720803c3b7b3bffdf972a
This commit is contained in:
1 parent
c51cb968e4
commit
7b8b17b97a
95 files changed
+2434
-324
No files matched your search
@@ -7,6 +7,7 @@ use crate::memory_citation::MemoryCitation;
|
||||
use crate::models::ContentItem;
|
||||
use crate::models::FunctionCallOutputBody;
|
||||
use crate::models::ImageDetail;
|
||||
use crate::models::ImageReference;
|
||||
use crate::models::MessagePhase;
|
||||
use crate::models::ResponseItem;
|
||||
use crate::models::WebSearchAction;
|
||||
@@ -554,7 +555,10 @@ impl UserMessageItem {
|
||||
self.content
|
||||
.iter()
|
||||
.filter_map(|c| match c {
|
||||
UserInput::Image { image_url, .. } => Some(image_url.clone()),
|
||||
UserInput::Image {
|
||||
image: ImageReference::Inline { image_url },
|
||||
..
|
||||
} => Some(image_url.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
@@ -565,7 +569,10 @@ impl UserMessageItem {
|
||||
self.content
|
||||
.iter()
|
||||
.filter_map(|c| match c {
|
||||
UserInput::Image { detail, .. } => Some(*detail),
|
||||
UserInput::Image {
|
||||
image: ImageReference::Inline { .. },
|
||||
detail,
|
||||
} => Some(*detail),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
@@ -615,7 +622,7 @@ impl UserMessageItem {
|
||||
}
|
||||
}
|
||||
|
||||
fn trim_trailing_default_image_details(
|
||||
pub(crate) fn trim_trailing_default_image_details(
|
||||
mut details: Vec<Option<ImageDetail>>,
|
||||
) -> Vec<Option<ImageDetail>> {
|
||||
while matches!(details.last(), Some(None)) {
|
||||
|
||||
@@ -20,6 +20,8 @@ use crate::items::SubAgentActivityItem;
|
||||
use crate::items::TurnItem;
|
||||
use crate::items::UserMessageItem;
|
||||
use crate::items::WebSearchItem;
|
||||
use crate::items::trim_trailing_default_image_details;
|
||||
use crate::models::ImageReference;
|
||||
use crate::protocol::AgentMessageContentDeltaEvent;
|
||||
use crate::protocol::AgentMessageEvent;
|
||||
use crate::protocol::AgentReasoningEvent;
|
||||
@@ -58,9 +60,11 @@ use crate::protocol::ReasoningContentDeltaEvent;
|
||||
use crate::protocol::ReasoningRawContentDeltaEvent;
|
||||
use crate::protocol::SubAgentActivityEvent;
|
||||
use crate::protocol::UserMessageEvent;
|
||||
use crate::protocol::UserMessageImageKind;
|
||||
use crate::protocol::ViewImageToolCallEvent;
|
||||
use crate::protocol::WebSearchBeginEvent;
|
||||
use crate::protocol::WebSearchEndEvent;
|
||||
use crate::user_input::UserInput;
|
||||
|
||||
/// Converts canonical item lifecycle events back into the legacy raw event stream used by
|
||||
/// compatibility consumers that have not migrated to `TurnItem`.
|
||||
@@ -78,11 +82,32 @@ impl UserMessageItem {
|
||||
pub fn as_legacy_user_message_event(&self) -> UserMessageEvent {
|
||||
// Legacy user-message events flatten only text inputs into `message` and
|
||||
// rebase text element ranges onto that concatenated text.
|
||||
let mut file_ids = Vec::new();
|
||||
let mut file_id_details = Vec::new();
|
||||
let mut image_order = Vec::new();
|
||||
for input in &self.content {
|
||||
if let UserInput::Image { image, detail } = input {
|
||||
match image {
|
||||
ImageReference::Inline { .. } => {
|
||||
image_order.push(UserMessageImageKind::Inline);
|
||||
}
|
||||
ImageReference::File { file_id } => {
|
||||
image_order.push(UserMessageImageKind::File);
|
||||
file_ids.push(file_id.clone());
|
||||
file_id_details.push(*detail);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let file_id_details = trim_trailing_default_image_details(file_id_details);
|
||||
UserMessageEvent {
|
||||
client_id: self.client_id.clone(),
|
||||
message: self.message(),
|
||||
images: Some(self.image_urls()),
|
||||
image_details: self.image_details(),
|
||||
file_ids: (!file_ids.is_empty()).then_some(file_ids),
|
||||
file_id_details,
|
||||
image_order,
|
||||
local_images: self.local_image_paths(),
|
||||
local_image_details: self.local_image_details(),
|
||||
audio: Some(self.audio_urls()),
|
||||
|
||||
@@ -8,6 +8,7 @@ use codex_utils_image::data_url_from_bytes;
|
||||
use codex_utils_image::load_for_prompt_bytes;
|
||||
|
||||
use crate::models::ImageDetail;
|
||||
use crate::models::ImageReference;
|
||||
use crate::user_input::UserInput;
|
||||
|
||||
/// Maximum accepted decoded byte length for prompt audio inputs.
|
||||
@@ -29,7 +30,9 @@ pub fn snapshot_local_user_input(input: &mut UserInput) -> io::Result<()> {
|
||||
let file_bytes = read_bounded_local_media(path, MAX_PROMPT_IMAGE_INPUT_BYTES, "image")?;
|
||||
let image = load_for_prompt_bytes(path, file_bytes, mode).map_err(io::Error::other)?;
|
||||
*input = UserInput::Image {
|
||||
image_url: image.into_data_url(),
|
||||
image: ImageReference::Inline {
|
||||
image_url: image.into_data_url(),
|
||||
},
|
||||
detail: image_detail,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -31,8 +31,10 @@ fn snapshots_local_image_user_input_with_requested_detail() -> Result<()> {
|
||||
|
||||
assert_eq!(
|
||||
UserInput::Image {
|
||||
image_url: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgAAIAAAUAAXpeqz8AAAAASUVORK5CYII="
|
||||
.to_string(),
|
||||
image: crate::models::ImageReference::Inline {
|
||||
image_url: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgAAIAAAUAAXpeqz8AAAAASUVORK5CYII="
|
||||
.to_string(),
|
||||
},
|
||||
detail,
|
||||
},
|
||||
input
|
||||
|
||||
@@ -898,6 +898,7 @@ pub enum ContentItem {
|
||||
#[ts(untagged)]
|
||||
pub enum ImageReference {
|
||||
Inline { image_url: String },
|
||||
File { file_id: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)]
|
||||
@@ -2008,13 +2009,11 @@ impl ResponseInputItem {
|
||||
.into_iter()
|
||||
.flat_map(|c| match c {
|
||||
UserInput::Text { text, .. } => vec![ContentItem::InputText { text }],
|
||||
UserInput::Image {
|
||||
image_url, detail, ..
|
||||
} => {
|
||||
UserInput::Image { image, detail, .. } => {
|
||||
image_index += 1;
|
||||
let detail = detail.unwrap_or(DEFAULT_IMAGE_DETAIL);
|
||||
vec![ContentItem::InputImage {
|
||||
image: ImageReference::Inline { image_url },
|
||||
image,
|
||||
detail: Some(detail),
|
||||
}]
|
||||
}
|
||||
@@ -3885,7 +3884,9 @@ mod tests {
|
||||
let image_url = "data:image/png;base64,abc".to_string();
|
||||
|
||||
let item = ResponseInputItem::from(vec![UserInput::Image {
|
||||
image_url: image_url.clone(),
|
||||
image: ImageReference::Inline {
|
||||
image_url: image_url.clone(),
|
||||
},
|
||||
detail: None,
|
||||
}]);
|
||||
|
||||
@@ -3903,6 +3904,43 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A file-backed user image must reach the Responses API without being resolved by Core.
|
||||
#[test]
|
||||
fn file_image_user_input_serializes_file_id() -> Result<()> {
|
||||
let file_id = "file_123".to_string();
|
||||
|
||||
let item = ResponseInputItem::from(vec![UserInput::Image {
|
||||
image: ImageReference::File {
|
||||
file_id: file_id.clone(),
|
||||
},
|
||||
detail: None,
|
||||
}]);
|
||||
|
||||
let expected = ResponseInputItem::Message {
|
||||
role: "user".to_string(),
|
||||
content: vec![ContentItem::InputImage {
|
||||
image: ImageReference::File { file_id },
|
||||
detail: Some(DEFAULT_IMAGE_DETAIL),
|
||||
}],
|
||||
phase: None,
|
||||
};
|
||||
assert_eq!(item, expected);
|
||||
assert_eq!(
|
||||
serde_json::to_value(item)?,
|
||||
serde_json::json!({
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
"content": [{
|
||||
"type": "input_image",
|
||||
"file_id": "file_123",
|
||||
"detail": "high"
|
||||
}]
|
||||
})
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializes_audio_user_input_without_tags() -> Result<()> {
|
||||
let audio_url = "data:audio/wav;base64,abc".to_string();
|
||||
@@ -4029,7 +4067,9 @@ mod tests {
|
||||
let image_url = "data:image/png;base64,abc".to_string();
|
||||
|
||||
let item = ResponseInputItem::from(vec![UserInput::Image {
|
||||
image_url: image_url.clone(),
|
||||
image: ImageReference::Inline {
|
||||
image_url: image_url.clone(),
|
||||
},
|
||||
detail: Some(ImageDetail::Original),
|
||||
}]);
|
||||
|
||||
@@ -4227,7 +4267,9 @@ mod tests {
|
||||
|
||||
let item = ResponseInputItem::from(vec![
|
||||
UserInput::Image {
|
||||
image_url: image_url.clone(),
|
||||
image: ImageReference::Inline {
|
||||
image_url: image_url.clone(),
|
||||
},
|
||||
detail: None,
|
||||
},
|
||||
UserInput::LocalImage {
|
||||
|
||||
@@ -2521,6 +2521,14 @@ pub struct AgentMessageEvent {
|
||||
pub questions: Option<Vec<AsyncUserInputQuestion>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[ts(rename_all = "snake_case")]
|
||||
pub enum UserMessageImageKind {
|
||||
Inline,
|
||||
File,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, JsonSchema, TS)]
|
||||
pub struct UserMessageEvent {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -2535,6 +2543,19 @@ pub struct UserMessageEvent {
|
||||
/// default image detail behavior.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub image_details: Vec<Option<ImageDetail>>,
|
||||
/// File IDs sourced from `UserInput::Image`. These are passed through as
|
||||
/// opaque references and are not created by image preparation.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub file_ids: Option<Vec<String>>,
|
||||
/// Detail hints for `file_ids`, indexed in parallel. Missing entries imply
|
||||
/// default image detail behavior.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub file_id_details: Vec<Option<ImageDetail>>,
|
||||
/// Inline and file-backed image kinds in their original input order.
|
||||
/// New producers populate this alongside `images` and `file_ids`; when it
|
||||
/// is absent, consumers retain the legacy inline-then-file ordering.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub image_order: Vec<UserMessageImageKind>,
|
||||
/// Local file paths sourced from `UserInput::LocalImage`. These are kept so
|
||||
/// the UI can reattach images when editing history. Local image prompts may
|
||||
/// include a display form of the path, but these should not be treated as
|
||||
@@ -2559,6 +2580,27 @@ pub struct UserMessageEvent {
|
||||
pub text_elements: Vec<crate::user_input::TextElement>,
|
||||
}
|
||||
|
||||
impl UserMessageEvent {
|
||||
/// Returns whether `image_order` accounts for every split image reference exactly once.
|
||||
pub fn has_complete_image_order(&self) -> bool {
|
||||
if self.image_order.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut inline_count = 0;
|
||||
let mut file_count = 0;
|
||||
for image_kind in &self.image_order {
|
||||
match image_kind {
|
||||
UserMessageImageKind::Inline => inline_count += 1,
|
||||
UserMessageImageKind::File => file_count += 1,
|
||||
}
|
||||
}
|
||||
|
||||
inline_count == self.images.as_ref().map_or(0, Vec::len)
|
||||
&& file_count == self.file_ids.as_ref().map_or(0, Vec::len)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the user-facing preview text for a user message.
|
||||
pub fn user_message_preview(user: &UserMessageEvent) -> Option<String> {
|
||||
let message = strip_user_message_prefix(user.message.as_str());
|
||||
@@ -2569,6 +2611,10 @@ pub fn user_message_preview(user: &UserMessageEvent) -> Option<String> {
|
||||
.images
|
||||
.as_ref()
|
||||
.is_some_and(|images| !images.is_empty())
|
||||
|| user
|
||||
.file_ids
|
||||
.as_ref()
|
||||
.is_some_and(|file_ids| !file_ids.is_empty())
|
||||
|| !user.local_images.is_empty()
|
||||
{
|
||||
return Some("[Image]".to_string());
|
||||
@@ -5944,6 +5990,9 @@ mod tests {
|
||||
Some(vec!["https://example.com/image.png".to_string()])
|
||||
);
|
||||
assert_eq!(event.image_details, Vec::<Option<ImageDetail>>::new());
|
||||
assert_eq!(event.file_ids, None);
|
||||
assert_eq!(event.file_id_details, Vec::<Option<ImageDetail>>::new());
|
||||
assert_eq!(event.image_order, Vec::<UserMessageImageKind>::new());
|
||||
assert_eq!(event.local_images, vec![PathBuf::from("/tmp/local.png")]);
|
||||
assert_eq!(event.local_image_details, Vec::<Option<ImageDetail>>::new());
|
||||
assert_eq!(event.audio, None);
|
||||
@@ -5959,11 +6008,21 @@ mod tests {
|
||||
let local_audio_path = PathBuf::from("/tmp/local.wav");
|
||||
let mut item = UserMessageItem::new(&[
|
||||
crate::user_input::UserInput::Image {
|
||||
image_url: "https://example.com/first.png".to_string(),
|
||||
image: crate::models::ImageReference::Inline {
|
||||
image_url: "https://example.com/first.png".to_string(),
|
||||
},
|
||||
detail: Some(ImageDetail::Original),
|
||||
},
|
||||
crate::user_input::UserInput::Image {
|
||||
image_url: "https://example.com/second.png".to_string(),
|
||||
image: crate::models::ImageReference::File {
|
||||
file_id: "file_123".to_string(),
|
||||
},
|
||||
detail: Some(ImageDetail::Low),
|
||||
},
|
||||
crate::user_input::UserInput::Image {
|
||||
image: crate::models::ImageReference::Inline {
|
||||
image_url: "https://example.com/second.png".to_string(),
|
||||
},
|
||||
detail: None,
|
||||
},
|
||||
crate::user_input::UserInput::LocalImage {
|
||||
@@ -5982,6 +6041,7 @@ mod tests {
|
||||
let EventMsg::UserMessage(event) = item.as_legacy_event() else {
|
||||
panic!("expected user message event");
|
||||
};
|
||||
let event_json = serde_json::to_value(&event).expect("serialize user message event");
|
||||
|
||||
assert_eq!(
|
||||
event.images,
|
||||
@@ -5992,6 +6052,22 @@ mod tests {
|
||||
);
|
||||
assert_eq!(event.client_id, Some("client-message-1".to_string()));
|
||||
assert_eq!(event.image_details, vec![Some(ImageDetail::Original)]);
|
||||
assert_eq!(event.file_ids, Some(vec!["file_123".to_string()]));
|
||||
assert_eq!(event.file_id_details, vec![Some(ImageDetail::Low)]);
|
||||
assert_eq!(
|
||||
event.image_order,
|
||||
vec![
|
||||
UserMessageImageKind::Inline,
|
||||
UserMessageImageKind::File,
|
||||
UserMessageImageKind::Inline,
|
||||
]
|
||||
);
|
||||
assert_eq!(event_json["file_ids"], json!(["file_123"]));
|
||||
assert_eq!(event_json["file_id_details"], json!(["low"]));
|
||||
assert_eq!(
|
||||
event_json["image_order"],
|
||||
json!(["inline", "file", "inline"])
|
||||
);
|
||||
assert_eq!(event.local_images, vec![local_path]);
|
||||
assert_eq!(event.local_image_details, vec![Some(ImageDetail::Original)]);
|
||||
assert_eq!(
|
||||
@@ -6011,6 +6087,16 @@ mod tests {
|
||||
assert_eq!(user_message_preview(&event), Some("[Audio]".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_only_user_message_has_placeholder_preview() {
|
||||
let event = UserMessageEvent {
|
||||
file_ids: Some(vec!["file_123".to_string()]),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert_eq!(user_message_preview(&event), Some("[Image]".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_aborted_event_deserializes_without_turn_id() -> Result<()> {
|
||||
let event: EventMsg = serde_json::from_value(json!({
|
||||
|
||||
@@ -4,6 +4,7 @@ use serde::Serialize;
|
||||
use ts_rs::TS;
|
||||
|
||||
use crate::models::ImageDetail;
|
||||
use crate::models::ImageReference;
|
||||
|
||||
/// Conservative cap so one user message cannot monopolize a large context window.
|
||||
pub const MAX_USER_INPUT_TEXT_CHARS: usize = 1 << 20;
|
||||
@@ -22,9 +23,10 @@ pub enum UserInput {
|
||||
#[serde(default)]
|
||||
text_elements: Vec<TextElement>,
|
||||
},
|
||||
/// Pre‑encoded data: URI image.
|
||||
/// Image reference forwarded to the Responses API.
|
||||
Image {
|
||||
image_url: String,
|
||||
#[serde(flatten)]
|
||||
image: ImageReference,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
detail: Option<ImageDetail>,
|
||||
|
||||
Reference in new issue
Block a user