Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(host-core): safely inline Read image results

vastsa09240145297e
diff --cc crates/host-core/src/tools/mod.rs
index 9be84c3cb,fdac4fdb4..62ee0dd33
--- a/crates/host-core/src/tools/mod.rs
+++ b/crates/host-core/src/tools/mod.rs
@@@ -5,7 -5,7 +5,7 @@@ use serde::{Deserialize, Serialize}
use serde_json::{json, Value};
use std::fs::File;
use std::future::pending;
--use std::io::{self, BufRead, BufReader, ErrorKind};
++use std::io::{self, BufRead, BufReader, ErrorKind, Read};
use std::path::{Path, PathBuf};
use std::process::{ExitStatus, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
@@@ -1207,6 -1207,74 +1207,87 @@@ fn root_label(root_kind: ToolRoot) -> &
}
}
+ /// 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 {
++ const MAX_INLINE_IMAGE_BYTES: usize = 10_000_000;
++ if size > MAX_INLINE_IMAGE_BYTES as u64 {
+ 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| {
++ let file = File::open(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 mut bytes = Vec::with_capacity(size as usize);
++ file.take((MAX_INLINE_IMAGE_BYTES + 1) as u64)
++ .read_to_end(&mut bytes)
++ .map_err(|e| ("TOOL_FAILED".into(), format!("read failed: {e}")))?;
++ if bytes.len() > MAX_INLINE_IMAGE_BYTES {
++ return Err((
++ "TOOL_FAILED".into(),
++ format!(
++ "{display} exceeds {MAX_INLINE_IMAGE_BYTES} bytes; images above this limit are not inlined"
++ ),
++ ));
++ }
++ let size = bytes.len();
+ 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>,
@@@ -3341,6 -3412,91 +3425,98 @@@ 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 mut big = vec![0u8; 10_000_001];
++ big[..8].copy_from_slice(b"\x89PNG\r\n\x1a\n");
++ let path = dir.path().join("big.png");
++ std::fs::write(&path, &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"));
++
++ // Simulate the file growing after metadata was checked: the bounded
++ // read must still reject it without trusting the stale size argument.
++ let error = read_image_block(&path, "big.png", 1, "image/png").unwrap_err();
++ assert_eq!(error.0, "TOOL_FAILED");
+ }
+
#[tokio::test]
async fn security_denylist_blocks_read_write_edit_and_hides_search_results() {
let dir = tempfile::tempdir().unwrap();
diff --cc packages/agent-runtime/src/runtime.ts
index 2ca10f5f5,86bea2319..4b3a47556
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@@ -1472,11 -1472,11 +1472,7 @@@ export function toolResultFromUi
m: UiMessage,
timestamp: number,
): ToolResultMessage {
-- const raw = m.toolResult as
-- | { content?: unknown; details?: unknown }
-- | string
-- | null
-- | undefined;
++ const raw: unknown = m.toolResult;
const blocks: ToolResultMessage["content"] = [];
const rawBlocks =
isRecord(raw) && Array.isArray(raw.content) ? raw.content : undefined;
@@@ -1496,7 -1496,26 +1492,27 @@@
} else if (typeof raw === "string" && raw.trim()) {
blocks.push({ type: "text", text: raw });
} else if (raw !== undefined && raw !== null) {
- blocks.push({ type: "text", text: safeJson(raw) });
+ // A host Read of an image file returns a top-level `images` array rather
+ // than content blocks; restore those as real image content so the model
+ // sees the picture across a restart, not just the JSON text (#1073).
- const images =
- isRecord(raw) && Array.isArray(raw.images) ? raw.images : undefined;
- if (images) {
- const { images: _images, ...rest } = raw;
++ const rawObject = isRecord(raw) ? raw : undefined;
++ const images = rawObject?.images;
++ if (rawObject && Array.isArray(images)) {
++ const rest = { ...rawObject };
++ delete rest.images;
+ blocks.push({ type: "text", text: safeJson(rest) });
+ for (const image of images) {
+ if (
+ isRecord(image) &&
+ typeof image.data === "string" &&
+ typeof image.mimeType === "string"
+ ) {
+ blocks.push({ type: "image", data: image.data, mimeType: image.mimeType });
+ }
+ }
+ } else {
+ blocks.push({ type: "text", text: safeJson(raw) });
+ }
}
const interrupted = m.toolStatus === "running";
const rawRecord: Record<string, unknown> | undefined = isRecord(raw)