lucida 1.1.0

Generate images and video with Google Gemini, Veo, Runway, Kling, a local ComfyUI, FLUX, Stability AI or OpenAI — a CLI and an MCP server
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
//! OpenAI — `gpt-image-1`, and the only provider here that can mask.
//!
//! Demoted to last in the roadmap on the grounds that it is a one-off whose
//! parameter model shares little with the others, and that reasoning held: no
//! seed, no negative prompt, no sampler, and a geometry model unlike any of the
//! four before it. It earns its place for one thing the roadmap named correctly
//! from the start — **mask-based editing** — which is the capability that finally
//! forced `ImageRequest` to grow a way of saying "this region of this image".
//!
//! # Two shapes nobody else has
//!
//! **Geometry is three fixed pixel sizes**, not ratios and not free dimensions:
//! `1024x1024`, `1024x1536`, `1536x1024`, plus `auto`. Read out of the API's own
//! validation error. They correspond to 1:1, 2:3 and 3:2, so Lucida presents
//! them as named ratios and translates — but the pixel count is not adjustable,
//! which is the same conclusion Stability forced for a different reason.
//!
//! **Two endpoints with different encodings.** Generation is JSON; editing is
//! `multipart/form-data`, because it carries files. Every other provider uses
//! one encoding for both.
//!
//! # The one genuinely reassuring thing
//!
//! **Unknown parameters are rejected, not ignored.** `seed` and `negative_prompt`
//! both come back as `Unknown parameter`, which is the opposite of Stability
//! silently dropping whatever it does not recognise. Capabilities here could
//! therefore be established by asking rather than by rendering.

use crate::provider::{
    AspectSupport, Capabilities, GeneratedImage, ImageProvider, ImageRequest, MaskSupport,
    Provenance,
};
use anyhow::{Context, Result, anyhow, bail};
use base64::{Engine as _, engine::general_purpose::STANDARD};
use serde_json::{Value, json};
use std::path::Path;
use std::time::Duration;

const API_ROOT: &str = "https://api.openai.com/v1";

/// The newest of the family, verified working, and the best at masking.
///
/// Measured against `gpt-image-1.5` on the same source and mask:
/// `gpt-image-2` concentrated 4.5x more change inside the mask than outside,
/// against 2.0x — and changed only 10.9/255 outside it, against 29.1. Neither
/// binds the mask, but the difference is large enough to decide the default.
///
/// **A 400 does not prove access.** Validation runs before the entitlement
/// check, so invalid-parameter errors come back for models a project cannot use.
/// Only a successful call, or a 403, settles it — worth remembering, because a
/// validation error reads exactly like proof that the model is reachable.
pub const DEFAULT_MODEL: &str = "gpt-image-2";

/// Latent grid for `gpt-image-2`, from its own validation error: "width and
/// height must both be divisible by 16".
const PIXEL_GRID: u32 = 16;

/// Target area for `gpt-image-2`, in pixels.
///
/// Sized by AREA rather than by long edge, which is a sixth geometry model
/// across five providers. The reason is a constraint that appears in no
/// documentation: a request below "the current minimum pixel budget" is
/// rejected, and long-edge sizing quietly falls under it as the ratio widens —
/// 16:9 at a 1024 long edge is 0.59 MP and refused, while the same long edge at
/// 1:1 is 1.05 MP and fine. Holding the area constant makes every ratio behave
/// the same way, which is what someone changing `--aspect` expects anyway.
const TARGET_AREA: u32 = 1024 * 1024;

/// The ratios the three supported pixel sizes correspond to.
pub const ASPECT_RATIOS: &[&str] = &["1:1", "2:3", "3:2"];

/// Quality tier when none is asked for.
///
/// Deliberately not the API's own default of `auto`, which resolves upward and
/// bills accordingly. A stated middling default is friendlier than an unstated
/// expensive one, and this is a provider where the difference is real money.
const DEFAULT_QUALITY: &str = "medium";

pub const MODEL_ALIASES: &[(&str, &str)] = &[
    ("openai", "gpt-image-2"),
    ("gpt-image", "gpt-image-2"),
    ("oai", "gpt-image-2"),
];

