aacode-rs 1.8.15

Rust port of the AACode ReAct coding agent, built on fastshell for mobile AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
// Copyright (c) 2026 xiefujin <490021684@qq.com>
// Licensed under GPL-3.0, see LICENSE file for full license terms.

//! Multimodal tools — understand_image / understand_video / understand_ui_design
//! / analyze_image_consistency.
//!
//! Supports both OpenAI and Anthropic vision formats based on the configured
//! model gateway. Uses `reqwest` async HTTP for vision API calls.

use super::registry::Tool;
use super::schema::{ParamType, ToolParameter, ToolSchema};
use crate::config::{Gateway, ModelConfig};
use crate::error::Result;
use base64::Engine;
use image::{GenericImageView, ImageEncoder};
use serde_json::{json, Value};
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};
use std::time::Duration;

/// Connect timeout for HTTP client (seconds). Separate from the total request
/// timeout so DNS/TCP hang is detected quickly rather than waiting for the
/// full request deadline.
const CONNECT_TIMEOUT_SECS: u64 = 10;

/// Maximum short-side pixel dimension before an image is downscaled.
/// Most vision models (GPT-4V, Claude, Kimi) recommend ≤ 1024 px for
/// cost/performance; sticking to this keeps uploads fast on mobile.
const MAX_IMAGE_DIMENSION: u32 = 1024;

/// JPEG quality for resized photos (trade-off between size and visual fidelity).
const JPEG_QUALITY: u8 = 80;

/// Downsize and re-encode an image if it exceeds `max_dim` on its short side.
/// Photos (JPEG / WebP / HEIC) are re-encoded as JPEG; screenshots / UI mocks
/// (PNG / BMP) stay as PNG to preserve text sharpness.
///
/// Never panics — on any failure the original bytes and MIME are returned
/// unchanged so downstream processing is not affected.
fn prepare_image(bytes: &[u8], ext: &str, max_dim: u32) -> (Vec<u8>, &'static str) {
    let original_mime = ext_to_mime(ext);

    // GIF — don't touch; frames would be lost, and GIFs are typically small.
    if ext == "gif" {
        return (bytes.to_vec(), original_mime);
    }

    let img = match image::load_from_memory(bytes) {
        Ok(v) => v,
        Err(_) => return (bytes.to_vec(), original_mime),
    };

    let (w, h) = img.dimensions();
    let short = w.min(h);
    if short <= max_dim {
        return (bytes.to_vec(), original_mime);
    }

    // Scale so the short side equals max_dim, preserving aspect ratio.
    let ratio = max_dim as f64 / short as f64;
    let new_w = (w as f64 * ratio).round() as u32;
    let new_h = (h as f64 * ratio).round() as u32;
    let resized = img.resize_exact(new_w, new_h, image::imageops::FilterType::Lanczos3);

    let is_photo = matches!(ext, "jpg" | "jpeg" | "webp" | "heic" | "heif");
    if is_photo {
        let rgb = resized.to_rgb8();
        let mut buf = Vec::new();
        let encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buf, JPEG_QUALITY);
        if encoder
            .write_image(
                &rgb,
                rgb.width(),
                rgb.height(),
                image::ExtendedColorType::Rgb8,
            )
            .is_ok()
        {
            return (buf, "image/jpeg");
        }
    } else {
        let rgba = resized.to_rgba8();
        let mut buf = Vec::new();
        let encoder = image::codecs::png::PngEncoder::new(&mut buf);
        if encoder
            .write_image(
                &rgba,
                rgba.width(),
                rgba.height(),
                image::ExtendedColorType::Rgba8,
            )
            .is_ok()
        {
            return (buf, "image/png");
        }
    }

    // Encoding failed — return originals.
    (bytes.to_vec(), original_mime)
}

fn ext_to_mime(ext: &str) -> &'static str {
    match ext {
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "webp" => "image/webp",
        "bmp" => "image/bmp",
        _ => "image/png",
    }
}

/// Shared config for the multimodal tools.
#[derive(Clone)]
pub struct MultimodalCtx {
    pub model: Option<ModelConfig>,
    pub project_path: PathBuf,
    pub timeout_secs: u64,
    /// Lazily-initialised shared HTTP client.
    client: Arc<Mutex<Option<reqwest::Client>>>,
}

