diff --git a/Cargo.lock b/Cargo.lock index 3dd11d0ac..d1aab7e7e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -280,6 +280,7 @@ dependencies = [ "toml 1.2.3+spec-1.1.0", "turso", "ureq", + "url", "uuid", "windows 0.62.2", ] diff --git a/crates/agent/Cargo.toml b/crates/agent/Cargo.toml index 60458c3cc..36d43e409 100644 --- a/crates/agent/Cargo.toml +++ b/crates/agent/Cargo.toml @@ -15,6 +15,7 @@ process = [ "dep:sha2", "dep:smol", "dep:ureq", + "dep:url", "dep:uuid", "dep:windows", "dep:libc", @@ -38,6 +39,7 @@ toml = { version = "1.1", optional = true } # The version the store in `tcode-services` pins: one Turso in the build. turso = { version = "=0.8.4", default-features = false, optional = true } ureq = { version = "3", default-features = false, features = ["rustls", "gzip"], optional = true } +url = { version = "2", optional = true } uuid = { version = "1", features = ["v4"], optional = true } [target.'cfg(unix)'.dependencies] diff --git a/crates/agent/src/acp_session.rs b/crates/agent/src/acp_session.rs index ed549e87a..6fdf3e130 100644 --- a/crates/agent/src/acp_session.rs +++ b/crates/agent/src/acp_session.rs @@ -183,6 +183,16 @@ pub(crate) trait Dialect: Send + Sync + 'static { notification: acp::SessionNotification, ) -> Vec; + /// Async enrichment on the canonical events produced for a notification, + /// run after the session state lock is released and before emission. + fn enrich_events( + &self, + _cwd: &Path, + _events: &mut [AgentEvent], + ) -> impl Future + Send { + async {} + } + /// Dialect-specific tool name when the generic ACP mapping finds none /// (for example Antigravity's `Run mcp__` titles). fn tool_name( @@ -1094,13 +1104,15 @@ async fn run_actor( let update = (method == "session/update") .then(|| acp::SessionNotification::deserialize(¶ms).ok()) .flatten(); - let events = { + let (mut events, cwd) = { let mut state = client.state.lock_recover(); - match update { + let events = match update { Some(update) => dialect.session_update(&mut state, update), None => dialect.notification(&mut state, &method, params), - } + }; + (events, state.cwd().to_path_buf()) }; + dialect.enrich_events(&cwd, &mut events).await; client.emit_all(events).await; Ok(()) } @@ -2662,6 +2674,11 @@ impl State { } } + /// The session's working directory. + pub(crate) fn cwd(&self) -> &Path { + &self.cwd + } + /// Whether `session/load` is still answering. pub(crate) fn loading(&self) -> bool { self.loading diff --git a/crates/agent/src/antigravity.rs b/crates/agent/src/antigravity.rs index a33797f19..ba0b45590 100644 --- a/crates/agent/src/antigravity.rs +++ b/crates/agent/src/antigravity.rs @@ -553,6 +553,60 @@ fn chunk_is_empty(block: &acp::ContentBlock) -> bool { } } +/// When Antigravity's `read_file` reads an image over ACP (`agy` 1.5.x), it +/// sends only the text placeholder `"Showing binary file of type image/..."` +/// with no `ContentBlock::Image`. Extract the file path and declared MIME type +/// so Tcode can capture the image bytes from disk. +fn binary_image_read_target(event: &AgentEvent, cwd: &Path) -> Option<(PathBuf, String)> { + let AgentEvent::ItemCompleted(ThreadItem { + content: + ItemContent::ToolCall { + image_reads, + output, + status: ItemStatus::Completed, + family, + .. + }, + .. + }) = event + else { + return None; + }; + if !image_reads.is_empty() { + return None; + } + let Some(crate::ToolFamily::Read { path, .. }) = family.as_deref() else { + return None; + }; + if path.is_empty() { + return None; + } + let mime = output + .as_deref()? + .trim() + .strip_prefix("Showing binary file of type ")? + .trim(); + mime.starts_with("image/") + .then(|| (cwd.join(path), mime.to_owned())) +} + +pub(super) fn read_image_file(path: &Path, declared_mime: Option<&str>) -> Option { + use base64::Engine as _; + match std::fs::read(path) { + Ok(bytes) => { + let encoded = base64::engine::general_purpose::STANDARD.encode(bytes); + crate::tool_output::image(declared_mime, &encoded) + } + Err(error) => { + log::warn!( + "antigravity: could not preserve image read {}: {error}", + path.display() + ); + None + } + } +} + fn tool_error_summary( content: Option<&[acp::ToolCallContent]>, raw_output: Option<&Value>, @@ -994,6 +1048,23 @@ impl Dialect for Antigravity { events } + async fn enrich_events(&self, cwd: &Path, events: &mut [AgentEvent]) { + for event in events { + let Some((path, mime)) = binary_image_read_target(event, cwd) else { + continue; + }; + if let Some(image) = + crate::process::unblock(move || read_image_file(&path, Some(&mime))).await + && let AgentEvent::ItemCompleted(ThreadItem { + content: ItemContent::ToolCall { image_reads, .. }, + .. + }) = event + { + image_reads.push(image); + } + } + } + fn tool_name( &self, title: &str, @@ -1701,4 +1772,129 @@ mod tests { assert_eq!(normalize_mcp_tool_name("Run schedule", &servers), None); assert_eq!(normalize_mcp_tool_name("read_file", &servers), None); } + + /// `read_file` on an image over `agy acp` 1.5.23 sends only the text + /// placeholder `"Showing binary file of type image/..."` with no inline + /// image block; `enrich_events` captures the file from disk, skips + /// non-image binaries, and does not duplicate inline images. + #[test] + fn read_file_image_captures_bytes_from_disk_and_skips_non_images() { + use base64::Engine as _; + + const PNG_B64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAEElEQVR4nGNgYPiPAw0pCQCpcD/BFMrqcwAAAABJRU5ErkJggg=="; + let dir = std::env::temp_dir().join(format!("tcode-agy-img-test-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let png_path = dir.join("shot.png"); + let pdf_path = dir.join("doc.pdf"); + std::fs::write( + &png_path, + base64::engine::general_purpose::STANDARD + .decode(PNG_B64) + .unwrap(), + ) + .unwrap(); + std::fs::write(&pdf_path, b"%PDF-1.4\n").unwrap(); + + let dialect = Antigravity::default(); + let mut state = State::new(ProviderKind::Antigravity, dir.clone()); + let _ = state.begin_agent_turn("turn-1"); + + let _ = dialect.session_update( + &mut state, + notification(json!({ + "sessionUpdate": "tool_call", + "toolCallId": "call_img", + "title": "File shot.png", + "kind": "read", + "status": "in_progress", + "locations": [{ "path": png_path }], + "rawInput": { "Path": png_path } + })), + ); + let mut completed = dialect.session_update( + &mut state, + notification(json!({ + "sessionUpdate": "tool_call_update", + "toolCallId": "call_img", + "status": "completed", + "rawOutput": "Showing binary file of type image/png", + "content": [{ + "type": "content", + "content": { "type": "text", "text": "Showing binary file of type image/png" } + }] + })), + ); + smol::block_on(dialect.enrich_events(&dir, &mut completed)); + assert!(matches!( + completed.as_slice(), + [AgentEvent::ItemCompleted(ThreadItem { + id, + content: ItemContent::ToolCall { + image_reads, + output: Some(output), + family: Some(family), + .. + }, + .. + })] if id == "call_img" + && output == "Showing binary file of type image/png" + && matches!(family.as_ref(), crate::ToolFamily::Read { .. }) + && image_reads.len() == 1 + && image_reads[0].media_type == "image/png" + && image_reads[0].data_base64 == PNG_B64 + )); + + // If ACP already delivered an inline image block, enrichment does not duplicate it. + let mut inline = dialect.session_update( + &mut state, + notification(json!({ + "sessionUpdate": "tool_call", + "toolCallId": "call_inline", + "title": "File shot.png", + "kind": "read", + "status": "completed", + "locations": [{ "path": png_path }], + "content": [ + { "type": "content", "content": { "type": "text", "text": "Showing binary file of type image/png" } }, + { "type": "content", "content": { "type": "image", "mimeType": "image/png", "data": PNG_B64 } } + ] + })), + ); + smol::block_on(dialect.enrich_events(&dir, &mut inline)); + assert!(matches!( + inline.as_slice(), + [AgentEvent::ItemCompleted(ThreadItem { + content: ItemContent::ToolCall { image_reads, .. }, + .. + })] if image_reads.len() == 1 + )); + + // Non-image binary reads (such as PDF) stay text-only. + let mut pdf = dialect.session_update( + &mut state, + notification(json!({ + "sessionUpdate": "tool_call", + "toolCallId": "call_pdf", + "title": "File doc.pdf", + "kind": "read", + "status": "completed", + "locations": [{ "path": pdf_path }], + "rawOutput": "Showing binary file of type application/pdf", + "content": [{ + "type": "content", + "content": { "type": "text", "text": "Showing binary file of type application/pdf" } + }] + })), + ); + smol::block_on(dialect.enrich_events(&dir, &mut pdf)); + assert!(matches!( + pdf.as_slice(), + [AgentEvent::ItemCompleted(ThreadItem { + content: ItemContent::ToolCall { image_reads, .. }, + .. + })] if image_reads.is_empty() + )); + + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/agent/src/antigravity/subagents.rs b/crates/agent/src/antigravity/subagents.rs index 03c24966f..37d42c14c 100644 --- a/crates/agent/src/antigravity/subagents.rs +++ b/crates/agent/src/antigravity/subagents.rs @@ -29,7 +29,7 @@ use smol::future; use super::record; use crate::acp_session::{State, TurnEnd}; -use crate::{AgentEvent, ItemContent, ItemStatus, ThreadItem, ToolFamily, TurnStatus}; +use crate::{AgentEvent, Attachment, ItemContent, ItemStatus, ThreadItem, ToolFamily, TurnStatus}; const POLL_INTERVAL: Duration = Duration::from_millis(200); @@ -262,6 +262,16 @@ struct ChildStep { content: Option, #[serde(default)] tool_calls: Option>, + #[serde(default)] + media: Vec, +} + +#[derive(Debug, Deserialize)] +struct ChildMedia { + #[serde(default)] + mime_type: Option, + #[serde(default)] + uri: Option, } #[derive(Debug, Deserialize)] @@ -278,7 +288,12 @@ struct PendingChildTool { } impl PendingChildTool { - fn content(&self, status: ItemStatus, output: Option) -> ItemContent { + fn content( + &self, + status: ItemStatus, + output: Option, + image_reads: Vec, + ) -> ItemContent { if self.name == "run_command" { let command = self .input @@ -310,12 +325,25 @@ impl PendingChildTool { input: self.input.clone(), output, status, - image_reads: Vec::new(), + image_reads, family, } } } +fn read_child_media(media: &ChildMedia) -> Option { + if let Some(mime) = media.mime_type.as_deref() + && !mime.starts_with("image/") + { + return None; + } + let path = url::Url::parse(media.uri.as_deref()?) + .ok()? + .to_file_path() + .ok()?; + super::read_image_file(&path, media.mime_type.as_deref()) +} + /// Incremental JSONL tailer and canonical mapper for one Antigravity subagent. pub(super) struct ChildTailer { parent_item_id: String, @@ -435,7 +463,7 @@ impl ChildTailer { name, input, }; - let content = tool.content(ItemStatus::InProgress, None); + let content = tool.content(ItemStatus::InProgress, None, Vec::new()); let id = tool.id.clone(); self.pending_tools.push_back(tool); events.push(AgentEvent::ItemStarted(self.child_item(id, content))); @@ -453,7 +481,7 @@ impl ChildTailer { } if step.status == "DONE" && !has_new_tools { while let Some(tool) = self.pending_tools.pop_front() { - let content = tool.content(ItemStatus::Completed, None); + let content = tool.content(ItemStatus::Completed, None, Vec::new()); events.push(AgentEvent::ItemCompleted(self.child_item(tool.id, content))); } self.turn_done = true; @@ -462,7 +490,9 @@ impl ChildTailer { "GENERIC" => { if let Some(tool) = self.pending_tools.pop_front() { let output = step.content.filter(|c| !c.trim().is_empty()); - let content = tool.content(ItemStatus::Completed, output); + let image_reads: Vec = + step.media.iter().filter_map(read_child_media).collect(); + let content = tool.content(ItemStatus::Completed, output, image_reads); events.push(AgentEvent::ItemCompleted(self.child_item(tool.id, content))); } } @@ -1336,4 +1366,95 @@ mod tests { }) if id == "call_res" && summary == "Finished" ))); } + + #[test] + fn subagent_media_steps_populate_image_reads() { + use base64::Engine as _; + + const PNG_B64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAEElEQVR4nGNgYPiPAw0pCQCpcD/BFMrqcwAAAABJRU5ErkJggg=="; + let scratch = Scratch::new(); + let media_dir = scratch.0.join("media files"); + std::fs::create_dir_all(&media_dir).unwrap(); + let png_path = media_dir.join("step_1.png"); + let pdf_path = media_dir.join("step_1.pdf"); + std::fs::write( + &png_path, + base64::engine::general_purpose::STANDARD + .decode(PNG_B64) + .unwrap(), + ) + .unwrap(); + std::fs::write(&pdf_path, b"%PDF-1.4\n").unwrap(); + let file_uri = |path: &Path| { + let raw = path + .to_string_lossy() + .replace('\\', "/") + .replace(' ', "%20"); + if raw.starts_with('/') { + format!("file://{raw}") + } else { + format!("file:///{raw}") + } + }; + + let mut watcher = WatcherState::new(scratch.0.clone(), "parent-img".into()); + watcher.on_spawn(SpawnedSubagent { + tool_call_id: "call_img_sub".into(), + agent_type: "research".into(), + description: "Inspect screenshot".into(), + prompt: None, + model: None, + }); + scratch.write_subagent( + "parent-img", + "child-img", + "research", + "Inspect screenshot", + "SUBAGENT_STATE_ALIVE", + 1, + ); + scratch.append_transcript( + "child-img", + &json!({ + "step_index": 1, + "type": "PLANNER_RESPONSE", + "status": "DONE", + "tool_calls": [{ + "name": "read_file", + "args": { "Path": serde_json::to_string(&png_path).unwrap() } + }] + }), + ); + scratch.append_transcript( + "child-img", + &json!({ + "step_index": 2, + "type": "GENERIC", + "status": "DONE", + "content": "Showing binary file of type image/png", + "media": [ + { "mime_type": "image/png", "uri": file_uri(&png_path) }, + { "mime_type": "application/pdf", "uri": file_uri(&pdf_path) } + ] + }), + ); + + let events = watcher.poll(); + assert!(events.iter().any(|event| matches!( + event, + AgentEvent::ItemCompleted(ThreadItem { + parent_item_id: Some(parent), + content: ItemContent::ToolCall { + name, + image_reads, + .. + }, + .. + }) if parent == "call_img_sub" + && name == "read_file" + && image_reads.len() == 1 + && image_reads[0].media_type == "image/png" + && image_reads[0].data_base64 == PNG_B64 + ))); + } } diff --git a/crates/agent/src/opencode.rs b/crates/agent/src/opencode.rs index 600b08d1c..4c5e2fccf 100644 --- a/crates/agent/src/opencode.rs +++ b/crates/agent/src/opencode.rs @@ -1671,9 +1671,6 @@ fn reverted_files(files: &Value) -> RewindFiles { } } -/// The attachments of a restored prompt that are files on this machine. An -/// inline attachment (Tcode sends its images as `data:` URLs) has no path to -/// put back in a composer, so the prompt comes back without it. /// The prompt's images that are local files: the composer takes images /// alone, and an inline (`data:`) one has no path to hand it. fn local_attachments(files: &Value) -> Vec { @@ -1687,36 +1684,13 @@ fn local_attachments(files: &Value) -> Vec { .is_some_and(|mime| mime.starts_with("image/")) }) .filter_map(|file| { - let path = file - .pointer("/source/uri")? - .as_str()? - .strip_prefix("file://")?; - Some(percent_decode(path)) + let uri = url::Url::parse(file.pointer("/source/uri")?.as_str()?).ok()?; + let path = uri.to_file_path().ok()?; + Some(path.to_string_lossy().into_owned()) }) .collect() } -/// `decodeURIComponent` of a `file://` URL's path. -fn percent_decode(path: &str) -> String { - let bytes = path.as_bytes(); - let mut decoded = Vec::with_capacity(bytes.len()); - let mut index = 0; - while index < bytes.len() { - if bytes[index] == b'%' - && let Some(byte) = path - .get(index + 1..index + 3) - .and_then(|hex| u8::from_str_radix(hex, 16).ok()) - { - decoded.push(byte); - index += 3; - } else { - decoded.push(bytes[index]); - index += 1; - } - } - String::from_utf8_lossy(&decoded).into_owned() -} - fn form_question(field: &Value) -> Option { let key = field["key"].as_str()?; let title = field["title"].as_str();