eclipse-core 0.13.4

Core library for eclipse: providers, tools, sessions, config, runtime
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
//! OpenAI-compatible chat message types.

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    System,
    User,
    Assistant,
    Tool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FunctionCall {
    pub name: String,
    /// JSON-encoded arguments, exactly as the model produced them.
    pub arguments: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolCall {
    pub id: String,
    #[serde(rename = "type", default = "function_kind")]
    pub kind: String,
    pub function: FunctionCall,
}

fn function_kind() -> String {
    "function".into()
}

/// One picture attached to a message (`#346`).
///
/// The bytes travel *in* the message as a `data:` URL, not as a path. A path is a reference the
/// model resolves with `read_file` — a tool call the user sees — and a stored session has to be
/// able to show what was sent without the file still being where it was. The cap and the type
/// check live where an image enters (`attach`), because this struct is also what a session reads
/// back from disk and re-checking every row on every load would be a cost for no gain.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImagePart {
    /// What the user called it, for the transcript and the compaction placeholder. Empty when a
    /// picture arrives without a name.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub name: String,
    pub mime: String,
    /// `data:<mime>;base64,<…>` — the wire's own spelling of a picture, so nothing has to
    /// reassemble it at request time.
    pub url: String,
    /// What a model that can see said about this picture (`#346`), written once.
    ///
    /// Kept beside the picture rather than in the prompt: a session replayed a week later must not
    /// pay for the same description again, and the prompt for a past turn must not change under the
    /// session that is still talking about it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seen: Option<String>,
}

/// How long a picture's name may be, once it has been cleaned up.
///
/// The name is interpolated into the composed block a model reads (`--- attached picture: NAME
/// (image/png) ---`) and into `label()`, so it is text with a shape, not an arbitrary string: a
/// newline in it could forge one of those delimiters and a control character could end the line
/// the compaction log is reading (`#380`).
const MAX_NAME_CHARS: usize = 100;

/// A name safe to put in a line of text: control characters become spaces, runs of whitespace
/// collapse, and the result is capped. Empty after all that is `picture`.
fn picture_name(raw: &str) -> String {
    let flattened: String = raw
        .chars()
        .map(|c| if c.is_control() { ' ' } else { c })
        .collect();
    let one = flattened.split_whitespace().collect::<Vec<_>>().join(" ");
    if one.is_empty() {
        return "picture".to_string();
    }
    one.chars().take(MAX_NAME_CHARS).collect()
}

/// Base64 to bytes, or `None` for anything that is not base64.
///
/// Hand-rolled because this crate carries no decoder, and the check is worth more than the
/// dependency: the point is to reject a payload that is not a picture *once*, before it is stored
/// and re-sent on every turn, not to be fast. Padding is optional; `=` anywhere but the end is not.
fn decode_base64(payload: &str) -> Option<Vec<u8>> {
    fn value(b: u8) -> Option<u32> {
        Some(match b {
            b'A'..=b'Z' => (b - b'A') as u32,
            b'a'..=b'z' => (b - b'a') as u32 + 26,
            b'0'..=b'9' => (b - b'0') as u32 + 52,
            b'+' => 62,
            b'/' => 63,
            _ => return None,
        })
    }
    let body = payload.trim_end_matches('=');
    if body.len() % 4 == 1 {
        return None;
    }
    let mut out = Vec::with_capacity(body.len() / 4 * 3 + 3);
    let mut acc = 0u32;
    let mut n = 0;
    for byte in body.bytes() {
        acc = (acc << 6) | value(byte)?;
        n += 1;
        if n == 4 {
            out.push((acc >> 16) as u8);
            out.push((acc >> 8) as u8);
            out.push(acc as u8);
            acc = 0;
            n = 0;
        }
    }
    match n {
        0 => {}
        2 => out.push((acc >> 4) as u8),
        3 => {
            out.push((acc >> 10) as u8);
            out.push((acc >> 2) as u8);
        }
        _ => return None,
    }
    Some(out)
}

