diff --git a/CHANGELOG.md b/CHANGELOG.md index a41c351dd..577b9de11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## Unreleased: `[ATTACHMENT:]` marker codec beside `[IMAGE:]`/`[FILE:]` (tinyagents#90) + +- `multimodal::markers` gains the compact `[ATTACHMENT:]` reference codec upstreamed from OpenHuman: `AttachmentRef` (with + `marker`, `description`, `from_description`), `AttachmentSegment`, + `attachment_segments`, `parse_attachment_markers`, `is_safe_relative_path`, + `sanitize_attachment_filename`, `enrich_user_message`, + `image_markers_from_message` and `should_forward_parent_images`, all + re-exported from `multimodal`. Encoding, decoding and path rejection are + byte-identical to OpenHuman's; path authorization and the upload layout + stay with the host. +- The `multimodal` feature now pulls in `form_urlencoded` (already in the + graph through `url`). + ## 3.1.4 - Releases are cut from `main`: the version bump merges through a pull request diff --git a/Cargo.lock b/Cargo.lock index 6a217c54c..ec592ae1d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2004,6 +2004,7 @@ dependencies = [ "chrono", "dirs", "flate2", + "form_urlencoded", "futures", "libc", "oxipng", diff --git a/crates/tinyagents-harness/Cargo.toml b/crates/tinyagents-harness/Cargo.toml index 0b32778dd..4a8570e1c 100644 --- a/crates/tinyagents-harness/Cargo.toml +++ b/crates/tinyagents-harness/Cargo.toml @@ -19,6 +19,9 @@ dirs = { version = "6", optional = true } tar = { version = "0.4", default-features = false, optional = true } zip = { version = "2", default-features = false, features = ["deflate-flate2", "flate2"], optional = true } flate2 = { version = "1", optional = true } +# `[ATTACHMENT:…]` marker bodies; the same crate `url::form_urlencoded` +# re-exports, so hosts encoding with either produce identical markers. +form_urlencoded = { version = "1.2", optional = true } oxipng = { version = "9", default-features = false, optional = true } futures = { workspace = true } libc = "0.2" @@ -65,7 +68,7 @@ sqlite = [] # ports, so a host's chosen backend (SQLite, MongoDB, memory) holds harness # data. storage-drivers = [] -multimodal = ["dep:flate2", "dep:reqwest", "dep:tar", "dep:zip"] +multimodal = ["dep:flate2", "dep:form_urlencoded", "dep:reqwest", "dep:tar", "dep:zip"] # Lossless PNG re-compression (`multimodal::optimize_png_lossless`) through # `oxipng`. Off by default: without it the helper returns `None` and callers # keep the original bytes, and `oxipng`/`libdeflater` (a C build) are not linked. diff --git a/crates/tinyagents-harness/src/multimodal/README.md b/crates/tinyagents-harness/src/multimodal/README.md index d02e9b1f9..94af0ec38 100644 --- a/crates/tinyagents-harness/src/multimodal/README.md +++ b/crates/tinyagents-harness/src/multimodal/README.md @@ -27,7 +27,11 @@ format contributes a header naming it plus a content hash. - [`markers`] — the marker vocabulary (`IMAGE_MARKER_PREFIX`, `FILE_MARKER_PREFIX`, placeholder tokens) and pure string transforms: `parse_image_markers`/`parse_file_markers`, placeholder - render/detect/extract/rehydrate functions, `extract_ollama_image_payload`. + render/detect/extract/rehydrate functions, `extract_ollama_image_payload`, + and the `[ATTACHMENT:…]` reference codec (`AttachmentRef`, + `attachment_segments`/`parse_attachment_markers`, `is_safe_relative_path`, + `sanitize_attachment_filename`, and the delegation helpers + `enrich_user_message`/`image_markers_from_message`/`should_forward_parent_images`). - [`mime`] — MIME detection (header → extension → magic bytes, in an order that differs deliberately between images and files) and the extension/magic lookup tables. diff --git a/crates/tinyagents-harness/src/multimodal/markers.rs b/crates/tinyagents-harness/src/multimodal/markers.rs index 7d78a79fa..c069e2c0d 100644 --- a/crates/tinyagents-harness/src/multimodal/markers.rs +++ b/crates/tinyagents-harness/src/multimodal/markers.rs @@ -1,6 +1,6 @@ //! The marker vocabulary, and the pure string transforms over it. //! -//! Four tokens make up the wire format between a host's ingress and its +//! Five tokens make up the wire format between a host's ingress and its //! provider dispatch: //! //! | Token | Written by | Read by | @@ -9,22 +9,31 @@ //! | `[FILE:]` | the user / renderer | ingress, then dispatch | //! | `[Image: #att:]` | ingress, replacing an image marker | dispatch, rehydrating | //! | `[FILE-EXTRACTED:…]` / `[FILE-ATTACHED:…]` | [`payload`](super::payload) | the model | +//! | `[ATTACHMENT:]` | ingress, after persisting an upload | transcript and dispatch | //! //! The placeholder is mixed-case on purpose: `[Image:` never collides with the //! `[IMAGE:` parser, so a persisted placeholder cannot be mistaken for an //! unresolved attachment and re-read. //! -//! Everything here is a pure function over `&str`. Message-level helpers — "how -//! many markers are in the latest user turn" — belong to the host, because only -//! the host knows what its message type is. +//! An `[ATTACHMENT:…]` reference ([`AttachmentRef`]) is the durable form of an +//! upload: compact metadata naming a workspace-relative path, never the bytes. +//! The codec here only encodes, decodes and rejects unsafe paths; where uploads +//! live and whether a path may be read stay host decisions. +//! +//! Everything here is a pure function over `&str` or over a single +//! [`Message`]. Transcript-level helpers — "how many markers are in the latest +//! user turn" — belong to the host, because only the host knows how its history +//! is shaped. use std::collections::HashMap; -use std::path::PathBuf; +use std::path::{Component, Path, PathBuf}; use base64::{ Engine as _, engine::general_purpose::{STANDARD, STANDARD_NO_PAD}, }; +use serde::{Deserialize, Serialize}; +use tinyinference_llm::message::{ContentBlock, Message}; /// Prefix of an inline image marker. pub const IMAGE_MARKER_PREFIX: &str = "[IMAGE:"; @@ -255,3 +264,241 @@ pub fn rehydrate_placeholders_in_text(text: &str, index: &HashMap String { + let json = serde_json::to_string(self).expect("attachment metadata serializes"); + format!( + "{ATTACHMENT_MARKER_PREFIX}{}]", + form_urlencoded::byte_serialize(json.as_bytes()).collect::() + ) + } + + /// The human-readable text a model sees in place of the marker. + pub fn description(&self) -> String { + format!( + "[Uploaded file: {}; {}; {} bytes; workspace path: {}]", + self.name, self.mime, self.size_bytes, self.path + ) + } + + /// The reference `text` is the [`description`](Self::description) of, + /// when it is exactly one. The name may hold anything, so the fixed + /// fields are read from the right and the result must describe itself + /// back byte for byte. + pub fn from_description(text: &str) -> Option { + let body = text.strip_prefix("[Uploaded file: ")?.strip_suffix(']')?; + let (head, path) = body.rsplit_once("; workspace path: ")?; + let (head, size) = head.strip_suffix(" bytes")?.rsplit_once("; ")?; + let (name, mime) = head.rsplit_once("; ")?; + let attachment = Self { + path: path.into(), + name: name.into(), + mime: mime.into(), + size_bytes: size.parse().ok()?, + }; + (attachment.description() == text).then_some(attachment) + } +} + +/// One piece of text split by [`attachment_segments`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AttachmentSegment { + /// Text between references, copied verbatim — including any marker that + /// failed to decode or named an unsafe path. + Text(String), + /// A well-formed reference with a safe relative path. + Attachment(AttachmentRef), +} + +/// Split `text` into captions and `[ATTACHMENT:…]` references in source order. +/// +/// Nothing is trimmed. A marker that does not decode to an [`AttachmentRef`], +/// or whose path fails [`is_safe_relative_path`], stays in the text verbatim; +/// an unterminated marker ends the scan and is kept with the remainder. +pub fn attachment_segments(text: &str) -> Vec { + let mut rest = text; + let mut parts = Vec::new(); + while let Some(start) = rest.find(ATTACHMENT_MARKER_PREFIX) { + if start > 0 { + parts.push(AttachmentSegment::Text(rest[..start].into())); + } + let tail = &rest[start + ATTACHMENT_MARKER_PREFIX.len()..]; + let Some(end) = tail.find(']') else { + parts.push(AttachmentSegment::Text(rest[start..].into())); + return parts; + }; + let encoded = format!("value={}", &tail[..end]); + let decoded = form_urlencoded::parse(encoded.as_bytes()) + .next() + .map(|(_, value)| value.into_owned()); + match decoded.and_then(|json| serde_json::from_str::(&json).ok()) { + Some(file) if is_safe_relative_path(&file.path) => { + parts.push(AttachmentSegment::Attachment(file)) + } + _ => parts.push(AttachmentSegment::Text( + rest[start..start + ATTACHMENT_MARKER_PREFIX.len() + end + 1].into(), + )), + } + rest = &tail[end + 1..]; + } + if !rest.is_empty() { + parts.push(AttachmentSegment::Text(rest.into())); + } + parts +} + +/// Strip every valid `[ATTACHMENT:…]` reference and return +/// `(remaining_text, refs_in_order)`. +/// +/// Unlike [`parse_image_markers`], the remaining text is **not** trimmed: it is +/// the concatenation of every [`AttachmentSegment::Text`], byte for byte, so +/// ordinary prose is never reinterpreted as a path. +pub fn parse_attachment_markers(text: &str) -> (String, Vec) { + let mut clean = String::new(); + let mut files = Vec::new(); + for segment in attachment_segments(text) { + match segment { + AttachmentSegment::Text(text) => clean.push_str(&text), + AttachmentSegment::Attachment(file) => files.push(file), + } + } + (clean, files) +} + +/// `true` when `path` is a non-empty relative path made only of normal +/// components. +/// +/// Rejects NUL and every `\` (so Windows separators, drive paths such as +/// `C:\x` and UNC paths cannot slip through on Unix), a root or prefix, and +/// any `.` or `..` component. Judged per [`Path::components`] on the running +/// platform, which elides empty and interior `.` components (`a//b`, `a/./b` +/// are accepted as `a/b`). On Unix a forward-slash drive path such as `C:/x` +/// is an ordinary relative directory named `C:`; on Windows it is a prefix and +/// rejected. This is a shape check only: the host still authorizes the joined +/// path against its own policy. +pub fn is_safe_relative_path(path: &str) -> bool { + !path.is_empty() + && !path.contains(['\0', '\\']) + && Path::new(path) + .components() + .all(|c| matches!(c, Component::Normal(_))) +} + +/// A filesystem-safe leaf name for a persisted upload. +/// +/// Keeps the last `/`- or `\`-separated component, replaces every character +/// other than alphanumerics, `.`, `-` and `_` with `_`, caps the result at 180 +/// UTF-8 bytes on a character boundary, and falls back to `attachment` when +/// nothing usable (or only `.` / `..`) remains. +pub fn sanitize_attachment_filename(name: &str) -> String { + let leaf = name + .rsplit(['/', '\\']) + .next() + .unwrap_or(DEFAULT_ATTACHMENT_NAME); + let mut sanitized = String::new(); + for c in leaf.chars() { + let c = if c.is_alphanumeric() || matches!(c, '.' | '-' | '_') { + c + } else { + '_' + }; + if sanitized.len() + c.len_utf8() > MAX_ATTACHMENT_FILENAME_BYTES { + break; + } + sanitized.push(c); + } + if sanitized.is_empty() || sanitized == "." || sanitized == ".." { + DEFAULT_ATTACHMENT_NAME.into() + } else { + sanitized + } +} + +/// Prefix the context a host added in front of a user turn's text without +/// flattening its typed media. +/// +/// `enriched` is `original_text` with context prepended; only that prefix is +/// inserted (all of `enriched` when it does not end with `original_text`). It +/// joins a leading text block so a plain turn keeps one text block, and +/// otherwise becomes a new first block. Non-user messages pass through. +pub fn enrich_user_message(input: Message, original_text: &str, enriched: &str) -> Message { + let Message::User(mut user) = input else { + return input; + }; + let prefix = enriched.strip_suffix(original_text).unwrap_or(enriched); + if !prefix.is_empty() { + if let Some(ContentBlock::Text(text)) = user.content.first_mut() { + text.insert_str(0, prefix); + } else { + user.content.insert(0, ContentBlock::Text(prefix.into())); + } + } + Message::User(user) +} + +/// `legacy` followed by an `[IMAGE:]` marker for each typed image block in +/// a user `input`, skipping duplicates — the image carrier a host forwards to a +/// delegated sub-agent without flattening the input. +pub fn image_markers_from_message(input: &Message, legacy: &[String]) -> Vec { + let mut images = legacy.to_vec(); + if let Message::User(user) = input { + for block in &user.content { + if let ContentBlock::Image(image) = block { + let marker = format!("{IMAGE_MARKER_PREFIX}{}]", image.url); + if !images.contains(&marker) { + images.push(marker); + } + } + } + } + images +} + +/// `true` when a delegation `prompt` selects no image itself, so the parent's +/// images should be forwarded automatically. +/// +/// An image `[ATTACHMENT:…]` reference, an `[IMAGE:…]` marker or an +/// `[Image: … #att:]` placeholder is an explicit selection and replaces +/// automatic forwarding. +pub fn should_forward_parent_images(prompt: &str) -> bool { + parse_attachment_markers(prompt) + .1 + .iter() + .all(|file| !file.mime.starts_with("image/")) + && parse_image_markers(prompt).1.is_empty() + && extract_image_placeholders_in_text(prompt).is_empty() +} + +#[cfg(test)] +#[path = "markers_tests.rs"] +mod tests; diff --git a/crates/tinyagents-harness/src/multimodal/markers_tests.rs b/crates/tinyagents-harness/src/multimodal/markers_tests.rs new file mode 100644 index 000000000..3d7259ce1 --- /dev/null +++ b/crates/tinyagents-harness/src/multimodal/markers_tests.rs @@ -0,0 +1,395 @@ +//! Tests for the `[ATTACHMENT:…]` reference codec. +//! +//! The wire format is persisted in transcripts, so the golden marker below pins +//! it byte for byte; the path cases pin every shape `is_safe_relative_path` +//! must refuse, because a decoded path is later joined onto a workspace root. + +use super::*; +use tinyinference_llm::message::{ImageRef, MediaRef, UserMessage}; + +fn upload(path: &str, name: &str, mime: &str) -> AttachmentRef { + AttachmentRef { + path: path.into(), + name: name.into(), + mime: mime.into(), + size_bytes: 3, + } +} + +// ── marker codec ───────────────────────────────────────────────────────────── + +#[test] +fn marker_encoding_is_pinned_byte_for_byte() { + let file = upload("uploads/t/id/a b.png", "a b.png", "image/png"); + assert_eq!( + file.marker(), + "[ATTACHMENT:%7B%22path%22%3A%22uploads%2Ft%2Fid%2Fa+b.png%22%2C%22name%22%3A%22a+b.png\ + %22%2C%22mime%22%3A%22image%2Fpng%22%2C%22size_bytes%22%3A3%7D]" + ); +} + +#[test] +fn marker_round_trips_through_parse() { + let file = upload( + "uploads/thread/id/Report_.zip", + "Report α] & [x].zip", + "application/zip", + ); + let marker = file.marker(); + assert_eq!(marker.matches(']').count(), 1, "body never holds a `]`"); + assert_eq!( + parse_attachment_markers(&marker), + (String::new(), vec![file]) + ); +} + +#[test] +fn segments_preserve_captions_and_order_without_trimming() { + let one = upload("uploads/t/1/one.txt", "one.txt", "text/plain"); + let two = upload("uploads/t/2/two.png", "two.png", "image/png"); + let text = format!(" first {} second {} third ", one.marker(), two.marker()); + assert_eq!( + attachment_segments(&text), + vec![ + AttachmentSegment::Text(" first ".into()), + AttachmentSegment::Attachment(one.clone()), + AttachmentSegment::Text(" second ".into()), + AttachmentSegment::Attachment(two.clone()), + AttachmentSegment::Text(" third ".into()), + ] + ); + assert_eq!( + parse_attachment_markers(&text), + (" first second third ".into(), vec![one, two]) + ); +} + +#[test] +fn adjacent_markers_emit_no_empty_text_segments() { + let a = upload("a", "a", "text/plain"); + let b = upload("b", "b", "text/plain"); + let text = format!("{}{}", a.marker(), b.marker()); + assert_eq!( + attachment_segments(&text), + vec![ + AttachmentSegment::Attachment(a), + AttachmentSegment::Attachment(b) + ] + ); + assert!(attachment_segments("").is_empty()); +} + +#[test] +fn malformed_and_unsafe_markers_stay_verbatim_text() { + let unsafe_path = upload("../escape", "x", "text/plain").marker(); + for marker in [ + "[ATTACHMENT:]".to_string(), + "[ATTACHMENT:not json]".to_string(), + "[ATTACHMENT:%7B%22path%22%3A%22a%22%7D]".to_string(), + unsafe_path, + ] { + let text = format!("a {marker} b"); + assert_eq!( + attachment_segments(&text), + vec![ + AttachmentSegment::Text("a ".into()), + AttachmentSegment::Text(marker.clone()), + AttachmentSegment::Text(" b".into()), + ], + "{marker}" + ); + assert_eq!(parse_attachment_markers(&text), (text.clone(), vec![])); + } +} + +#[test] +fn unterminated_marker_ends_the_scan_verbatim() { + assert_eq!( + attachment_segments("x [ATTACHMENT:%7B tail"), + vec![ + AttachmentSegment::Text("x ".into()), + AttachmentSegment::Text("[ATTACHMENT:%7B tail".into()), + ] + ); +} + +#[test] +fn a_half_typed_marker_swallows_up_to_the_next_bracket_as_text() { + // The first `]` closes the half-typed marker, so the valid one after it is + // part of an undecodable body and survives only as text. + let valid = upload("a", "a", "text/plain").marker(); + let text = format!("x [ATTACHMENT:%7B {valid} y"); + assert_eq!( + attachment_segments(&text), + vec![ + AttachmentSegment::Text("x ".into()), + AttachmentSegment::Text(format!("[ATTACHMENT:%7B {valid}")), + AttachmentSegment::Text(" y".into()), + ] + ); +} + +#[test] +fn unknown_json_fields_are_ignored() { + let json = r#"{"path":"a","name":"n","mime":"text/plain","size_bytes":1,"extra":true}"#; + let marker = format!( + "{ATTACHMENT_MARKER_PREFIX}{}]", + form_urlencoded::byte_serialize(json.as_bytes()).collect::() + ); + let (_, files) = parse_attachment_markers(&marker); + assert_eq!(files.len(), 1); + assert_eq!(files[0].path, "a"); +} + +#[test] +fn image_markers_are_not_attachment_markers() { + let text = "[IMAGE:uploads/a.png] [FILE:b.txt]"; + assert_eq!(parse_attachment_markers(text), (text.into(), vec![])); +} + +// ── description ────────────────────────────────────────────────────────────── + +#[test] +fn description_round_trips_even_with_separators_in_the_name() { + for name in ["a.png", "weird; name; 3 bytes; workspace path: x", ""] { + let file = upload("uploads/t/id/a.png", name, "image/png"); + let text = file.description(); + assert_eq!(AttachmentRef::from_description(&text), Some(file), "{text}"); + } + assert_eq!( + upload("p", "n", "m").description(), + "[Uploaded file: n; m; 3 bytes; workspace path: p]" + ); +} + +#[test] +fn from_description_rejects_non_canonical_text() { + for text in [ + "", + "[Uploaded file: n; m; 3 bytes; workspace path: p", + "Uploaded file: n; m; 3 bytes; workspace path: p]", + "[Uploaded file: n; m; three bytes; workspace path: p]", + "[Uploaded file: n; m; +3 bytes; workspace path: p]", + "[Uploaded file: n; m; 03 bytes; workspace path: p]", + "[Uploaded file: n m; 3 bytes; workspace path: p]", + ] { + assert_eq!(AttachmentRef::from_description(text), None, "{text}"); + } +} + +// ── safe relative paths ────────────────────────────────────────────────────── + +#[test] +fn safe_relative_path_accepts_normal_relative_paths() { + for path in [ + "uploads/thread/id/file.png", + "file", + "a//b", + "a/./b", + "a/", + "uploads/..hidden/x", + ] { + assert!(is_safe_relative_path(path), "{path:?}"); + } +} + +#[test] +fn safe_relative_path_rejects_traversal_roots_and_separators() { + for path in [ + // OpenHuman's original cases. + "../escape", + "/absolute", + "uploads\\escape", + // Empty and current/parent components. + "", + ".", + "..", + "./a", + "a/..", + "a/../b", + "uploads/../../etc/passwd", + // Absolute and rooted forms. + "/", + "//server/share", + "/etc/passwd", + // Windows drive and UNC prefixes. + "C:\\Windows", + "C:\\", + "\\\\server\\share", + "\\\\?\\C:\\x", + "\\absolute", + "..\\escape", + // NUL. + "a\0b", + "\0", + "uploads/a.png\0.txt", + ] { + assert!(!is_safe_relative_path(path), "{path:?}"); + } +} + +#[cfg(windows)] +#[test] +fn safe_relative_path_rejects_forward_slash_drive_paths_on_windows() { + for path in ["C:/Windows", "C:x", "C:", "//?/C:/x"] { + assert!(!is_safe_relative_path(path), "{path:?}"); + } +} + +#[cfg(unix)] +#[test] +fn forward_slash_drive_path_is_an_ordinary_component_on_unix() { + // `C:` is a valid directory name here; joining it under a root stays under + // that root. Pinned so a platform change is a visible decision. + assert!(is_safe_relative_path("C:/Windows")); +} + +// ── filenames ──────────────────────────────────────────────────────────────── + +#[test] +fn filename_keeps_the_sanitized_leaf() { + for (name, expected) in [ + ("../../same.zip", "same.zip"), + ("dir\\sub\\b.txt", "b.txt"), + ("héllo wörld!.txt", "héllo_wörld_.txt"), + ("a:b*c?.png", "a_b_c_.png"), + ("", "attachment"), + (".", "attachment"), + ("..", "attachment"), + ("dir/", "attachment"), + ("...", "..."), + ("a\0b", "a_b"), + ] { + assert_eq!(sanitize_attachment_filename(name), expected, "{name:?}"); + } +} + +#[test] +fn filename_caps_at_180_bytes_on_a_char_boundary() { + let unicode_name = sanitize_attachment_filename(&"界".repeat(100)); + assert!(unicode_name.len() <= 180); + assert!(unicode_name.len() >= 177); + let mixed = sanitize_attachment_filename(&format!("a{}", "界".repeat(100))); + assert_eq!(mixed.len(), 178); + assert_eq!(sanitize_attachment_filename(&"x".repeat(500)).len(), 180); + for name in [unicode_name, mixed] { + assert!(is_safe_relative_path(&format!("uploads/t/id/{name}"))); + } +} + +// ── message helpers ────────────────────────────────────────────────────────── + +#[test] +fn enrichment_preserves_typed_media_and_image_forwarding() { + let media = MediaRef::Path { + path: "uploads/thread/id/media".into(), + media_type: Some("audio/wav".into()), + }; + let blocks = vec![ + ContentBlock::Text("caption".into()), + ContentBlock::Image(ImageRef { + url: "uploads/thread/id/image.png".into(), + mime_type: None, + }), + ContentBlock::Audio(media.clone()), + ContentBlock::Video(media.clone()), + ContentBlock::Document(media), + ]; + let input = Message::User(UserMessage { + content: blocks.clone(), + }); + let images = image_markers_from_message(&input, &[]); + assert_eq!(images, vec!["[IMAGE:uploads/thread/id/image.png]"]); + let Message::User(enriched) = enrich_user_message(input, "caption", "context\ncaption") else { + panic!("user") + }; + assert_eq!(&enriched.content[1..], &blocks[1..]); + assert_eq!( + enriched.content[0], + ContentBlock::Text("context\ncaption".into()) + ); + assert!(!should_forward_parent_images(&images[0])); + assert!(should_forward_parent_images( + "analyze the user's attachments" + )); +} + +#[test] +fn enriched_plain_turn_stays_one_text_block() { + assert_eq!( + enrich_user_message(Message::user("caption"), "caption", "context\ncaption"), + Message::user("context\ncaption") + ); +} + +#[test] +fn enrichment_edge_cases() { + // Not a suffix: the whole enriched text is the prefix. + assert_eq!( + enrich_user_message(Message::user("b"), "caption", "context"), + Message::user("contextb") + ); + // Nothing added: unchanged. + assert_eq!( + enrich_user_message(Message::user("caption"), "caption", "caption"), + Message::user("caption") + ); + // Media-first turn gains a new leading text block. + let image = ContentBlock::Image(ImageRef { + url: "uploads/a.png".into(), + mime_type: None, + }); + let input = Message::User(UserMessage { + content: vec![image.clone()], + }); + assert_eq!( + enrich_user_message(input, "", "context"), + Message::User(UserMessage { + content: vec![ContentBlock::Text("context".into()), image], + }) + ); + // Non-user messages pass through. + assert_eq!( + enrich_user_message(Message::assistant("hi"), "", "context"), + Message::assistant("hi") + ); +} + +#[test] +fn image_markers_keep_legacy_first_and_skip_duplicates() { + let image = |url: &str| { + ContentBlock::Image(ImageRef { + url: url.into(), + mime_type: Some("image/png".into()), + }) + }; + let input = Message::User(UserMessage { + content: vec![image("a.png"), image("b.png"), image("a.png")], + }); + let legacy = vec![ + "[Image: old #att:1]".to_string(), + "[IMAGE:b.png]".to_string(), + ]; + assert_eq!( + image_markers_from_message(&input, &legacy), + vec!["[Image: old #att:1]", "[IMAGE:b.png]", "[IMAGE:a.png]"] + ); + assert_eq!( + image_markers_from_message(&Message::assistant("x"), &legacy), + legacy + ); +} + +#[test] +fn explicit_image_selection_replaces_parent_forwarding() { + let image = upload("uploads/t/id/a.png", "a.png", "image/png").marker(); + let doc = upload("uploads/t/id/a.pdf", "a.pdf", "application/pdf").marker(); + assert!(!should_forward_parent_images(&format!("look {image}"))); + assert!(should_forward_parent_images(&format!("read {doc}"))); + assert!(!should_forward_parent_images("see [Image: photo #att:abc]")); + assert!(!should_forward_parent_images("see [IMAGE:/tmp/a.png]")); + assert!(should_forward_parent_images("see [IMAGE:]")); + assert!(should_forward_parent_images( + "[Image: (could not be processed)]" + )); +} diff --git a/crates/tinyagents-harness/src/multimodal/mod.rs b/crates/tinyagents-harness/src/multimodal/mod.rs index 58f6a2db2..d3a04955d 100644 --- a/crates/tinyagents-harness/src/multimodal/mod.rs +++ b/crates/tinyagents-harness/src/multimodal/mod.rs @@ -97,10 +97,12 @@ pub use blob_stash::{BlobAttachmentStash, StashedAttachment}; pub use config::{ALLOWED_IMAGE_MIME_TYPES, FileLimits, ImageLimits}; pub use error::{MultimodalError, Result}; pub use markers::{ - FILE_MARKER_PREFIX, IMAGE_MARKER_PREFIX, IMAGE_PLACEHOLDER_PREFIX, IMAGE_STASH_REF, - extract_image_placeholders_in_text, extract_ollama_image_payload, image_placeholder, + ATTACHMENT_MARKER_PREFIX, AttachmentRef, AttachmentSegment, FILE_MARKER_PREFIX, + IMAGE_MARKER_PREFIX, IMAGE_PLACEHOLDER_PREFIX, IMAGE_STASH_REF, attachment_segments, + enrich_user_message, extract_image_placeholders_in_text, extract_ollama_image_payload, + image_markers_from_message, image_placeholder, is_safe_relative_path, parse_attachment_markers, parse_file_markers, parse_image_markers, rehydrate_placeholders_in_text, - text_has_image_placeholders, + sanitize_attachment_filename, should_forward_parent_images, text_has_image_placeholders, }; pub use payload::{FilePayload, compose_multimodal_message, sha256_prefix, truncate_chars}; pub use request::{