/// Measured against the live API, which distinguishes "no access" (403) from
/// "does not exist" (400) — a distinction worth exploiting, because it maps the
/// catalogue without an entitlement.
///
/// **DALL·E is gone.** `dall-e-3` and `dall-e-2` both report *does not exist*,
/// not merely no access, so the aliases that pointed at them were shipping a
/// dead end. Removed rather than kept as a courtesy.
pub const KNOWN_MODELS: &[&str] = &[
    "gpt-image-2",
    "chatgpt-image-latest",
    "gpt-image-1.5",
    "gpt-image-1-mini",
    "gpt-image-1",
];

/// Whether a model takes free dimensions rather than the three fixed sizes.
///
/// `gpt-image-2` alone: "width and height must both be divisible by 16", where
/// its siblings accept only 1024x1024, 1024x1536, 1536x1024 and auto. The same
/// per-model divergence BFL forced, arriving again in a different provider —
/// which is now less a surprise than a pattern.
fn free_dimensions(model: &str) -> bool {
    model == "gpt-image-2"
}

pub fn resolve_model(input: &str) -> String {
    let key = input.trim().to_ascii_lowercase();
    MODEL_ALIASES
        .iter()
        .find(|(alias, _)| *alias == key)
        .map(|(_, id)| (*id).to_string())
        .unwrap_or(key)
}

pub fn capabilities(model: &str) -> Capabilities {
    let id = resolve_model(model);
    let free = free_dimensions(&id);

    Capabilities {
        provider: "openai",
        // The masking claim is gone from here on purpose. It read "the ONLY
        // provider that can mask an edit to part of an image", which was the
        // reason this provider was added and was false from v0.9.0 — while
        // sitting in the one field whose doc comment says it lives beside the
        // capabilities so that it stays true. Whether a provider masks, and what
        // its mask means, is generated from `mask` below; a tagline says why
        // someone would pick this provider over another that also does.
        tagline: "gpt-image. Paid, seconds, and the fastest way to mask an edit — \
                  no local server, no model download. No seed and no negative \
                  prompt at all; gpt-image-2 takes free dimensions while the rest \
                  take three fixed sizes.",
        aspect: if free {
            AspectSupport::Free {
                multiple_of: PIXEL_GRID,
            }
        } else {
            AspectSupport::Named(ASPECT_RATIOS)
        },
        // Only gpt-image-2 lets the pixel count be chosen; its siblings offer
        // three fixed sizes, so asking for one there is an error not a rounding.
        size: free,
        // Rejected outright by the API: "Unknown parameter: 'seed'".
        seed: false,
        // Likewise "Unknown parameter: 'negative_prompt'".
        negative_prompt: false,
        references: true,
        // Advisory on every model in the family, and the numbers differ only in
        // degree: gpt-image-2 concentrates 4.5x, gpt-image-1.5 twice, and both
        // regenerate the rest of the picture. Nothing here builds the graph, so
        // there is no way to make it bind — see `comfy.rs` for the one that does.
        mask: MaskSupport::Advisory,
        workflow: false,
        steps: false,
        guidance: false,
        // Measured on a real gpt-image-1.5 render: a caBX chunk carrying a C2PA
        // manifest asserting trainedAlgorithmicMedia, and no SynthID. Third
        // provider in this category — marked, but only in metadata.
        provenance: Provenance::C2paOnly,
    }
}

pub struct Client {
    key: String,
    http: reqwest::blocking::Client,
    /// `API_ROOT` in production; a recorded-response server in tests.
    base: String,
}

impl Client {
    pub fn from_env() -> Result<Self> {
        let key = crate::config::var("OPENAI_API_KEY").ok_or_else(|| {
            let where_to_put_it = match crate::config::preferred_path() {
                Some(path) => format!(
                    "Set OPENAI_API_KEY, or add it to {} — \
                     `lucida config --set OPENAI_API_KEY` prompts for it and shows \
                     asterisks rather than the value.",
                    path.display()
                ),
                None => "Set OPENAI_API_KEY.".to_string(),
            };
            anyhow!("no OpenAI API key found.\n\n{where_to_put_it}")
        })?;

        let http = reqwest::blocking::Client::builder()
            .timeout(Duration::from_secs(300))
            .connect_timeout(crate::retry::CONNECT_TIMEOUT)
            .build()
            .context("building HTTP client")?;

        Ok(Self {
            key,
            http,
            base: API_ROOT.to_string(),
        })
    }

