Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(host-core): return image files from Read as inline image blocks
yexisu94ac5ffcde6c
diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rsindex 9be84c3cb..39a5402d7 100644--- a/crates/host-core/src/tools/mod.rs+++ b/crates/host-core/src/tools/mod.rs@@ -1207,6 +1207,71 @@ fn root_label(root_kind: ToolRoot) -> &'static str {}}+/// Image extensions Read returns as an inline image block instead of refusing+/// them as binary content. Mirrors the mime types pi-ai can attach to a tool+/// result for vision models (issue #1073); everything else, including svg,+/// keeps the text/binary refusal below.+fn inline_image_mime(extension: &str) -> Option<&'static str> {+ match extension {+ "png" => Some("image/png"),+ "jpg" | "jpeg" => Some("image/jpeg"),+ "gif" => Some("image/gif"),+ "webp" => Some("image/webp"),+ _ => None,+ }+}++/// Read an image file and return it as a structured image block. The runtime+/// converts a top-level `images` array into pi-ai `ImageContent` blocks, so a+/// vision-capable model receives the picture itself instead of a binary-file+/// refusal (issue #1073). Signature bytes are checked so a text file with an+/// image extension is never inlined as picture data.+fn read_image_block(+ resolved: &Path,+ display: &str,+ size: u64,+ mime: &str,+) -> Result<Value, (String, String)> {+ // Matches MAX_INLINE_IMAGE_BYTES in packages/shared/src/attachment-limits.ts;+ // host-core cannot import the TS constant.+ const MAX_INLINE_IMAGE_BYTES: u64 = 10_000_000;+ if size > MAX_INLINE_IMAGE_BYTES {+ return Err((+ "TOOL_FAILED".into(),+ format!(+ "{display} is {size} bytes; images above {MAX_INLINE_IMAGE_BYTES} bytes are not inlined"+ ),+ ));+ }+ let bytes = std::fs::read(resolved).map_err(|e| {+ if e.kind() == std::io::ErrorKind::NotFound {+ ("FILE_NOT_FOUND".into(), format!("File not found: {display}"))+ } else {+ ("TOOL_FAILED".into(), format!("read failed: {e}"))+ }+ })?;+ let signature_ok = match mime {+ "image/png" => bytes.starts_with(b"\x89PNG\r\n\x1a\n"),+ "image/jpeg" => bytes.starts_with(b"\xff\xd8\xff"),+ "image/gif" => bytes.starts_with(b"GIF8"),+ "image/webp" => bytes.len() >= 12 && &bytes[8..12] == b"WEBP",+ _ => false,+ };+ if !signature_ok {+ return Err((+ "TOOL_BINARY_CONTENT".into(),+ format!("{display} does not look like a valid {mime} image"),+ ));+ }+ use base64::Engine as _;+ let data = base64::engine::general_purpose::STANDARD.encode(&bytes);+ Ok(json!({+ "path": display,+ "text": format!("Image file {display} ({size} bytes, {mime}); the image is attached to this result."),+ "images": [{ "data": data, "mimeType": mime }],+ }))+}+fn tool_read(workspace: Option<&Path>,scratch: Option<&Path>,@@ -1264,6 +1329,9 @@ fn tool_read(.extension().map(|ext| ext.to_string_lossy().to_lowercase());if let Some(ext) = &extension {+ if let Some(mime) = inline_image_mime(ext) {+ return read_image_block(&resolved, &display, meta.len(), mime);+ }if BINARY_EXTENSIONS.contains(&ext.as_str()) {return Err(("TOOL_BINARY_CONTENT".into(),@@ -3341,6 +3409,87 @@ mod tests {}}+ #[tokio::test]+ async fn read_returns_image_blocks_for_image_files() {+ // Minimal real signatures so the sniffing branch is exercised.+ let png = b"\x89PNG\r\n\x1a\nfake-png-body";+ let jpeg = b"\xff\xd8\xff\xe0fake-jpeg-body";+ let gif = b"GIF89afake-gif-body";+ let webp = b"RIFF\x00\x00\x00\x00WEBPVP8 fake-webp-body";+ let dir = tempfile::tempdir().unwrap();+ std::fs::write(dir.path().join("a.png"), png).unwrap();+ std::fs::write(dir.path().join("b.jpeg"), jpeg).unwrap();+ std::fs::write(dir.path().join("c.gif"), gif).unwrap();+ std::fs::write(dir.path().join("d.webp"), webp).unwrap();++ let result = execute_tool(+ Some(dir.path()),+ None,+ "Read",+ &serde_json::json!({ "path": "a.png" }),+ 5_000,+ )+ .await;+ assert!(result.ok, "png should read as an image block: {:?}", result.error_code);+ let content = result.content.as_object().expect("object result");+ let images = content["images"].as_array().expect("images array");+ assert_eq!(images.len(), 1);+ assert_eq!(images[0]["mimeType"], "image/png");+ use base64::Engine as _;+ assert_eq!(+ base64::engine::general_purpose::STANDARD+ .decode(images[0]["data"].as_str().unwrap())+ .unwrap(),+ png+ );+ assert!(content["text"].as_str().unwrap().contains("a.png"));++ for name in ["b.jpeg", "c.gif", "d.webp"] {+ let result = execute_tool(+ Some(dir.path()),+ None,+ "Read",+ &serde_json::json!({ "path": name }),+ 5_000,+ )+ .await;+ assert!(result.ok, "{name} should read as an image block");+ }+ }++ #[tokio::test]+ async fn read_refuses_image_extension_with_non_image_bytes() {+ let dir = tempfile::tempdir().unwrap();+ std::fs::write(dir.path().join("fake.png"), b"plain text, not a png").unwrap();+ let result = execute_tool(+ Some(dir.path()),+ None,+ "Read",+ &serde_json::json!({ "path": "fake.png" }),+ 5_000,+ )+ .await;+ assert!(!result.ok);+ assert_eq!(result.error_code.as_deref(), Some("TOOL_BINARY_CONTENT"));+ }++ #[tokio::test]+ async fn read_refuses_oversized_images() {+ let dir = tempfile::tempdir().unwrap();+ let big = vec![0u8; 10_000_001];+ std::fs::write(dir.path().join("big.png"), &big).unwrap();+ let result = execute_tool(+ Some(dir.path()),+ None,+ "Read",+ &serde_json::json!({ "path": "big.png" }),+ 5_000,+ )+ .await;+ assert!(!result.ok);+ assert_eq!(result.error_code.as_deref(), Some("TOOL_FAILED"));+ }+#[tokio::test]async fn security_denylist_blocks_read_write_edit_and_hides_search_results() {let dir = tempfile::tempdir().unwrap();