impl MultimodalCtx {
    pub fn new(model: Option<ModelConfig>, project_path: PathBuf, timeout_secs: u64) -> Self {
        MultimodalCtx {
            model,
            project_path,
            timeout_secs,
            client: Arc::new(Mutex::new(None)),
        }
    }
    fn resolve_path(&self, p: &str) -> PathBuf {
        let path = PathBuf::from(p);
        if path.is_absolute() {
            path
        } else {
            self.project_path.join(p)
        }
    }

    async fn image_data_uri(&self, path: &str) -> Option<String> {
        let full = self.resolve_path(path);
        let ext = full
            .extension()
            .map(|e| e.to_string_lossy().to_lowercase())
            .unwrap_or_else(|| "png".into());
        let bytes = tokio::task::spawn_blocking(move || std::fs::read(&full))
            .await
            .ok()?
            .ok()?;
        let (img_bytes, mime) = prepare_image(&bytes, &ext, MAX_IMAGE_DIMENSION);
        let b64 = base64::engine::general_purpose::STANDARD.encode(&img_bytes);
        Some(format!("data:{mime};base64,{b64}"))
    }

    async fn vision_chat(&self, prompt: &str, image_paths: &[&str]) -> Result<String> {
        let model = self.model.as_ref().ok_or_else(|| {
            crate::error::AacodeError::Config(
                "no multimodal (vision) model configured — set a vision-capable model in Settings (multimodal model) to use image/vision tools"
                    .into(),
            )
        })?;
        let is_anthropic = model.gateway == Gateway::Anthropic;
        let timeout_secs = model.request_timeout_secs.unwrap_or(self.timeout_secs);

        let endpoint = if is_anthropic {
            let base = model.resolved_base_url();
            if base.contains("minimax") || base.contains("deepseek") || base.contains("moonshot") {
                format!("{}/anthropic/v1/messages", base.trim_end_matches('/'))
            } else {
                format!("{}/v1/messages", base.trim_end_matches('/'))
            }
        } else {
            format!(
                "{}/chat/completions",
                model.resolved_base_url().trim_end_matches('/')
            )
        };

        let (body, auth_name, auth_val, anthropic_ver) = if is_anthropic {
            self.build_anthropic_body(model, prompt, image_paths)
                .await?
        } else {
            self.build_openai_body(model, prompt, image_paths).await?
        };

        async fn do_vision(
            client: &reqwest::Client,
            endpoint: &str,
            body: &Value,
            auth_name: &str,
            auth_val: &str,
            anthropic_ver: &str,
            is_anthropic: bool,
        ) -> Result<String> {
            let mut req = client
                .post(endpoint)
                .header(auth_name, auth_val)
                .header("Content-Type", "application/json");
            if !anthropic_ver.is_empty() {
                req = req.header("anthropic-version", anthropic_ver);
            }
            let resp = req.json(body).send().await.map_err(|e| {
                crate::error::AacodeError::Network(format!("vision: {}", error_chain_display(&e)))
            })?;
            if !resp.status().is_success() {
                let code = resp.status().as_u16();
                let msg = resp.text().await.unwrap_or_default();
                return Err(crate::error::AacodeError::Api(format!(
                    "vision HTTP {code}: {}",
                    truncate(&msg, 300)
                )));
            }
            let v: Value = resp.json().await.map_err(|e| {
                crate::error::AacodeError::Network(format!(
                    "vision response: {}",
                    error_chain_display(&e)
                ))
            })?;
            Ok(extract_text(&v, is_anthropic))
        }

        let client = self.get_or_init_http_client(timeout_secs)?;
        do_vision(
            &client,
            &endpoint,
            &body,
            &auth_name,
            &auth_val,
            &anthropic_ver,
            is_anthropic,
        )
        .await
    }

    async fn build_openai_body(
        &self,
        model: &ModelConfig,
        prompt: &str,
        image_paths: &[&str],
    ) -> Result<(Value, String, String, String)> {
        let api_key = model
            .api_key
            .clone()
            .filter(|k| !k.trim().is_empty())
            .ok_or_else(|| {
                crate::error::AacodeError::Config("multimodal api key missing".into())
            })?;
        let mut parts: Vec<Value> = vec![json!({"type":"text","text":prompt})];
        for p in image_paths {
            match self.image_data_uri(p).await {
                Some(uri) => parts.push(json!({"type":"image_url","image_url":{"url":uri}})),
                None => {
                    return Err(crate::error::AacodeError::Io(format!(
                        "cannot read image: {p}"
                    )))
                }
            }
        }
        let body = json!({"model":model.name,"messages":[{"role":"user","content":parts}],"max_tokens":model.max_tokens});
        Ok((
            body,
            "Authorization".into(),
            format!("Bearer {api_key}"),
            String::new(),
        ))
    }