    /// Maps a requested ratio onto one of the three sizes the API accepts.
    ///
    /// `auto` when nothing was asked for, which lets the model choose a shape to
    /// suit the prompt — a genuinely useful default that no other provider here
    /// offers.
    /// The aspect an edit should keep when none was asked for.
    ///
    /// `auto` lets the model choose a shape from the prompt, which is a good
    /// default for a fresh image and a bad one for an edit: gpt-image-1-mini
    /// turned a 1024x1024 source into 1024x1536, reshaping a picture nobody
    /// asked to reshape. So an edit with no stated geometry follows its source,
    /// which is what the local lane and BFL already do.
    fn implied_aspect(req: &ImageRequest) -> Option<crate::provider::Aspect> {
        if req.aspect.is_some() || req.references.is_empty() {
            return req.aspect;
        }
        let first = req.references.first()?;
        let bytes = std::fs::read(first).ok()?;
        // Sniffed from the bytes rather than the name: guessing JPEG for every
        // non-.png reference meant a .webp source failed dimension-reading and
        // silently fell back to `auto` — the reshaping this exists to prevent.
        let mime = crate::sniff_mime(&bytes)?;
        let (w, h) = crate::image_dimensions(&bytes, mime)?;
        Some(crate::provider::Aspect { w, h })
    }

    fn size_for(req: &ImageRequest, model: &str) -> String {
        let asked = Self::implied_aspect(req);

        if free_dimensions(model) {
            // Nothing asked for still means `auto`, which lets the model choose a
            // shape to suit the prompt — worth keeping rather than imposing a
            // square by default.
            if asked.is_none() && req.size.is_none() {
                return "auto".to_string();
            }
            let scoped = ImageRequest {
                aspect: asked,
                ..req.clone()
            };
            let (w, h) = area_dimensions(&scoped, TARGET_AREA);
            return format!("{w}x{h}");
        }

        match asked.map(|a| (a.w, a.h)) {
            None => "auto".to_string(),
            Some((w, h)) if w == h => "1024x1024".to_string(),
            Some((w, h)) if w > h => "1536x1024".to_string(),
            Some(_) => "1024x1536".to_string(),
        }
    }

    fn generate_fresh(&self, req: &ImageRequest, model: &str) -> Result<Vec<u8>> {
        let body = json!({
            "model": model,
            "prompt": req.prompt,
            "size": Self::size_for(req, model),
            "quality": DEFAULT_QUALITY,
            "output_format": "png",
            "n": 1,
        });

        let response = self
            .http
            .post(format!("{}/images/generations", self.base))
            .header("Authorization", format!("Bearer {}", self.key))
            .json(&body)
            .send()
            .context("calling the OpenAI image API")?;

        self.decode(response, model)
    }

    /// Editing, with an optional mask.
    ///
    /// Multipart rather than JSON because the images travel as files. The mask
    /// is a PNG whose **transparent** pixels mark what to change — the inverse of
    /// what most people assume, and worth stating in the error rather than
    /// letting someone edit the wrong half of a picture.
    ///
    /// **The mask is advisory, and how advisory depends on the model.** Measured
    /// on one source with one mask:
    ///
    /// | model | inside | outside | concentration |
    /// |---|---|---|---|
    /// | `gpt-image-1.5` | 58.0/255 | 29.1/255 | 2.0x |
    /// | `gpt-image-2` | 49.2/255 | 10.9/255 | 4.5x |
    ///
    /// Neither confines the edit — `gpt-image-1.5` lost an object nowhere near
    /// the mask — but `gpt-image-2` leaves the rest of the picture far closer to
    /// untouched, which is why it is the default.
    fn edit(&self, req: &ImageRequest, model: &str) -> Result<Vec<u8>> {
        let mut form = reqwest::blocking::multipart::Form::new()
            .text("model", model.to_string())
            .text("prompt", req.prompt.clone())
            .text("size", Self::size_for(req, model))
            .text("quality", DEFAULT_QUALITY)
            // Explicit, matching generate_fresh, rather than trusting the
            // endpoint's default to stay PNG. Probed 2026-08-02: /images/edits
            // accepts output_format (png, webp, jpeg) — its validation error
            // names all three — so the PNG this result is reported as is now
            // the PNG that was asked for.
            .text("output_format", "png");

        for path in &req.references {
            // `image[]` rather than `image`: gpt-image-1 accepts several, and the
            // singular form silently keeps only the last.
            form = form.part("image[]", file_part(path)?);
        }
        if let Some(mask) = &req.mask {
            form = form.part("mask", file_part(mask)?);
        }

        let response = self
            .http
            .post(format!("{}/images/edits", self.base))
            .header("Authorization", format!("Bearer {}", self.key))
            .multipart(form)
            .send()
            .context("calling the OpenAI image edit API")?;

        self.decode(response, model)
    }

