eclipse-core 0.13.2

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
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
//! A cassette is one run's provider traffic, recorded and replayed.
//!
//! The point of a cassette is that a prompt does not change by accident: replay the
//! recorded requests, and the first divergence — in the messages, in the tools offered,
//! or in the number of turns — fails the run with the effect named. That is a test that
//! cannot rot, unlike a snapshot of the output.
//!
//! A cassette is deliberately narrow: it covers provider traffic, not tool side effects.
//! Tool results depend on the filesystem, so a replay would be dishonest about them;
//! the transcript and the hooks carry those. What a cassette proves is that the loop
//! asks the model the same question every time.
//!
//! # Recording
//!
//! [`RecordingProvider`] wraps another provider: everything it sends is recorded in order,
//! along with what came back. Recording is invisible — the run cannot tell the difference
//! except that it is slightly slower.
//!
//! # Replay
//!
//! [`ReplayProvider`] answers from the cassette instead of the network. Each recorded
//! request is checked against the live one, so a changed preamble, a different tool
//! surface or a different history fails with the turn named.

use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use serde::{Deserialize, Serialize};

use crate::error::{Error, Result};
use crate::message::Message;
use crate::provider::ChatProvider;
use crate::stream::DeltaFn;
use crate::tools::ToolSpec;

/// One recorded request: the messages, the tools offered, and the reply that came back.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RecordedRequest {
    pub messages: Vec<Message>,
    pub tools: Vec<serde_json::Value>,
    pub reply: Message,
}

/// The cassette format this build writes. Bumped to 2 when a picture started being stored as its
/// digest rather than its bytes (`#375`): a version-1 file carries base64, so it is not silently
/// accepted and quietly compared against stubs.
pub const CASSETTE_VERSION: u32 = 2;

/// A cassette file on disk: a name plus the effects of one run, in order.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Cassette {
    pub version: u32,
    pub name: String,
    pub requests: Vec<RecordedRequest>,
}

/// What a cassette target is: record to a file, or replay from one.
pub enum CassetteTarget {
    Recording {
        name: String,
        path: std::path::PathBuf,
    },
    Replay(Cassette),
}

impl Cassette {
    /// Serialize for writing; the name is kept separate from the file so the file name and
    /// the cassette name cannot disagree.
    pub fn save(&self, path: &std::path::Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                Error::Config(format!("cannot create cassette dir {parent:?}: {e}"))
            })?;
        }
        let json = serde_json::to_string_pretty(self)
            .map_err(|e| Error::Config(format!("cannot serialize cassette: {e}")))?;
        // `#456`: a cassette is the run verbatim — every message of every prompt, the tool specs
        // and the replies — and it is a debugging artifact people copy around and commit. Left to
        // the umask it lands 0644, so the whole conversation is readable by anyone on the box. It is
        // created 0600 instead. Redaction is deliberately *not* applied on the way in: `check`
        // compares the live request with the recorded one, so a redacted cassette diverges from the
        // run it is supposed to replay at the first turn that carried a secret. A shareable
        // cassette, if it is ever wanted, is a separate verb that rewrites a copy.
        let mut options = std::fs::OpenOptions::new();
        options.write(true).create(true).truncate(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            options.mode(0o600);
        }
        let mut file = options
            .open(path)
            .map_err(|e| Error::Config(format!("cannot write cassette {path:?}: {e}")))?;
        std::io::Write::write_all(&mut file, json.as_bytes())
            .map_err(|e| Error::Config(format!("cannot write cassette {path:?}: {e}")))?;
        Ok(())
    }

    pub fn load(path: &std::path::Path) -> Result<Self> {
        let text = std::fs::read_to_string(path)
            .map_err(|e| Error::Config(format!("cannot read cassette {path:?}: {e}")))?;
        let cassette: Cassette = serde_json::from_str(&text)
            .map_err(|e| Error::Config(format!("cannot read cassette {path:?}: {e}")))?;
        if cassette.version != CASSETTE_VERSION {
            return Err(Error::Config(format!(
                "cassette {path:?} is version {} and this build reads {CASSETTE_VERSION}: a version-1 \
                 cassette stores a picture's bytes where this one stores its digest. Re-record it",
                cassette.version
            )));
        }
        Ok(cassette)
    }
}

impl RecordedRequest {
    fn same_request(&self, messages: &[Message], tools: &[ToolSpec]) -> bool {
        let live: Vec<serde_json::Value> = tools
            .iter()
            .map(|t| serde_json::to_value(t).expect("a tool spec serializes"))
            .collect();
        // The live side is stubbed too, so a picture is compared by its digest (`#375`).
        self.messages == stubbed(messages) && self.tools == live
    }
}