/// Bytes to a `data:` URL — the other half of [`decode_base64`], and the only encoder this build
/// has. Hand-rolled for the same reason: one picture per attach, not a hot path.
pub fn data_url(mime: &str, bytes: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(24 + bytes.len() / 3 * 4 + 4);
    out.push_str("data:");
    out.push_str(mime);
    out.push_str(";base64,");
    for chunk in bytes.chunks(3) {
        let b = [
            chunk[0],
            chunk.get(1).copied().unwrap_or(0),
            chunk.get(2).copied().unwrap_or(0),
        ];
        let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32;
        out.push(ALPHABET[(n >> 18) as usize & 0x3F] as char);
        out.push(ALPHABET[(n >> 12) as usize & 0x3F] as char);
        out.push(if chunk.len() > 1 {
            ALPHABET[(n >> 6) as usize & 0x3F] as char
        } else {
            '='
        });
        out.push(if chunk.len() > 2 {
            ALPHABET[n as usize & 0x3F] as char
        } else {
            '='
        });
    }
    out
}

/// Whether these bytes begin like the picture the header claims they are.
fn looks_like_picture(mime: &str, bytes: &[u8]) -> bool {
    match mime {
        "image/png" => bytes.starts_with(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]),
        "image/jpeg" => bytes.starts_with(&[0xFF, 0xD8, 0xFF]),
        "image/gif" => bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a"),
        "image/webp" => bytes.len() > 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP",
        _ => false,
    }
}

/// The picture types a message may carry, and how big one may be once decoded.
///
/// Every surface that accepts a picture checks this — the dashboard's composer and the gateway's
/// `image_url` parts alike — because a 40 MB phone photo is a 54 MB data URL that rides in the
/// request body and in every later request's history, and the symptom months later is "the
/// dashboard got slow" (`#346`, `#364`).
pub const PICTURE_TYPES: &[&str] = &["image/png", "image/jpeg", "image/webp", "image/gif"];
/// What one picture may weigh *on the wire*: the request body and every later turn's history.
pub const MAX_PICTURE_BYTES: usize = 2 * 1024 * 1024;
/// What may be *attached* (`#499`). A camera photo is far over the wire limit and is exactly what
/// someone wants to send; the original is kept on disk and a copy under [`MAX_PICTURE_BYTES`] is
/// what the request carries. This is the absolute ceiling — past it the refusal stands, because a
/// 200 MB file is not a picture anyone meant to attach.
pub const MAX_UPLOAD_BYTES: usize = 32 * 1024 * 1024;