    async fn build_anthropic_body(
        &self,
        model: &ModelConfig,
        prompt: &str,
        image_paths: &[&str],
    ) -> Result<(Value, String, String, String)> {
        let api_key = model
            .api_key
            .clone()
            .filter(|k| !k.trim().is_empty())
            .ok_or_else(|| {
                crate::error::AacodeError::Config("multimodal api key missing".into())
            })?;
        let mut blocks: Vec<Value> = Vec::new();
        for p in image_paths {
            let uri = self
                .image_data_uri(p)
                .await
                .ok_or_else(|| crate::error::AacodeError::Io(format!("cannot read image: {p}")))?;
            let (media_type, b64) = parse_data_uri(&uri);
            blocks.push(json!({"type":"image","source":{"type":"base64","media_type":media_type,"data":b64}}));
        }
        blocks.push(json!({"type":"text","text":prompt}));
        let body = json!({"model":model.name,"max_tokens":model.max_tokens,"messages":[{"role":"user","content":blocks}]});
        Ok((body, "x-api-key".into(), api_key, "2023-06-01".into()))
    }
    fn get_or_init_http_client(&self, timeout_secs: u64) -> Result<reqwest::Client> {
        let mut guard = self.client.lock().unwrap_or_else(|e| e.into_inner());
        if let Some(c) = guard.as_ref() {
            return Ok(c.clone());
        }
        let c = reqwest::Client::builder()
            .connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))
            .timeout(Duration::from_secs(timeout_secs))
            .build()
            .map_err(|e| crate::error::AacodeError::Network(e.to_string()))?;
        *guard = Some(c.clone());
        Ok(c)
    }
}

/// Walk an error's source chain for full diagnostics (e.g. reqwest errors
/// whose Display only says "error sending request for url" while the real
/// cause — timeout / DNS / TLS — is buried in the source).
fn error_chain_display(e: &dyn std::error::Error) -> String {
    let mut s = e.to_string();
    let mut source = e.source();
    while let Some(src) = source {
        s.push_str(": ");
        s.push_str(&src.to_string());
        source = src.source();
    }
    s
}

fn parse_data_uri(uri: &str) -> (String, String) {
    if let Some(rest) = uri.strip_prefix("data:") {
        let parts: Vec<&str> = rest.splitn(2, ';').collect();
        let media = parts
            .first()
            .map(|s| s.to_string())
            .unwrap_or_else(|| "image/png".into());
        let b64 = parts
            .last()
            .map(|s| s.strip_prefix("base64,").unwrap_or(s))
            .unwrap_or(uri)
            .to_string();
        (media, b64)
    } else {
        ("image/png".into(), uri.to_string())
    }
}

fn extract_text(v: &Value, is_anthropic: bool) -> String {
    if is_anthropic {
        v["content"]
            .as_array()
            .and_then(|arr| {
                arr.iter()
                    .find_map(|b| b["text"].as_str().map(|s| s.to_string()))
            })
            .unwrap_or_default()
    } else {
        v["choices"][0]["message"]["content"]
            .as_str()
            .unwrap_or("")
            .to_string()
    }
}

fn truncate(s: &str, n: usize) -> String {
    if s.chars().count() <= n {
        s.to_string()
    } else {
        let h: String = s.chars().take(n).collect();
        format!("{h}...")
    }
}

fn split_paths(s: &str) -> Vec<&str> {
    s.split(',')
        .map(|p| p.trim())
        .filter(|p| !p.is_empty())
        .collect()
}

pub struct UnderstandImageTool {
    pub ctx: MultimodalCtx,
}
#[async_trait::async_trait]
impl Tool for UnderstandImageTool {
    fn schema(&self) -> ToolSchema {
        ToolSchema::new("understand_image","Understand image content (one or more, comma-separated). Analyze screenshots, photos, design drafts.",
            vec![
                ToolParameter::new("image_path",ParamType::String,true,"Image path(s), comma-separated",&["image","path","file"]),
                ToolParameter::new("prompt",ParamType::String,false,"What to ask about the image",&["question","query"]),
            ],
        )
    }
    async fn call(&self, args: &Value, _c: &AtomicBool) -> Result<String> {
        let paths_s = args
            .get("image_path")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let prompt = args
            .get("prompt")
            .and_then(|v| v.as_str())
            .unwrap_or("Describe this image in detail.");
        let paths = split_paths(paths_s);
        if paths.is_empty() {
            return Ok(json!({"success":false,"error":"no image_path"}).to_string());
        }
        match self.ctx.vision_chat(prompt, &paths).await {
            Ok(desc) => Ok(
                json!({"success":true,"description":desc,"images_count":paths.len()}).to_string(),
            ),
            Err(e) => Ok(json!({"success":false,"error":e.to_string()}).to_string()),
        }
    }
}

