Skip to main content

tinyharness_lib/
image.rs

1use std::path::PathBuf;
2use std::str::FromStr;
3
4use serde::{Deserialize, Serialize};
5
6/// Maximum image file size: 20 MB.
7/// Larger files are rejected to avoid memory issues.
8pub const MAX_IMAGE_BYTES: u64 = 20 * 1024 * 1024;
9
10/// Supported image MIME types for multimodal models.
11pub const SUPPORTED_MIME_TYPES: &[&str] = &[
12    "image/png",
13    "image/jpeg",
14    "image/jpg",
15    "image/webp",
16    "image/gif",
17    "image/bmp",
18];
19
20/// An image attachment for multimodal chat messages.
21///
22/// Stores both the filesystem path (for reference) and the base64-encoded
23/// content (for self-contained session persistence).
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct ImageAttachment {
26    /// Original path the image was loaded from (for display and `/image` listing).
27    pub path: PathBuf,
28    /// MIME type (e.g. "image/png", "image/jpeg").
29    pub mime_type: String,
30    /// Base64-encoded image bytes (without the `data:` prefix).
31    pub base64_data: String,
32    /// File size in bytes.
33    pub size_bytes: u64,
34    /// Image dimensions: (width, height) in pixels, if detectable.
35    /// Currently not parsed; reserved for future use.
36    #[serde(skip_serializing_if = "Option::is_none", default)]
37    pub dimensions: Option<(u32, u32)>,
38}
39
40/// Error type for image loading operations.
41#[derive(Debug)]
42pub enum ImageError {
43    FileNotFound(PathBuf),
44    IoError(std::io::Error),
45    TooLarge { path: PathBuf, size: u64, max: u64 },
46    UnsupportedMime { path: PathBuf, mime: String },
47    EncodeError(String),
48}
49
50impl std::fmt::Display for ImageError {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        match self {
53            ImageError::FileNotFound(p) => write!(f, "File not found: {}", p.display()),
54            ImageError::IoError(e) => write!(f, "I/O error: {}", e),
55            ImageError::TooLarge { path, size, max } => {
56                write!(
57                    f,
58                    "Image too large: {} ({} bytes, max {} bytes)",
59                    path.display(),
60                    size,
61                    max
62                )
63            }
64            ImageError::UnsupportedMime { path, mime } => {
65                write!(
66                    f,
67                    "Unsupported image format '{}' for {}",
68                    mime,
69                    path.display()
70                )
71            }
72            ImageError::EncodeError(msg) => write!(f, "{}", msg),
73        }
74    }
75}
76
77impl std::error::Error for ImageError {}
78
79/// Guess MIME type from a file extension.
80fn guess_mime(ext: &str) -> Option<&'static str> {
81    match ext.to_lowercase().as_str() {
82        "png" => Some("image/png"),
83        "jpg" | "jpeg" => Some("image/jpeg"),
84        "webp" => Some("image/webp"),
85        "gif" => Some("image/gif"),
86        "bmp" => Some("image/bmp"),
87        "svg" => Some("image/svg+xml"),
88        _ => None,
89    }
90}
91
92/// Base64 character set (standard, with '+' and '/').
93const BASE64_CHARS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
94
95/// Encode arbitrary bytes as a standard base64 string.
96fn encode_base64(bytes: &[u8]) -> String {
97    let mut result = String::with_capacity(bytes.len().div_ceil(3) * 4);
98
99    for chunk in bytes.chunks(3) {
100        let b0 = chunk[0];
101        let b1 = chunk.get(1).copied().unwrap_or(0);
102        let b2 = chunk.get(2).copied().unwrap_or(0);
103
104        let i0 = (b0 >> 2) as usize;
105        let i1 = (((b0 & 0x03) << 4) | (b1 >> 4)) as usize;
106        let i2 = if chunk.len() > 1 {
107            (((b1 & 0x0f) << 2) | (b2 >> 6)) as usize
108        } else {
109            64
110        };
111        let i3 = if chunk.len() > 2 {
112            (b2 & 0x3f) as usize
113        } else {
114            64
115        };
116
117        result.push(BASE64_CHARS[i0] as char);
118        result.push(BASE64_CHARS[i1] as char);
119        result.push(if i2 < 64 { BASE64_CHARS[i2] } else { b'=' } as char);
120        result.push(if i3 < 64 { BASE64_CHARS[i3] } else { b'=' } as char);
121    }
122
123    result
124}
125
126impl ImageAttachment {
127    /// Load an image from disk, encode it as base64, and validate.
128    ///
129    /// Rejects files larger than `MAX_IMAGE_BYTES` and files with unsupported
130    /// MIME types (based on extension).
131    pub fn load(path: PathBuf) -> Result<Self, ImageError> {
132        // Read file bytes
133        let bytes = std::fs::read(&path).map_err(|e| {
134            if e.kind() == std::io::ErrorKind::NotFound {
135                ImageError::FileNotFound(path.clone())
136            } else {
137                ImageError::IoError(e)
138            }
139        })?;
140
141        let size = bytes.len() as u64;
142
143        // Size check
144        if size > MAX_IMAGE_BYTES {
145            return Err(ImageError::TooLarge {
146                path: path.clone(),
147                size,
148                max: MAX_IMAGE_BYTES,
149            });
150        }
151
152        // Guess MIME type from extension
153        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
154        let mime = guess_mime(ext).ok_or_else(|| ImageError::UnsupportedMime {
155            path: path.clone(),
156            mime: ext.to_string(),
157        })?;
158
159        // Base64 encode (pure std, no extra deps)
160        let base64_data = encode_base64(&bytes);
161
162        Ok(ImageAttachment {
163            path,
164            mime_type: mime.to_string(),
165            base64_data,
166            size_bytes: size,
167            dimensions: None,
168        })
169    }
170
171    /// Load an image from disk with an absolute path.
172    /// Convenience wrapper that canonicalises the path.
173    pub fn load_from_str(path_str: &str) -> Result<Self, ImageError> {
174        let path = PathBuf::from_str(path_str)
175            .map_err(|_| ImageError::FileNotFound(PathBuf::from(path_str)))?;
176        let abs_path = if path.is_absolute() {
177            path
178        } else {
179            // Resolve relative to CWD
180            std::env::current_dir()
181                .unwrap_or_else(|_| PathBuf::from("."))
182                .join(&path)
183        };
184        Self::load(abs_path)
185    }
186
187    /// Format as a `data:` URI for use in OpenAI-compatible APIs.
188    pub fn data_uri(&self) -> String {
189        format!("data:{};base64,{}", self.mime_type, self.base64_data)
190    }
191
192    /// Display name (file name, fallback to full path).
193    pub fn display_name(&self) -> String {
194        self.path
195            .file_name()
196            .map(|n| n.to_string_lossy().to_string())
197            .unwrap_or_else(|| self.path.to_string_lossy().to_string())
198    }
199
200    /// Human-readable size.
201    pub fn size_display(&self) -> String {
202        let bytes = self.size_bytes;
203        if bytes < 1024 {
204            format!("{} B", bytes)
205        } else if bytes < 1024 * 1024 {
206            format!("{:.1} KB", bytes as f64 / 1024.0)
207        } else {
208            format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
209        }
210    }
211
212    /// Returns true if the file still exists on disk.
213    pub fn exists_on_disk(&self) -> bool {
214        self.path.is_file()
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    #[test]
223    fn test_encode_base64() {
224        assert_eq!(encode_base64(b"f"), "Zg==");
225        assert_eq!(encode_base64(b"fo"), "Zm8=");
226        assert_eq!(encode_base64(b"foo"), "Zm9v");
227        assert_eq!(encode_base64(b"foob"), "Zm9vYg==");
228        assert_eq!(encode_base64(b"fooba"), "Zm9vYmE=");
229        assert_eq!(encode_base64(b"foobar"), "Zm9vYmFy");
230        // Empty input
231        assert_eq!(encode_base64(b""), "");
232    }
233
234    use std::io::Write;
235
236    fn make_png() -> Vec<u8> {
237        // Minimal valid PNG (1x1 black pixel)
238        vec![
239            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG signature
240            0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, // IHDR chunk
241            0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90,
242            0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, // IDAT chunk
243            0x54, 0x08, 0xD7, 0x63, 0xF8, 0xFF, 0xFF, 0x3F, 0x00, 0x05, 0xFE, 0x02, 0xFE, 0xDC,
244            0xCC, 0x59, 0xE7, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, // IEND chunk
245            0x44, 0xAE, 0x42, 0x60, 0x82,
246        ]
247    }
248
249    #[test]
250    fn test_load_png() {
251        let dir = tempfile::tempdir().unwrap();
252        let file_path = dir.path().join("test.png");
253        let png_bytes = make_png();
254        let mut f = std::fs::File::create(&file_path).unwrap();
255        f.write_all(&png_bytes).unwrap();
256
257        let img = ImageAttachment::load(file_path.clone()).unwrap();
258        assert_eq!(img.mime_type, "image/png");
259        assert!(!img.base64_data.is_empty());
260        assert_eq!(img.size_bytes, png_bytes.len() as u64);
261        assert!(img.data_uri().starts_with("data:image/png;base64,"));
262    }
263
264    #[test]
265    fn test_load_jpeg() {
266        let dir = tempfile::tempdir().unwrap();
267        let file_path = dir.path().join("photo.jpg");
268        // Minimal JPEG (not valid, but extension test should work)
269        std::fs::write(&file_path, b"\xff\xd8\xff\xe0").unwrap();
270
271        let img = ImageAttachment::load(file_path).unwrap();
272        assert_eq!(img.mime_type, "image/jpeg");
273    }
274
275    #[test]
276    fn test_load_unsupported_extension() {
277        let dir = tempfile::tempdir().unwrap();
278        let file_path = dir.path().join("doc.pdf");
279        std::fs::write(&file_path, b"not a pdf").unwrap();
280
281        let err = ImageAttachment::load(file_path).unwrap_err();
282        match err {
283            ImageError::UnsupportedMime { .. } => {}
284            other => panic!("expected UnsupportedMime, got {:?}", other),
285        }
286    }
287
288    #[test]
289    fn test_load_nonexistent() {
290        let path = PathBuf::from("/nonexistent/image.png");
291        let err = ImageAttachment::load(path).unwrap_err();
292        match err {
293            ImageError::FileNotFound(_) => {}
294            other => panic!("expected FileNotFound, got {:?}", other),
295        }
296    }
297
298    #[test]
299    fn test_display_name() {
300        let img = ImageAttachment {
301            path: PathBuf::from("/tmp/screenshot.png"),
302            mime_type: "image/png".to_string(),
303            base64_data: "aaaa".to_string(),
304            size_bytes: 100,
305            dimensions: None,
306        };
307        assert_eq!(img.display_name(), "screenshot.png");
308        assert_eq!(img.size_display(), "100 B");
309    }
310
311    #[test]
312    fn test_size_display() {
313        let img = ImageAttachment {
314            path: PathBuf::from("/tmp/big.png"),
315            mime_type: "image/png".to_string(),
316            base64_data: "x".repeat(1024 * 1024),
317            size_bytes: 1_500_000,
318            dimensions: None,
319        };
320        assert!(img.size_display().contains("1.4 MB"));
321    }
322}