返回 CodeWhale
tests.rs
根目录 / crates / engine / src / image_attach / tests.rs
1 use super::test_support::*;
2 use super::*;
3 use codewhale_models::Role;
4 use codewhale_models::image_window::is_remote_image_url;
5
6 #[test]
7 fn sniffs_every_accepted_format_from_magic_bytes() {
8 assert_eq!(sniff_media_type(PNG_1X1), Some("image/png"));
9 assert_eq!(
10 sniff_media_type(&[0xff, 0xd8, 0xff, 0xe0, 0x00]),
11 Some("image/jpeg")
12 );
13 assert_eq!(sniff_media_type(b"GIF89a....."), Some("image/gif"));
14 assert_eq!(sniff_media_type(b"GIF87a....."), Some("image/gif"));
15 assert_eq!(
16 sniff_media_type(b"RIFF\x00\x00\x00\x00WEBPVP8 "),
17 Some("image/webp")
18 );
19 }
20
21 /// Noise defeats compression, so the shrink ladder has to re-encode for real.
22 fn noise_payload(width: u32, height: u32) -> Vec<u8> {
23 use image::ImageEncoder as _;
24 let mut pixels = image::RgbImage::new(width, height);
25 for (x, y, pixel) in pixels.enumerate_pixels_mut() {
26 *pixel = image::Rgb([
27 (x.wrapping_mul(31) ^ y.wrapping_mul(17)) as u8,
28 (x.wrapping_mul(7) ^ y.wrapping_mul(29)) as u8,
29 (x.wrapping_add(y).wrapping_mul(13)) as u8,
30 ]);
31 }
32 let mut bytes = Vec::new();
33 image::codecs::png::PngEncoder::new_with_quality(
34 &mut bytes,
35 image::codecs::png::CompressionType::Fast,
36 image::codecs::png::FilterType::NoFilter,
37 )
38 .write_image(
39 pixels.as_raw(),
40 width,
41 height,
42 image::ExtendedColorType::Rgb8,
43 )
44 .expect("encode fixture png");
45 bytes
46 }
47
48 fn image_blocks_fixture() -> Vec<codewhale_models::Message> {
49 let payload = STANDARD.encode(noise_payload(320, 320));
50 vec![
51 codewhale_models::Message {
52 role: Role::User,
53 content: vec![
54 ContentBlock::Text {
55 text: "look at this".to_string(),
56 cache_control: None,
57 },
58 ContentBlock::ImageUrl {
59 image_url: ImageUrlContent {
60 url: format!("data:image/png;base64,{payload}"),
61 },
62 },
63 ],
64 },
65 codewhale_models::Message {
66 role: Role::User,
67 content: vec![ContentBlock::ToolResult {
68 execution_id: None,
69 tool_use_id: "call_1".to_string(),
70 content: "Read image file [image/png]".to_string(),
71 is_error: None,
72 content_blocks: Some(vec![serde_json::json!({
73 "type": "image",
74 "mime_type": "image/png",
75 "data": payload,
76 })]),
77 }],
78 },
79 ]
80 }
81
82 #[test]
83 fn compaction_shrink_rewrites_both_image_carriers_under_budget() {
84 let budget = 64 * 1024;
85 let mut messages = image_blocks_fixture();
86 let outcome = shrink_images_for_request_with_budget(&mut messages, budget);
87 assert_eq!(outcome.images, 2, "both carriers are rewritten");
88 assert!(outcome.bytes_after < outcome.bytes_before);
89
90 let ContentBlock::ImageUrl { image_url } = &messages[0].content[1] else {
91 panic!("image block survives the shrink");
92 };
93 let (mime, payload) = parse_data_url(&image_url.url).expect("data url");
94 assert!(matches!(mime, "image/png" | "image/jpeg"), "{mime}");
95 let bytes = STANDARD.decode(payload).expect("base64");
96 assert!(bytes.len() <= budget, "{} <= {budget}", bytes.len());
97 assert_eq!(sniff_media_type(&bytes), Some(mime));
98
99 let ContentBlock::ToolResult { content_blocks, .. } = &messages[1].content[0] else {
100 panic!("tool result survives the shrink");
101 };
102 let block = &content_blocks.as_ref().expect("blocks")[0];
103 assert_eq!(block["type"], "image");
104 let nested = STANDARD
105 .decode(block["data"].as_str().expect("data"))
106 .expect("nested base64");
107 assert!(nested.len() <= budget);
108 assert_eq!(
109 sniff_media_type(&nested),
110 block["mime_type"].as_str(),
111 "the mime must match the rewritten bytes"
112 );
113 }
114
115 #[test]
116 fn compaction_shrink_leaves_an_under_budget_history_untouched() {
117 let mut messages = image_blocks_fixture();
118 let before = messages.clone();
119 let outcome = shrink_images_for_request_with_budget(&mut messages, 32 * 1024 * 1024);
120 assert_eq!(outcome.images, 0, "a fitting request is never rewritten");
121 assert_eq!(
122 outcome.images_seen, 2,
123 "the request still carried images, and the ladder must be able to tell"
124 );
125 assert_eq!(messages, before);
126 }
127
128 #[test]
129 fn compaction_placeholder_keeps_the_image_visible_as_text() {
130 let mut messages = image_blocks_fixture();
131 let replaced = replace_images_with_placeholders(
132 &mut messages,
133 "the summary request exceeded the provider's request-body limit (HTTP 413)",
134 );
135 assert_eq!(replaced, 2);
136
137 let ContentBlock::Text { text, .. } = &messages[0].content[1] else {
138 panic!("image_url becomes a note");
139 };
140 assert!(text.contains("omitted from this summary pass"), "{text}");
141 assert!(text.contains("do not describe"), "{text}");
142
143 let ContentBlock::ToolResult {
144 content,
145 content_blocks,
146 ..
147 } = &messages[1].content[0]
148 else {
149 panic!("tool result survives");
150 };
151 assert!(content_blocks.is_none(), "no base64 may remain");
152 assert!(content.contains("1 image(s)"), "{content}");
153 assert!(content.contains("Read image file [image/png]"), "{content}");
154 }
155
156 #[test]
157 fn sniffing_ignores_the_extension_and_believes_the_bytes() {
158 // A JPEG named .png must be declared image/jpeg, or the provider
159 // rejects the media-type mismatch.
160 let jpeg = [0xff, 0xd8, 0xff, 0xe0, 0x11, 0x22];
161 let attached = encode_image_bytes(&jpeg, "screenshot.png").expect("attach");
162 assert_eq!(attached.media_type, "image/jpeg");
163 assert!(attached.data_url.starts_with("data:image/jpeg;base64,"));
164 }
165
166 #[test]
167 fn rich_tool_images_reject_corruption_mime_spoofing_and_decode_bombs() {
168 use crate::tools::spec::{RichToolResult, ToolResult};
169 use codewhale_tools::ToolResultContentBlock;
170 let mut oversized_header = PNG_1X1.to_vec();
171 oversized_header[16..20].copy_from_slice(&(MAX_IMAGE_DIMENSION + 1).to_be_bytes());
172 for (mime, bytes) in [
173 ("image/png", &PNG_1X1[..8]),
174 ("image/jpeg", PNG_1X1),
175 ("image/png", oversized_header.as_slice()),
176 ] {
177 assert!(prepare_tool_image_bytes(bytes, mime).block.is_none());
178 let rich = bound_rich_tool_result(RichToolResult::with_content_blocks(
179 ToolResult::success("capture receipt"),
180 vec![ToolResultContentBlock::Image {
181 mime_type: mime.into(),
182 data: STANDARD.encode(bytes),
183 }],
184 ));
185 assert!(rich.result.success);
186 assert!(rich.content_blocks.is_empty());
187 assert!(rich.result.content.starts_with("capture receipt"));
188 assert!(
189 rich.result
190 .content
191 .contains("1 tool-result image block(s) omitted")
192 );
193 let stored = vec![
194 serde_json::json!({"type":"image","mime_type":mime,"data":STANDARD.encode(bytes)}),
195 ];
196 let (image, omitted) = provider_tool_result_image_refs(Some(&stored));
197 assert!(
198 image.is_none(),
199 "restored history must not bypass validation"
200 );
201 assert_eq!(omitted, 1);
202 }
203 }
204
205 #[test]
206 fn lowercase_read_image_preparation_is_typed_and_bounded() {
207 let prepared = prepare_tool_image_bytes(PNG_1X1, "image/png");
208 assert_eq!(prepared.note, "Read image file [image/png]");
209 let codewhale_tools::ToolResultContentBlock::Image { mime_type, data } =
210 prepared.block.expect("typed image");
211 assert_eq!(mime_type, "image/png");
212 assert_eq!(STANDARD.decode(data).expect("base64"), PNG_1X1);
213
214 let omitted = prepare_tool_image_bytes(b"BMnot-a-safe-bitmap", "image/bmp");
215 assert!(omitted.block.is_none());
216 assert!(omitted.note.contains("Image omitted"), "{}", omitted.note);
217 }
218
219 #[test]
220 fn blind_route_removes_nested_tool_result_image() {
221 let mut messages = vec![codewhale_models::Message {
222 role: Role::User,
223 content: vec![ContentBlock::ToolResult {
224 execution_id: None,
225 tool_use_id: "call-image".to_string(),
226 content: "Read image file [image/png]".to_string(),
227 is_error: None,
228 content_blocks: Some(vec![serde_json::json!({
229 "type": "image",
230 "mime_type": "image/png",
231 "data": "QUJD",
232 })]),
233 }],
234 }];
235
236 assert_eq!(
237 strip_images_when_unsupported(&mut messages, SupportState::Unsupported, "text-only",),
238 1
239 );
240 let ContentBlock::ToolResult {
241 content,
242 content_blocks,
243 ..
244 } = &messages[0].content[0]
245 else {
246 panic!("tool result")
247 };
248 assert!(content_blocks.is_none());
249 assert!(content.contains("text-only"), "{content}");
250 }
251
252 #[test]
253 fn copy_projection_never_contains_inline_image_bytes() {
254 const SENTINEL: &str = "U0VOU0lUSVZFX0JBU0U2NA==";
255 let projected = safe_tool_result_content_blocks(Some(&[serde_json::json!({
256 "type": "image",
257 "mime_type": "image/png",
258 "data": SENTINEL,
259 })]))
260 .expect("projection");
261 let encoded = serde_json::to_string(&projected).expect("json");
262 assert!(!encoded.contains(SENTINEL), "{encoded}");
263 assert!(
264 encoded.contains("inline_or_local_image_payload"),
265 "{encoded}"
266 );
267 }
268
269 #[test]
270 fn riff_that_is_not_webp_is_not_an_image() {
271 // A WAV file is also RIFF. Matching on "RIFF" alone would attach audio.
272 assert_eq!(sniff_media_type(b"RIFF\x00\x00\x00\x00WAVEfmt "), None);
273 }
274
275 #[test]
276 fn encodes_a_png_to_a_data_url_that_round_trips() {
277 let attached = encode_image_bytes(PNG_1X1, "shot.png").expect("attach");
278 assert_eq!(attached.media_type, "image/png");
279 assert_eq!(attached.source_bytes, PNG_1X1.len());
280
281 let (media_type, payload) = parse_data_url(&attached.data_url).expect("parse");
282 assert_eq!(media_type, "image/png");
283 assert_eq!(STANDARD.decode(payload).expect("decode"), PNG_1X1);
284 }
285
286 #[test]
287 fn rejects_a_file_over_the_size_limit() {
288 let oversized = vec![0u8; MAX_IMAGE_BYTES + 1];
289 let error = encode_image_bytes(&oversized, "huge.png").expect_err("must reject");
290 assert!(
291 matches!(error, ImageAttachError::TooLarge { .. }),
292 "got {error:?}"
293 );
294 let rendered = error.to_string();
295 assert!(rendered.contains("5.0 MB"), "{rendered}");
296 assert!(rendered.contains("huge.png"), "{rendered}");
297 }
298
299 #[test]
300 fn accepts_a_file_exactly_at_the_size_limit() {
301 // The boundary is inclusive; an off-by-one here would reject images
302 // the providers accept.
303 let mut at_limit = PNG_1X1.to_vec();
304 at_limit.resize(MAX_IMAGE_BYTES, 0);
305 assert!(encode_image_bytes(&at_limit, "edge.png").is_ok());
306 }
307
308 #[test]
309 fn rejects_a_real_image_in_an_unsupported_format_by_name() {
310 for (bytes, name) in [
311 (b"BM\x00\x00\x00\x00".as_slice(), "BMP"),
312 (b"II\x2a\x00extra".as_slice(), "TIFF"),
313 (b"MM\x00\x2aextra".as_slice(), "TIFF"),
314 (b"<svg xmlns=".as_slice(), "SVG"),
315 (b"%PDF-1.7".as_slice(), "PDF"),
316 ] {
317 let error = encode_image_bytes(bytes, "f").expect_err("must reject");
318 match error {
319 ImageAttachError::UnsupportedFormat { detected, .. } => {
320 assert_eq!(detected, name);
321 }
322 other => panic!("expected UnsupportedFormat for {name}, got {other:?}"),
323 }
324 }
325 }
326
327 #[test]
328 fn rejects_a_file_that_is_not_an_image_at_all() {
329 let error = encode_image_bytes(b"#!/bin/sh\necho hi\n", "script.png").expect_err("must reject");
330 assert!(
331 matches!(error, ImageAttachError::NotAnImage { .. }),
332 "got {error:?}"
333 );
334 }
335
336 #[test]
337 fn rejects_an_empty_file() {
338 let error = encode_image_bytes(b"", "empty.png").expect_err("must reject");
339 assert!(
340 matches!(error, ImageAttachError::Empty { .. }),
341 "got {error:?}"
342 );
343 }
344
345 #[test]
346 fn parses_and_rejects_data_urls() {
347 assert_eq!(
348 parse_data_url("data:image/png;base64,QUJD"),
349 Some(("image/png", "QUJD"))
350 );
351 // Not base64-tagged: Anthropic has no shape for a raw data URL.
352 assert_eq!(parse_data_url("data:image/png,QUJD"), None);
353 // Remote URLs are a different source type, not a malformed data URL.
354 assert_eq!(parse_data_url("https://example.com/a.png"), None);
355 // Degenerate forms must not produce an empty base64 payload that the
356 // provider would reject with an opaque error.
357 assert_eq!(parse_data_url("data:;base64,QUJD"), None);
358 assert_eq!(parse_data_url("data:image/png;base64,"), None);
359 assert_eq!(parse_data_url("data:image/png;base64"), None);
360 }
361
362 #[test]
363 fn classifies_remote_urls() {
364 assert!(is_remote_image_url("https://example.com/a.png"));
365 assert!(is_remote_image_url("http://example.com/a.png"));
366 assert!(!is_remote_image_url("data:image/png;base64,QUJD"));
367 assert!(!is_remote_image_url("file:///tmp/a.png"));
368 }
369
370 fn message_with_image(url: &str) -> codewhale_models::Message {
371 codewhale_models::Message {
372 role: Role::User,
373 content: vec![
374 ContentBlock::ImageUrl {
375 image_url: ImageUrlContent {
376 url: url.to_string(),
377 },
378 },
379 ContentBlock::Text {
380 text: "what is this?".to_string(),
381 cache_control: None,
382 },
383 ],
384 }
385 }
386
387 fn write_png(dir: &std::path::Path, name: &str) -> std::path::PathBuf {
388 let path = dir.join(name);
389 std::fs::write(&path, PNG_1X1).expect("write fixture");
390 path
391 }
392
393 #[test]
394 fn expands_a_placeholder_into_an_image_block() {
395 let dir = tempfile::tempdir().expect("tempdir");
396 let path = write_png(dir.path(), "shot.png");
397 let text = format!("look at this\n[Attached image: {}]", path.display());
398
399 let expanded = expand_attachment_blocks(&text);
400
401 assert!(expanded.notices.is_empty(), "{expanded:?}");
402 // Bracketed: open tag naming the path, the image, close tag.
403 assert_eq!(expanded.blocks.len(), 3, "{expanded:?}");
404 match &expanded.blocks[0] {
405 ContentBlock::Text { text, .. } => {
406 assert!(text.starts_with("<image path=\""), "{text}");
407 assert!(text.contains("shot.png"), "{text}");
408 }
409 other => panic!("expected an opening tag, got {other:?}"),
410 }
411 match &expanded.blocks[1] {
412 ContentBlock::ImageUrl { image_url } => {
413 assert!(image_url.url.starts_with("data:image/png;base64,"));
414 }
415 other => panic!("expected an image block, got {other:?}"),
416 }
417 assert_eq!(
418 expanded.blocks[2],
419 ContentBlock::Text {
420 text: "</image>".to_string(),
421 cache_control: None
422 }
423 );
424 }
425
426 #[test]
427 fn expands_multiple_placeholders_in_order() {
428 let dir = tempfile::tempdir().expect("tempdir");
429 let first = write_png(dir.path(), "one.png");
430 let second = write_png(dir.path(), "two.png");
431 std::fs::write(&second, [0xff, 0xd8, 0xff, 0xe0, 0x01]).expect("write jpeg");
432 let text = format!(
433 "[Attached image: {}]\nand\n[Attached image: {}]",
434 first.display(),
435 second.display()
436 );
437
438 let expanded = expand_attachment_blocks(&text);
439
440 let media: Vec<_> = expanded
441 .blocks
442 .iter()
443 .filter_map(|block| match block {
444 ContentBlock::ImageUrl { image_url } => Some(
445 parse_data_url(&image_url.url)
446 .expect("data url")
447 .0
448 .to_string(),
449 ),
450 _ => None,
451 })
452 .collect();
453 assert_eq!(media, vec!["image/png", "image/jpeg"]);
454
455 // Each image carries its own path tag, so the model can tell two
456 // screenshots in one turn apart.
457 let tags: Vec<_> = expanded
458 .blocks
459 .iter()
460 .filter_map(|block| match block {
461 ContentBlock::Text { text, .. } if text.starts_with("<image path=") => {
462 Some(text.clone())
463 }
464 _ => None,
465 })
466 .collect();
467 assert_eq!(tags.len(), 2, "{tags:?}");
468 assert!(tags[0].contains("one.png"), "{tags:?}");
469 assert!(tags[1].contains("two.png"), "{tags:?}");
470 }
471
472 #[test]
473 fn ingest_does_not_consult_model_capability() {
474 // Capability is a route property and is re-decided per request. If
475 // ingest started gating on it, attaching under a text-only model would
476 // destroy the image for the rest of the session.
477 let dir = tempfile::tempdir().expect("tempdir");
478 let path = write_png(dir.path(), "shot.png");
479 let text = format!("[Attached image: {}]", path.display());
480
481 let expanded = expand_attachment_blocks(&text);
482
483 assert_eq!(expanded.blocks.len(), 3);
484 assert!(expanded.notices.is_empty());
485 }
486
487 #[test]
488 fn a_blind_route_gets_text_in_place_of_every_image() {
489 let mut messages = vec![
490 message_with_image("data:image/png;base64,QUJD"),
491 codewhale_models::Message {
492 role: Role::Assistant,
493 content: vec![ContentBlock::Text {
494 text: "sure".to_string(),
495 cache_control: None,
496 }],
497 },
498 ];
499
500 let stripped =
501 strip_images_when_unsupported(&mut messages, SupportState::Unsupported, "deepseek-chat");
502
503 assert_eq!(stripped, 1);
504 assert!(
505 !messages[0]
506 .content
507 .iter()
508 .any(|block| matches!(block, ContentBlock::ImageUrl { .. })),
509 "no image may survive to a route that cannot read one"
510 );
511 match &messages[0].content[0] {
512 ContentBlock::Text { text, .. } => {
513 assert!(text.contains("deepseek-chat"), "{text}");
514 assert!(text.contains("/model"), "{text}");
515 assert!(text.contains("omitted"), "{text}");
516 }
517 other => panic!("expected replacement text, got {other:?}"),
518 }
519 }
520
521 #[test]
522 fn a_supported_or_unknown_route_keeps_its_images() {
523 // Unknown is the common case: models.dev has no modality data for most
524 // routes. Stripping there would make the feature dead on arrival for
525 // self-hosted and custom providers.
526 for vision in [SupportState::Supported, SupportState::Unknown] {
527 let mut messages = vec![message_with_image("data:image/png;base64,QUJD")];
528
529 let stripped = strip_images_when_unsupported(&mut messages, vision, "some-model");
530
531 assert_eq!(stripped, 0, "{vision:?} must not strip");
532 assert!(
533 messages[0]
534 .content
535 .iter()
536 .any(|block| matches!(block, ContentBlock::ImageUrl { .. })),
537 "{vision:?} must keep the image"
538 );
539 }
540 }
541
542 #[test]
543 fn offline_seed_route_for_a_vision_model_keeps_the_image() {
544 // #6396: the bundled seed lists Claude as text-only. An offline cold
545 // start resolves the route from that seed alone; the image must still go.
546 let route = codewhale_config::route::RouteResolver::new()
547 .resolve(&codewhale_config::route::RouteRequest {
548 explicit_provider: Some(codewhale_config::ProviderKind::Anthropic),
549 model_selector: Some(codewhale_config::route::LogicalModelRef::from(
550 "claude-opus-5",
551 )),
552 saved_provider_model: None,
553 base_url_override: None,
554 limit_overrides: Vec::new(),
555 wire_override: None,
556 responses_profile_override: None,
557 })
558 .expect("bundled Anthropic route resolves offline");
559 let mut messages = vec![message_with_image("data:image/png;base64,QUJD")];
560
561 let stripped = strip_images_when_unsupported(
562 &mut messages,
563 route.capabilities().image_input,
564 "claude-opus-5",
565 );
566
567 assert_eq!(stripped, 0);
568 }
569
570 #[test]
571 fn stripping_replaces_every_image_across_every_message() {
572 let mut messages = vec![
573 message_with_image("data:image/png;base64,AAAA"),
574 message_with_image("data:image/jpeg;base64,BBBB"),
575 ];
576
577 let stripped = strip_images_when_unsupported(&mut messages, SupportState::Unsupported, "blind");
578
579 assert_eq!(
580 stripped, 2,
581 "a per-message early return would miss the second"
582 );
583 }
584
585 #[test]
586 fn a_missing_file_becomes_a_notice_not_a_dropped_turn() {
587 let text = "[Attached image: /nonexistent/definitely-not-here.png]";
588
589 let expanded = expand_attachment_blocks(text);
590
591 assert!(expanded.blocks.is_empty());
592 assert_eq!(expanded.notices.len(), 1);
593 assert!(
594 expanded.notices[0].contains("definitely-not-here.png"),
595 "{:?}",
596 expanded.notices
597 );
598 }
599
600 #[test]
601 fn one_bad_attachment_does_not_suppress_a_good_one() {
602 let dir = tempfile::tempdir().expect("tempdir");
603 let good = write_png(dir.path(), "good.png");
604 let text = format!(
605 "[Attached image: /nope/missing.png]\n[Attached image: {}]",
606 good.display()
607 );
608
609 let expanded = expand_attachment_blocks(&text);
610
611 assert_eq!(expanded.blocks.len(), 3);
612 assert_eq!(expanded.notices.len(), 1);
613 }
614
615 #[test]
616 fn video_attachments_are_left_as_text() {
617 let text = "[Attached video: /tmp/clip.mp4]";
618
619 let expanded = expand_attachment_blocks(text);
620
621 assert!(expanded.blocks.is_empty(), "{expanded:?}");
622 assert!(expanded.notices.is_empty(), "{expanded:?}");
623 }
624
625 #[test]
626 fn text_with_no_attachments_produces_nothing() {
627 let expanded = expand_attachment_blocks("just a normal question");
628 assert!(expanded.blocks.is_empty());
629 assert!(expanded.notices.is_empty());
630 }
631
632 #[test]
633 fn notice_block_names_the_failure_and_forbids_guessing() {
634 assert_eq!(notice_block(&[]), None);
635 let block =
636 notice_block(&["Cannot attach a.png: the file is empty".to_string()]).expect("block");
637 match block {
638 ContentBlock::Text { text, .. } => {
639 assert!(text.contains("<attachment_notice>"), "{text}");
640 assert!(text.contains("a.png"), "{text}");
641 assert!(text.contains("Do not describe"), "{text}");
642 }
643 other => panic!("expected text, got {other:?}"),
644 }
645 }
646
647 #[test]
648 fn attach_from_path_reports_an_unreadable_file() {
649 let error = attach_image_from_path(Path::new("/nonexistent/x.png")).expect_err("must fail");
650 assert!(
651 matches!(error, ImageAttachError::Unreadable { .. }),
652 "got {error:?}"
653 );
654 }
655
656 #[test]
657 fn runtime_image_validation_preserves_exact_bytes_and_rejects_corruption() {
658 let input = runtime_image_fixture(7);
659 let blocks = prepare_runtime_images(std::slice::from_ref(&input)).unwrap();
660 assert_eq!(
661 runtime_images_from_blocks(&blocks).unwrap().as_slice(),
662 std::slice::from_ref(&input)
663 );
664 for bad in [
665 codewhale_app_server_protocol::runtime::RuntimeImageInput {
666 mime: "image/jpeg".into(),
667 ..input.clone()
668 },
669 codewhale_app_server_protocol::runtime::RuntimeImageInput {
670 data_base64: "not base64".into(),
671 ..input.clone()
672 },
673 codewhale_app_server_protocol::runtime::RuntimeImageInput {
674 data_base64: String::new(),
675 ..input.clone()
676 },
677 // Existing signature sniffing alone accepted this truncated PNG.
678 codewhale_app_server_protocol::runtime::RuntimeImageInput {
679 data_base64: STANDARD.encode(b"\x89PNG\r\n\x1a\n"),
680 ..input.clone()
681 },
682 ] {
683 assert!(prepare_runtime_images(&[bad]).is_err());
684 }
685 }
686
687 #[test]
688 fn runtime_image_validation_bounds_count_encoded_size_and_decode_dimensions() {
689 let input = runtime_image_fixture(7);
690 assert!(prepare_runtime_images(&vec![input.clone(); 11]).is_err());
691 assert!(
692 prepare_runtime_images(
693 &[codewhale_app_server_protocol::runtime::RuntimeImageInput {
694 data_base64: "A".repeat(MAX_IMAGE_BYTES.div_ceil(3) * 4 + 1),
695 ..input
696 }]
697 )
698 .is_err()
699 );
700 let wide = image::DynamicImage::ImageRgba8(image::RgbaImage::new(MAX_IMAGE_DIMENSION + 1, 1));
701 let mut bytes = std::io::Cursor::new(Vec::new());
702 wide.write_to(&mut bytes, image::ImageFormat::Png).unwrap();
703 let input = codewhale_app_server_protocol::runtime::RuntimeImageInput {
704 mime: "image/png".into(),
705 data_base64: STANDARD.encode(bytes.into_inner()),
706 };
707 assert!(prepare_runtime_images(&[input]).is_err());
708 }
709
710 #[test]
711 fn runtime_image_network_four_mib_and_historical_five_mib_bounds_are_distinct() {
712 let at_network_limit = runtime_image_fixture_bytes(MAX_RUNTIME_IMAGE_BYTES);
713 assert!(prepare_runtime_images(&[at_network_limit]).is_ok());
714 let historical = runtime_image_fixture_bytes(MAX_RUNTIME_IMAGE_BYTES + 1);
715 assert!(prepare_runtime_images(std::slice::from_ref(&historical)).is_err());
716 let stored = prepare_stored_images(std::slice::from_ref(&historical)).unwrap();
717 assert_eq!(runtime_images_from_blocks(&stored).unwrap(), [historical]);
718 assert!(prepare_stored_images(&[runtime_image_fixture_bytes(MAX_IMAGE_BYTES)]).is_ok());
719 assert!(prepare_stored_images(&[runtime_image_fixture_bytes(MAX_IMAGE_BYTES + 1)]).is_err());
720 let three_mib = runtime_image_fixture_bytes(3 * 1024 * 1024);
721 assert!(prepare_runtime_images(&[three_mib.clone(), three_mib.clone()]).is_err());
722 assert!(prepare_stored_images(&[three_mib.clone(), three_mib]).is_ok());
723 assert!(prepare_stored_images(&vec![runtime_image_fixture(1); 11]).is_ok());
724 }
725
726 fn noise_png(width: u32, height: u32) -> Vec<u8> {
727 // A cheap xorshift so the PNG does not compress: a stand-in for a busy
728 // Retina screenshot that exceeds the 5 MiB inline limit as PNG.
729 let mut state = 0x2545_f491_u32;
730 let buffer = image::RgbImage::from_fn(width, height, |_, _| {
731 state ^= state << 13;
732 state ^= state >> 17;
733 state ^= state << 5;
734 // Low-amplitude gray noise: too busy for PNG, like screenshot
735 // texture, yet flat enough to stay on the PNG rungs once fitted.
736 let level = 96 + (state & 15) as u8;
737 image::Rgb([level, level, level])
738 });
739 let mut bytes = Vec::new();
740 image::DynamicImage::ImageRgb8(buffer)
741 .write_to(
742 &mut std::io::Cursor::new(&mut bytes),
743 image::ImageFormat::Png,
744 )
745 .expect("encode noise png");
746 bytes
747 }
748
749 fn attached_dimensions(attached: &AttachedImage) -> (u32, u32) {
750 let (_, payload) = parse_data_url(&attached.data_url).expect("data url");
751 let bytes = STANDARD.decode(payload).expect("base64");
752 image::load_from_memory(&bytes)
753 .expect("decodable attachment")
754 .to_rgb8()
755 .dimensions()
756 }
757
758 #[test]
759 fn oversized_screenshot_is_downscaled_at_attach_time() {
760 let png = noise_png(2880, 1800);
761 assert!(
762 png.len() > MAX_IMAGE_BYTES,
763 "fixture must exceed the inline limit"
764 );
765 let dir = tempfile::tempdir().expect("tempdir");
766 let path = dir.path().join("retina.png");
767 std::fs::write(&path, &png).expect("write fixture");
768
769 let attached = attach_image_from_path(&path).expect("large screenshot attaches");
770 assert!(attached.source_bytes <= MAX_IMAGE_BYTES);
771 let (width, height) = attached_dimensions(&attached);
772 assert_eq!(width, ATTACH_MAX_EDGE_PX);
773 assert!(
774 (1279..=1281).contains(&height),
775 "aspect ratio is kept: {height}"
776 );
777 }
778
779 #[test]
780 fn small_file_with_a_long_edge_is_fitted_to_the_attach_edge() {
781 let wide = image::RgbImage::from_pixel(4000, 200, image::Rgb([30, 30, 30]));
782 let mut png = Vec::new();
783 image::DynamicImage::ImageRgb8(wide)
784 .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
785 .expect("encode");
786 assert!(png.len() < MAX_IMAGE_BYTES);
787 let dir = tempfile::tempdir().expect("tempdir");
788 let path = dir.path().join("wide.png");
789 std::fs::write(&path, &png).expect("write fixture");
790
791 let attached = attach_image_from_path(&path).expect("attach");
792 assert_eq!(attached.media_type, "image/png", "flat content stays PNG");
793 let (width, height) = attached_dimensions(&attached);
794 assert_eq!(width, ATTACH_MAX_EDGE_PX);
795 assert!(
796 (102..=103).contains(&height),
797 "aspect ratio is kept: {height}"
798 );
799 }
800
801 #[test]
802 fn small_image_attaches_byte_for_byte() {
803 let dir = tempfile::tempdir().expect("tempdir");
804 let path = dir.path().join("dot.png");
805 std::fs::write(&path, PNG_1X1).expect("write fixture");
806 let attached = attach_image_from_path(&path).expect("attach");
807 let (_, payload) = parse_data_url(&attached.data_url).expect("data url");
808 assert_eq!(STANDARD.decode(payload).expect("base64"), PNG_1X1);
809 }
810
811 #[test]
812 fn only_images_since_the_latest_prompt_count_as_this_turns() {
813 let image = || ContentBlock::ImageUrl {
814 image_url: ImageUrlContent {
815 url: "data:image/png;base64,AAAA".to_string(),
816 },
817 };
818 let text = |text: &str| ContentBlock::Text {
819 text: text.to_string(),
820 cache_control: None,
821 };
822 let old_turn = codewhale_models::Message {
823 role: Role::User,
824 content: vec![text("earlier screenshot"), image()],
825 };
826 let reply = codewhale_models::Message {
827 role: Role::Assistant,
828 content: vec![text("seen")],
829 };
830 let prompt = |content| codewhale_models::Message {
831 role: Role::User,
832 content,
833 };
834 let tool_image = codewhale_models::Message {
835 role: Role::User,
836 content: vec![ContentBlock::ToolResult {
837 execution_id: None,
838 tool_use_id: "call".to_string(),
839 content: "Read image".to_string(),
840 is_error: None,
841 content_blocks: Some(vec![serde_json::json!({"type": "image"})]),
842 }],
843 };
844
845 let history_only = vec![old_turn.clone(), reply.clone(), prompt(vec![text("go on")])];
846 assert_eq!(images_since_last_user_prompt(&history_only), 0);
847
848 let fresh = vec![
849 old_turn,
850 reply,
851 prompt(vec![text("look"), image()]),
852 tool_image,
853 ];
854 assert_eq!(images_since_last_user_prompt(&fresh), 2);
855 }
856
857 /// The founder's failing drop: a macOS screencaptureui temp file whose name
858 /// has spaces, delivered as a shell-escaped path.
859 fn dropped_screenshot(dir: &std::path::Path) -> std::path::PathBuf {
860 write_png(dir, "Screenshot 2026-10-04 at 22.25.47.png")
861 }
862
863 #[cfg(not(windows))]
864 #[test]
865 fn a_dropped_path_in_every_terminal_spelling_is_an_image() {
866 let dir = tempfile::tempdir().expect("tempdir");
867 let shot = dropped_screenshot(dir.path());
868 let plain = shot.display().to_string();
869 let escaped = plain.replace(' ', "\\ ");
870 let file_url = url::Url::from_file_path(&shot)
871 .expect("file url")
872 .to_string();
873 assert!(file_url.contains("%20"), "{file_url}");
874
875 for spelling in [
876 escaped.clone(),
877 plain.clone(),
878 format!("\"{plain}\""),
879 format!("'{plain}'"),
880 file_url,
881 format!(" {escaped}\n"),
882 ] {
883 assert_eq!(
884 pasted_image_paths(&spelling),
885 Some(vec![shot.clone()]),
886 "{spelling}"
887 );
888 }
889 }
890
891 #[cfg(not(windows))]
892 #[test]
893 fn several_dropped_images_attach_in_order() {
894 let dir = tempfile::tempdir().expect("tempdir");
895 let shot = dropped_screenshot(dir.path());
896 let second = write_png(dir.path(), "second.png");
897 let text = format!(
898 "{} {}",
899 shot.display().to_string().replace(' ', "\\ "),
900 second.display()
901 );
902 assert_eq!(pasted_image_paths(&text), Some(vec![shot, second]));
903 }
904
905 #[test]
906 fn a_paste_that_is_not_only_image_paths_stays_text() {
907 let dir = tempfile::tempdir().expect("tempdir");
908 let shot = dropped_screenshot(dir.path());
909 let notes = dir.path().join("notes.txt");
910 std::fs::write(&notes, "hello").expect("write notes");
911 let escaped = shot.display().to_string().replace(' ', "\\ ");
912
913 for text in [
914 format!("look at {escaped}"),
915 "shot.png".to_string(),
916 notes.display().to_string(),
917 dir.path().join("missing.png").display().to_string(),
918 format!("{escaped} {}", notes.display()),
919 String::new(),
920 ] {
921 assert_eq!(pasted_image_paths(&text), None, "{text}");
922 }
923 }
924
925 #[cfg(not(windows))]
926 #[test]
927 fn a_dropped_screenshot_becomes_an_image_part_or_a_text_only_notice() {
928 let dir = tempfile::tempdir().expect("tempdir");
929 let shot = dropped_screenshot(dir.path());
930 let paths = pasted_image_paths(&shot.display().to_string().replace(' ', "\\ "))
931 .expect("dropped path is an image");
932 let text = format!(
933 "what is wrong here?\n[Attached image: {}]",
934 paths[0].display()
935 );
936
937 let expanded = expand_attachment_blocks(&text);
938 assert!(expanded.notices.is_empty(), "{expanded:?}");
939 let mut messages = vec![codewhale_models::Message {
940 role: Role::User,
941 content: expanded.blocks,
942 }];
943 assert!(
944 messages[0]
945 .content
946 .iter()
947 .any(|block| matches!(block, ContentBlock::ImageUrl { image_url } if image_url.url.starts_with("data:image/png;base64,"))),
948 "a vision route receives the image itself"
949 );
950
951 let stripped =
952 strip_images_when_unsupported(&mut messages, SupportState::Unsupported, "text-only-model");
953 assert_eq!(stripped, 1);
954 assert!(messages[0].content.iter().any(|block| matches!(
955 block,
956 ContentBlock::Text { text, .. } if text.contains("text-only-model") && text.contains("does not accept image input")
957 )));
958 }
959
960 #[test]
961 fn only_an_image_the_user_attached_is_admitted_outside_the_workspace() {
962 let dir = tempfile::tempdir().expect("tempdir");
963 let shot = dropped_screenshot(dir.path());
964 let other = write_png(dir.path(), "other.png");
965 let text = |text: String| ContentBlock::Text {
966 text,
967 cache_control: None,
968 };
969 let messages = vec![
970 codewhale_models::Message {
971 role: Role::User,
972 content: vec![text(format!("see\n[Attached image: {}]", shot.display()))],
973 },
974 codewhale_models::Message {
975 role: Role::Assistant,
976 content: vec![text(format!("[Attached image: {}]", other.display()))],
977 },
978 ];
979
980 let references = user_attached_image_references(&messages);
981 assert_eq!(references, vec![shot.display().to_string()]);
982 let canonical = std::fs::canonicalize(&shot).expect("canonical");
983 assert_eq!(
984 resolve_user_attached_image(&references, &shot.display().to_string()),
985 Some(canonical)
986 );
987 assert_eq!(
988 resolve_user_attached_image(&references, &other.display().to_string()),
989 None,
990 "model-authored text never widens what a read may open"
991 );
992 assert_eq!(
993 resolve_user_attached_image(&references, "Screenshot.png"),
994 None
995 );
996
997 std::fs::write(&shot, b"no longer an image").expect("overwrite");
998 assert_eq!(
999 resolve_user_attached_image(&references, &shot.display().to_string()),
1000 None,
1001 "admission requires image bytes, not just an attached name"
1002 );
1003 }
1004
1005 #[test]
1006 fn read_downscales_an_oversized_screenshot_instead_of_omitting_it() {
1007 let png = noise_png(2880, 1800);
1008 assert!(png.len() > MAX_IMAGE_BYTES, "fixture must exceed the limit");
1009
1010 let prepared = prepare_tool_image_bytes(&png, "image/png");
1011 let codewhale_tools::ToolResultContentBlock::Image { mime_type, data } = prepared
1012 .block
1013 .expect("oversized screenshot is still delivered");
1014 let bytes = STANDARD.decode(data).expect("base64");
1015 assert!(bytes.len() <= crate::tools::read_media::READ_IMAGE_BYTE_BUDGET);
1016 assert_eq!(sniff_media_type(&bytes), Some(mime_type.as_str()));
1017 assert!(prepared.note.contains("re-encoded"), "{}", prepared.note);
1018 }
1019
1020 #[cfg(not(windows))]
1021 #[test]
1022 fn a_message_that_starts_with_a_dropped_image_attaches_it_and_keeps_the_question() {
1023 let dir = tempfile::tempdir().expect("tempdir");
1024 let shot = dropped_screenshot(dir.path());
1025 let plain = shot.display().to_string();
1026 let escaped = plain.replace(' ', "\\ ");
1027 let question = "why does it show jobs 2?";
1028
1029 for message in [
1030 format!("{escaped} {question}"),
1031 format!("{plain} {question}"),
1032 format!("'{plain}' {question}"),
1033 format!("{escaped}\n{question}"),
1034 ] {
1035 assert_eq!(
1036 leading_dropped_image(&message),
1037 Some((shot.clone(), question.to_string())),
1038 "{message}"
1039 );
1040 }
1041 assert_eq!(leading_dropped_image(&escaped), Some((shot, String::new())));
1042 }
1043
1044 #[test]
1045 fn a_message_that_only_mentions_an_image_is_left_alone() {
1046 let dir = tempfile::tempdir().expect("tempdir");
1047 let shot = dropped_screenshot(dir.path());
1048 let notes = dir.path().join("notes.txt");
1049 std::fs::write(&notes, "hello").expect("write notes");
1050
1051 for message in [
1052 format!("look at {}", shot.display()),
1053 format!("{} what is this", notes.display()),
1054 format!("{} what is this", dir.path().join("missing.png").display()),
1055 "/model".to_string(),
1056 "shot.png what".to_string(),
1057 ] {
1058 assert_eq!(leading_dropped_image(&message), None, "{message}");
1059 }
1060 }
1061
1061 lines RUST