    /// Pulls the image out of a response, or explains why there is not one.
    fn decode(&self, response: reqwest::blocking::Response, model: &str) -> Result<Vec<u8>> {
        let status = response.status();
        if !status.is_success() {
            let text = response.text().unwrap_or_default();
            bail!("{}", explain_error(status.as_u16(), &text, model));
        }

        let payload: Value = response.json().context("parsing the API response")?;

        // gpt-image-1 always returns base64; the older models can return a URL
        // instead, so both are handled rather than assuming the modern shape.
        let first = &payload["data"][0];
        if let Some(encoded) = first["b64_json"].as_str() {
            return STANDARD.decode(encoded).context("decoding the image");
        }
        if let Some(url) = first["url"].as_str() {
            let bytes = crate::retry::send_idempotent("downloading the image", || self.http.get(url))
                .with_context(|| {
                    format!(
                        "downloading the generated image. The render was billed; \
                         its URL expires shortly:\n\n  {url}"
                    )
                })?
                .bytes()
                .context("reading image bytes")?;
            return Ok(bytes.to_vec());
        }

        bail!("the response contained no image: {payload}")
    }
}

impl ImageProvider for Client {
    fn list_models(&self) -> Result<Vec<String>> {
        // `/v1/models` does not list image models for a project key even when
        // they work — measured, and confusing enough to be worth saying rather
        // than reporting an empty list.
        let response = crate::retry::send_idempotent("checking the key", || {
            self.http
                .get(format!("{}/models", self.base))
                .header("Authorization", format!("Bearer {}", self.key))
        })
        .context("checking the OpenAI key")?;

        let status = response.status();
        if !status.is_success() {
            let text = response.text().unwrap_or_default();
            bail!("{}", explain_error(status.as_u16(), &text, "models"));
        }

        eprintln!(
            "Key is valid. Note /v1/models does not list image models even when \
             they are usable, so the list below is Lucida's own."
        );
        Ok(KNOWN_MODELS.iter().map(|m| (*m).to_string()).collect())
    }

    fn generate(&self, req: &ImageRequest) -> Result<GeneratedImage> {
        let model = resolve_model(&req.model);
        let size = Self::size_for(req, &model);

        let bytes = if req.references.is_empty() {
            eprintln!("Rendering {size} with {model} (quality {DEFAULT_QUALITY})…");
            self.generate_fresh(req, &model)?
        } else {
            let scope = match &req.mask {
                Some(mask) => format!("masked by {mask}"),
                None => "whole image".to_string(),
            };
            eprintln!(
                "Editing {} reference(s), {scope}, {size} with {model}…",
                req.references.len()
            );
            self.edit(req, &model)?
        };

        Ok(GeneratedImage {
            bytes,
            mime_type: "image/png".to_string(),
            commentary: None,
            // No seed exists to report; the API rejects the parameter outright.
            seed: None,
        })
    }
}

/// Dimensions holding `target` pixels at the requested ratio, on the 16-grid.
///
/// `--size` scales the budget rather than setting an edge: asking for 2K on a
/// provider measured in area means "about four times the pixels", which is the
/// only reading that keeps a ratio change from also changing the resolution.
fn area_dimensions(req: &ImageRequest, target: u32) -> (u32, u32) {
    let ratio = req.aspect.map_or(1.0, |a| f64::from(a.w) / f64::from(a.h));

    // A requested long edge is honoured as a scale on the budget, since there is
    // no edge to set directly.
    let target = match req.size {
        Some(size) => {
            let scale = f64::from(size.0) / 1024.0;
            (f64::from(target) * scale * scale) as u32
        }
        None => target,
    };

    let height = (f64::from(target) / ratio).sqrt();
    let width = height * ratio;

    let round = |v: f64| {
        let n = ((v / f64::from(PIXEL_GRID)).round() as u32).max(1);
        n * PIXEL_GRID
    };
    (round(width), round(height))
}

