Skip to main content

tinyharness_lib/
image.rs

1use std::path::{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    ///
174    /// Relative paths resolve against the process CWD — use
175    /// [`ImageAttachment::load_from_str_in`] to supply an explicit base
176    /// directory (e.g. [`Paths::project_dir`](crate::paths::Paths::project_dir)).
177    pub fn load_from_str(path_str: &str) -> Result<Self, ImageError> {
178        let base = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
179        Self::load_from_str_in(&base, path_str)
180    }
181
182    /// Load an image, resolving relative paths against `base_dir`.
183    pub fn load_from_str_in(base_dir: &Path, path_str: &str) -> Result<Self, ImageError> {
184        let path = PathBuf::from_str(path_str)
185            .map_err(|_| ImageError::FileNotFound(PathBuf::from(path_str)))?;
186        let abs_path = if path.is_absolute() {
187            path
188        } else {
189            base_dir.join(&path)
190        };
191        Self::load(abs_path)
192    }
193
194    /// Format as a `data:` URI for use in OpenAI-compatible APIs.
195    pub fn data_uri(&self) -> String {
196        format!("data:{};base64,{}", self.mime_type, self.base64_data)
197    }
198
199    /// Display name (file name, fallback to full path).
200    pub fn display_name(&self) -> String {
201        self.path
202            .file_name()
203            .map(|n| n.to_string_lossy().to_string())
204            .unwrap_or_else(|| self.path.to_string_lossy().to_string())
205    }
206
207    /// Human-readable size.
208    pub fn size_display(&self) -> String {
209        let bytes = self.size_bytes;
210        if bytes < 1024 {
211            format!("{} B", bytes)
212        } else if bytes < 1024 * 1024 {
213            format!("{:.1} KB", bytes as f64 / 1024.0)
214        } else {
215            format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
216        }
217    }
218
219    /// Returns true if the file still exists on disk.
220    pub fn exists_on_disk(&self) -> bool {
221        self.path.is_file()
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn test_encode_base64() {
231        assert_eq!(encode_base64(b"f"), "Zg==");
232        assert_eq!(encode_base64(b"fo"), "Zm8=");
233        assert_eq!(encode_base64(b"foo"), "Zm9v");
234        assert_eq!(encode_base64(b"foob"), "Zm9vYg==");
235        assert_eq!(encode_base64(b"fooba"), "Zm9vYmE=");
236        assert_eq!(encode_base64(b"foobar"), "Zm9vYmFy");
237        // Empty input
238        assert_eq!(encode_base64(b""), "");
239    }
240
241    use std::io::Write;
242
243    fn make_png() -> Vec<u8> {
244        // Minimal valid PNG (1x1 black pixel)
245        vec![
246            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG signature
247            0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, // IHDR chunk
248            0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90,
249            0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, // IDAT chunk
250            0x54, 0x08, 0xD7, 0x63, 0xF8, 0xFF, 0xFF, 0x3F, 0x00, 0x05, 0xFE, 0x02, 0xFE, 0xDC,
251            0xCC, 0x59, 0xE7, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, // IEND chunk
252            0x44, 0xAE, 0x42, 0x60, 0x82,
253        ]
254    }
255
256    #[test]
257    fn test_load_png() {
258        let dir = tempfile::tempdir().unwrap();
259        let file_path = dir.path().join("test.png");
260        let png_bytes = make_png();
261        let mut f = std::fs::File::create(&file_path).unwrap();
262        f.write_all(&png_bytes).unwrap();
263
264        let img = ImageAttachment::load(file_path.clone()).unwrap();
265        assert_eq!(img.mime_type, "image/png");
266        assert!(!img.base64_data.is_empty());
267        assert_eq!(img.size_bytes, png_bytes.len() as u64);
268        assert!(img.data_uri().starts_with("data:image/png;base64,"));
269    }
270
271    #[test]
272    fn test_load_jpeg() {
273        let dir = tempfile::tempdir().unwrap();
274        let file_path = dir.path().join("photo.jpg");
275        // Minimal JPEG (not valid, but extension test should work)
276        std::fs::write(&file_path, b"\xff\xd8\xff\xe0").unwrap();
277
278        let img = ImageAttachment::load(file_path).unwrap();
279        assert_eq!(img.mime_type, "image/jpeg");
280    }
281
282    #[test]
283    fn test_load_unsupported_extension() {
284        let dir = tempfile::tempdir().unwrap();
285        let file_path = dir.path().join("doc.pdf");
286        std::fs::write(&file_path, b"not a pdf").unwrap();
287
288        let err = ImageAttachment::load(file_path).unwrap_err();
289        match err {
290            ImageError::UnsupportedMime { .. } => {}
291            other => panic!("expected UnsupportedMime, got {:?}", other),
292        }
293    }
294
295    #[test]
296    fn test_load_nonexistent() {
297        let path = PathBuf::from("/nonexistent/image.png");
298        let err = ImageAttachment::load(path).unwrap_err();
299        match err {
300            ImageError::FileNotFound(_) => {}
301            other => panic!("expected FileNotFound, got {:?}", other),
302        }
303    }
304
305    #[test]
306    fn test_display_name() {
307        let img = ImageAttachment {
308            path: PathBuf::from("/tmp/screenshot.png"),
309            mime_type: "image/png".to_string(),
310            base64_data: "aaaa".to_string(),
311            size_bytes: 100,
312            dimensions: None,
313        };
314        assert_eq!(img.display_name(), "screenshot.png");
315        assert_eq!(img.size_display(), "100 B");
316    }
317
318    #[test]
319    fn test_size_display() {
320        let img = ImageAttachment {
321            path: PathBuf::from("/tmp/big.png"),
322            mime_type: "image/png".to_string(),
323            base64_data: "x".repeat(1024 * 1024),
324            size_bytes: 1_500_000,
325            dimensions: None,
326        };
327        assert!(img.size_display().contains("1.4 MB"));
328    }
329}