/// What a cassette stores in place of a picture's bytes (`#375`).
///
/// A cassette is a fixture that gets committed: a screenshot's base64 in one is megabytes in a
/// diff, a repository that grows on every re-record, and a person's picture sitting in version
/// control. Replay does not need the bytes — the reply is what it replays — but it does need to
/// notice that the picture changed, and the SHA-256 of the payload does that exactly.
///
/// The `stubbed:` scheme keeps the result from being mistakable for a picture: nothing that reads
/// a `data:` URL will accept it back.
fn stub(url: &str) -> String {
    let Some(rest) = url.strip_prefix("data:") else {
        return url.to_string();
    };
    let Some((meta, payload)) = rest.split_once(',') else {
        return url.to_string();
    };
    // The type, not the encoding: the `;base64` in a data URL's meta describes bytes that are no
    // longer here.
    let mime = meta.split(';').next().unwrap_or("");
    let digest = ring::digest::digest(&ring::digest::SHA256, payload.as_bytes());
    let mut hex = String::with_capacity(digest.as_ref().len() * 2);
    for byte in digest.as_ref() {
        hex.push_str(&format!("{byte:02x}"));
    }
    format!("stubbed:{mime};len={};sha256={hex}", payload.len())
}

/// The messages as a cassette stores them: each picture replaced by its stub.
fn stubbed(messages: &[Message]) -> Vec<Message> {
    messages
        .iter()
        .map(|message| {
            let mut message = message.clone();
            for image in &mut message.images {
                image.url = stub(&image.url);
            }
            message
        })
        .collect()
}

/// A provider that records every request and reply through to disk.
///
/// The recorded reply is the one that came back — no synthesis, no re-encoding.
pub struct RecordingProvider {
    inner: Arc<dyn ChatProvider>,
    effect: Mutex<Vec<RecordedRequest>>,
}

impl RecordingProvider {
    pub fn new(inner: Arc<dyn ChatProvider>) -> Self {
        Self {
            inner,
            effect: Mutex::new(Vec::new()),
        }
    }

    /// The recorded effects so far, in the order the requests were sent.
    pub fn effects(&self) -> Vec<RecordedRequest> {
        self.effect
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .clone()
    }

    /// Save the recorded effects to a cassette file.
    pub fn save(&self, path: &std::path::Path, name: &str) -> Result<()> {
        let effects = self
            .effect
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .clone();
        let cassette = Cassette {
            version: CASSETTE_VERSION,
            name: name.to_string(),
            requests: effects,
        };
        cassette.save(path)
    }
}

#[async_trait]
impl ChatProvider for RecordingProvider {
    async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Message> {
        let reply = self.inner.chat(messages, tools).await?;
        self.effect
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .push(RecordedRequest {
                messages: stubbed(messages),
                tools: tools
                    .iter()
                    .map(|t| serde_json::to_value(t).expect("a tool spec serializes"))
                    .collect(),
                reply: reply.clone(),
            });
        Ok(reply)
    }

    async fn chat_stream(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        on_delta: DeltaFn<'_>,
    ) -> Result<Message> {
        let reply = self.inner.chat_stream(messages, tools, on_delta).await?;
        self.effect
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .push(RecordedRequest {
                messages: stubbed(messages),
                tools: tools
                    .iter()
                    .map(|t| serde_json::to_value(t).expect("a tool spec serializes"))
                    .collect(),
                reply: reply.clone(),
            });
        Ok(reply)
    }

    async fn chat_stream_patched(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        on_delta: DeltaFn<'_>,
        patch: &crate::hooks::RequestPatch,
    ) -> Result<Message> {
        let reply = self
            .inner
            .chat_stream_patched(messages, tools, on_delta, patch)
            .await?;
        self.effect
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .push(RecordedRequest {
                messages: stubbed(messages),
                tools: tools
                    .iter()
                    .map(|t| serde_json::to_value(t).expect("a tool spec serializes"))
                    .collect(),
                reply: reply.clone(),
            });
        Ok(reply)
    }

    /// Whatever the wrapped provider declares (`#361`). Without this, a recording run refuses a
    /// picture the model it is recording can read, and the cassette has no turn to replay.
    fn can_see(&self) -> bool {
        self.inner.can_see()
    }
}

/// A provider that answers from a cassette instead of the network.
///
/// The first request that does not match a recorded request fails the run with the turn
/// named — the cassette is not a hint, it is the test.
pub struct ReplayProvider {
    cassette: Cassette,
    index: Mutex<usize>,
}