pub struct UnderstandVideoTool {
    pub ctx: MultimodalCtx,
}
#[async_trait::async_trait]
impl Tool for UnderstandVideoTool {
    fn schema(&self) -> ToolSchema {
        ToolSchema::new(
            "understand_video",
            "Video understanding is not supported yet.",
            vec![
                ToolParameter::new(
                    "video_path",
                    ParamType::String,
                    true,
                    "Video file path",
                    &["video", "path", "file"],
                ),
                ToolParameter::new(
                    "prompt",
                    ParamType::String,
                    false,
                    "What to ask about the video",
                    &["question", "query"],
                ),
            ],
        )
    }
    async fn call(&self, args: &Value, _c: &AtomicBool) -> Result<String> {
        let path = args
            .get("video_path")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        if path.is_empty() {
            return Ok(json!({"success":false,"error":"no video_path"}).to_string());
        }
        Ok(
            json!({"success":false,"error":"video understanding is not supported yet."})
                .to_string(),
        )
    }
}

pub struct UnderstandUiDesignTool {
    pub ctx: MultimodalCtx,
}
#[async_trait::async_trait]
impl Tool for UnderstandUiDesignTool {
    fn schema(&self) -> ToolSchema {
        ToolSchema::new(
            "understand_ui_design",
            "Analyze UI design mockups/screenshots and generate frontend code.",
            vec![
                ToolParameter::new(
                    "design_path",
                    ParamType::String,
                    true,
                    "Path to the design image file",
                    &["design", "image", "path"],
                ),
                ToolParameter::new(
                    "prompt",
                    ParamType::String,
                    false,
                    "What to focus on (e.g., 'generate HTML/CSS')",
                    &["question", "focus"],
                ),
                ToolParameter::new(
                    "generate_code",
                    ParamType::Boolean,
                    false,
                    "Whether to generate frontend code",
                    &["code", "html"],
                ),
            ],
        )
    }
    async fn call(&self, args: &Value, _c: &AtomicBool) -> Result<String> {
        let path = args
            .get("design_path")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        if path.is_empty() {
            return Ok(json!({"success":false,"error":"no design_path"}).to_string());
        }
        let gen_code = args
            .get("generate_code")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let base = args
            .get("prompt")
            .and_then(|v| v.as_str())
            .unwrap_or("Describe this UI design.");
        let prompt = if gen_code {
            format!("{base}. Generate HTML/CSS code for this design.")
        } else {
            base.to_string()
        };
        match self.ctx.vision_chat(&prompt, &[path]).await {
            Ok(desc) => Ok(
                json!({"success":true,"description":desc,"code_generated":gen_code}).to_string(),
            ),
            Err(e) => Ok(json!({"success":false,"error":e.to_string()}).to_string()),
        }
    }
}