fn file_part(path: &str) -> Result<reqwest::blocking::multipart::Part> {
    let bytes = std::fs::read(path).with_context(|| format!("reading {path}"))?;
    let name = Path::new(path)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("image.png")
        .to_string();
    let mime = if name.to_ascii_lowercase().ends_with(".webp") {
        "image/webp"
    } else if name.to_ascii_lowercase().ends_with(".jpg")
        || name.to_ascii_lowercase().ends_with(".jpeg")
    {
        "image/jpeg"
    } else {
        "image/png"
    };
    reqwest::blocking::multipart::Part::bytes(bytes)
        .file_name(name)
        .mime_str(mime)
        .context("attaching the image")
}

/// Turns an OpenAI error body into something worth reading.
///
/// Their shape is `{"error": {"message", "type", "param", "code"}}` — a fifth
/// distinct shape across five providers, which is itself worth noting: there is
/// no common error format to normalize toward.
pub fn explain_error(status: u16, body: &str, model: &str) -> String {
    let parsed: Value = serde_json::from_str(body).unwrap_or(Value::Null);
    let error = &parsed["error"];
    let message = error["message"].as_str().unwrap_or(body.trim());
    let param = error["param"].as_str().unwrap_or_default();

    match status {
        401 => format!(
            "HTTP 401 — the OpenAI API key was rejected: {message}\n\n\
             Check OPENAI_API_KEY, or run `lucida config` to see what this process \
             can read."
        ),
        // Measured: this arrives naming the *project*, not the organisation.
        // OpenAI gates models per project, so enabling one org-wide does not
        // reach a project created before or outside that change — and the first
        // message here blamed organisation verification, which sent the reader
        // to the wrong settings page entirely.
        403 => format!(
            "HTTP 403 — this project may not use `{model}`.\n\n{message}\n\n\
             Model access on OpenAI is granted PER PROJECT, not per organisation \
             or per key. In the console open the project named above, then \
             Limits (or Model permissions) and enable `{model}` for that project \
             specifically. Enabling it org-wide, or having billing active, does \
             not do this on its own.\n\n\
             If the project name is not one you recognise, the key belongs to a \
             different project than you edited — check which key `lucida config` \
             is reading."
        ),
        429 => format!(
            "HTTP 429 — rate limited or out of quota: {message}\n\n\
             Check the billing dashboard; OpenAI reports both conditions here."
        ),
        400 if param == "mask" => format!(
            "HTTP 400 — the mask was rejected: {message}\n\n\
             A mask must be a PNG with an alpha channel, the same dimensions as \
             the image it applies to, and under 4 MB. Note the sense of it: the \
             **transparent** pixels are the part that gets changed."
        ),
        400 => format!("HTTP 400 — {message}"),
        _ => format!("HTTP {status} — {message}"),
    }
}

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

    fn with_aspect(text: &str) -> ImageRequest {
        ImageRequest {
            aspect: Some(Aspect::parse(text).unwrap()),
            ..Default::default()
        }
    }

    /// Three fixed sizes, picked by shape. Not a rounding of a requested pixel
    /// count — there is no pixel count to request.
    #[test]
    fn ratios_map_onto_the_three_supported_sizes() {
        let m = "gpt-image-1.5";
        assert_eq!(Client::size_for(&with_aspect("1:1"), m), "1024x1024");
        assert_eq!(Client::size_for(&with_aspect("3:2"), m), "1536x1024");
        assert_eq!(Client::size_for(&with_aspect("16:9"), m), "1536x1024");
        assert_eq!(Client::size_for(&with_aspect("2:3"), m), "1024x1536");
        assert_eq!(Client::size_for(&with_aspect("9:16"), m), "1024x1536");
        // Nothing asked for lets the model choose, which no other provider offers.
        assert_eq!(Client::size_for(&ImageRequest::default(), m), "auto");
    }

    /// gpt-image-2 diverges from its own siblings, which is the BFL lesson
    /// arriving in a second provider: capabilities are a property of the model.
    #[test]
    fn gpt_image_2_takes_free_dimensions() {
        assert_eq!(Client::size_for(&ImageRequest::default(), "gpt-image-2"), "auto");
        assert!(capabilities("gpt-image-2").size);
        assert!(!capabilities("gpt-image-1.5").size);
        assert!(!capabilities("gpt-image-1").size);
    }

    /// Every ratio must clear the undocumented pixel-budget floor. Long-edge
    /// sizing did not: 16:9 came out 1024x576, which the API refuses while
    /// accepting 1024x1024 at the same long edge.
    #[test]
    fn every_ratio_holds_roughly_the_same_area() {
        for ratio in ["1:1", "16:9", "9:16", "21:9", "3:2", "2:3"] {
            let (w, h) = area_dimensions(&with_aspect(ratio), TARGET_AREA);
            let area = w * h;
            assert_eq!(w % 16, 0, "{ratio} width off-grid");
            assert_eq!(h % 16, 0, "{ratio} height off-grid");
            assert!(
                area > 900_000,
                "{ratio} came out {w}x{h} = {area}px, under the budget that 16:9 \
                 originally tripped"
            );
            // …and not wildly over, or a wide ratio silently costs more.
            assert!(area < 1_250_000, "{ratio} came out {w}x{h} = {area}px");
        }
    }

    /// An edit with no stated geometry follows its source rather than letting
    /// the model choose: gpt-image-1-mini turned a square source into a portrait,
    /// reshaping a picture nobody asked to reshape.
    #[test]
    fn an_edit_keeps_the_sources_shape() {
        let dir = std::env::temp_dir().join("lucida-openai-shape-test");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("wide.png");
        // A minimal PNG header is enough: only IHDR is read.
        let mut png = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
        png.extend_from_slice(&13u32.to_be_bytes());
        png.extend_from_slice(b"IHDR");
        png.extend_from_slice(&1536u32.to_be_bytes());
        png.extend_from_slice(&1024u32.to_be_bytes());
        std::fs::write(&path, &png).unwrap();

        let edit = ImageRequest {
            references: vec![path.to_string_lossy().into_owned()],
            ..Default::default()
        };
        // 3:2 source, so the landscape size rather than `auto`.
        assert_eq!(Client::size_for(&edit, "gpt-image-1.5"), "1536x1024");

        // A fresh image still lets the model choose.
        assert_eq!(
            Client::size_for(&ImageRequest::default(), "gpt-image-1.5"),
            "auto"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The format comes from the bytes, not the filename: a PNG named `.webp`
    /// used to be read as JPEG, fail, and silently fall back to `auto` — and a
    /// real WebP source failed the same way for lacking a parser at all.
    #[test]
    fn a_sources_shape_survives_a_lying_or_webp_filename() {
        let dir = std::env::temp_dir().join("lucida-openai-sniff-test");
        std::fs::create_dir_all(&dir).unwrap();

        // PNG bytes behind a .webp name.
        let misnamed = dir.join("wide.webp");
        let mut png = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
        png.extend_from_slice(&13u32.to_be_bytes());
        png.extend_from_slice(b"IHDR");
        png.extend_from_slice(&1536u32.to_be_bytes());
        png.extend_from_slice(&1024u32.to_be_bytes());
        std::fs::write(&misnamed, &png).unwrap();

        let edit = ImageRequest {
            references: vec![misnamed.to_string_lossy().into_owned()],
            ..Default::default()
        };
        assert_eq!(Client::size_for(&edit, "gpt-image-1.5"), "1536x1024");

        // An actual WebP (lossy layout), portrait.
        let real = dir.join("tall.webp");
        let mut webp = b"RIFF\0\0\0\0WEBPVP8 ".to_vec();
        webp.extend_from_slice(&[0; 4]);
        webp.extend_from_slice(&[0; 3]);
        webp.extend_from_slice(&[0x9D, 0x01, 0x2A]);
        webp.extend_from_slice(&1024u16.to_le_bytes());
        webp.extend_from_slice(&1536u16.to_le_bytes());
        std::fs::write(&real, &webp).unwrap();

        let edit = ImageRequest {
            references: vec![real.to_string_lossy().into_owned()],
            ..Default::default()
        };
        assert_eq!(Client::size_for(&edit, "gpt-image-1.5"), "1024x1536");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// `--size` scales the budget, since there is no edge to set.
    #[test]
    fn size_scales_the_area_budget() {
        let big = ImageRequest {
            size: Some(crate::provider::Size::TWO_K),
            ..with_aspect("1:1")
        };
        let (w, h) = area_dimensions(&big, TARGET_AREA);
        // 2K means twice the edge, so about four times the pixels.
        assert!((w as f64 - 2048.0).abs() < 32.0, "got {w}x{h}");
    }

    /// DALL·E reports "does not exist", not "no access" — it is retired, and
    /// pointing an alias at it would ship a dead end.
    #[test]
    fn dall_e_is_not_offered() {
        assert!(!KNOWN_MODELS.iter().any(|m| m.contains("dall")));
        assert!(!MODEL_ALIASES.iter().any(|(_, t)| t.contains("dall")));
    }

    /// Masking is no longer unique to this provider, and the pair is worth
    /// pinning rather than the exclusivity.
    ///
    /// This test used to assert openai was the only provider that masks — the
    /// capability that justified it existing at all. That stopped being true
    /// when the local lane learned to inpaint, and the interesting fact now is
    /// the *difference*: openai's mask is advisory, measured at 4.5x
    /// concentration with the rest of the frame still moving, while comfyui's
    /// is binding because Lucida builds that graph and composites the render
    /// back through the mask — measured at 0.00/255 outside it.
    ///
    /// It also used to ask that question in a message rather than in the type,
    /// and the answer was carried in prose on seven surfaces while `mask` stayed
    /// a `bool`. Six of them still said "advisory" a release after the local
    /// lane began to bind. Now the kind *is* the capability, so this asserts the
    /// variants and a third masking provider has to pick one.
    #[test]
    fn exactly_two_providers_mask_and_they_differ_in_kind() {
        use crate::provider::{Backend, MaskSupport, capabilities_for, mask_providers};

        let masking: Vec<&str> = Backend::ALL
            .iter()
            .filter(|b| capabilities_for(**b, b.default_model()).mask.accepted())
            .map(|b| b.name())
            .collect();

        assert_eq!(
            masking,
            vec!["comfyui", "openai"],
            "the set of masking providers changed; is the new one advisory or binding?"
        );

        assert_eq!(mask_providers(MaskSupport::Binding), vec!["comfyui"]);
        assert_eq!(mask_providers(MaskSupport::Advisory), vec!["openai"]);
        assert_eq!(capabilities("gpt-image-1").mask, MaskSupport::Advisory);
    }

    /// Both were measured as rejected rather than ignored, so declaring them
    /// false is a fact rather than a caution.
    #[test]
    fn neither_seed_nor_negative_prompt_exists() {
        let caps = capabilities("gpt-image-1");
        assert!(!caps.seed);
        assert!(!caps.negative_prompt);
        assert!(!caps.size);
    }

    /// Measured against the live API: the 403 names the project, and the fix is
    /// a per-project setting. The first version of this message blamed
    /// organisation verification and would have sent the reader to the wrong
    /// page — plausible, and wrong.
    #[test]
    fn a_403_points_at_per_project_model_access() {
        let body = r#"{"error":{"message":"Project `proj_x` does not have access to model `gpt-image-1`","type":"x"}}"#;
        let message = explain_error(403, body, "gpt-image-1");
        assert!(message.contains("PER PROJECT"));
        assert!(message.contains("proj_x"), "must echo the project it named");
        assert!(!message.contains("organisation to be verified"));
    }

    #[test]
    fn a_rejected_mask_explains_which_pixels_change() {
        let body = r#"{"error":{"message":"bad mask","param":"mask","type":"x"}}"#;
        let message = explain_error(400, body, "gpt-image-1");
        assert!(message.contains("transparent"));
        assert!(message.contains("alpha"));
    }

    #[test]
    fn aliases_resolve() {
        assert_eq!(resolve_model("openai"), "gpt-image-2");
        assert_eq!(resolve_model("something-new"), "something-new");
    }

    // --- recorded responses -------------------------------------------------

    use crate::provider::ImageProvider;
    use crate::testserver::{Reply, serve};

    fn wired(server: &crate::testserver::Server) -> Client {
        Client {
            key: "test-key".into(),
            base: server.url().to_string(),
            http: reqwest::blocking::Client::builder()
                .timeout(std::time::Duration::from_secs(10))
                .connect_timeout(crate::retry::CONNECT_TIMEOUT)
                .no_proxy()
                .build()
                .unwrap(),
        }
    }

    fn b64_reply(bytes: &[u8]) -> String {
        format!(r#"{{"data":[{{"b64_json":"{}"}}]}}"#, STANDARD.encode(bytes))
    }

    /// Generation is JSON, and the quality default is Lucida's stated `medium`
    /// rather than the API's `auto` — which resolves upward and bills
    /// accordingly, so its presence on the wire is worth a test.
    #[test]
    fn generation_is_json_with_the_stated_quality_default() {
        let server = serve(vec![Reply::json(&b64_reply(b"png-bytes"))]);

        let request = ImageRequest {
            prompt: "a fox".into(),
            model: "gpt-image-2".into(),
            ..Default::default()
        };
        let image = wired(&server).generate(&request).unwrap();
        assert_eq!(image.bytes, b"png-bytes");
        assert_eq!(image.seed, None, "no seed exists to report");

        let requests = server.finish();
        assert_eq!(requests[0].method, "POST");
        assert_eq!(requests[0].path, "/images/generations");
        assert_eq!(requests[0].header("authorization"), Some("Bearer test-key"));
        let body = requests[0].json();
        assert_eq!(body["model"], "gpt-image-2");
        assert_eq!(body["quality"], "medium");
        assert_eq!(body["output_format"], "png");
        assert_eq!(body["n"], 1);
        assert_eq!(body["size"], "auto", "nothing asked for lets the model choose");
    }

    /// An edit switches encodings entirely: multipart, `image[]` fields (the
    /// singular form silently keeps only the last), the mask as its own part,
    /// and a size implied by the source rather than `auto`.
    #[test]
    fn an_edit_is_multipart_with_the_sources_implied_size() {
        let dir = std::env::temp_dir().join("lucida-openai-wire-test");
        std::fs::create_dir_all(&dir).unwrap();
        let source = dir.join("square.png");
        let mut png = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
        png.extend_from_slice(&13u32.to_be_bytes());
        png.extend_from_slice(b"IHDR");
        png.extend_from_slice(&1024u32.to_be_bytes());
        png.extend_from_slice(&1024u32.to_be_bytes());
        std::fs::write(&source, &png).unwrap();
        let mask = dir.join("mask.png");
        std::fs::write(&mask, b"mask-bytes").unwrap();

        let server = serve(vec![Reply::json(&b64_reply(b"edited"))]);
        let request = ImageRequest {
            prompt: "make it night".into(),
            model: "gpt-image-1.5".into(),
            references: vec![source.to_string_lossy().into_owned()],
            mask: Some(mask.to_string_lossy().into_owned()),
            ..Default::default()
        };
        let image = wired(&server).generate(&request).unwrap();
        assert_eq!(image.bytes, b"edited");

        let requests = server.finish();
        assert_eq!(requests[0].path, "/images/edits");
        let body = requests[0].body_text();
        assert!(body.contains("name=\"image[]\""), "plural field, or extras are dropped");
        assert!(body.contains("name=\"mask\""));
        assert!(body.contains("filename=\"square.png\""));
        // Probed: the edits endpoint takes output_format, so the reported PNG
        // must be requested rather than assumed from the endpoint's default.
        assert!(body.contains("name=\"output_format\""));
        // The regression this pins: an edit follows its source's shape rather
        // than sending `auto` and letting the model reshape the picture.
        assert!(body.contains("name=\"size\""));
        assert!(body.contains("1024x1024"), "a square source implies the square size");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Older models may answer with a URL instead of inline base64. The download
    /// is a signed URL, so — as with BFL — it must carry no credential.
    #[test]
    fn a_url_response_is_downloaded_without_the_key() {
        let listing = r#"{"data":[{"url":"{{server}}/dl/img.png"}]}"#;
        let server = serve(vec![
            Reply::json(listing),
            Reply::bytes("image/png", b"downloaded"),
        ]);
        let request = ImageRequest {
            prompt: "a fox".into(),
            model: "gpt-image-1".into(),
            ..Default::default()
        };
        let image = wired(&server).generate(&request).unwrap();
        assert_eq!(image.bytes, b"downloaded");

        let requests = server.finish();
        assert_eq!(requests[1].path, "/dl/img.png");
        assert_eq!(requests[1].header("authorization"), None);
    }
}