impl ImagePart {
    /// A picture from a `data:` URL — the wire's own spelling, and the only one that *is* a
    /// picture. A path is a reference the agent resolves with `read_file` (a tool call the user
    /// sees, and a confinement question), and a link is `fetch`; neither is bytes.
    ///
    /// One sentence per refusal, on every surface: two surfaces wording the same refusal
    /// differently is how one bug gets reported twice (`#364`).
    pub fn from_data_url(name: &str, url: &str) -> Result<Self, String> {
        let name = picture_name(name);
        let url = url.trim();
        let Some(rest) = url.strip_prefix("data:") else {
            return Err(format!(
                "{name}: a picture has to be a base64 data: URL; a path or a link is a reference \
                 the agent resolves itself, not a picture"
            ));
        };
        let Some((meta, payload)) = rest.split_once(',') else {
            return Err(format!("{name}: that data URL has no body"));
        };
        let mut bits = meta.split(';');
        let mime = bits.next().unwrap_or("").to_ascii_lowercase();
        if !bits.any(|bit| bit.eq_ignore_ascii_case("base64")) {
            return Err(format!("{name}: only base64 data URLs are accepted"));
        }
        if !PICTURE_TYPES.contains(&mime.as_str()) {
            return Err(format!(
                "{name}: {mime} is not a picture this build can carry ({}). Convert it.",
                PICTURE_TYPES.join(", ")
            ));
        }
        // The payload is decoded once, here, rather than measured as base64: the length of the
        // encoded text says the size only roughly, and it says nothing at all about whether these
        // bytes are a picture. A bad payload used to be stored for good and re-sent on every turn
        // of the session, where it poisoned each request that carried it (`#381`).
        let decoded = decode_base64(payload)
            .ok_or_else(|| format!("{name}: that data URL is not valid base64"))?;
        if decoded.is_empty() {
            return Err(format!("{name}: that data URL carries no picture"));
        }
        // `#499`: the wire limit is not the attach limit. A picture over it is kept at full size
        // and a copy is sent — so the only refusal left here is a file nobody meant to attach.
        if decoded.len() > MAX_UPLOAD_BYTES {
            return Err(format!(
                "{name}: about {} KB, and a picture may be at most {} MB",
                decoded.len() / 1024,
                MAX_UPLOAD_BYTES / (1024 * 1024)
            ));
        }
        // The header's word for the type is not evidence. A PNG renamed `image/jpeg` is a 400 from
        // the model later, on a turn that already stored it.
        if !looks_like_picture(&mime, &decoded) {
            return Err(format!(
                "{name}: the bytes are not {mime}; the data URL's own type has to match the picture"
            ));
        }
        Ok(Self::new(name, mime, url))
    }

    /// The bytes behind a `data:` URL, or `None` when this part is not one.
    ///
    /// `#499` needs them twice — once to keep the original, once to know how big the copy has to
    /// be — and the URL is the only place they live, so this is the one decoder in the product.
    pub fn bytes(&self) -> Option<Vec<u8>> {
        let rest = self.url.trim().strip_prefix("data:")?;
        let (_, payload) = rest.split_once(',')?;
        decode_base64(payload)
    }

    /// This picture, carrying different bytes — what a working copy replaces.
    pub fn with_data(&self, mime: &str, bytes: &[u8]) -> Self {
        Self {
            name: self.name.clone(),
            mime: mime.to_string(),
            url: data_url(mime, bytes),
            seen: None,
        }
    }

    /// How many bytes the payload holds, without decoding it.
    pub fn payload_len(&self) -> usize {
        self.url
            .trim()
            .split_once(',')
            .map(|(_, payload)| payload.trim_end_matches('=').len() / 4 * 3)
            .unwrap_or(0)
    }

    pub fn new(name: impl Into<String>, mime: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            mime: mime.into(),
            url: url.into(),
            seen: None,
        }
    }

    /// This picture, with the description a seeing model gave of it.
    pub fn with_seen(mut self, text: impl Into<String>) -> Self {
        self.seen = Some(text.into());
        self
    }

    /// What one picture is called in text a model reads when it cannot see it: the compaction
    /// handoff, a transcript line, a refusal sentence.
    pub fn label(&self) -> String {
        let name = if self.name.is_empty() {
            "image"
        } else {
            self.name.as_str()
        };
        format!("[{name} ({})]", self.mime)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    pub role: Role,
    #[serde(default)]
    pub content: Option<String>,
    /// Pictures this message carries (`#346`). Kept apart from `content` so every existing reader
    /// of the text — compaction, memory, the transcript, naming — sees exactly what it saw before
    /// pictures existed, and the wire's parts array is built at request time by `wire_content`.
    /// Skipped when empty, so a text-only message serialises byte-identically to how it always did.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub images: Vec<ImagePart>,
    /// Reasoning/thinking text emitted by reasoning-capable models. Kept so a backend that
    /// needs it round-tripped in the next request can get it — but only included in the
    /// request body when the profile says the backend wants it.
    #[serde(
        rename = "reasoning_content",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub reasoning: Option<String>,
    /// The finish reason the server reported (`stop`, `tool_calls`, `length`, ...). Metadata,
    /// not wire payload: skipped on serialize so history never echoes a lie about the reply.
    #[serde(skip)]
    pub finish_reason: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tool_calls: Vec<ToolCall>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<String>,
    /// The row's sequence number in the session store, when this message was loaded from one.
    /// Not wire payload and not persisted (the row already carries it): it exists so a compiled
    /// handoff can cite `[#N]` and that ref lands on a real row.
    #[serde(skip)]
    pub seq: Option<u64>,
}