pub struct ImageConsistencyTool {
    pub ctx: MultimodalCtx,
}
#[async_trait::async_trait]
impl Tool for ImageConsistencyTool {
    fn schema(&self) -> ToolSchema {
        ToolSchema::new(
            "analyze_image_consistency",
            "Check image consistency (people or objects) across multiple images.",
            vec![
                ToolParameter::new(
                    "image_paths",
                    ParamType::String,
                    true,
                    "Comma-separated image paths (at least 2)",
                    &["images", "paths", "files"],
                ),
                ToolParameter::new(
                    "prompt",
                    ParamType::String,
                    false,
                    "What aspect to check for consistency",
                    &["question", "aspect"],
                ),
            ],
        )
    }
    async fn call(&self, args: &Value, _c: &AtomicBool) -> Result<String> {
        let paths_s = args
            .get("image_paths")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let paths = split_paths(paths_s);
        if paths.len() < 2 {
            return Ok(
                json!({"success":false,"error":"need at least 2 images for consistency check"})
                    .to_string(),
            );
        }
        let prompt = args
            .get("prompt")
            .and_then(|v| v.as_str())
            .unwrap_or("Compare these images and check for consistency.");
        match self.ctx.vision_chat(prompt, &paths).await {
            Ok(desc) => Ok(
                json!({"success":true,"description":desc,"images_count":paths.len()}).to_string(),
            ),
            Err(e) => Ok(json!({"success":false,"error":e.to_string()}).to_string()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn error_chain_display_single() {
        let e = std::io::Error::new(std::io::ErrorKind::TimedOut, "operation timed out");
        let out = error_chain_display(&e);
        assert!(out.contains("operation timed out"));
    }

    #[test]
    fn error_chain_display_source_chain() {
        let inner = std::io::Error::new(std::io::ErrorKind::TimedOut, "operation timed out");
        let outer = std::io::Error::new(std::io::ErrorKind::Other, inner);
        let out = error_chain_display(&outer);
        assert!(
            out.contains("operation timed out"),
            "must include source: {out}"
        );
    }

    #[test]
    fn error_chain_no_source() {
        let e = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let out = error_chain_display(&e);
        assert_eq!(out, "file not found");
    }

    #[test]
    fn truncate_short_enough() {
        assert_eq!(truncate("hi", 10), "hi");
    }

    #[test]
    fn truncate_too_long() {
        let s = "0123456789".repeat(5);
        let out = truncate(&s, 5);
        assert!(out.len() <= 10);
        assert!(out.ends_with("..."));
    }

    #[test]
    fn split_paths_empty() {
        assert!(split_paths("").is_empty());
    }

    #[test]
    fn split_paths_multiple() {
        let v = split_paths("a.jpg, b.png , c.gif");
        assert_eq!(v, vec!["a.jpg", "b.png", "c.gif"]);
    }

    // ── prepare_image tests ──────────────────────────────────────────

    fn make_test_rgba(w: u32, h: u32) -> Vec<u8> {
        let mut img = image::RgbaImage::new(w, h);
        // fill with a simple gradient so it's not blank
        for (x, _y, px) in img.enumerate_pixels_mut() {
            *px = image::Rgba([(x % 256) as u8, 128, 200, 255]);
        }
        let mut buf = Vec::new();
        let enc = image::codecs::png::PngEncoder::new(&mut buf);
        enc.write_image(&img, w, h, image::ExtendedColorType::Rgba8)
            .unwrap();
        buf
    }

    #[test]
    fn prepare_image_resizes_large_photo() {
        let png = make_test_rgba(2048, 1536);
        let (out, mime) = prepare_image(&png, "jpg", MAX_IMAGE_DIMENSION);
        assert_eq!(mime, "image/jpeg");
        // Verify short side is ≤ max_dim after resize
        let decoded = image::load_from_memory(&out).unwrap();
        let (w, h) = decoded.dimensions();
        assert_eq!(w.min(h), MAX_IMAGE_DIMENSION);
    }

    #[test]
    fn prepare_image_resizes_large_screenshot() {
        let png = make_test_rgba(3000, 4000);
        let (out, mime) = prepare_image(&png, "png", MAX_IMAGE_DIMENSION);
        assert_eq!(mime, "image/png");
        let decoded = image::load_from_memory(&out).unwrap();
        let (w, h) = decoded.dimensions();
        assert_eq!(w.min(h), MAX_IMAGE_DIMENSION);
    }

    #[test]
    fn prepare_image_small_unchanged() {
        let png = make_test_rgba(200, 150);
        let (out, mime) = prepare_image(&png, "png", MAX_IMAGE_DIMENSION);
        assert_eq!(mime, "image/png");
        assert_eq!(out, png, "small image must be returned unchanged");
    }

    #[test]
    fn prepare_image_gif_untouched() {
        let png = make_test_rgba(2000, 2000);
        let (out, mime) = prepare_image(&png, "gif", MAX_IMAGE_DIMENSION);
        assert_eq!(mime, "image/gif");
        assert_eq!(out, png, "GIF must be returned unchanged");
    }

    #[test]
    fn prepare_image_invalid_bytes_fallback() {
        let garbage = b"not an image at all";
        let (out, mime) = prepare_image(garbage, "jpg", MAX_IMAGE_DIMENSION);
        assert_eq!(mime, "image/jpeg");
        assert_eq!(
            out,
            garbage.as_slice(),
            "invalid bytes must fall back to original"
        );
    }

    #[test]
    fn prepare_image_webp_to_jpeg() {
        let png = make_test_rgba(3000, 2000);
        let (out, mime) = prepare_image(&png, "webp", MAX_IMAGE_DIMENSION);
        assert_eq!(mime, "image/jpeg");
        let decoded = image::load_from_memory(&out).unwrap();
        let (w, h) = decoded.dimensions();
        assert_eq!(w.min(h), MAX_IMAGE_DIMENSION);
    }
}