impl ReplayProvider {
    pub fn new(cassette: Cassette) -> Self {
        Self {
            cassette,
            index: Mutex::new(0),
        }
    }

    /// How many recorded requests remain.
    pub fn remaining(&self) -> usize {
        self.cassette.requests.len() - *self.index.lock().unwrap_or_else(|p| p.into_inner())
    }

    fn recorded(&self) -> Result<&RecordedRequest> {
        let mut index = self.index.lock().unwrap_or_else(|p| p.into_inner());
        let turn = *index;
        if turn >= self.cassette.requests.len() {
            return Err(Error::Provider(crate::error::ProviderFailure::Response {
                message: format!(
                    "cassette `{}` ran out after {turn} turns; the run asked for more than the recording",
                    self.cassette.name
                ),
                body: None,
            }));
        }
        let recorded = &self.cassette.requests[turn];
        *index += 1;
        Ok(recorded)
    }

    /// The recorded request for this call, checked against the request that came in.
    /// Failing here — before any network or agent work — is what "fails at the first
    /// divergence" means.
    fn check(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<&RecordedRequest> {
        let recorded = self.recorded()?;
        if !recorded.same_request(messages, tools) {
            let turn = *self.index.lock().unwrap_or_else(|p| p.into_inner()) - 1;
            return Err(Error::Provider(crate::error::ProviderFailure::Response {
                message: format!(
                    "cassette `{}` diverged at turn {turn}: the request does not match the recording",
                    self.cassette.name
                ),
                body: Some(format!(
                    "recorded {} messages / {} tools, live {} messages / {} tools",
                    recorded.messages.len(),
                    recorded.tools.len(),
                    messages.len(),
                    tools.len()
                )),
            }));
        }
        Ok(recorded)
    }
}

#[async_trait]
impl ChatProvider for ReplayProvider {
    async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Message> {
        Ok(self.check(messages, tools)?.reply.clone())
    }

    async fn chat_stream(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        on_delta: DeltaFn<'_>,
    ) -> Result<Message> {
        let recorded = self.check(messages, tools)?.clone();
        // A replay speaks as the recorded reply did: the deltas are the reply's text,
        // delivered once, in two chunks, to exercise the same rendering path as a real
        // stream rather than the "no deltas" path.
        if let Some(text) = &recorded.reply.content {
            // `#417`: `len()` is bytes, so half of it is regularly *inside* a character — `日本語`
            // is 9 bytes and its midpoint is 4 — and slicing there panics. The split only exists to
            // exercise the two-chunk rendering path, so it is moved to the nearest boundary below.
            let mid = text.floor_char_boundary(text.len() / 2);
            on_delta(crate::stream::Delta::Text(text[..mid].to_string()));
            on_delta(crate::stream::Delta::Text(text[mid..].to_string()));
        }
        Ok(recorded.reply)
    }

    async fn chat_stream_patched(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        on_delta: DeltaFn<'_>,
        _patch: &crate::hooks::RequestPatch,
    ) -> Result<Message> {
        // A recorded run was a no-patch run; a patched replay cannot be the same run.
        self.chat_stream(messages, tools, on_delta).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::{FunctionCall, ToolCall};

    fn msg(text: &str) -> Message {
        Message::assistant(text)
    }

    fn tool_call(name: &str, args: &str) -> Message {
        Message::assistant_tool_calls(
            None,
            vec![ToolCall {
                id: "c1".into(),
                kind: "function".into(),
                function: FunctionCall {
                    name: name.into(),
                    arguments: args.into(),
                },
            }],
        )
    }

    /// A stub provider that answers with a recorded reply and counts calls.
    struct Stub {
        replies: Vec<Message>,
    }

    #[async_trait]
    impl ChatProvider for Stub {
        async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> Result<Message> {
            Ok(self.replies[0].clone())
        }

        async fn chat_stream(
            &self,
            _: &[Message],
            _: &[ToolSpec],
            on_delta: DeltaFn<'_>,
        ) -> Result<Message> {
            let reply = self.replies[0].clone();
            if let Some(text) = &reply.content {
                on_delta(crate::stream::Delta::Text(text.clone()));
            }
            Ok(reply)
        }
    }

    #[tokio::test]
    async fn records_requests_and_replays_them() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.cassette.json");
        let inner = Arc::new(Stub {
            replies: vec![msg("hi there")],
        });
        let recorder = RecordingProvider::new(inner);
        let messages = vec![Message::user("hello")];
        recorder.chat(&messages, &[]).await.unwrap();
        recorder.save(&path, "a").unwrap();

        let cassette = Cassette::load(&path).unwrap();
        assert_eq!(cassette.version, CASSETTE_VERSION);
        assert_eq!(cassette.name, "a");
        assert_eq!(cassette.requests.len(), 1);

        let replay = ReplayProvider::new(cassette);
        let reply = replay.chat(&messages, &[]).await.unwrap();
        assert_eq!(reply.content.as_deref(), Some("hi there"));
        assert_eq!(replay.remaining(), 0);
    }