/// Two messages are the same when they say the same thing. `seq` is provenance — the row a
/// message came from — not part of its identity, so a message built in a test equals the same
/// message loaded from a session.
impl PartialEq for Message {
    fn eq(&self, other: &Self) -> bool {
        self.role == other.role
            && self.content == other.content
            && self.reasoning == other.reasoning
            && self.finish_reason == other.finish_reason
            && self.tool_calls == other.tool_calls
            && self.tool_call_id == other.tool_call_id
            && self.images == other.images
    }
}

impl Message {
    pub fn system(text: impl Into<String>) -> Self {
        Self::text(Role::System, text)
    }

    pub fn user(text: impl Into<String>) -> Self {
        Self::text(Role::User, text)
    }

    pub fn assistant(text: impl Into<String>) -> Self {
        Self::text(Role::Assistant, text)
    }

    pub fn assistant_tool_calls(content: Option<String>, calls: Vec<ToolCall>) -> Self {
        Self {
            role: Role::Assistant,
            content,
            reasoning: None,
            finish_reason: None,
            tool_calls: calls,
            tool_call_id: None,
            images: Vec::new(),
            seq: None,
        }
    }

    pub fn tool_result(call_id: impl Into<String>, text: impl Into<String>) -> Self {
        Self {
            role: Role::Tool,
            content: Some(text.into()),
            reasoning: None,
            finish_reason: None,
            tool_calls: Vec::new(),
            tool_call_id: Some(call_id.into()),
            images: Vec::new(),
            seq: None,
        }
    }

    /// Attach a picture to this message. Builder-shaped because the usual case is "a user turn
    /// plus what they pasted", and the alternative is every caller spelling out six fields.
    pub fn with_image(mut self, image: ImagePart) -> Self {
        self.images.push(image);
        self
    }

    /// The same message with its pictures removed — what a turn model is sent when the mode says
    /// it must never see bytes (`[vision] mode = "text"`).
    pub fn without_images(mut self) -> Self {
        self.images.clear();
        self
    }

    /// The `content` field as the chat-completions API defines it: a plain string, or — when the
    /// message carries pictures — the array of parts. `None` when the message has neither.
    ///
    /// Only the provider calls this: the store keeps `images` as a key of its own, and a text-only
    /// message is a string here, which is what keeps the wire bytes identical to what they were
    /// before pictures existed (`#346`).
    pub fn wire_content(&self) -> Option<serde_json::Value> {
        if self.images.is_empty() {
            return self.content.clone().map(serde_json::Value::String);
        }
        let mut parts: Vec<serde_json::Value> = Vec::with_capacity(self.images.len() + 1);
        // Text first: the question is what the picture is *for*, and a backend that reads parts in
        // order (most local VLMs do) then reads the prompt before the picture.
        if let Some(text) = self.content.as_ref().filter(|text| !text.is_empty()) {
            parts.push(serde_json::json!({"type": "text", "text": text}));
        }
        for image in &self.images {
            parts.push(serde_json::json!({
                "type": "image_url",
                "image_url": {"url": image.url},
            }));
        }
        Some(serde_json::Value::Array(parts))
    }

