Skip to main content

eclipse_core/
cassette.rs

1//! A cassette is one run's provider traffic, recorded and replayed.
2//!
3//! The point of a cassette is that a prompt does not change by accident: replay the
4//! recorded requests, and the first divergence — in the messages, in the tools offered,
5//! or in the number of turns — fails the run with the effect named. That is a test that
6//! cannot rot, unlike a snapshot of the output.
7//!
8//! A cassette is deliberately narrow: it covers provider traffic, not tool side effects.
9//! Tool results depend on the filesystem, so a replay would be dishonest about them;
10//! the transcript and the hooks carry those. What a cassette proves is that the loop
11//! asks the model the same question every time.
12//!
13//! # Recording
14//!
15//! [`RecordingProvider`] wraps another provider: everything it sends is recorded in order,
16//! along with what came back. Recording is invisible — the run cannot tell the difference
17//! except that it is slightly slower.
18//!
19//! # Replay
20//!
21//! [`ReplayProvider`] answers from the cassette instead of the network. Each recorded
22//! request is checked against the live one, so a changed preamble, a different tool
23//! surface or a different history fails with the turn named.
24
25use std::sync::{Arc, Mutex};
26
27use async_trait::async_trait;
28use serde::{Deserialize, Serialize};
29
30use crate::error::{Error, Result};
31use crate::message::Message;
32use crate::provider::ChatProvider;
33use crate::stream::DeltaFn;
34use crate::tools::ToolSpec;
35
36/// One recorded request: the messages, the tools offered, and the reply that came back.
37#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
38pub struct RecordedRequest {
39    pub messages: Vec<Message>,
40    pub tools: Vec<serde_json::Value>,
41    pub reply: Message,
42}
43
44/// The cassette format this build writes. Bumped to 2 when a picture started being stored as its
45/// digest rather than its bytes (`#375`): a version-1 file carries base64, so it is not silently
46/// accepted and quietly compared against stubs.
47pub const CASSETTE_VERSION: u32 = 2;
48
49/// A cassette file on disk: a name plus the effects of one run, in order.
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct Cassette {
52    pub version: u32,
53    pub name: String,
54    pub requests: Vec<RecordedRequest>,
55}
56
57/// What a cassette target is: record to a file, or replay from one.
58pub enum CassetteTarget {
59    Recording {
60        name: String,
61        path: std::path::PathBuf,
62    },
63    Replay(Cassette),
64}
65
66impl Cassette {
67    /// Serialize for writing; the name is kept separate from the file so the file name and
68    /// the cassette name cannot disagree.
69    pub fn save(&self, path: &std::path::Path) -> Result<()> {
70        if let Some(parent) = path.parent() {
71            std::fs::create_dir_all(parent).map_err(|e| {
72                Error::Config(format!("cannot create cassette dir {parent:?}: {e}"))
73            })?;
74        }
75        let json = serde_json::to_string_pretty(self)
76            .map_err(|e| Error::Config(format!("cannot serialize cassette: {e}")))?;
77        // `#456`: a cassette is the run verbatim — every message of every prompt, the tool specs
78        // and the replies — and it is a debugging artifact people copy around and commit. Left to
79        // the umask it lands 0644, so the whole conversation is readable by anyone on the box. It is
80        // created 0600 instead. Redaction is deliberately *not* applied on the way in: `check`
81        // compares the live request with the recorded one, so a redacted cassette diverges from the
82        // run it is supposed to replay at the first turn that carried a secret. A shareable
83        // cassette, if it is ever wanted, is a separate verb that rewrites a copy.
84        let mut options = std::fs::OpenOptions::new();
85        options.write(true).create(true).truncate(true);
86        #[cfg(unix)]
87        {
88            use std::os::unix::fs::OpenOptionsExt;
89            options.mode(0o600);
90        }
91        let mut file = options
92            .open(path)
93            .map_err(|e| Error::Config(format!("cannot write cassette {path:?}: {e}")))?;
94        std::io::Write::write_all(&mut file, json.as_bytes())
95            .map_err(|e| Error::Config(format!("cannot write cassette {path:?}: {e}")))?;
96        Ok(())
97    }
98
99    pub fn load(path: &std::path::Path) -> Result<Self> {
100        let text = std::fs::read_to_string(path)
101            .map_err(|e| Error::Config(format!("cannot read cassette {path:?}: {e}")))?;
102        let cassette: Cassette = serde_json::from_str(&text)
103            .map_err(|e| Error::Config(format!("cannot read cassette {path:?}: {e}")))?;
104        if cassette.version != CASSETTE_VERSION {
105            return Err(Error::Config(format!(
106                "cassette {path:?} is version {} and this build reads {CASSETTE_VERSION}: a version-1 \
107                 cassette stores a picture's bytes where this one stores its digest. Re-record it",
108                cassette.version
109            )));
110        }
111        Ok(cassette)
112    }
113}
114
115impl RecordedRequest {
116    fn same_request(&self, messages: &[Message], tools: &[ToolSpec]) -> bool {
117        let live: Vec<serde_json::Value> = tools
118            .iter()
119            .map(|t| serde_json::to_value(t).expect("a tool spec serializes"))
120            .collect();
121        // The live side is stubbed too, so a picture is compared by its digest (`#375`).
122        self.messages == stubbed(messages) && self.tools == live
123    }
124}
125
126/// What a cassette stores in place of a picture's bytes (`#375`).
127///
128/// A cassette is a fixture that gets committed: a screenshot's base64 in one is megabytes in a
129/// diff, a repository that grows on every re-record, and a person's picture sitting in version
130/// control. Replay does not need the bytes — the reply is what it replays — but it does need to
131/// notice that the picture changed, and the SHA-256 of the payload does that exactly.
132///
133/// The `stubbed:` scheme keeps the result from being mistakable for a picture: nothing that reads
134/// a `data:` URL will accept it back.
135fn stub(url: &str) -> String {
136    let Some(rest) = url.strip_prefix("data:") else {
137        return url.to_string();
138    };
139    let Some((meta, payload)) = rest.split_once(',') else {
140        return url.to_string();
141    };
142    // The type, not the encoding: the `;base64` in a data URL's meta describes bytes that are no
143    // longer here.
144    let mime = meta.split(';').next().unwrap_or("");
145    let digest = ring::digest::digest(&ring::digest::SHA256, payload.as_bytes());
146    let mut hex = String::with_capacity(digest.as_ref().len() * 2);
147    for byte in digest.as_ref() {
148        hex.push_str(&format!("{byte:02x}"));
149    }
150    format!("stubbed:{mime};len={};sha256={hex}", payload.len())
151}
152
153/// The messages as a cassette stores them: each picture replaced by its stub.
154fn stubbed(messages: &[Message]) -> Vec<Message> {
155    messages
156        .iter()
157        .map(|message| {
158            let mut message = message.clone();
159            for image in &mut message.images {
160                image.url = stub(&image.url);
161            }
162            message
163        })
164        .collect()
165}
166
167/// A provider that records every request and reply through to disk.
168///
169/// The recorded reply is the one that came back — no synthesis, no re-encoding.
170pub struct RecordingProvider {
171    inner: Arc<dyn ChatProvider>,
172    effect: Mutex<Vec<RecordedRequest>>,
173}
174
175impl RecordingProvider {
176    pub fn new(inner: Arc<dyn ChatProvider>) -> Self {
177        Self {
178            inner,
179            effect: Mutex::new(Vec::new()),
180        }
181    }
182
183    /// The recorded effects so far, in the order the requests were sent.
184    pub fn effects(&self) -> Vec<RecordedRequest> {
185        self.effect
186            .lock()
187            .unwrap_or_else(|p| p.into_inner())
188            .clone()
189    }
190
191    /// Save the recorded effects to a cassette file.
192    pub fn save(&self, path: &std::path::Path, name: &str) -> Result<()> {
193        let effects = self
194            .effect
195            .lock()
196            .unwrap_or_else(|p| p.into_inner())
197            .clone();
198        let cassette = Cassette {
199            version: CASSETTE_VERSION,
200            name: name.to_string(),
201            requests: effects,
202        };
203        cassette.save(path)
204    }
205}
206
207#[async_trait]
208impl ChatProvider for RecordingProvider {
209    async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Message> {
210        let reply = self.inner.chat(messages, tools).await?;
211        self.effect
212            .lock()
213            .unwrap_or_else(|p| p.into_inner())
214            .push(RecordedRequest {
215                messages: stubbed(messages),
216                tools: tools
217                    .iter()
218                    .map(|t| serde_json::to_value(t).expect("a tool spec serializes"))
219                    .collect(),
220                reply: reply.clone(),
221            });
222        Ok(reply)
223    }
224
225    async fn chat_stream(
226        &self,
227        messages: &[Message],
228        tools: &[ToolSpec],
229        on_delta: DeltaFn<'_>,
230    ) -> Result<Message> {
231        let reply = self.inner.chat_stream(messages, tools, on_delta).await?;
232        self.effect
233            .lock()
234            .unwrap_or_else(|p| p.into_inner())
235            .push(RecordedRequest {
236                messages: stubbed(messages),
237                tools: tools
238                    .iter()
239                    .map(|t| serde_json::to_value(t).expect("a tool spec serializes"))
240                    .collect(),
241                reply: reply.clone(),
242            });
243        Ok(reply)
244    }
245
246    async fn chat_stream_patched(
247        &self,
248        messages: &[Message],
249        tools: &[ToolSpec],
250        on_delta: DeltaFn<'_>,
251        patch: &crate::hooks::RequestPatch,
252    ) -> Result<Message> {
253        let reply = self
254            .inner
255            .chat_stream_patched(messages, tools, on_delta, patch)
256            .await?;
257        self.effect
258            .lock()
259            .unwrap_or_else(|p| p.into_inner())
260            .push(RecordedRequest {
261                messages: stubbed(messages),
262                tools: tools
263                    .iter()
264                    .map(|t| serde_json::to_value(t).expect("a tool spec serializes"))
265                    .collect(),
266                reply: reply.clone(),
267            });
268        Ok(reply)
269    }
270
271    /// Whatever the wrapped provider declares (`#361`). Without this, a recording run refuses a
272    /// picture the model it is recording can read, and the cassette has no turn to replay.
273    fn can_see(&self) -> bool {
274        self.inner.can_see()
275    }
276}
277
278/// A provider that answers from a cassette instead of the network.
279///
280/// The first request that does not match a recorded request fails the run with the turn
281/// named — the cassette is not a hint, it is the test.
282pub struct ReplayProvider {
283    cassette: Cassette,
284    index: Mutex<usize>,
285}
286
287impl ReplayProvider {
288    pub fn new(cassette: Cassette) -> Self {
289        Self {
290            cassette,
291            index: Mutex::new(0),
292        }
293    }
294
295    /// How many recorded requests remain.
296    pub fn remaining(&self) -> usize {
297        self.cassette.requests.len() - *self.index.lock().unwrap_or_else(|p| p.into_inner())
298    }
299
300    fn recorded(&self) -> Result<&RecordedRequest> {
301        let mut index = self.index.lock().unwrap_or_else(|p| p.into_inner());
302        let turn = *index;
303        if turn >= self.cassette.requests.len() {
304            return Err(Error::Provider(crate::error::ProviderFailure::Response {
305                message: format!(
306                    "cassette `{}` ran out after {turn} turns; the run asked for more than the recording",
307                    self.cassette.name
308                ),
309                body: None,
310            }));
311        }
312        let recorded = &self.cassette.requests[turn];
313        *index += 1;
314        Ok(recorded)
315    }
316
317    /// The recorded request for this call, checked against the request that came in.
318    /// Failing here — before any network or agent work — is what "fails at the first
319    /// divergence" means.
320    fn check(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<&RecordedRequest> {
321        let recorded = self.recorded()?;
322        if !recorded.same_request(messages, tools) {
323            let turn = *self.index.lock().unwrap_or_else(|p| p.into_inner()) - 1;
324            return Err(Error::Provider(crate::error::ProviderFailure::Response {
325                message: format!(
326                    "cassette `{}` diverged at turn {turn}: the request does not match the recording",
327                    self.cassette.name
328                ),
329                body: Some(format!(
330                    "recorded {} messages / {} tools, live {} messages / {} tools",
331                    recorded.messages.len(),
332                    recorded.tools.len(),
333                    messages.len(),
334                    tools.len()
335                )),
336            }));
337        }
338        Ok(recorded)
339    }
340}
341
342#[async_trait]
343impl ChatProvider for ReplayProvider {
344    async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Message> {
345        Ok(self.check(messages, tools)?.reply.clone())
346    }
347
348    async fn chat_stream(
349        &self,
350        messages: &[Message],
351        tools: &[ToolSpec],
352        on_delta: DeltaFn<'_>,
353    ) -> Result<Message> {
354        let recorded = self.check(messages, tools)?.clone();
355        // A replay speaks as the recorded reply did: the deltas are the reply's text,
356        // delivered once, in two chunks, to exercise the same rendering path as a real
357        // stream rather than the "no deltas" path.
358        if let Some(text) = &recorded.reply.content {
359            // `#417`: `len()` is bytes, so half of it is regularly *inside* a character — `日本語`
360            // is 9 bytes and its midpoint is 4 — and slicing there panics. The split only exists to
361            // exercise the two-chunk rendering path, so it is moved to the nearest boundary below.
362            let mid = text.floor_char_boundary(text.len() / 2);
363            on_delta(crate::stream::Delta::Text(text[..mid].to_string()));
364            on_delta(crate::stream::Delta::Text(text[mid..].to_string()));
365        }
366        Ok(recorded.reply)
367    }
368
369    async fn chat_stream_patched(
370        &self,
371        messages: &[Message],
372        tools: &[ToolSpec],
373        on_delta: DeltaFn<'_>,
374        _patch: &crate::hooks::RequestPatch,
375    ) -> Result<Message> {
376        // A recorded run was a no-patch run; a patched replay cannot be the same run.
377        self.chat_stream(messages, tools, on_delta).await
378    }
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384    use crate::message::{FunctionCall, ToolCall};
385
386    fn msg(text: &str) -> Message {
387        Message::assistant(text)
388    }
389
390    fn tool_call(name: &str, args: &str) -> Message {
391        Message::assistant_tool_calls(
392            None,
393            vec![ToolCall {
394                id: "c1".into(),
395                kind: "function".into(),
396                function: FunctionCall {
397                    name: name.into(),
398                    arguments: args.into(),
399                },
400            }],
401        )
402    }
403
404    /// A stub provider that answers with a recorded reply and counts calls.
405    struct Stub {
406        replies: Vec<Message>,
407    }
408
409    #[async_trait]
410    impl ChatProvider for Stub {
411        async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> Result<Message> {
412            Ok(self.replies[0].clone())
413        }
414
415        async fn chat_stream(
416            &self,
417            _: &[Message],
418            _: &[ToolSpec],
419            on_delta: DeltaFn<'_>,
420        ) -> Result<Message> {
421            let reply = self.replies[0].clone();
422            if let Some(text) = &reply.content {
423                on_delta(crate::stream::Delta::Text(text.clone()));
424            }
425            Ok(reply)
426        }
427    }
428
429    #[tokio::test]
430    async fn records_requests_and_replays_them() {
431        let dir = tempfile::tempdir().unwrap();
432        let path = dir.path().join("a.cassette.json");
433        let inner = Arc::new(Stub {
434            replies: vec![msg("hi there")],
435        });
436        let recorder = RecordingProvider::new(inner);
437        let messages = vec![Message::user("hello")];
438        recorder.chat(&messages, &[]).await.unwrap();
439        recorder.save(&path, "a").unwrap();
440
441        let cassette = Cassette::load(&path).unwrap();
442        assert_eq!(cassette.version, CASSETTE_VERSION);
443        assert_eq!(cassette.name, "a");
444        assert_eq!(cassette.requests.len(), 1);
445
446        let replay = ReplayProvider::new(cassette);
447        let reply = replay.chat(&messages, &[]).await.unwrap();
448        assert_eq!(reply.content.as_deref(), Some("hi there"));
449        assert_eq!(replay.remaining(), 0);
450    }
451
452    /// `#456`: a cassette holds every message of every request it recorded, so it must not be
453    /// readable by everyone on the box. `fs::write` left it at the umask's 0644.
454    #[cfg(unix)]
455    #[tokio::test]
456    async fn a_cassette_is_readable_by_its_owner_only() {
457        use std::os::unix::fs::PermissionsExt;
458        let dir = tempfile::tempdir().unwrap();
459        let path = dir.path().join("secret.cassette.json");
460        let inner = Arc::new(Stub {
461            replies: vec![msg("hi")],
462        });
463        let recorder = RecordingProvider::new(inner);
464        recorder.chat(&[Message::user("hello")], &[]).await.unwrap();
465        recorder.save(&path, "secret").unwrap();
466        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
467        assert_eq!(mode, 0o600, "a cassette is a secret: mode {mode:o}");
468    }
469
470    /// `#456`: the index is a counter, not a fact worth failing a run over. A panic while the guard
471    /// was held poisoned it and every later call died on `PoisonError` rather than on anything about
472    /// the recording.
473    #[tokio::test]
474    async fn a_poisoned_index_still_replays() {
475        let dir = tempfile::tempdir().unwrap();
476        let path = dir.path().join("c.cassette.json");
477        let inner = Arc::new(Stub {
478            replies: vec![msg("hi there")],
479        });
480        let recorder = RecordingProvider::new(inner);
481        let messages = vec![Message::user("hello")];
482        recorder.chat(&messages, &[]).await.unwrap();
483        recorder.save(&path, "c").unwrap();
484        let replay = ReplayProvider::new(Cassette::load(&path).unwrap());
485        assert_eq!(replay.remaining(), 1);
486
487        // Poison the index exactly as a panic inside a recording would: take the guard, panic.
488        let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
489            let _held = replay.index.lock().unwrap();
490            panic!("a panic while the index was held");
491        }));
492        assert!(poisoned.is_err(), "the guard was held across a panic");
493        assert!(replay.index.is_poisoned(), "and it is poisoned");
494
495        assert_eq!(replay.remaining(), 1, "the count survived the poisoning");
496        let reply = replay.chat(&messages, &[]).await.unwrap();
497        assert_eq!(reply.content.as_deref(), Some("hi there"));
498    }
499
500    #[tokio::test]
501    async fn replay_fails_at_the_first_divergence_naming_the_turn() {
502        let dir = tempfile::tempdir().unwrap();
503        let path = dir.path().join("b.cassette.json");
504        let inner = Arc::new(Stub {
505            replies: vec![msg("ok")],
506        });
507        let recorder = RecordingProvider::new(inner);
508        let messages = vec![Message::user("hello")];
509        recorder.chat(&messages, &[]).await.unwrap();
510        recorder.save(&path, "b").unwrap();
511
512        let replay = ReplayProvider::new(Cassette::load(&path).unwrap());
513        let err = replay
514            .chat(&[Message::user("changed")], &[])
515            .await
516            .unwrap_err();
517        let text = err.to_string();
518        assert!(text.contains("diverged at turn 0"), "{text}");
519        assert!(text.contains("cassette `b`"), "{text}");
520    }
521
522    #[tokio::test]
523    async fn replay_refuses_a_turn_the_recording_does_not_have() {
524        let inner = Arc::new(Stub {
525            replies: vec![msg("one")],
526        });
527        let recorder = RecordingProvider::new(inner);
528        let messages = vec![Message::user("hello")];
529        recorder.chat(&messages, &[]).await.unwrap();
530        let effects = recorder.effects();
531        let replay = ReplayProvider::new(Cassette {
532            version: CASSETTE_VERSION,
533            name: "c".into(),
534            requests: effects,
535        });
536        replay.chat(&messages, &[]).await.unwrap();
537        let err = replay.chat(&messages, &[]).await.unwrap_err();
538        assert!(err.to_string().contains("ran out"), "{err}");
539    }
540
541    #[tokio::test]
542    async fn replay_delivers_deltas_for_streamed_replies() {
543        let inner = Arc::new(Stub {
544            replies: vec![msg("hello world")],
545        });
546        let recorder = RecordingProvider::new(inner);
547        recorder.chat(&[Message::user("hi")], &[]).await.unwrap();
548        let cassette = Cassette {
549            version: CASSETTE_VERSION,
550            name: "d".into(),
551            requests: recorder.effects(),
552        };
553        let replay = ReplayProvider::new(cassette);
554        let deltas = std::sync::Mutex::new(Vec::new());
555        let collected = |d: crate::stream::Delta| deltas.lock().unwrap().push(d);
556        let reply = replay
557            .chat_stream(&[Message::user("hi")], &[], &collected)
558            .await
559            .unwrap();
560        assert_eq!(reply.content.as_deref(), Some("hello world"));
561        let got = deltas.into_inner().unwrap();
562        assert!(!got.is_empty());
563        let text: String = got
564            .iter()
565            .filter_map(|d| match d {
566                crate::stream::Delta::Text(t) => Some(t.clone()),
567                _ => None,
568            })
569            .collect();
570        assert_eq!(text, "hello world");
571    }
572
573    /// `#417`: the two-chunk split took `text.len() / 2`, and `len()` is bytes — a reply in any
574    /// non-ASCII script lands that midpoint inside a character regularly (`日本語` is 9 bytes, so
575    /// the midpoint is 4) and the slice panicted. Every recorded reply in that script crashed
576    /// `--replay-cassette`.
577    #[tokio::test]
578    async fn replay_splits_a_reply_at_a_character_boundary() {
579        let inner = Arc::new(Stub {
580            replies: vec![msg("日本語")],
581        });
582        let recorder = RecordingProvider::new(inner);
583        recorder.chat(&[Message::user("hi")], &[]).await.unwrap();
584        let cassette = Cassette {
585            version: CASSETTE_VERSION,
586            name: "d".into(),
587            requests: recorder.effects(),
588        };
589        let replay = ReplayProvider::new(cassette);
590        let deltas = std::sync::Mutex::new(Vec::new());
591        let collected = |d: crate::stream::Delta| deltas.lock().unwrap().push(d);
592        let reply = replay
593            .chat_stream(&[Message::user("hi")], &[], &collected)
594            .await
595            .expect("a reply in a non-ASCII script is not a slice error");
596        assert_eq!(reply.content.as_deref(), Some("日本語"));
597        let text: String = deltas
598            .into_inner()
599            .unwrap()
600            .iter()
601            .filter_map(|d| match d {
602                crate::stream::Delta::Text(t) => Some(t.clone()),
603                _ => None,
604            })
605            .collect();
606        assert_eq!(text, "日本語", "the chunks still add up to the reply");
607    }
608
609    #[tokio::test]
610    async fn recorded_tool_calls_are_not_lost() {
611        let inner = Arc::new(Stub {
612            replies: vec![tool_call("read_file", "{\"path\":\"a\"}")],
613        });
614        let recorder = RecordingProvider::new(inner);
615        recorder.chat(&[Message::user("hi")], &[]).await.unwrap();
616        let cassette = Cassette {
617            version: CASSETTE_VERSION,
618            name: "e".into(),
619            requests: recorder.effects(),
620        };
621        assert_eq!(cassette.requests[0].reply.tool_calls.len(), 1);
622        let replay = ReplayProvider::new(cassette);
623        let reply = replay.chat(&[Message::user("hi")], &[]).await.unwrap();
624        assert_eq!(reply.tool_calls.len(), 1);
625        assert_eq!(reply.tool_calls[0].function.name, "read_file");
626    }
627
628    /// `#375`: a cassette is a fixture that gets committed. A screenshot in one is megabytes in a
629    /// diff, a repository that grows on every re-record, and a person's picture in version control.
630    /// What replay actually needs is to notice the picture changed, so the payload is stored as a
631    /// length and a digest.
632    #[tokio::test]
633    async fn a_picture_is_recorded_as_a_digest_and_still_catches_a_different_one() {
634        let png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFAAH/q842iQAAAABJRU5ErkJggg==";
635        let shot = |url: &str| {
636            Message::user("what is this?").with_image(crate::message::ImagePart::new(
637                "shot.png",
638                "image/png",
639                url,
640            ))
641        };
642        let inner = Arc::new(Stub {
643            replies: vec![msg("a red square")],
644        });
645        let recorder = RecordingProvider::new(inner);
646        let live = shot(png);
647        recorder
648            .chat(std::slice::from_ref(&live), &[])
649            .await
650            .unwrap();
651        let cassette = Cassette {
652            version: CASSETTE_VERSION,
653            name: "p".into(),
654            requests: recorder.effects(),
655        };
656
657        let json = serde_json::to_string(&cassette).unwrap();
658        assert!(
659            !json.contains("iVBORw0KGgo"),
660            "the picture's bytes are not in the file: {json}"
661        );
662        assert!(json.contains("stubbed:image/png;len="), "{json}");
663        assert!(json.contains("sha256="), "{json}");
664
665        // The same picture replays, because the digest matches.
666        let replay = ReplayProvider::new(cassette.clone());
667        replay.chat(&[live], &[]).await.unwrap();
668
669        // A different picture is a divergence, named at the turn — not a silent pass on the
670        // strength of "a picture was attached".
671        let replay = ReplayProvider::new(cassette);
672        let other = shot("data:image/png;base64,iVBORw0KGgo=");
673        let err = replay.chat(&[other], &[]).await.unwrap_err();
674        assert!(err.to_string().contains("diverged at turn 0"), "{err}");
675
676        // And a stub can never be sent as a picture by mistake.
677        assert!(
678            crate::message::ImagePart::from_data_url("shot.png", &stub(png)).is_err(),
679            "a stubbed part is not a data URL"
680        );
681    }
682}