    /// `#456`: a cassette holds every message of every request it recorded, so it must not be
    /// readable by everyone on the box. `fs::write` left it at the umask's 0644.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_cassette_is_readable_by_its_owner_only() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("secret.cassette.json");
        let inner = Arc::new(Stub {
            replies: vec![msg("hi")],
        });
        let recorder = RecordingProvider::new(inner);
        recorder.chat(&[Message::user("hello")], &[]).await.unwrap();
        recorder.save(&path, "secret").unwrap();
        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "a cassette is a secret: mode {mode:o}");
    }

    /// `#456`: the index is a counter, not a fact worth failing a run over. A panic while the guard
    /// was held poisoned it and every later call died on `PoisonError` rather than on anything about
    /// the recording.
    #[tokio::test]
    async fn a_poisoned_index_still_replays() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("c.cassette.json");
        let inner = Arc::new(Stub {
            replies: vec![msg("hi there")],
        });
        let recorder = RecordingProvider::new(inner);
        let messages = vec![Message::user("hello")];
        recorder.chat(&messages, &[]).await.unwrap();
        recorder.save(&path, "c").unwrap();
        let replay = ReplayProvider::new(Cassette::load(&path).unwrap());
        assert_eq!(replay.remaining(), 1);

        // Poison the index exactly as a panic inside a recording would: take the guard, panic.
        let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _held = replay.index.lock().unwrap();
            panic!("a panic while the index was held");
        }));
        assert!(poisoned.is_err(), "the guard was held across a panic");
        assert!(replay.index.is_poisoned(), "and it is poisoned");

        assert_eq!(replay.remaining(), 1, "the count survived the poisoning");
        let reply = replay.chat(&messages, &[]).await.unwrap();
        assert_eq!(reply.content.as_deref(), Some("hi there"));
    }

    #[tokio::test]
    async fn replay_fails_at_the_first_divergence_naming_the_turn() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("b.cassette.json");
        let inner = Arc::new(Stub {
            replies: vec![msg("ok")],
        });
        let recorder = RecordingProvider::new(inner);
        let messages = vec![Message::user("hello")];
        recorder.chat(&messages, &[]).await.unwrap();
        recorder.save(&path, "b").unwrap();

        let replay = ReplayProvider::new(Cassette::load(&path).unwrap());
        let err = replay
            .chat(&[Message::user("changed")], &[])
            .await
            .unwrap_err();
        let text = err.to_string();
        assert!(text.contains("diverged at turn 0"), "{text}");
        assert!(text.contains("cassette `b`"), "{text}");
    }

    #[tokio::test]
    async fn replay_refuses_a_turn_the_recording_does_not_have() {
        let inner = Arc::new(Stub {
            replies: vec![msg("one")],
        });
        let recorder = RecordingProvider::new(inner);
        let messages = vec![Message::user("hello")];
        recorder.chat(&messages, &[]).await.unwrap();
        let effects = recorder.effects();
        let replay = ReplayProvider::new(Cassette {
            version: CASSETTE_VERSION,
            name: "c".into(),
            requests: effects,
        });
        replay.chat(&messages, &[]).await.unwrap();
        let err = replay.chat(&messages, &[]).await.unwrap_err();
        assert!(err.to_string().contains("ran out"), "{err}");
    }

    #[tokio::test]
    async fn replay_delivers_deltas_for_streamed_replies() {
        let inner = Arc::new(Stub {
            replies: vec![msg("hello world")],
        });
        let recorder = RecordingProvider::new(inner);
        recorder.chat(&[Message::user("hi")], &[]).await.unwrap();
        let cassette = Cassette {
            version: CASSETTE_VERSION,
            name: "d".into(),
            requests: recorder.effects(),
        };
        let replay = ReplayProvider::new(cassette);
        let deltas = std::sync::Mutex::new(Vec::new());
        let collected = |d: crate::stream::Delta| deltas.lock().unwrap().push(d);
        let reply = replay
            .chat_stream(&[Message::user("hi")], &[], &collected)
            .await
            .unwrap();
        assert_eq!(reply.content.as_deref(), Some("hello world"));
        let got = deltas.into_inner().unwrap();
        assert!(!got.is_empty());
        let text: String = got
            .iter()
            .filter_map(|d| match d {
                crate::stream::Delta::Text(t) => Some(t.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(text, "hello world");
    }

    /// `#417`: the two-chunk split took `text.len() / 2`, and `len()` is bytes — a reply in any
    /// non-ASCII script lands that midpoint inside a character regularly (`日本語` is 9 bytes, so
    /// the midpoint is 4) and the slice panicted. Every recorded reply in that script crashed
    /// `--replay-cassette`.
    #[tokio::test]
    async fn replay_splits_a_reply_at_a_character_boundary() {
        let inner = Arc::new(Stub {
            replies: vec![msg("日本語")],
        });
        let recorder = RecordingProvider::new(inner);
        recorder.chat(&[Message::user("hi")], &[]).await.unwrap();
        let cassette = Cassette {
            version: CASSETTE_VERSION,
            name: "d".into(),
            requests: recorder.effects(),
        };
        let replay = ReplayProvider::new(cassette);
        let deltas = std::sync::Mutex::new(Vec::new());
        let collected = |d: crate::stream::Delta| deltas.lock().unwrap().push(d);
        let reply = replay
            .chat_stream(&[Message::user("hi")], &[], &collected)
            .await
            .expect("a reply in a non-ASCII script is not a slice error");
        assert_eq!(reply.content.as_deref(), Some("日本語"));
        let text: String = deltas
            .into_inner()
            .unwrap()
            .iter()
            .filter_map(|d| match d {
                crate::stream::Delta::Text(t) => Some(t.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(text, "日本語", "the chunks still add up to the reply");
    }

    #[tokio::test]
    async fn recorded_tool_calls_are_not_lost() {
        let inner = Arc::new(Stub {
            replies: vec![tool_call("read_file", "{\"path\":\"a\"}")],
        });
        let recorder = RecordingProvider::new(inner);
        recorder.chat(&[Message::user("hi")], &[]).await.unwrap();
        let cassette = Cassette {
            version: CASSETTE_VERSION,
            name: "e".into(),
            requests: recorder.effects(),
        };
        assert_eq!(cassette.requests[0].reply.tool_calls.len(), 1);
        let replay = ReplayProvider::new(cassette);
        let reply = replay.chat(&[Message::user("hi")], &[]).await.unwrap();
        assert_eq!(reply.tool_calls.len(), 1);
        assert_eq!(reply.tool_calls[0].function.name, "read_file");
    }

    /// `#375`: a cassette is a fixture that gets committed. A screenshot in one is megabytes in a
    /// diff, a repository that grows on every re-record, and a person's picture in version control.
    /// What replay actually needs is to notice the picture changed, so the payload is stored as a
    /// length and a digest.
    #[tokio::test]
    async fn a_picture_is_recorded_as_a_digest_and_still_catches_a_different_one() {
        let png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFAAH/q842iQAAAABJRU5ErkJggg==";
        let shot = |url: &str| {
            Message::user("what is this?").with_image(crate::message::ImagePart::new(
                "shot.png",
                "image/png",
                url,
            ))
        };
        let inner = Arc::new(Stub {
            replies: vec![msg("a red square")],
        });
        let recorder = RecordingProvider::new(inner);
        let live = shot(png);
        recorder
            .chat(std::slice::from_ref(&live), &[])
            .await
            .unwrap();
        let cassette = Cassette {
            version: CASSETTE_VERSION,
            name: "p".into(),
            requests: recorder.effects(),
        };

        let json = serde_json::to_string(&cassette).unwrap();
        assert!(
            !json.contains("iVBORw0KGgo"),
            "the picture's bytes are not in the file: {json}"
        );
        assert!(json.contains("stubbed:image/png;len="), "{json}");
        assert!(json.contains("sha256="), "{json}");

        // The same picture replays, because the digest matches.
        let replay = ReplayProvider::new(cassette.clone());
        replay.chat(&[live], &[]).await.unwrap();

        // A different picture is a divergence, named at the turn — not a silent pass on the
        // strength of "a picture was attached".
        let replay = ReplayProvider::new(cassette);
        let other = shot("data:image/png;base64,iVBORw0KGgo=");
        let err = replay.chat(&[other], &[]).await.unwrap_err();
        assert!(err.to_string().contains("diverged at turn 0"), "{err}");

        // And a stub can never be sent as a picture by mistake.
        assert!(
            crate::message::ImagePart::from_data_url("shot.png", &stub(png)).is_err(),
            "a stubbed part is not a data URL"
        );
    }
}