    /// What this message says in text, with each picture standing in as `[name (mime)]` and, when
    /// one has already been paid for, the description it was given (`#362`).
    ///
    /// Every reader that has only text — the compaction handoff, the transcript, `session_search`'s
    /// index, the Markdown export, the digest a judgement pass reads — goes through this, so a
    /// picture is never silently dropped from the account of a session, and a compacted turn does
    /// not forget what the picture showed while the description sits unread on the part.
    pub fn text_with_pictures(&self) -> String {
        let mut out = self.content.clone().unwrap_or_default();
        for image in &self.images {
            if !out.is_empty() {
                out.push(' ');
            }
            out.push_str(&image.label());
            if let Some(seen) = image.seen.as_deref().filter(|text| !text.is_empty()) {
                out.push_str(" — ");
                out.push_str(seen);
            }
        }
        out
    }

    fn text(role: Role, text: impl Into<String>) -> Self {
        Self {
            role,
            content: Some(text.into()),
            reasoning: None,
            finish_reason: None,
            tool_calls: Vec::new(),
            tool_call_id: None,
            images: Vec::new(),
            seq: None,
        }
    }
}

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

    /// The whole session history goes through this struct on every request. If adding pictures
    /// changed the JSON of a message with none, every warm prefix cache in the fleet would be
    /// thrown away on upgrade — so this asserts the bytes, not the shape.
    #[test]
    fn a_text_only_message_serialises_exactly_as_it_did_before_pictures_existed() {
        assert_eq!(
            serde_json::to_string(&Message::user("hi")).unwrap(),
            r#"{"role":"user","content":"hi"}"#
        );
        assert_eq!(
            serde_json::to_string(&Message::tool_result("call-1", "ok")).unwrap(),
            r#"{"role":"tool","content":"ok","tool_call_id":"call-1"}"#
        );
    }

    #[test]
    fn a_picture_becomes_an_image_url_part_and_no_key_of_its_own() {
        let m = Message::user("what is this?").with_image(ImagePart::new(
            "shot.png",
            "image/png",
            "data:image/png;base64,iVBORw0KGgo=",
        ));
        let content = m.wire_content().expect("pictures make parts");
        assert_eq!(
            content,
            serde_json::json!([
                {"type": "text", "text": "what is this?"},
                {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}},
            ])
        );
        // The store's shape is not the wire's: the key stays off the wire entirely.
        let stored = serde_json::to_value(&m).unwrap();
        assert_eq!(stored["images"][0]["name"], "shot.png");
        assert!(stored.get("content").is_some());
    }

    #[test]
    fn a_picture_with_no_words_is_a_parts_array_with_only_the_picture() {
        let mut m = Message::user(String::new());
        m.content = None;
        let m = m.with_image(ImagePart::new(
            "",
            "image/png",
            "data:image/png;base64,iVBORw0KGgo=",
        ));
        assert_eq!(
            m.wire_content().unwrap(),
            serde_json::json!([
                {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}}
            ])
        );
    }

    #[test]
    fn an_empty_text_does_not_become_an_empty_text_part() {
        // A text part holding "" is a part some backends reject, and it says nothing.
        let m = Message::user("").with_image(ImagePart::new(
            "a.png",
            "image/png",
            "data:image/png;base64,iVBORw0KGgo=",
        ));
        let parts = m.wire_content().unwrap();
        assert_eq!(parts.as_array().unwrap().len(), 1);
        assert_eq!(parts[0]["type"], "image_url");
    }

    #[test]
    fn stripping_the_pictures_leaves_the_words() {
        let m = Message::user("look")
            .with_image(ImagePart::new(
                "a.png",
                "image/png",
                "data:image/png;base64,iVBORw0KGgo=",
            ))
            .without_images();
        assert!(m.images.is_empty());
        assert_eq!(m.wire_content().unwrap(), serde_json::json!("look"));
    }

    #[test]
    fn the_text_form_names_each_picture_instead_of_dropping_it() {
        let m = Message::user("look").with_image(ImagePart::new(
            "shot.png",
            "image/png",
            "data:image/png;base64,iVBORw0KGgo=",
        ));
        assert_eq!(m.text_with_pictures(), "look [shot.png (image/png)]");
        // Two messages are the same only when they carry the same pictures.
        assert_ne!(Message::user("look"), m);
    }

    /// `#362`: the description is part of what the message says, not a private field on the part.
    /// Every reader that only has text — the handoff, the transcript, the search index — reads
    /// this, so an already-paid-for description cannot fall out of the account of a session.
    #[test]
    fn the_text_form_carries_the_description_the_picture_was_given() {
        let m = Message::user("what is this?").with_image(
            ImagePart::new(
                "shot.png",
                "image/png",
                "data:image/png;base64,iVBORw0KGgo=",
            )
            .with_seen("a red square with the word STOP"),
        );
        let text = m.text_with_pictures();
        assert!(text.contains("what is this?"), "{text}");
        assert!(text.contains("[shot.png (image/png)]"), "{text}");
        assert!(text.contains("a red square with the word STOP"), "{text}");

        // A picture with no words of its own is not nothing: the label is what says a turn had one.
        let bare = Message::user("").with_image(ImagePart::new(
            "shot.png",
            "image/png",
            "data:image/png;base64,iVBORw0KGgo=",
        ));
        assert_eq!(bare.text_with_pictures(), "[shot.png (image/png)]");
    }

    /// `#379`, `#380`: the name is text with a shape. It is interpolated into a `--- … ---` block
    /// a model reads and into `label()`, so a newline could forge a delimiter and a control
    /// character could end the line the compaction log reads.
    #[test]
    fn a_picture_name_is_flattened_and_capped() {
        let part = ImagePart::from_data_url(
            "a\n--- end of x ---\u{7}\tb",
            "data:image/png;base64,iVBORw0KGgo=",
        )
        .unwrap();
        assert_eq!(part.name, "a --- end of x --- b");
        let long = ImagePart::from_data_url(&"n".repeat(500), "data:image/png;base64,iVBORw0KGgo=")
            .unwrap();
        assert_eq!(long.name.chars().count(), MAX_NAME_CHARS);
        // A name that is nothing at all is still a name a person can read.
        let unnamed =
            ImagePart::from_data_url("   ", "data:image/png;base64,iVBORw0KGgo=").unwrap();
        assert_eq!(unnamed.name, "picture");
    }

    /// `#381`: a payload is decoded once, here, so an empty, invalid or mislabelled picture is
    /// refused before it is stored and re-sent on every turn of the session.
    #[test]
    fn a_payload_that_is_not_a_picture_is_refused() {
        // Nothing after the comma used to pass: the size bound was arithmetic on zero.
        let err = ImagePart::from_data_url("x.png", "data:image/png;base64,").unwrap_err();
        assert!(err.contains("carries no picture"), "{err}");
        // Not base64 at all.
        let err = ImagePart::from_data_url("x.png", "data:image/png;base64,!!!!").unwrap_err();
        assert!(err.contains("not valid base64"), "{err}");
        // Valid base64, real bytes, wrong type in the header.
        let err =
            ImagePart::from_data_url("x.png", "data:image/jpeg;base64,iVBORw0KGgo=").unwrap_err();
        assert!(err.contains("the bytes are not image/jpeg"), "{err}");
        // And the honest one is accepted, sized from the decoded bytes.
        let ok = ImagePart::from_data_url("x.png", "data:image/png;base64,iVBORw0KGgo=").unwrap();
        assert_eq!(ok.mime, "image/png");
    }

    #[test]
    fn base64_decodes_padded_and_unpadded_alike() {
        assert_eq!(decode_base64("AAAA").as_deref(), Some(&[0u8, 0, 0][..]));
        assert_eq!(decode_base64("AAA").as_deref(), Some(&[0u8, 0][..]));
        assert_eq!(decode_base64("AA").as_deref(), Some(&[0u8][..]));
        assert_eq!(decode_base64("iVBORw0KGgo=").unwrap().len(), 8);
        assert!(
            decode_base64("A").is_none(),
            "one spare character is not base64"
        );
        assert!(decode_base64("A=AA").is_none(), "`=` only at the end");
    }
}