返回 CodeWhale
read_media.rs
根目录 / crates / engine / src / tools / read_media.rs
1 //! `read_media` tool — safe, first-class image reading and preprocessing.
2 //!
3 //! Provides bounded decoding, decompression-bomb protection, active route
4 //! vision-capability checks, crop region extraction, resolution detail modes,
5 //! and typed receipt metadata without leaking credentials.
6 //!
7 //! Delivery is byte-budget-first: after an optional crop and the detail-mode
8 //! edge cap, the image descends an encoding ladder (JPEG quality steps for
9 //! photo-like content, PNG for alpha-bearing or flat/line-art content, then
10 //! longest-edge halving) until the payload fits the budget. Results carry a
11 //! delivery note stating exactly how the image was delivered (untouched /
12 //! downsampled / crop / full) with zoom guidance, and the pre-compression
13 //! original is persisted in the content-addressed [`codewhale_runtime::media_originals`]
14 //! store so a later crop read can pull the full-resolution source. When no
15 //! ladder result fits the budget the tool fails closed — nothing is sent —
16 //! with the exact conversion command to retry with.
17
18 #[cfg(test)]
19 use image::ImageReader;
20 #[cfg(test)]
21 use std::io::Cursor;
22
23 use async_trait::async_trait;
24 use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
25 use codewhale_config::route::CapabilityState;
26 use image::codecs::jpeg::JpegEncoder;
27 use image::codecs::png::{CompressionType, FilterType as PngFilter, PngEncoder};
28 use image::imageops::FilterType;
29 use image::{DynamicImage, ExtendedColorType, GenericImageView, ImageEncoder};
30 use serde::{Deserialize, Serialize};
31 use serde_json::{Value, json};
32
33 use super::spec::{
34 ApprovalRequirement, RichToolResult, ToolCapability, ToolContext, ToolError, ToolResult,
35 ToolResultContentBlock, ToolSpec, optional_str, required_str, type_mismatch,
36 };
37
38 /// Maximum source image size before decoding (20 MiB).
39 pub const MAX_SOURCE_IMAGE_BYTES: usize = 20 * 1024 * 1024;
40
41 use crate::image_attach::decode_and_guard_image;
42
43 /// Maximum inline image payload admitted on the wire (5 MiB).
44 pub const MAX_WIRE_IMAGE_BYTES: usize = crate::image_attach::MAX_IMAGE_BYTES;
45
46 /// Delivery byte budget for a default read (`detail` `low`/`auto`), 256 KiB.
47 ///
48 /// Matches the reference budget in kimi-code's `READ_IMAGE_BYTE_BUDGET`: after
49 /// base64 inflation this is ~350 KB on the wire — far under the 5 MiB provider
50 /// ceiling — and it keeps routine reads from spending megabytes of context on
51 /// PNG screenshots when a JPEG ladder step fits. `high`/`original` detail and
52 /// crop (deliberate zoom) reads keep the full [`MAX_WIRE_IMAGE_BYTES`] budget.
53 pub const READ_IMAGE_BYTE_BUDGET: usize = 256 * 1024;
54
55 /// JPEG quality steps tried highest-first at each ladder rung (mirrors
56 /// kimi-code's `JPEG_QUALITY_STEPS`).
57 const JPEG_QUALITY_LADDER: [u8; 4] = [80, 60, 40, 20];
58
59 /// Longest-edge floor for ladder halving (px); below this the ladder fails
60 /// closed rather than delivering an unreadable thumbnail.
61 const MIN_DELIVERY_EDGE_PX: u32 = 256;
62
63 /// Flat/line-art images keep PNG rungs down to this longest edge before the
64 /// ladder falls back to JPEG (mirrors kimi-code's `PNG_RESCALE_FLOOR_PX`).
65 const PNG_EDGE_FLOOR_PX: u32 = 1000;
66
67 /// Opaque images whose colorfulness sigma (spread of the `r-g` and
68 /// `(r+g)/2-b` opponent channels, measured on a ≤128 px thumbnail) falls below
69 /// this threshold are treated as flat/line-art and stay PNG; above it the
70 /// image is photo-like and takes the JPEG ladder. Solid fills and line art
71 /// score ~0; ordinary photos score well above. Heuristic, deliberately simple.
72 const FLAT_COLORFULNESS_THRESHOLD: f64 = 12.0;
73
74 /// Resolution/detail preference for image processing.
75 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
76 #[serde(rename_all = "snake_case")]
77 pub enum DetailMode {
78 #[default]
79 Auto,
80 Low,
81 High,
82 Original,
83 }
84
85 impl DetailMode {
86 fn from_str_opt(s: Option<&str>) -> Result<Self, ToolError> {
87 match s {
88 None | Some("auto") => Ok(Self::Auto),
89 Some("low") => Ok(Self::Low),
90 Some("high") => Ok(Self::High),
91 Some("original") | Some("full") => Ok(Self::Original),
92 Some(other) => Err(ToolError::invalid_input(format!(
93 "invalid detail mode '{other}'; expected 'auto', 'low', 'high', or 'original'"
94 ))),
95 }
96 }
97
98 fn max_dimension(self) -> u32 {
99 match self {
100 Self::Low => 1024,
101 Self::Auto => 2048,
102 Self::High | Self::Original => 4096,
103 }
104 }
105
106 /// Delivery byte budget for a full (non-crop) read at this detail level.
107 /// Crop reads are the deliberate zoom action and always get the full wire
108 /// budget, matching kimi-code's `cropImageForModel` default.
109 fn byte_budget(self) -> usize {
110 match self {
111 Self::Low | Self::Auto => READ_IMAGE_BYTE_BUDGET,
112 Self::High | Self::Original => MAX_WIRE_IMAGE_BYTES,
113 }
114 }
115
116 fn as_str(self) -> &'static str {
117 match self {
118 Self::Auto => "auto",
119 Self::Low => "low",
120 Self::High => "high",
121 Self::Original => "original",
122 }
123 }
124 }
125
126 /// Optional bounding box for cropping an image.
127 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
128 pub struct CropRegion {
129 pub x: u32,
130 pub y: u32,
131 pub width: u32,
132 pub height: u32,
133 }
134
135 impl CropRegion {
136 fn parse_from_value(value: Option<&Value>) -> Result<Option<Self>, ToolError> {
137 let Some(val) = value else {
138 return Ok(None);
139 };
140 if val.is_null() {
141 return Ok(None);
142 }
143 let obj = val
144 .as_object()
145 .ok_or_else(|| type_mismatch("crop", val, "an object with x, y, width, and height"))?;
146
147 let extract_u32 = |field: &str| -> Result<u32, ToolError> {
148 let num_val = obj.get(field).ok_or_else(|| {
149 ToolError::invalid_input(format!("crop missing required field '{field}'"))
150 })?;
151 if let Some(n) = num_val.as_u64() {
152 u32::try_from(n).map_err(|_| {
153 ToolError::invalid_input(format!(
154 "crop field '{field}' is out of range for u32"
155 ))
156 })
157 } else if let Some(n) = num_val.as_i64() {
158 if n < 0 {
159 return Err(ToolError::invalid_input(format!(
160 "crop field '{field}' must be non-negative; got {n}"
161 )));
162 }
163 u32::try_from(n).map_err(|_| {
164 ToolError::invalid_input(format!(
165 "crop field '{field}' is out of range for u32"
166 ))
167 })
168 } else {
169 Err(type_mismatch(
170 &format!("crop.{field}"),
171 num_val,
172 "an integer",
173 ))
174 }
175 };
176
177 let x = extract_u32("x")?;
178 let y = extract_u32("y")?;
179 let width = extract_u32("width")?;
180 let height = extract_u32("height")?;
181
182 if width == 0 || height == 0 {
183 return Err(ToolError::invalid_input(
184 "crop width and height must be greater than 0",
185 ));
186 }
187
188 Ok(Some(Self {
189 x,
190 y,
191 width,
192 height,
193 }))
194 }
195 }
196
197 /// The first-class `read_media` tool.
198 pub struct ReadMediaTool;
199
200 impl Default for ReadMediaTool {
201 fn default() -> Self {
202 Self
203 }
204 }
205
206 #[async_trait]
207 impl ToolSpec for ReadMediaTool {
208 fn name(&self) -> &'static str {
209 "read_media"
210 }
211
212 fn description(&self) -> &'static str {
213 "Read an image file (PNG, JPEG, GIF, WebP) into context for multimodal/vision inspection, with optional crop region and detail level. Safe, bounded decode with pixel and byte guards."
214 }
215
216 fn input_schema(&self) -> Value {
217 json!({
218 "type": "object",
219 "properties": {
220 "path": {
221 "type": "string",
222 "description": "Path to the image file (relative to workspace or absolute). PNG, JPEG, GIF, and WebP are supported."
223 },
224 "crop": {
225 "type": "object",
226 "description": "Optional bounding box to crop [x, y, width, height] in pixel coordinates.",
227 "properties": {
228 "x": {
229 "type": "integer",
230 "description": "Left coordinate (X) of the crop region in pixels (0-based)."
231 },
232 "y": {
233 "type": "integer",
234 "description": "Top coordinate (Y) of the crop region in pixels (0-based)."
235 },
236 "width": {
237 "type": "integer",
238 "description": "Width of the crop region in pixels (must be > 0)."
239 },
240 "height": {
241 "type": "integer",
242 "description": "Height of the crop region in pixels (must be > 0)."
243 }
244 },
245 "required": ["x", "y", "width", "height"]
246 },
247 "detail": {
248 "type": "string",
249 "enum": ["auto", "low", "high", "original"],
250 "description": "Resolution/detail preference. 'auto' (default) downscales large images to max 2048px; 'low' to max 1024px; 'high' / 'original' preserves resolution up to max 4096px within the 5 MiB payload limit."
251 }
252 },
253 "required": ["path"]
254 })
255 }
256
257 fn capabilities(&self) -> Vec<ToolCapability> {
258 vec![ToolCapability::ReadOnly, ToolCapability::Sandboxable]
259 }
260
261 fn approval_requirement(&self) -> ApprovalRequirement {
262 ApprovalRequirement::Auto
263 }
264
265 fn supports_parallel(&self) -> bool {
266 true
267 }
268
269 fn defer_loading(&self) -> bool {
270 true
271 }
272
273 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
274 self.execute_rich(input, context)
275 .await
276 .map(RichToolResult::into_result)
277 }
278
279 async fn execute_rich(
280 &self,
281 input: Value,
282 context: &ToolContext,
283 ) -> Result<RichToolResult, ToolError> {
284 execute_read_media(input, context).await
285 }
286 }
287
288 /// Execute the `read_media` tool logic.
289 pub async fn execute_read_media(
290 input: Value,
291 context: &ToolContext,
292 ) -> Result<RichToolResult, ToolError> {
293 // 0. Check cancellation early (before any path resolution, capability checks, or I/O)
294 if context
295 .cancel_token
296 .as_ref()
297 .is_some_and(tokio_util::sync::CancellationToken::is_cancelled)
298 {
299 return Err(ToolError::cancelled("Operation aborted"));
300 }
301
302 let path_str = required_str(&input, "path")?;
303 let detail_str = optional_str(&input, "detail")?;
304 let detail_mode = DetailMode::from_str_opt(detail_str)?;
305 let crop_region = CropRegion::parse_from_value(input.get("crop"))?;
306
307 // 1. Check active route vision capability
308 if context.route_capabilities.image_input == CapabilityState::Unsupported {
309 return Err(ToolError::execution_failed(
310 "read_media: the active model route does not support image input. Switch to a route marked vision-capable with /model, or configure the route's image_input capability, then try again.",
311 ));
312 }
313
314 // 2. Resolve path and protect credentials (including symlink/canonicalization escapes)
315 let plan = crate::tools::file::resolve_read_open_plan_for_media(context, path_str).await?;
316 let file_path = plan.file_path.clone();
317
318 if context
319 .cancel_token
320 .as_ref()
321 .is_some_and(tokio_util::sync::CancellationToken::is_cancelled)
322 {
323 return Err(ToolError::cancelled("Operation aborted"));
324 }
325
326 let originals_dir = context.runtime.media_originals_dir.clone();
327 let processed = tokio::task::spawn_blocking(move || {
328 process_media_plan(&plan, crop_region, detail_mode, originals_dir)
329 })
330 .await
331 .map_err(|join_err| {
332 ToolError::execution_failed(format!("read_media task failed: {join_err}"))
333 })??;
334
335 // Check cancellation after await
336 if context
337 .cancel_token
338 .as_ref()
339 .is_some_and(tokio_util::sync::CancellationToken::is_cancelled)
340 {
341 return Err(ToolError::cancelled("Operation aborted"));
342 }
343
344 // 10. Construct receipt and typed metadata without credentials
345 context.note_file_read(&file_path);
346
347 let crop_summary = if let Some(crop) = crop_region {
348 format!(
349 "region [x: {}, y: {}, w: {}, h: {}]",
350 crop.x, crop.y, crop.width, crop.height
351 )
352 } else {
353 "none".to_string()
354 };
355
356 let delivery_note = build_delivery_note(&processed, crop_region);
357
358 let mut content_text = format!(
359 "Read media file: {path_str} [{delivered_mime}]\n\
360 Original dimensions: {orig_width}x{orig_height} ({mime_type})\n\
361 Processed dimensions: {final_width}x{final_height}\n\
362 Crop: {crop_summary}\n\
363 Detail: {}\n\
364 Delivery: {delivery_note}\n\
365 Size: {} (source) -> {} (wire payload)",
366 detail_mode.as_str(),
367 human_bytes(processed.source_bytes),
368 human_bytes(processed.encoded_bytes),
369 delivered_mime = processed.delivered_mime,
370 orig_width = processed.orig_width,
371 orig_height = processed.orig_height,
372 mime_type = processed.source_mime,
373 final_width = processed.final_width,
374 final_height = processed.final_height,
375 );
376 if context.route_capabilities.image_input == CapabilityState::Unknown {
377 content_text.push_str(
378 "\nRoute image support is unverified; if the model cannot see this image, use image_ocr.",
379 );
380 }
381
382 let metadata_json = json!({
383 "path": path_str,
384 "mime_type": processed.delivered_mime,
385 "original_width": processed.orig_width,
386 "original_height": processed.orig_height,
387 "original_mime_type": processed.source_mime,
388 "width": processed.final_width,
389 "height": processed.final_height,
390 "cropped": processed.crop_applied,
391 "crop": crop_region.map(|c| json!({
392 "x": c.x,
393 "y": c.y,
394 "width": c.width,
395 "height": c.height
396 })),
397 "detail": detail_mode.as_str(),
398 "delivery": processed.delivery.as_str(),
399 "original_path": processed
400 .original_path
401 .as_ref()
402 .map(|p| p.display().to_string()),
403 "source_bytes": processed.source_bytes,
404 "encoded_bytes": processed.encoded_bytes
405 });
406
407 Ok(RichToolResult::with_content_blocks(
408 ToolResult::success(content_text).with_metadata(metadata_json),
409 vec![ToolResultContentBlock::Image {
410 mime_type: processed.delivered_mime.to_string(),
411 data: processed.base64_payload,
412 }],
413 ))
414 }
415
416 /// The delivery-mode sentence of the result note: exactly how the image was
417 /// delivered, plus zoom/offset guidance. Compression is never silent.
418 fn build_delivery_note(processed: &ProcessedMedia, crop_region: Option<CropRegion>) -> String {
419 let delivered_size = human_bytes(processed.encoded_bytes);
420 match processed.delivery {
421 DeliveryMode::Untouched => format!(
422 "untouched — delivered at native resolution {}x{} ({}, {}); no downsampling applied.",
423 processed.final_width, processed.final_height, processed.delivered_mime, delivered_size
424 ),
425 DeliveryMode::Full => format!(
426 "full — shown at native resolution {}x{} ({}, {}); no downscaling applied.",
427 processed.final_width, processed.final_height, processed.delivered_mime, delivered_size
428 ),
429 DeliveryMode::Downsampled { resolution_lost } => {
430 let how = if resolution_lost {
431 format!(
432 "downsampled to {}x{}",
433 processed.final_width, processed.final_height
434 )
435 } else {
436 format!(
437 "re-encoded at native resolution {}x{}",
438 processed.final_width, processed.final_height
439 )
440 };
441 let mut note = format!(
442 "{how} ({}, {delivered_size}) to fit model limits; fine detail may be lost. \
443 To inspect fine detail, call read_media again with the crop parameter \
444 (original-image pixel coordinates) to view a region at full fidelity.",
445 processed.delivered_mime
446 );
447 if let Some(original_path) = &processed.original_path {
448 note.push_str(&format!(
449 " The uncompressed original is preserved at \"{}\".",
450 original_path.display()
451 ));
452 }
453 note
454 }
455 DeliveryMode::Crop { resized } => {
456 let region = crop_region.expect("crop delivery implies a crop region");
457 format!(
458 "crop (x={}, y={}, width={}, height={}) of the original image{} ({}, {}). \
459 To output coordinates in original-image pixels, locate them within this crop \
460 and add the region offset (x={}, y={}).",
461 region.x,
462 region.y,
463 region.width,
464 region.height,
465 if resized {
466 format!(
467 ", downsampled to {}x{}",
468 processed.final_width, processed.final_height
469 )
470 } else {
471 " at native resolution".to_string()
472 },
473 processed.delivered_mime,
474 delivered_size,
475 region.x,
476 region.y
477 )
478 }
479 }
480 }
481
482 /// How the delivered payload relates to the source image.
483 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
484 enum DeliveryMode {
485 /// Native resolution, first ladder step, `detail` `low`/`auto`.
486 Untouched,
487 /// Native resolution, first ladder step, `detail` `high`/`original`.
488 Full,
489 /// Resolution and/or encoding quality was reduced to fit the budget.
490 Downsampled { resolution_lost: bool },
491 /// A crop region was delivered; `resized` when the crop itself had to
492 /// shrink to fit the budget.
493 Crop { resized: bool },
494 }
495
496 impl DeliveryMode {
497 fn as_str(self) -> &'static str {
498 match self {
499 Self::Untouched => "untouched",
500 Self::Full => "full",
501 Self::Downsampled { .. } => "downsampled",
502 Self::Crop { .. } => "crop",
503 }
504 }
505 }
506
507 struct ProcessedMedia {
508 base64_payload: String,
509 delivered_mime: &'static str,
510 orig_width: u32,
511 orig_height: u32,
512 source_mime: &'static str,
513 final_width: u32,
514 final_height: u32,
515 crop_applied: bool,
516 delivery: DeliveryMode,
517 source_bytes: usize,
518 encoded_bytes: usize,
519 original_path: Option<std::path::PathBuf>,
520 }
521
522 fn process_media_plan(
523 plan: &crate::tools::file::ReadOpenPlan,
524 crop_region: Option<CropRegion>,
525 detail_mode: DetailMode,
526 originals_dir: Option<std::path::PathBuf>,
527 ) -> Result<ProcessedMedia, ToolError> {
528 use std::io::Read as _;
529
530 let file_path = plan.file_path.as_path();
531 let Some((file, _fd_path)) =
532 crate::tools::file::open_verified_read_handle(plan, true, true, false)?
533 else {
534 return Err(ToolError::execution_failed(format!(
535 "read_media: image file does not exist: {}",
536 file_path.display()
537 )));
538 };
539
540 let meta = file.metadata().map_err(|e| {
541 ToolError::execution_failed(format!(
542 "read_media: failed to inspect {}: {e}",
543 file_path.display()
544 ))
545 })?;
546
547 if meta.is_dir() {
548 return Err(ToolError::execution_failed(format!(
549 "read_media: path is a directory, not an image file: {}",
550 file_path.display()
551 )));
552 }
553
554 let file_len = meta.len();
555 if file_len == 0 {
556 return Err(ToolError::execution_failed(format!(
557 "read_media: image file is empty (0 bytes): {}",
558 file_path.display()
559 )));
560 }
561
562 if file_len > MAX_SOURCE_IMAGE_BYTES as u64 {
563 return Err(ToolError::execution_failed(format!(
564 "read_media: image file size ({}) exceeds the maximum source limit of {}. Downscale or crop the file first.",
565 human_bytes(file_len as usize),
566 human_bytes(MAX_SOURCE_IMAGE_BYTES)
567 )));
568 }
569
570 let mut raw_bytes = Vec::new();
571 file.take((MAX_SOURCE_IMAGE_BYTES + 1) as u64)
572 .read_to_end(&mut raw_bytes)
573 .map_err(|e| {
574 ToolError::execution_failed(format!(
575 "read_media: failed to read {}: {e}",
576 file_path.display()
577 ))
578 })?;
579
580 if raw_bytes.is_empty() {
581 return Err(ToolError::execution_failed(format!(
582 "read_media: image file is empty (0 bytes): {}",
583 file_path.display()
584 )));
585 }
586
587 if raw_bytes.len() > MAX_SOURCE_IMAGE_BYTES {
588 return Err(ToolError::execution_failed(format!(
589 "read_media: image file size ({}) exceeds the maximum source limit of {}. Downscale or crop the file first.",
590 human_bytes(raw_bytes.len()),
591 human_bytes(MAX_SOURCE_IMAGE_BYTES)
592 )));
593 }
594
595 // 5. Sniff format and guard against non-images or rejected formats
596 let sniffed_mime = crate::image_attach::sniff_media_type(&raw_bytes);
597 let mime_type = match sniffed_mime {
598 Some(m) => m,
599 None => {
600 if let Some(rejected) = crate::image_attach::detect_rejected_format(&raw_bytes) {
601 return Err(ToolError::execution_failed(format!(
602 "read_media: {rejected} format is not directly supported by vision models. Convert it to PNG, JPEG, GIF, or WebP first."
603 )));
604 }
605 return Err(ToolError::execution_failed(format!(
606 "read_media: file is not a recognized or supported image format (expected PNG, JPEG, GIF, or WebP): {}",
607 file_path.display()
608 )));
609 }
610 };
611
612 // 6. Bounded decoding with decompression-bomb guards
613 let (processed_image, orig_width, orig_height) = decode_and_guard_image(&raw_bytes)
614 .map_err(|error| ToolError::execution_failed(format!("read_media: {error}")))?;
615
616 // 7. Apply crop if requested
617 let (cropped_image, crop_applied) = if let Some(crop) = crop_region {
618 let crop_right = crop.x.checked_add(crop.width);
619 let crop_bottom = crop.y.checked_add(crop.height);
620 if crop_right.is_none_or(|right| right > orig_width)
621 || crop_bottom.is_none_or(|bottom| bottom > orig_height)
622 {
623 return Err(ToolError::invalid_input(format!(
624 "read_media: crop region [x: {}, y: {}, width: {}, height: {}] is out of bounds for image dimensions {}x{}",
625 crop.x, crop.y, crop.width, crop.height, orig_width, orig_height
626 )));
627 }
628 let cropped =
629 image::imageops::crop_imm(&processed_image, crop.x, crop.y, crop.width, crop.height)
630 .to_image();
631 (DynamicImage::ImageRgba8(cropped), true)
632 } else {
633 (processed_image, false)
634 };
635
636 // 8. Apply detail resolution resizing
637 let (current_w, current_h) = cropped_image.dimensions();
638 let max_target = detail_mode.max_dimension();
639 let detail_resized = current_w > max_target || current_h > max_target;
640 let fitted_image = if detail_resized {
641 cropped_image.resize(max_target, max_target, FilterType::Lanczos3)
642 } else {
643 cropped_image
644 };
645
646 // 9. Byte-budget-first encoding ladder: classify the content, then descend
647 // quality/edge rungs until the payload fits the delivery budget. Fails
648 // closed (nothing sent) with a conversion recipe when nothing fits.
649 let policy = classify_image(&fitted_image);
650 let budget = if crop_applied {
651 MAX_WIRE_IMAGE_BYTES
652 } else {
653 detail_mode.byte_budget()
654 };
655 let outcome = encode_within_budget(&fitted_image, policy, budget, file_path)?;
656
657 // 10. Persist the pre-compression original whenever the delivered copy is
658 // degraded, so a later crop read can pull the full-resolution source.
659 // Best effort: persistence never blocks delivery.
660 let degraded = detail_resized || outcome.resized || outcome.quality_reduced;
661 let original_path = if degraded && !crop_applied {
662 originals_dir.and_then(|dir| {
663 codewhale_runtime::media_originals::persist_original_image(&raw_bytes, mime_type, &dir)
664 })
665 } else {
666 None
667 };
668
669 let delivery = if crop_applied {
670 DeliveryMode::Crop { resized: degraded }
671 } else if degraded {
672 DeliveryMode::Downsampled {
673 resolution_lost: detail_resized || outcome.resized,
674 }
675 } else {
676 match detail_mode {
677 DetailMode::High | DetailMode::Original => DeliveryMode::Full,
678 DetailMode::Low | DetailMode::Auto => DeliveryMode::Untouched,
679 }
680 };
681
682 let source_bytes = raw_bytes.len();
683 let encoded_bytes = outcome.bytes.len();
684 let base64_payload = BASE64.encode(&outcome.bytes);
685
686 Ok(ProcessedMedia {
687 base64_payload,
688 delivered_mime: outcome.mime,
689 orig_width,
690 orig_height,
691 source_mime: mime_type,
692 final_width: outcome.width,
693 final_height: outcome.height,
694 crop_applied,
695 delivery,
696 source_bytes,
697 encoded_bytes,
698 original_path,
699 })
700 }
701
702 /// How the encoding ladder should treat an image's content.
703 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
704 enum EncodePolicy {
705 /// Meaningful alpha present: PNG only. JPEG would silently destroy the
706 /// alpha channel, so the ladder fails closed rather than falling back.
707 RequireAlphaPng,
708 /// Opaque and flat (solid fills, line art, UI screenshots): PNG rungs
709 /// first — flat content compresses well losslessly and JPEG rings on hard
710 /// edges — then the JPEG ladder below the PNG edge floor.
711 PreferPng,
712 /// Opaque and photo-like: the JPEG quality ladder immediately. Photos as
713 /// PNG waste an order of magnitude of context bytes.
714 PreferJpeg,
715 }
716
717 impl EncodePolicy {
718 fn prefers_png(self) -> bool {
719 !matches!(self, Self::PreferJpeg)
720 }
721 }
722
723 /// Content classification for the ladder: alpha first (correctness), then a
724 /// colorfulness heuristic on a small thumbnail (cost).
725 fn classify_image(image: &DynamicImage) -> EncodePolicy {
726 if has_meaningful_alpha(image) {
727 return EncodePolicy::RequireAlphaPng;
728 }
729 if colorfulness_sigma(image) < FLAT_COLORFULNESS_THRESHOLD {
730 EncodePolicy::PreferPng
731 } else {
732 EncodePolicy::PreferJpeg
733 }
734 }
735
736 /// Whether any pixel is actually transparent — not merely whether the decoded
737 /// layout has an alpha channel (an opaque RGBA PNG decodes to `Rgba8` too).
738 fn has_meaningful_alpha(image: &DynamicImage) -> bool {
739 match image {
740 DynamicImage::ImageRgba8(buf) => buf.pixels().any(|p| p.0[3] != u8::MAX),
741 DynamicImage::ImageLumaA8(buf) => buf.pixels().any(|p| p.0[1] != u8::MAX),
742 DynamicImage::ImageRgba16(buf) => buf.pixels().any(|p| p.0[3] != u16::MAX),
743 DynamicImage::ImageLumaA16(buf) => buf.pixels().any(|p| p.0[1] != u16::MAX),
744 _ => false,
745 }
746 }
747
748 /// Spread of the opponent color channels (Hasler–Süsstrunk sigma terms only —
749 /// the mean terms would inflate saturated flat fills), measured on a ≤128 px
750 /// thumbnail for speed. Solid fills and line art score ~0.
751 fn colorfulness_sigma(image: &DynamicImage) -> f64 {
752 let thumb = image.thumbnail(128, 128);
753 let rgb = thumb.to_rgb8();
754 let n = (rgb.len() / 3) as f64;
755 if n == 0.0 {
756 return 0.0;
757 }
758 let (mut sum_rg, mut sum_yb, mut sum_rg2, mut sum_yb2) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
759 // An `Rgb<u8>` buffer is exactly 3 bytes per pixel, so the remainder is
760 // always empty; `as_chunks` makes the pixel stride a compile-time fact.
761 let (pixels, remainder) = rgb.as_raw().as_chunks::<3>();
762 debug_assert!(
763 remainder.is_empty(),
764 "RGB8 buffer length must be a multiple of 3"
765 );
766 for &[r, g, b] in pixels {
767 let (r, g, b) = (f64::from(r), f64::from(g), f64::from(b));
768 let rg = r - g;
769 let yb = (r + g) / 2.0 - b;
770 sum_rg += rg;
771 sum_yb += yb;
772 sum_rg2 += rg * rg;
773 sum_yb2 += yb * yb;
774 }
775 let var_rg = (sum_rg2 / n - (sum_rg / n).powi(2)).max(0.0);
776 let var_yb = (sum_yb2 / n - (sum_yb / n).powi(2)).max(0.0);
777 (var_rg + var_yb).sqrt()
778 }
779
780 /// One encoded ladder candidate.
781 struct EncodedImage {
782 bytes: Vec<u8>,
783 mime: &'static str,
784 width: u32,
785 height: u32,
786 }
787
788 /// The ladder's winning candidate plus how it got there.
789 #[derive(Debug)]
790 struct LadderOutcome {
791 bytes: Vec<u8>,
792 mime: &'static str,
793 width: u32,
794 height: u32,
795 /// The candidate's dimensions differ from the ladder's input image.
796 resized: bool,
797 /// A JPEG quality step below the ladder's first (80) was needed.
798 quality_reduced: bool,
799 }
800
801 fn encode_png_best(image: &DynamicImage) -> Result<EncodedImage, ToolError> {
802 let (width, height) = image.dimensions();
803 let mut bytes: Vec<u8> = Vec::new();
804 let encoder =
805 PngEncoder::new_with_quality(&mut bytes, CompressionType::Best, PngFilter::Adaptive);
806 if image.color().has_alpha() {
807 let rgba = image.to_rgba8();
808 encoder
809 .write_image(rgba.as_raw(), width, height, ExtendedColorType::Rgba8)
810 .map_err(|e| {
811 ToolError::execution_failed(format!("read_media: failed to encode PNG: {e}"))
812 })?;
813 } else {
814 let rgb = image.to_rgb8();
815 encoder
816 .write_image(rgb.as_raw(), width, height, ExtendedColorType::Rgb8)
817 .map_err(|e| {
818 ToolError::execution_failed(format!("read_media: failed to encode PNG: {e}"))
819 })?;
820 }
821 Ok(EncodedImage {
822 bytes,
823 mime: "image/png",
824 width,
825 height,
826 })
827 }
828
829 fn encode_jpeg(image: &DynamicImage, quality: u8) -> Result<EncodedImage, ToolError> {
830 let (width, height) = image.dimensions();
831 // Only reached for images without meaningful alpha, so dropping the
832 // channel changes nothing visible.
833 let rgb = image.to_rgb8();
834 let mut bytes: Vec<u8> = Vec::new();
835 JpegEncoder::new_with_quality(&mut bytes, quality)
836 .write_image(rgb.as_raw(), width, height, ExtendedColorType::Rgb8)
837 .map_err(|e| {
838 ToolError::execution_failed(format!("read_media: failed to encode JPEG: {e}"))
839 })?;
840 Ok(EncodedImage {
841 bytes,
842 mime: "image/jpeg",
843 width,
844 height,
845 })
846 }
847
848 /// Half-size Lanczos copy, or `None` once the longest edge is at the floor.
849 fn halved(image: &DynamicImage) -> Option<DynamicImage> {
850 let (w, h) = image.dimensions();
851 if w.max(h) <= MIN_DELIVERY_EDGE_PX {
852 return None;
853 }
854 Some(image.resize((w / 2).max(1), (h / 2).max(1), FilterType::Lanczos3))
855 }
856
857 fn track_smallest(smallest: &mut Option<EncodedImage>, candidate: EncodedImage) {
858 if smallest
859 .as_ref()
860 .is_none_or(|s| candidate.bytes.len() < s.bytes.len())
861 {
862 *smallest = Some(candidate);
863 }
864 }
865
866 /// Descend the encoding ladder until a rung fits `budget`.
867 ///
868 /// Rung order (mirrors kimi-code's `encodeWithinBudget`): PNG-preferring
869 /// images try best-compression PNG at the current size, then halved PNG rungs
870 /// down to [`PNG_EDGE_FLOOR_PX`], then the JPEG quality ladder; photo-like
871 /// images start at the JPEG ladder; alpha-bearing images only ever see PNG
872 /// rungs. JPEG rungs repeat the quality ladder at each halved edge down to
873 /// [`MIN_DELIVERY_EDGE_PX`]. The first fitting rung wins (highest fidelity
874 /// within budget). When nothing fits, fails closed — nothing is sent — with
875 /// the exact conversion command to retry with.
876 fn encode_within_budget(
877 image: &DynamicImage,
878 policy: EncodePolicy,
879 budget: usize,
880 path: &std::path::Path,
881 ) -> Result<LadderOutcome, ToolError> {
882 let (start_w, start_h) = image.dimensions();
883 let mut smallest: Option<EncodedImage> = None;
884 let mut candidate = image.clone();
885
886 if policy.prefers_png() {
887 let png_floor = match policy {
888 EncodePolicy::RequireAlphaPng => MIN_DELIVERY_EDGE_PX,
889 _ => PNG_EDGE_FLOOR_PX,
890 };
891 loop {
892 let encoded = encode_png_best(&candidate)?;
893 if encoded.bytes.len() <= budget {
894 let resized = encoded.width != start_w || encoded.height != start_h;
895 return Ok(LadderOutcome {
896 bytes: encoded.bytes,
897 mime: encoded.mime,
898 width: encoded.width,
899 height: encoded.height,
900 resized,
901 quality_reduced: false,
902 });
903 }
904 let longest = encoded.width.max(encoded.height);
905 track_smallest(&mut smallest, encoded);
906 if longest <= png_floor {
907 break;
908 }
909 let Some(next) = halved(&candidate) else {
910 break;
911 };
912 candidate = next;
913 }
914 if policy == EncodePolicy::RequireAlphaPng {
915 return Err(over_budget_error(path, budget, smallest));
916 }
917 }
918
919 loop {
920 for (step, quality) in JPEG_QUALITY_LADDER.iter().enumerate() {
921 let encoded = encode_jpeg(&candidate, *quality)?;
922 if encoded.bytes.len() <= budget {
923 let resized = encoded.width != start_w || encoded.height != start_h;
924 return Ok(LadderOutcome {
925 bytes: encoded.bytes,
926 mime: encoded.mime,
927 width: encoded.width,
928 height: encoded.height,
929 resized,
930 quality_reduced: step > 0,
931 });
932 }
933 track_smallest(&mut smallest, encoded);
934 }
935 let Some(next) = halved(&candidate) else {
936 break;
937 };
938 candidate = next;
939 }
940 Err(over_budget_error(path, budget, smallest))
941 }
942
943 /// Fit `image` to `max_edge` and encode it within `budget` on the same ladder
944 /// `read_media` delivers with. Attach-time ingest (`image_attach`) shares it,
945 /// so a pasted Retina screenshot is normalized exactly like a tool read.
946 pub fn fit_and_encode(
947 image: &DynamicImage,
948 max_edge: u32,
949 budget: usize,
950 path: &std::path::Path,
951 ) -> Result<(Vec<u8>, &'static str), ToolError> {
952 let (width, height) = image.dimensions();
953 let fitted = if width.max(height) > max_edge {
954 image.resize(max_edge, max_edge, FilterType::Lanczos3)
955 } else {
956 image.clone()
957 };
958 let outcome = encode_within_budget(&fitted, classify_image(&fitted), budget, path)?;
959 Ok((outcome.bytes, outcome.mime))
960 }
961
962 /// Fail-closed error naming the exact conversion recipe to retry with.
963 fn over_budget_error(
964 path: &std::path::Path,
965 budget: usize,
966 smallest: Option<EncodedImage>,
967 ) -> ToolError {
968 let smallest_desc = match &smallest {
969 Some(s) => format!(
970 "smallest deliverable: {} at {}x{}",
971 human_bytes(s.bytes.len()),
972 s.width,
973 s.height
974 ),
975 None => "no encodable result".to_string(),
976 };
977 ToolError::execution_failed(format!(
978 "read_media: {path} could not be compressed under the {budget} delivery budget ({smallest_desc}). \
979 Nothing was sent to the model; do not retry the same file unchanged. \
980 Create a smaller copy and read that instead: \
981 `sips -Z 1024 \"{path}\" --out /tmp/codewhale-smaller.png` (macOS) or \
982 `magick \"{path}\" -resize 1024x1024 /tmp/codewhale-smaller.png` (ImageMagick); \
983 for a photo-like image, JPEG output (`--out /tmp/codewhale-smaller.jpg` / `-quality 70`) \
984 compresses further. Then call read_media on the smaller copy.",
985 path = path.display(),
986 budget = human_bytes(budget),
987 ))
988 }
989
990 fn human_bytes(bytes: usize) -> String {
991 if bytes >= 1024 * 1024 {
992 format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
993 } else if bytes >= 1024 {
994 format!("{:.1} KB", bytes as f64 / 1024.0)
995 } else {
996 format!("{bytes} bytes")
997 }
998 }
999
1000 #[cfg(test)]
1001 mod tests {
1002 use super::*;
1003 use codewhale_models::Role;
1004 use image::ImageFormat;
1005 use tempfile::tempdir;
1006
1007 fn create_test_png(width: u32, height: u32, color: [u8; 4]) -> Vec<u8> {
1008 let img = image::RgbaImage::from_pixel(width, height, image::Rgba(color));
1009 let mut cursor = Cursor::new(Vec::new());
1010 img.write_to(&mut cursor, ImageFormat::Png).unwrap();
1011 cursor.into_inner()
1012 }
1013
1014 fn create_test_jpeg(width: u32, height: u32) -> Vec<u8> {
1015 let img = image::RgbImage::from_pixel(width, height, image::Rgb([120, 200, 50]));
1016 let mut cursor = Cursor::new(Vec::new());
1017 img.write_to(&mut cursor, ImageFormat::Jpeg).unwrap();
1018 cursor.into_inner()
1019 }
1020
1021 #[tokio::test]
1022 async fn read_media_spec_metadata_and_capabilities() {
1023 let tool = ReadMediaTool;
1024 assert_eq!(tool.name(), "read_media");
1025 assert!(tool.capabilities().contains(&ToolCapability::ReadOnly));
1026 assert!(tool.capabilities().contains(&ToolCapability::Sandboxable));
1027 assert!(tool.supports_parallel());
1028 assert!(tool.defer_loading());
1029 assert_eq!(tool.approval_requirement(), ApprovalRequirement::Auto);
1030 }
1031
1032 #[tokio::test]
1033 async fn read_media_success_png_roundtrip() {
1034 let dir = tempdir().unwrap();
1035 let img_path = dir.path().join("test.png");
1036 let png_data = create_test_png(100, 50, [255, 0, 0, 255]);
1037 std::fs::write(&img_path, &png_data).unwrap();
1038
1039 let mut ctx = ToolContext::new(dir.path());
1040 ctx.route_capabilities.image_input = CapabilityState::Supported;
1041
1042 let tool = ReadMediaTool;
1043 let input = json!({
1044 "path": "test.png",
1045 "detail": "auto"
1046 });
1047
1048 let rich = tool.execute_rich(input, &ctx).await.unwrap();
1049 assert!(rich.success);
1050 assert_eq!(rich.content_blocks.len(), 1);
1051 let ToolResultContentBlock::Image { mime_type, data } = &rich.content_blocks[0];
1052 assert_eq!(mime_type, "image/png");
1053 assert!(!data.is_empty());
1054
1055 let meta = rich.metadata.as_ref().unwrap();
1056 assert_eq!(meta["path"], "test.png");
1057 assert_eq!(meta["original_width"], 100);
1058 assert_eq!(meta["original_height"], 50);
1059 assert_eq!(meta["width"], 100);
1060 assert_eq!(meta["height"], 50);
1061 assert_eq!(meta["cropped"], false);
1062 assert_eq!(meta["detail"], "auto");
1063 }
1064
1065 #[tokio::test]
1066 async fn read_media_success_jpeg_decoded_and_reencoded_to_png() {
1067 let dir = tempdir().unwrap();
1068 let img_path = dir.path().join("photo.jpg");
1069 let jpeg_data = create_test_jpeg(80, 60);
1070 std::fs::write(&img_path, &jpeg_data).unwrap();
1071
1072 let mut ctx = ToolContext::new(dir.path());
1073 ctx.route_capabilities.image_input = CapabilityState::Supported;
1074
1075 let tool = ReadMediaTool;
1076 let input = json!({
1077 "path": "photo.jpg",
1078 "detail": "low"
1079 });
1080
1081 let rich = tool.execute_rich(input, &ctx).await.unwrap();
1082 assert!(rich.success);
1083 let ToolResultContentBlock::Image { mime_type, data } = &rich.content_blocks[0];
1084 assert_eq!(mime_type, "image/png");
1085 assert!(!data.is_empty());
1086
1087 let meta = rich.metadata.as_ref().unwrap();
1088 assert_eq!(meta["original_width"], 80);
1089 assert_eq!(meta["original_height"], 60);
1090 assert_eq!(meta["original_mime_type"], "image/jpeg");
1091 }
1092
1093 #[tokio::test]
1094 async fn read_media_crop_region_bounds_and_execution() {
1095 let dir = tempdir().unwrap();
1096 let img_path = dir.path().join("grid.png");
1097 let png_data = create_test_png(200, 100, [0, 255, 0, 255]);
1098 std::fs::write(&img_path, &png_data).unwrap();
1099
1100 let mut ctx = ToolContext::new(dir.path());
1101 ctx.route_capabilities.image_input = CapabilityState::Supported;
1102
1103 let tool = ReadMediaTool;
1104
1105 // 1. Valid crop
1106 let valid_input = json!({
1107 "path": "grid.png",
1108 "crop": {
1109 "x": 10,
1110 "y": 20,
1111 "width": 50,
1112 "height": 40
1113 }
1114 });
1115 let rich = tool.execute_rich(valid_input, &ctx).await.unwrap();
1116 assert!(rich.success);
1117 let meta = rich.metadata.as_ref().unwrap();
1118 assert_eq!(meta["cropped"], true);
1119 assert_eq!(meta["width"], 50);
1120 assert_eq!(meta["height"], 40);
1121
1122 // 2. Out-of-bounds crop
1123 let oob_input = json!({
1124 "path": "grid.png",
1125 "crop": {
1126 "x": 180,
1127 "y": 20,
1128 "width": 50,
1129 "height": 40
1130 }
1131 });
1132 let err = tool.execute_rich(oob_input, &ctx).await.unwrap_err();
1133 assert!(err.to_string().contains("out of bounds"));
1134
1135 // 3. Zero-dimension crop
1136 let zero_input = json!({
1137 "path": "grid.png",
1138 "crop": {
1139 "x": 10,
1140 "y": 10,
1141 "width": 0,
1142 "height": 10
1143 }
1144 });
1145 let err = tool.execute_rich(zero_input, &ctx).await.unwrap_err();
1146 assert!(err.to_string().contains("greater than 0"));
1147
1148 // Adversarial coordinates must be rejected rather than wrapping in
1149 // release builds or panicking in debug builds.
1150 for overflow_input in [
1151 json!({
1152 "path": "grid.png",
1153 "crop": {
1154 "x": u32::MAX,
1155 "y": 0,
1156 "width": 2,
1157 "height": 1
1158 }
1159 }),
1160 json!({
1161 "path": "grid.png",
1162 "crop": {
1163 "x": 0,
1164 "y": u32::MAX,
1165 "width": 1,
1166 "height": 2
1167 }
1168 }),
1169 ] {
1170 let err = tool.execute_rich(overflow_input, &ctx).await.unwrap_err();
1171 assert!(err.to_string().contains("out of bounds"), "{err}");
1172 }
1173 }
1174
1175 #[tokio::test]
1176 async fn read_media_detail_modes_and_resizing() {
1177 let dir = tempdir().unwrap();
1178 let img_path = dir.path().join("large.png");
1179 let png_data = create_test_png(3000, 1500, [0, 0, 255, 255]);
1180 std::fs::write(&img_path, &png_data).unwrap();
1181
1182 let mut ctx = ToolContext::new(dir.path());
1183 ctx.route_capabilities.image_input = CapabilityState::Supported;
1184 let tool = ReadMediaTool;
1185
1186 // Low detail -> max 1024
1187 let low_input = json!({ "path": "large.png", "detail": "low" });
1188 let rich_low = tool.execute_rich(low_input, &ctx).await.unwrap();
1189 let meta_low = rich_low.metadata.as_ref().unwrap();
1190 assert_eq!(meta_low["width"], 1024);
1191 assert_eq!(meta_low["height"], 512);
1192
1193 // Auto detail -> max 2048
1194 let auto_input = json!({ "path": "large.png", "detail": "auto" });
1195 let rich_auto = tool.execute_rich(auto_input, &ctx).await.unwrap();
1196 let meta_auto = rich_auto.metadata.as_ref().unwrap();
1197 assert_eq!(meta_auto["width"], 2048);
1198 assert_eq!(meta_auto["height"], 1024);
1199
1200 // Original detail -> within 4096, keeps 3000x1500
1201 let orig_input = json!({ "path": "large.png", "detail": "original" });
1202 let rich_orig = tool.execute_rich(orig_input, &ctx).await.unwrap();
1203 let meta_orig = rich_orig.metadata.as_ref().unwrap();
1204 assert_eq!(meta_orig["width"], 3000);
1205 assert_eq!(meta_orig["height"], 1500);
1206 }
1207
1208 #[tokio::test]
1209 async fn read_media_route_capability_unsupported_fails_actionable() {
1210 let dir = tempdir().unwrap();
1211 let img_path = dir.path().join("img.png");
1212 let png_data = create_test_png(10, 10, [1, 2, 3, 255]);
1213 std::fs::write(&img_path, &png_data).unwrap();
1214
1215 let mut ctx = ToolContext::new(dir.path());
1216 ctx.route_capabilities.image_input = CapabilityState::Unsupported;
1217
1218 let tool = ReadMediaTool;
1219 let input = json!({ "path": "img.png" });
1220 let err = tool.execute_rich(input, &ctx).await.unwrap_err();
1221 let err_msg = err.to_string();
1222 assert!(err_msg.contains("active model route does not support image input"));
1223 assert!(err_msg.contains("/model"));
1224 assert!(err_msg.contains("image_input"));
1225 assert!(!err_msg.contains("deepseek-v4-pro"));
1226 }
1227
1228 #[tokio::test]
1229 async fn read_media_missing_file_fails_actionable() {
1230 let dir = tempdir().unwrap();
1231 let ctx = ToolContext::new(dir.path());
1232 let tool = ReadMediaTool;
1233 let input = json!({ "path": "nonexistent.png" });
1234 let err = tool.execute_rich(input, &ctx).await.unwrap_err();
1235 assert!(err.to_string().contains("image file does not exist"));
1236 }
1237
1238 #[tokio::test]
1239 async fn read_media_empty_file_fails_actionable() {
1240 let dir = tempdir().unwrap();
1241 let img_path = dir.path().join("empty.png");
1242 std::fs::write(&img_path, b"").unwrap();
1243
1244 let ctx = ToolContext::new(dir.path());
1245 let tool = ReadMediaTool;
1246 let input = json!({ "path": "empty.png" });
1247 let err = tool.execute_rich(input, &ctx).await.unwrap_err();
1248 assert!(err.to_string().contains("image file is empty"));
1249 }
1250
1251 #[tokio::test]
1252 async fn read_media_corrupted_or_non_image_fails_actionable() {
1253 let dir = tempdir().unwrap();
1254 let bad_path = dir.path().join("corrupted.png");
1255 std::fs::write(&bad_path, b"not a real image payload at all").unwrap();
1256
1257 let ctx = ToolContext::new(dir.path());
1258 let tool = ReadMediaTool;
1259 let input = json!({ "path": "corrupted.png" });
1260 let err = tool.execute_rich(input, &ctx).await.unwrap_err();
1261 assert!(
1262 err.to_string()
1263 .contains("not a recognized or supported image format")
1264 );
1265 }
1266
1267 #[tokio::test]
1268 async fn read_media_rejected_format_svg_fails_with_conversion_hint() {
1269 let dir = tempdir().unwrap();
1270 let svg_path = dir.path().join("vector.svg");
1271 std::fs::write(&svg_path, b"<svg><circle r='10'/></svg>").unwrap();
1272
1273 let ctx = ToolContext::new(dir.path());
1274 let tool = ReadMediaTool;
1275 let input = json!({ "path": "vector.svg" });
1276 let err = tool.execute_rich(input, &ctx).await.unwrap_err();
1277 let msg = err.to_string();
1278 assert!(msg.contains("SVG format is not directly supported by vision models"));
1279 assert!(msg.contains("Convert it to PNG, JPEG, GIF, or WebP"));
1280 }
1281
1282 #[allow(clippy::await_holding_lock)]
1283 #[tokio::test]
1284 async fn read_media_credential_path_is_denied() {
1285 let _env_lock = crate::test_support::lock_test_env();
1286 let tmp = tempdir().expect("tempdir");
1287 let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path());
1288 let _config_path = crate::test_support::EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
1289 let _legacy_config_path = crate::test_support::EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
1290
1291 std::fs::write(tmp.path().join("config.toml"), "api_key = \"secret\"\n")
1292 .expect("write config");
1293
1294 let ctx = ToolContext::new(tmp.path().to_path_buf());
1295 let tool = ReadMediaTool;
1296 let input = json!({ "path": "config.toml" });
1297 let err = tool.execute_rich(input, &ctx).await.unwrap_err();
1298 assert!(
1299 err.to_string()
1300 .contains("cannot read Codewhale configuration or credential-store"),
1301 "{}",
1302 err
1303 );
1304 }
1305
1306 #[allow(clippy::await_holding_lock)]
1307 #[cfg(unix)]
1308 #[tokio::test]
1309 async fn read_media_credential_symlink_escape_is_denied() {
1310 let _env_lock = crate::test_support::lock_test_env();
1311 let home_tmp = tempdir().expect("home tempdir");
1312 let ws_tmp = tempdir().expect("workspace tempdir");
1313 let _codewhale_home =
1314 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home_tmp.path());
1315 let _config_path = crate::test_support::EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
1316 let _legacy_config_path = crate::test_support::EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
1317
1318 let real_config = home_tmp.path().join("config.toml");
1319 std::fs::write(&real_config, "api_key = \"secret_in_home\"\n").expect("write config");
1320
1321 // Create a symlink in the workspace pointing to the credentials
1322 let symlink_path = ws_tmp.path().join("fake_image.png");
1323 std::os::unix::fs::symlink(&real_config, &symlink_path).expect("create symlink");
1324
1325 {
1326 // Case 1: Default context (no symlink follow outside workspace) -> path escape error
1327 let ctx_default = ToolContext::new(ws_tmp.path().to_path_buf());
1328 let tool = ReadMediaTool;
1329 let input = json!({ "path": "fake_image.png" });
1330 let err_default = tool
1331 .execute_rich(input.clone(), &ctx_default)
1332 .await
1333 .unwrap_err();
1334 let msg_default = err_default.to_string();
1335 assert!(
1336 msg_default.contains("escapes workspace") || msg_default.contains("credential"),
1337 "default policy must reject symlink outside workspace: {msg_default}"
1338 );
1339
1340 // Case 2: follow_symlinks enabled -> credential guard must still deny read
1341 let ctx_follow =
1342 ToolContext::new(ws_tmp.path().to_path_buf()).with_follow_symlinks(true);
1343 let err_follow = tool.execute_rich(input, &ctx_follow).await.unwrap_err();
1344 assert!(
1345 err_follow
1346 .to_string()
1347 .contains("cannot read Codewhale configuration or credential-store"),
1348 "follow_symlinks policy must catch canonical credential path: {}",
1349 err_follow
1350 );
1351 }
1352 }
1353
1354 #[tokio::test]
1355 async fn read_media_path_escape_is_rejected() {
1356 let dir = tempdir().unwrap();
1357 let ctx = ToolContext::new(dir.path());
1358 let tool = ReadMediaTool;
1359 let input = json!({ "path": "../../etc/shadow" });
1360 let err = tool.execute_rich(input, &ctx).await.unwrap_err();
1361 assert!(
1362 err.to_string().contains("escapes workspace") || err.to_string().contains("permission"),
1363 "{}",
1364 err
1365 );
1366 }
1367
1368 #[tokio::test]
1369 async fn read_media_respects_cancel_token() {
1370 let dir = tempdir().unwrap();
1371 let img_path = dir.path().join("cancel.png");
1372 let png_data = create_test_png(10, 10, [1, 2, 3, 255]);
1373 std::fs::write(&img_path, &png_data).unwrap();
1374
1375 let cancel_token = tokio_util::sync::CancellationToken::new();
1376 cancel_token.cancel();
1377 let mut ctx = ToolContext::new(dir.path()).with_cancel_token(cancel_token);
1378 ctx.route_capabilities.image_input = CapabilityState::Supported;
1379
1380 let tool = ReadMediaTool;
1381 let err = tool
1382 .execute_rich(json!({ "path": "cancel.png" }), &ctx)
1383 .await
1384 .unwrap_err();
1385 let msg = err.to_string();
1386 assert!(msg.contains("aborted") || msg.contains("cancel"), "{msg}");
1387 }
1388
1389 #[tokio::test]
1390 async fn read_media_cancellation_before_dispatch_fails_without_read() {
1391 let dir = tempdir().unwrap();
1392 let cancel_token = tokio_util::sync::CancellationToken::new();
1393 cancel_token.cancel();
1394 let mut ctx = ToolContext::new(dir.path()).with_cancel_token(cancel_token);
1395 ctx.route_capabilities.image_input = CapabilityState::Supported;
1396
1397 let tool = ReadMediaTool;
1398 // A non-existent file path would normally fail with "image file does not exist",
1399 // but when cancelled before dispatch, it must abort with Cancelled without touching disk.
1400 let input = json!({ "path": "nonexistent_before_dispatch.png" });
1401 let err = tool.execute_rich(input, &ctx).await.unwrap_err();
1402 let msg = err.to_string();
1403 assert!(
1404 msg.contains("aborted") || msg.contains("cancel"),
1405 "expected cancellation error before dispatch, got: {msg}"
1406 );
1407 assert!(
1408 !msg.contains("does not exist"),
1409 "should not reach filesystem checks when cancelled before dispatch"
1410 );
1411 }
1412
1413 #[tokio::test]
1414 async fn read_media_provider_request_wiring_integration() {
1415 let dir = tempdir().unwrap();
1416 let img_path = dir.path().join("wire.png");
1417 let png_data = create_test_png(40, 40, [10, 20, 30, 255]);
1418 std::fs::write(&img_path, &png_data).unwrap();
1419
1420 let ctx = ToolContext::new(dir.path());
1421 let tool = ReadMediaTool;
1422 let rich = tool
1423 .execute_rich(json!({ "path": "wire.png" }), &ctx)
1424 .await
1425 .unwrap();
1426
1427 let ToolResultContentBlock::Image { mime_type, data } = &rich.content_blocks[0];
1428
1429 // 1. Check Anthropic tool result wiring
1430 let anthropic_content = crate::client::anthropic_tool_result_content_for_test(
1431 &rich.content,
1432 Some(&[json!({
1433 "type": "image",
1434 "mime_type": mime_type,
1435 "data": data
1436 })]),
1437 );
1438 let blocks = anthropic_content
1439 .as_array()
1440 .expect("anthropic content array");
1441 assert!(
1442 blocks
1443 .iter()
1444 .any(|b| b["type"] == "image" && b["source"]["media_type"] == "image/png")
1445 );
1446
1447 // 2. Check OpenAI Responses tool output wiring
1448 let responses_content = crate::client::responses_tool_output_for_test(
1449 &rich.content,
1450 Some(&[json!({
1451 "type": "image",
1452 "mime_type": mime_type,
1453 "data": data
1454 })]),
1455 );
1456 let resp_blocks = responses_content
1457 .as_array()
1458 .expect("responses content array");
1459 assert!(resp_blocks.iter().any(|b| b["type"] == "input_image"));
1460
1461 // 3. Check Chat Completions provider request body wiring
1462 let messages = vec![
1463 codewhale_models::Message {
1464 role: Role::Assistant,
1465 content: vec![codewhale_models::ContentBlock::ToolUse {
1466 execution_id: None,
1467 id: "call_read_media".to_string(),
1468 name: "read_media".to_string(),
1469 input: json!({ "path": "wire.png" }),
1470 caller: None,
1471 thought_signature: None,
1472 }],
1473 },
1474 codewhale_models::Message {
1475 role: Role::User,
1476 content: vec![codewhale_models::ContentBlock::ToolResult {
1477 execution_id: None,
1478 tool_use_id: "call_read_media".to_string(),
1479 content: rich.content.clone(),
1480 is_error: None,
1481 content_blocks: Some(vec![json!({
1482 "type": "image",
1483 "mime_type": mime_type,
1484 "data": data
1485 })]),
1486 }],
1487 },
1488 ];
1489 let chat_msgs = crate::client::chat_messages_for_test(&messages);
1490 let tool_msg = chat_msgs
1491 .iter()
1492 .find(|m| m["role"] == "tool" && m["tool_call_id"] == "call_read_media")
1493 .expect("tool response message");
1494 assert!(
1495 tool_msg["content"]
1496 .as_str()
1497 .unwrap()
1498 .contains("Read media file")
1499 );
1500 let follow_up_user = chat_msgs
1501 .iter()
1502 .find(|m| m["role"] == "user" && m["content"].is_array())
1503 .expect("follow-up user message carrying tool image");
1504 let parts = follow_up_user["content"].as_array().unwrap();
1505 assert!(
1506 parts.iter().any(|part| {
1507 part["type"] == "image_url"
1508 && part["image_url"]["url"]
1509 .as_str()
1510 .is_some_and(|u| u.starts_with("data:image/png;base64,"))
1511 }),
1512 "expected image_url part in chat completions follow-up message: {parts:?}"
1513 );
1514
1515 // 4. Check Chat Completions provider tool result refs helper
1516 let blocks = [json!({
1517 "type": "image",
1518 "mime_type": mime_type,
1519 "data": data
1520 })];
1521 let (image_ref, omitted) =
1522 crate::image_attach::provider_tool_result_image_refs(Some(&blocks));
1523 assert_eq!(omitted, 0);
1524 assert!(image_ref.is_some());
1525 let (sniffed_mime, payload) = image_ref.unwrap();
1526 assert_eq!(sniffed_mime, "image/png");
1527 assert_eq!(payload, data);
1528 }
1529
1530 #[tokio::test]
1531 async fn read_media_decompression_bomb_rejected() {
1532 let dir = tempdir().unwrap();
1533 let bomb_path = dir.path().join("bomb.png");
1534
1535 // Construct a synthetic PNG header with 10,000 x 10,000 dimensions (100 megapixels > 33.5 megapixel guard)
1536 // PNG signature + IHDR chunk (length 13, type IHDR, width, height, bit depth 8, color type 6, etc.)
1537 let mut fake_png = Vec::new();
1538 fake_png.extend_from_slice(b"\x89PNG\r\n\x1a\n");
1539 fake_png.extend_from_slice(&13_u32.to_be_bytes()); // IHDR length
1540 fake_png.extend_from_slice(b"IHDR");
1541 fake_png.extend_from_slice(&10_000_u32.to_be_bytes()); // width: 10,000
1542 fake_png.extend_from_slice(&10_000_u32.to_be_bytes()); // height: 10,000
1543 fake_png.extend_from_slice(&[8, 6, 0, 0, 0]); // 8-bit RGBA
1544 fake_png.extend_from_slice(&[0, 0, 0, 0]); // CRC (dummy)
1545 std::fs::write(&bomb_path, &fake_png).unwrap();
1546
1547 let ctx = ToolContext::new(dir.path());
1548 let tool = ReadMediaTool;
1549 let err = tool
1550 .execute_rich(json!({ "path": "bomb.png" }), &ctx)
1551 .await
1552 .unwrap_err();
1553 let msg = err.to_string();
1554 assert!(
1555 msg.contains("decompression bomb")
1556 || msg.contains("exceed safe limits")
1557 || msg.contains("guard triggered"),
1558 "{}",
1559 msg
1560 );
1561 }
1562
1563 #[tokio::test]
1564 async fn read_media_gif_format_supported() {
1565 let dir = tempdir().unwrap();
1566 let gif_path = dir.path().join("anim.gif");
1567 let img = image::RgbaImage::from_pixel(30, 30, image::Rgba([100, 150, 200, 255]));
1568 let mut cursor = Cursor::new(Vec::new());
1569 img.write_to(&mut cursor, ImageFormat::Gif).unwrap();
1570 std::fs::write(&gif_path, cursor.into_inner()).unwrap();
1571
1572 let ctx = ToolContext::new(dir.path());
1573 let tool = ReadMediaTool;
1574 let rich = tool
1575 .execute_rich(json!({ "path": "anim.gif" }), &ctx)
1576 .await
1577 .unwrap();
1578 assert!(rich.success);
1579 let meta = rich.metadata.as_ref().unwrap();
1580 assert_eq!(meta["original_mime_type"], "image/gif");
1581 assert_eq!(meta["mime_type"], "image/png");
1582 }
1583
1584 #[tokio::test]
1585 async fn read_media_webp_format_supported() {
1586 let dir = tempdir().unwrap();
1587 let webp_path = dir.path().join("image.webp");
1588 let webp_bytes = BASE64
1589 .decode("UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAADABAJ0BKgEAAQABABwlpAADcAD+/gbQAA==")
1590 .expect("valid webp");
1591 std::fs::write(&webp_path, webp_bytes).unwrap();
1592
1593 let ctx = ToolContext::new(dir.path());
1594 let tool = ReadMediaTool;
1595 let rich = tool
1596 .execute_rich(json!({ "path": "image.webp" }), &ctx)
1597 .await
1598 .unwrap();
1599 assert!(rich.success);
1600 let meta = rich.metadata.as_ref().unwrap();
1601 assert_eq!(meta["original_mime_type"], "image/webp");
1602 assert_eq!(meta["mime_type"], "image/png");
1603 }
1604
1605 #[tokio::test]
1606 async fn read_media_supported_and_unknown_routes_admitted() {
1607 let dir = tempdir().unwrap();
1608 let img_path = dir.path().join("check.png");
1609 let png_data = create_test_png(20, 20, [50, 50, 50, 255]);
1610 std::fs::write(&img_path, &png_data).unwrap();
1611
1612 let tool = ReadMediaTool;
1613
1614 // 1. Supported route
1615 let mut ctx_sup = ToolContext::new(dir.path());
1616 ctx_sup.route_capabilities.image_input = CapabilityState::Supported;
1617 let res_sup = tool
1618 .execute_rich(json!({ "path": "check.png" }), &ctx_sup)
1619 .await;
1620 assert!(res_sup.is_ok());
1621
1622 // Unknown deliberately matches the established attachment contract:
1623 // custom/self-hosted routes frequently lack modality metadata, so
1624 // only a known Unsupported verdict blocks this explicit user action
1625 // and the provider remains authoritative.
1626 let mut ctx_unk = ToolContext::new(dir.path());
1627 ctx_unk.route_capabilities.image_input = CapabilityState::Unknown;
1628 let res_unk = tool
1629 .execute_rich(json!({ "path": "check.png" }), &ctx_unk)
1630 .await;
1631 let rich_unk = res_unk.unwrap();
1632 assert!(rich_unk.content.contains(
1633 "Route image support is unverified; if the model cannot see this image, use image_ocr."
1634 ));
1635 }
1636
1637 #[tokio::test]
1638 async fn read_media_receipt_contains_no_credentials() {
1639 let dir = tempdir().unwrap();
1640 let img_path = dir.path().join("safe.png");
1641 let png_data = create_test_png(15, 15, [255, 255, 255, 255]);
1642 std::fs::write(&img_path, &png_data).unwrap();
1643
1644 let ctx = ToolContext::new(dir.path());
1645 let tool = ReadMediaTool;
1646 let rich = tool
1647 .execute_rich(json!({ "path": "safe.png" }), &ctx)
1648 .await
1649 .unwrap();
1650
1651 let meta = rich.metadata.as_ref().unwrap();
1652 let meta_str = meta.to_string();
1653 assert!(!meta_str.contains("key"));
1654 assert!(!meta_str.contains("secret"));
1655 assert!(!meta_str.contains("token"));
1656 assert!(!meta_str.contains("password"));
1657 assert!(!meta_str.contains("auth"));
1658 }
1659
1660 /// Deterministic photo-like noise image (high colorfulness, hard to
1661 /// compress), so the ladder takes the JPEG path without any network or
1662 /// fixture dependency.
1663 fn create_noise_png(width: u32, height: u32) -> Vec<u8> {
1664 let mut img = image::RgbImage::new(width, height);
1665 let mut state: u32 = 0x1234_5678;
1666 let mut next = move || {
1667 state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1668 (state >> 24) as u8
1669 };
1670 for px in img.pixels_mut() {
1671 *px = image::Rgb([next(), next(), next()]);
1672 }
1673 let mut cursor = Cursor::new(Vec::new());
1674 img.write_to(&mut cursor, ImageFormat::Png).unwrap();
1675 cursor.into_inner()
1676 }
1677
1678 fn decode_payload(data: &str) -> (u32, u32, Vec<u8>) {
1679 let bytes = BASE64.decode(data).expect("valid base64 payload");
1680 let img = ImageReader::new(Cursor::new(&bytes))
1681 .with_guessed_format()
1682 .unwrap()
1683 .decode()
1684 .expect("delivered payload decodes");
1685 (img.width(), img.height(), bytes)
1686 }
1687
1688 #[tokio::test]
1689 async fn read_media_photo_over_budget_arrives_under_budget_as_jpeg() {
1690 let dir = tempdir().unwrap();
1691 let img_path = dir.path().join("photo.png");
1692 let png_data = create_noise_png(1600, 1200);
1693 assert!(
1694 png_data.len() > READ_IMAGE_BYTE_BUDGET,
1695 "test image must start over the default read budget"
1696 );
1697 std::fs::write(&img_path, &png_data).unwrap();
1698
1699 let mut ctx = ToolContext::new(dir.path());
1700 ctx.route_capabilities.image_input = CapabilityState::Supported;
1701
1702 let tool = ReadMediaTool;
1703 let rich = tool
1704 .execute_rich(json!({ "path": "photo.png", "detail": "auto" }), &ctx)
1705 .await
1706 .unwrap();
1707 assert!(rich.success);
1708
1709 let ToolResultContentBlock::Image { mime_type, data } = &rich.content_blocks[0];
1710 assert_eq!(
1711 mime_type, "image/jpeg",
1712 "photo-like content must go out as JPEG, not PNG"
1713 );
1714 let payload_len = BASE64.decode(data).unwrap().len();
1715 assert!(
1716 payload_len <= READ_IMAGE_BYTE_BUDGET,
1717 "delivered payload {payload_len} must fit the {}-byte read budget",
1718 READ_IMAGE_BYTE_BUDGET
1719 );
1720
1721 let meta = rich.metadata.as_ref().unwrap();
1722 assert_eq!(meta["mime_type"], "image/jpeg");
1723 assert_eq!(meta["original_width"], 1600);
1724 assert_eq!(meta["original_height"], 1200);
1725 assert_eq!(
1726 meta["delivery"], "downsampled",
1727 "a quality- or resolution-reduced delivery is never silent"
1728 );
1729 assert!(rich.content.contains("fine detail may be lost"));
1730 assert!(
1731 rich.content
1732 .contains("crop parameter (original-image pixel coordinates)")
1733 );
1734 }
1735
1736 #[tokio::test]
1737 async fn read_media_small_image_passes_untouched() {
1738 let dir = tempdir().unwrap();
1739 let img_path = dir.path().join("small.png");
1740 let png_data = create_test_png(120, 80, [10, 120, 200, 255]);
1741 std::fs::write(&img_path, &png_data).unwrap();
1742
1743 let mut ctx = ToolContext::new(dir.path());
1744 ctx.route_capabilities.image_input = CapabilityState::Supported;
1745
1746 let tool = ReadMediaTool;
1747 let rich = tool
1748 .execute_rich(json!({ "path": "small.png" }), &ctx)
1749 .await
1750 .unwrap();
1751 assert!(rich.success);
1752
1753 let meta = rich.metadata.as_ref().unwrap();
1754 assert_eq!(meta["delivery"], "untouched");
1755 assert_eq!(meta["mime_type"], "image/png");
1756 assert_eq!(meta["width"], 120);
1757 assert_eq!(meta["height"], 80);
1758 assert!(
1759 meta["original_path"].is_null(),
1760 "untouched reads keep no stored copy"
1761 );
1762 assert!(rich.content.contains("untouched"));
1763 assert!(rich.content.contains("no downsampling applied"));
1764 }
1765
1766 #[tokio::test]
1767 async fn read_media_alpha_image_stays_png() {
1768 let dir = tempdir().unwrap();
1769 let img_path = dir.path().join("alpha.png");
1770 // Colorful RGB with a real alpha gradient: alpha must survive.
1771 let mut img = image::RgbaImage::new(640, 480);
1772 for (x, _y, px) in img.enumerate_pixels_mut() {
1773 *px = image::Rgba([(x % 256) as u8, 200, 90, if x < 320 { 255 } else { 100 }]);
1774 }
1775 let mut cursor = Cursor::new(Vec::new());
1776 img.write_to(&mut cursor, ImageFormat::Png).unwrap();
1777 std::fs::write(&img_path, cursor.into_inner()).unwrap();
1778
1779 let mut ctx = ToolContext::new(dir.path());
1780 ctx.route_capabilities.image_input = CapabilityState::Supported;
1781
1782 let tool = ReadMediaTool;
1783 let rich = tool
1784 .execute_rich(json!({ "path": "alpha.png" }), &ctx)
1785 .await
1786 .unwrap();
1787 assert!(rich.success);
1788
1789 let ToolResultContentBlock::Image { mime_type, data } = &rich.content_blocks[0];
1790 assert_eq!(
1791 mime_type, "image/png",
1792 "meaningful alpha must never be flattened to JPEG"
1793 );
1794 let (w, h, bytes) = decode_payload(data);
1795 assert_eq!((w, h), (640, 480));
1796 let decoded = ImageReader::new(Cursor::new(&bytes))
1797 .with_guessed_format()
1798 .unwrap()
1799 .decode()
1800 .unwrap()
1801 .to_rgba8();
1802 assert!(
1803 decoded.pixels().any(|p| p.0[3] == 100),
1804 "alpha channel must survive delivery"
1805 );
1806 }
1807
1808 #[tokio::test]
1809 async fn read_media_delivery_note_reports_mode_dims_and_zoom_guidance() {
1810 let dir = tempdir().unwrap();
1811 let img_path = dir.path().join("big.png");
1812 let png_data = create_test_png(3000, 1500, [0, 0, 255, 255]);
1813 std::fs::write(&img_path, &png_data).unwrap();
1814
1815 let mut ctx = ToolContext::new(dir.path());
1816 ctx.route_capabilities.image_input = CapabilityState::Supported;
1817
1818 let tool = ReadMediaTool;
1819 let rich = tool
1820 .execute_rich(json!({ "path": "big.png", "detail": "auto" }), &ctx)
1821 .await
1822 .unwrap();
1823 assert!(rich.success);
1824
1825 let meta = rich.metadata.as_ref().unwrap();
1826 assert_eq!(meta["delivery"], "downsampled");
1827 assert_eq!(meta["width"], 2048);
1828 assert_eq!(meta["height"], 1024);
1829
1830 let note = &rich.content;
1831 assert!(note.contains("Original dimensions: 3000x1500"), "{note}");
1832 assert!(note.contains("downsampled to 2048x1024"), "{note}");
1833 assert!(note.contains("fine detail may be lost"), "{note}");
1834 assert!(
1835 note.contains(
1836 "call read_media again with the crop parameter (original-image pixel coordinates)"
1837 ),
1838 "downsampled note must guide zoom via crop: {note}"
1839 );
1840 }
1841
1842 #[tokio::test]
1843 async fn read_media_crop_after_downsample_pulls_full_res_stored_original() {
1844 let dir = tempdir().unwrap();
1845 let store_dir = dir.path().join("media-originals");
1846 let img_path = dir.path().join("scene.png");
1847 // 2600x1300 photo-like source: auto detail downsamples to 2048x1024.
1848 std::fs::write(&img_path, create_noise_png(2600, 1300)).unwrap();
1849
1850 let mut ctx = ToolContext::new(dir.path()).with_runtime_services(
1851 crate::tools::spec::RuntimeToolServices {
1852 media_originals_dir: Some(store_dir.clone()),
1853 ..crate::tools::spec::RuntimeToolServices::default()
1854 },
1855 );
1856 ctx.route_capabilities.image_input = CapabilityState::Supported;
1857
1858 let tool = ReadMediaTool;
1859 let rich = tool
1860 .execute_rich(json!({ "path": "scene.png", "detail": "auto" }), &ctx)
1861 .await
1862 .unwrap();
1863 let meta = rich.metadata.as_ref().unwrap();
1864 assert_eq!(meta["delivery"], "downsampled");
1865 let delivered_width = meta["width"].as_u64().unwrap();
1866 assert!(
1867 delivered_width <= 2048,
1868 "auto detail caps at 2048px; noise may ladder further: {delivered_width}"
1869 );
1870 assert_eq!(meta["original_width"], 2600);
1871 assert_eq!(meta["original_height"], 1300);
1872
1873 // The pre-compression original is persisted, content-addressed.
1874 let original_path = meta["original_path"]
1875 .as_str()
1876 .expect("downsampled reads persist the original")
1877 .to_string();
1878 assert!(original_path.starts_with(store_dir.to_str().unwrap()));
1879 let stored = std::fs::read(&original_path).expect("stored original bytes");
1880 let stored_img = ImageReader::new(Cursor::new(&stored))
1881 .with_guessed_format()
1882 .unwrap()
1883 .decode()
1884 .unwrap();
1885 assert_eq!(
1886 (stored_img.width(), stored_img.height()),
1887 (2600, 1300),
1888 "the store holds the full-resolution source, not the downsampled copy"
1889 );
1890
1891 // A crop that is out of bounds for the downsampled 2048-wide copy but
1892 // valid for the 2600-wide original must succeed at the requested
1893 // pixel size — proof the crop pulls the full-res stored source.
1894 let crop = tool
1895 .execute_rich(
1896 json!({
1897 "path": original_path,
1898 "crop": { "x": 2200, "y": 900, "width": 300, "height": 300 }
1899 }),
1900 &ctx,
1901 )
1902 .await
1903 .unwrap();
1904 let crop_meta = crop.metadata.as_ref().unwrap();
1905 assert_eq!(crop_meta["delivery"], "crop");
1906 assert_eq!(crop_meta["width"], 300);
1907 assert_eq!(crop_meta["height"], 300);
1908 assert_eq!(crop_meta["original_width"], 2600);
1909 assert!(
1910 crop.content.contains("region offset (x=2200, y=900)"),
1911 "crop note must carry the offset guidance: {}",
1912 crop.content
1913 );
1914 }
1915
1916 #[tokio::test]
1917 async fn read_media_over_budget_failure_names_conversion_recipe() {
1918 let dir = tempdir().unwrap();
1919 let img_path = dir.path().join("noise.png");
1920 std::fs::write(&img_path, create_noise_png(512, 512)).unwrap();
1921 let raw = std::fs::read(&img_path).unwrap();
1922 let (image, _, _) = decode_and_guard_image(&raw).unwrap();
1923
1924 // A 1024-byte budget is unreachable even at the 256px/q20 floor.
1925 let err =
1926 encode_within_budget(&image, EncodePolicy::PreferJpeg, 1024, &img_path).unwrap_err();
1927 let msg = err.to_string();
1928 assert!(msg.contains("Nothing was sent"), "{msg}");
1929 assert!(msg.contains("sips -Z 1024"), "recipe names sips: {msg}");
1930 assert!(msg.contains("magick"), "recipe names ImageMagick: {msg}");
1931 assert!(msg.contains("smaller copy"), "{msg}");
1932
1933 // Alpha-bearing images fail closed the same way rather than
1934 // falling back to JPEG.
1935 let err = encode_within_budget(&image, EncodePolicy::RequireAlphaPng, 1024, &img_path)
1936 .unwrap_err();
1937 assert!(err.to_string().contains("Nothing was sent"), "{err}");
1938 }
1939
1940 #[cfg(unix)]
1941 #[allow(clippy::await_holding_lock)]
1942 #[tokio::test]
1943 async fn read_media_refuses_swapped_parent_symlink_to_denied_image() {
1944 let _env_lock = crate::test_support::lock_test_env();
1945 let workspace = tempdir().unwrap();
1946 let denied = tempdir().unwrap();
1947 let sub = workspace.path().join("images");
1948 std::fs::create_dir_all(&sub).unwrap();
1949 let benign = sub.join("shot.png");
1950 std::fs::write(&benign, create_test_png(16, 16, [0, 128, 255, 255])).unwrap();
1951 let secret = denied.path().join("shot.png");
1952 std::fs::write(&secret, create_test_png(16, 16, [255, 0, 0, 255])).unwrap();
1953
1954 let ctx = ToolContext::new(workspace.path());
1955 let plan = crate::tools::file::resolve_read_open_plan_for_media(&ctx, "images/shot.png")
1956 .await
1957 .expect("resolve plan before swap");
1958
1959 std::fs::remove_dir_all(&sub).unwrap();
1960 std::os::unix::fs::symlink(denied.path(), &sub).unwrap();
1961
1962 let denylist = codewhale_sandbox::read_guard::ReadDenylist::build(
1963 true,
1964 &[denied.path().to_path_buf()],
1965 &[],
1966 );
1967 codewhale_sandbox::read_guard::with_test_active_denylist(denylist, || {
1968 let Err(err) = process_media_plan(&plan, None, DetailMode::Auto, None) else {
1969 panic!("swapped parent symlink must be refused on open");
1970 };
1971 assert!(matches!(err, ToolError::PermissionDenied { .. }), "{err:?}");
1972 });
1973 }
1974 }
1975
1975 lines RUST