eclipse-core 0.13.3

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
//! Context-window management: bound what is sent to the model per request.
//!
//! Sizes are **estimates** (characters / 4, rounded up, plus a few tokens of per-message
//! framing). Real tokenizers differ by model and language (CJK text and code are usually
//! far more tokens per character), so treat the budget as a coarse safety rail, not a
//! guarantee that the endpoint will accept the request.
//!
//! Trimming drops whole *turns* (a user message and everything the agent did in answer,
//! tool calls and their results included) from the oldest end, so a tool call is never
//! separated from its result. The system prompt and the tool definitions are always
//! sent, and the latest turn is always kept, even if it alone exceeds the budget. The
//! stored session is not modified; only the request is shortened.
//!
//! What replaces the dropped turns in the system prompt is the compiled handoff
//! ([`crate::compact`]) and, under it, [`compiled_tail`]'s note about what was left out. The
//! budget itself uses a character heuristic, so it is a rail rather than a promise: the
//! handoff's own size is bounded separately by `[context] handoff_chars`.

use crate::message::{Message, Role};

/// Rough per-message overhead (role, separators) in tokens.
const MESSAGE_OVERHEAD: usize = 4;

/// What one picture costs, before its description is counted.
///
/// A picture is not characters. The wire carries a data URL whose base64 length says nothing about
/// the tokens a model spends on the pixels — a 2 MB JPEG is 2.7 M characters and roughly a thousand
/// tokens — so counting the URL would overcharge by three orders of magnitude while counting nothing
/// (which is what this did) lets a native turn grow the window past the budget with no compaction
/// planned. A flat charge is coarse on purpose and errs high: the estimate only has to plan a
/// compaction before a request is refused.
const PICTURE_TOKENS: usize = 900;

pub fn estimate_text_tokens(text: &str) -> usize {
    text.chars().count().div_ceil(4)
}

pub fn estimate_message_tokens(m: &Message) -> usize {
    let mut chars = m.content.as_deref().map_or(0, |c| c.chars().count());
    for call in &m.tool_calls {
        chars += call.id.chars().count()
            + call.function.name.chars().count()
            + call.function.arguments.chars().count();
    }
    let mut tokens = chars.div_ceil(4) + MESSAGE_OVERHEAD;
    for picture in &m.images {
        tokens += PICTURE_TOKENS;
        // The name rides in the request beside the picture, and a stored description is re-sent as
        // text on a turn that reads it (`#346`) — both are charged where they are spent.
        tokens += estimate_text_tokens(&picture.name);
        if let Some(seen) = &picture.seen {
            tokens += estimate_text_tokens(seen);
        }
    }
    tokens
}

/// What [`trim_to_budget`] did.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Trimmed {
    pub turns: usize,
    pub messages: usize,
}

/// The note placed in the system prompt in place of dropped turns.
pub fn trim_note(t: Trimmed) -> String {
    format!(
        "[trimmed {} older turn{} ({} message{}) to fit the context budget; \
         earlier conversation is not shown]",
        t.turns,
        if t.turns == 1 { "" } else { "s" },
        t.messages,
        if t.messages == 1 { "" } else { "s" },
    )
}

/// The line under a compiled handoff: how much it stands in for, and that the handoff itself is
/// what replaced it — "earlier conversation is not shown" would be a lie once it is.
pub fn compiled_tail(t: Trimmed) -> String {
    format!(
        "[compiled {} older turn{} ({} message{}) into the handoff above; every [#N] row is still \
         in the session and one session_search away]",
        t.turns,
        if t.turns == 1 { "" } else { "s" },
        t.messages,
        if t.messages == 1 { "" } else { "s" },
    )
}

/// How many turns stay verbatim at the tail when a request has to be shortened. A turn is
/// a user message and everything the agent did in answer, so twenty is a lot of live state.
pub const DEFAULT_PROTECT_LAST_N: usize = 20;

/// Which parts of the history a request keeps once it no longer fits: the first turn
/// (the ask, verbatim — it is the goal, and a summary of it is a guess), the last
/// `protect_last_n` turns (the live state), and nothing in between.
///
/// `history[..head_end]` and `history[tail_start..]` are sent; `history[head_end..tail_start]`
/// is what does not fit — dropped by [`trim_to_budget`], compiled by the compaction pass.
/// Nothing is dropped when `tail_start == head_end` (including both zero, which is how "the
/// whole history fits" is spelled).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Windows {
    pub head_end: usize,
    pub tail_start: usize,
    pub dropped: Trimmed,
}

impl Windows {
    /// True when a request would leave something out.
    pub fn drops_anything(&self) -> bool {
        self.tail_start > self.head_end
    }

    /// The turns that are not sent verbatim.
    pub fn dropped(&self) -> std::ops::Range<usize> {
        self.head_end..self.tail_start
    }
}

/// Turn starts: the index of every user message, and 0 if the history does not begin with
/// one (anything before the first user message belongs to the first turn).
fn turn_starts(history: &[Message]) -> Vec<usize> {
    let mut starts: Vec<usize> = history
        .iter()
        .enumerate()
        .filter(|(_, m)| m.role == Role::User)
        .map(|(i, _)| i)
        .collect();
    if starts.first() != Some(&0) {
        starts.insert(0, 0);
    }
    starts
}

fn turn_cost(history: &[Message], starts: &[usize], n: usize) -> usize {
    let end = starts.get(n + 1).copied().unwrap_or(history.len());
    history[starts[n]..end]
        .iter()
        .map(estimate_message_tokens)
        .sum()
}

/// Plan the three windows for one request. Pure arithmetic, no messages are built.
///
/// A `budget_tokens` of 0 disables it all; `fixed_tokens` (the tool definitions) counts
/// against the budget. A history that fits is sent untouched. Past the budget the tail is
/// filled newest-first — at most `protect_last_n` turns — and the first turn is kept when
/// there is room for both.
///
/// The tail has priority, with one reservation: when the first turn costs no more than half
/// the budget it is paid for first, so a conversation with slack keeps its goal instead of
/// spending the last of it on one more recent turn. A first turn that costs more than half
/// the budget is not reserved for — an enormous pasted prompt is not worth starving the live
/// state for — and the tail then takes what it can, which is the oldest-turns-go behaviour
/// this replaced. A turn is never split, so a tool call cannot be separated from its result.
/// The plan a manual compaction asks for: keep the first turn and the newest `protect_last_n`
/// turns verbatim and replace everything between them with the handoff, whether or not the
/// request would have fitted. It is the same calculation with the budget taken out of the
/// decision, which is why it cannot drift from [`plan_windows`].
pub fn plan_forced(system: &Message, history: &[Message], protect_last_n: usize) -> Windows {
    // No budget at all, rather than an enormous one: the planner answers "drop nothing" when the
    // history fits, and half of `usize::MAX` is a number no real history reaches — which is how a
    // forced compaction came to be a no-op (`#562`).
    plan(system, history, 0, 0, protect_last_n, true)
}

pub fn plan_windows(
    system: &Message,
    history: &[Message],
    budget_tokens: usize,
    fixed_tokens: usize,
    protect_last_n: usize,
) -> Windows {
    plan(
        system,
        history,
        budget_tokens,
        fixed_tokens,
        protect_last_n,
        false,
    )
}

/// The one planner, with `forced` as the only difference between the two callers.
///
/// `forced` is a manual compaction: the person asked for it, so the budget does not get a vote —
/// the head and the newest `protect_last_n` turns are kept and everything between them goes,
/// whatever the history costs. Everything else (which turns count as a turn, that a turn is never
/// split, that a `protect_last_n` of 0 still keeps one) is shared, which is what keeps the two
/// paths from drifting.
fn plan(
    system: &Message,
    history: &[Message],
    budget_tokens: usize,
    fixed_tokens: usize,
    protect_last_n: usize,
    forced: bool,
) -> Windows {
    let nothing = Windows::default();
    if history.is_empty() || (!forced && budget_tokens == 0) {
        return nothing;
    }
    let used = estimate_message_tokens(system) + fixed_tokens;
    let total: usize = history.iter().map(estimate_message_tokens).sum();
    if !forced && used + total <= budget_tokens {
        return nothing;
    }
    let starts = turn_starts(history);
    // One turn is the whole conversation: the latest turn is never sacrificed, so there is
    // nothing to choose between.
    if starts.len() < 2 {
        return nothing;
    }

    let first_end = starts[1];
    let head_cost: usize = history[..first_end]
        .iter()
        .map(estimate_message_tokens)
        .sum();
    // The ask is paid for first only when it is not the whole point of the budget — and always,
    // when a person asked for the compaction instead of the budget.
    let reserve = if forced || head_cost * 2 <= budget_tokens {
        head_cost
    } else {
        0
    };

    let mut tail_start = history.len();
    let mut tail_used = used;
    let keep = protect_last_n.max(1);
    for n in (0..starts.len()).rev() {
        if starts.len() - n > keep {
            break;
        }
        let cost = turn_cost(history, &starts, n);
        // The newest turn is kept unconditionally; older ones only while they fit — and all
        // `protect_last_n` of them when the compaction is a forced one.
        if !forced && tail_start != history.len() && tail_used + cost + reserve > budget_tokens {
            break;
        }
        tail_used += cost;
        tail_start = starts[n];
    }

    let head_end = if reserve > 0
        && first_end <= tail_start
        && (forced || head_cost + tail_used <= budget_tokens)
    {
        first_end
    } else {
        0
    };
    if head_end >= tail_start {
        return nothing;
    }
    Windows {
        head_end,
        tail_start,
        dropped: Trimmed {
            turns: starts
                .iter()
                .filter(|&&s| s >= head_end && s < tail_start)
                .count(),
            messages: tail_start - head_end,
        },
    }
}

/// The request messages: `system` (with `note` appended when given), the head of the history
/// and then the tail, with the dropped middle left out.
pub fn assemble(
    system: &Message,
    history: &[Message],
    windows: Windows,
    note: Option<&str>,
) -> Vec<Message> {
    let mut sys = system.clone();
    if let Some(note) = note {
        sys.content = Some(match sys.content.take() {
            Some(c) if !c.is_empty() => format!("{c}\n\n{note}"),
            _ => note.to_string(),
        });
    }
    let head = &history[..windows.head_end.min(history.len())];
    let tail = &history[windows.tail_start.min(history.len())..];
    let mut v = Vec::with_capacity(1 + head.len() + tail.len());
    v.push(sys);
    v.extend_from_slice(head);
    v.extend_from_slice(tail);
    v
}

/// Build the request messages: `system`, then as many of the most recent turns of
/// `history` as fit in `budget_tokens` (after `fixed_tokens`, e.g. the tool definitions).
/// A `budget_tokens` of 0 disables trimming. When turns are dropped the system message
/// gets a [`trim_note`] appended, so the model knows the conversation is incomplete.
pub fn trim_to_budget(
    system: &Message,
    history: &[Message],
    budget_tokens: usize,
    fixed_tokens: usize,
) -> (Vec<Message>, Trimmed) {
    let windows = plan_windows(
        system,
        history,
        budget_tokens,
        fixed_tokens,
        DEFAULT_PROTECT_LAST_N,
    );
    let note = windows.drops_anything().then(|| trim_note(windows.dropped));
    (
        assemble(system, history, windows, note.as_deref()),
        windows.dropped,
    )
}

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

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

    /// `n` turns of user / tool call / tool result / assistant, each text 40 chars.
    fn history(n: usize) -> Vec<Message> {
        let pad = "x".repeat(40);
        (0..n)
            .flat_map(|i| {
                [
                    Message::user(format!("q{i} {pad}")),
                    call(&format!("c{i}")),
                    Message::tool_result(format!("c{i}"), format!("r{i} {pad}")),
                    Message::assistant(format!("a{i} {pad}")),
                ]
            })
            .collect()
    }

    fn total(msgs: &[Message]) -> usize {
        msgs.iter().map(estimate_message_tokens).sum()
    }

    /// `#562`: a manual compaction was a no-op. `plan_forced` handed the planner a budget of
    /// `usize::MAX / 2`, and the planner answers "drop nothing" when the history fits — which every
    /// real history does at half of `usize::MAX` — so `/compress` and the dashboard's compaction
    /// threw nothing away. There was no test on the forced path at all, which is why the gate could
    /// not see it.
    #[test]
    fn a_forced_plan_drops_the_middle_of_a_history_that_fits_any_budget() {
        let history = history(4);
        let system = Message::system("sys");

        // The ordinary plan on a budget this history fits: nothing to do.
        assert!(!plan_windows(&system, &history, 1_000_000, 0, 2).drops_anything());

        // Forced: the first turn and the newest two are kept, the turn between them goes.
        let forced = plan_forced(&system, &history, 2);
        assert!(forced.drops_anything(), "a forced plan drops: {forced:?}");
        assert_eq!(forced.head_end, 4, "the first turn is kept whole");
        assert_eq!(forced.tail_start, 8, "the newest two turns are kept");
        assert_eq!(forced.dropped.turns, 1);
        assert_eq!(forced.dropped.messages, 4, "one turn is four messages");

        let kept = assemble(&system, &history, forced, None);
        assert_eq!(kept.len(), 1 + 4 + 8, "system, head, tail");
        assert!(kept[1].content.as_deref().unwrap_or("").starts_with("q0"));
        assert!(kept[5].content.as_deref().unwrap_or("").starts_with("q2"));
    }

    /// A forced plan on a history with nothing between the head and the tail has nothing to do, and
    /// says so rather than reporting a compaction that did not happen.
    #[test]
    fn a_forced_plan_of_two_turns_drops_nothing() {
        let history = history(2);
        let system = Message::system("sys");
        let forced = plan_forced(&system, &history, 2);
        assert!(!forced.drops_anything(), "{forced:?}");
        assert_eq!(assemble(&system, &history, forced, None).len(), 1 + 8);
    }

    #[test]
    fn a_forced_plan_of_an_empty_history_is_empty() {
        let system = Message::system("sys");
        assert!(!plan_forced(&system, &[], 3).drops_anything());
    }

    #[test]
    fn estimate_is_chars_over_four() {
        assert_eq!(estimate_text_tokens(""), 0);
        assert_eq!(estimate_text_tokens("abcd"), 1);
        assert_eq!(estimate_text_tokens("abcde"), 2);
        assert_eq!(estimate_text_tokens("ééééé"), 2, "counts chars, not bytes");
        let m = Message::user("a".repeat(40));
        assert_eq!(estimate_message_tokens(&m), 10 + MESSAGE_OVERHEAD);
        assert!(estimate_message_tokens(&call("c1")) > MESSAGE_OVERHEAD);
    }

    #[test]
    fn disabled_budget_sends_everything() {
        let h = history(5);
        let (msgs, t) = trim_to_budget(&Message::system("sys"), &h, 0, 0);
        assert_eq!(t, Trimmed::default());
        assert_eq!(msgs.len(), h.len() + 1);
        assert_eq!(msgs[0].content.as_deref(), Some("sys"));
    }

    #[test]
    fn within_budget_is_untouched() {
        let h = history(2);
        let (msgs, t) = trim_to_budget(&Message::system("sys"), &h, 100_000, 0);
        assert_eq!(t, Trimmed::default());
        assert_eq!(msgs[0].content.as_deref(), Some("sys"));
        assert_eq!(&msgs[1..], &h[..]);
    }

    /// Over budget, the middle goes: the ask stays (it is the goal), the newest turn stays
    /// (it is the live state), and the drops are named in the system prompt.
    #[test]
    fn the_middle_is_dropped_and_named_and_the_system_prompt_stays() {
        let h = history(6);
        let sys = Message::system("be helpful");
        let per_turn = total(&h[..4]);
        let budget = estimate_message_tokens(&sys) + per_turn * 2 + 5;
        let (msgs, t) = trim_to_budget(&sys, &h, budget, 0);
        assert_eq!(
            t,
            Trimmed {
                turns: 4,
                messages: 16
            }
        );
        assert_eq!(msgs.len(), 1 + 4 + 4, "the ask, then the newest turn");
        let sys_text = msgs[0].content.as_deref().unwrap();
        assert!(sys_text.starts_with("be helpful\n\n[trimmed 4 older turns (16 messages)"));
        assert_eq!(&msgs[1..5], &h[..4], "the ask, verbatim and whole");
        assert_eq!(&msgs[5..], &h[20..], "the newest turn, in order");
        assert_eq!(msgs[1].role, Role::User, "never starts mid-turn");
        assert_eq!(
            msgs[5].role,
            Role::User,
            "and never resumes mid-turn either"
        );
        assert!(total(&msgs[1..]) + estimate_message_tokens(&sys) <= budget);
    }

    #[test]
    fn tool_calls_stay_paired_with_their_results() {
        let h = history(8);
        for budget in (10..400).step_by(7) {
            let (msgs, _) = trim_to_budget(&Message::system("s"), &h, budget, 0);
            let calls: Vec<_> = msgs
                .iter()
                .flat_map(|m| m.tool_calls.iter().map(|c| c.id.clone()))
                .collect();
            let results: Vec<_> = msgs.iter().filter_map(|m| m.tool_call_id.clone()).collect();
            assert_eq!(calls, results, "budget {budget}");
        }
    }

    #[test]
    fn latest_turn_is_kept_even_when_over_budget() {
        let h = history(3);
        let (msgs, t) = trim_to_budget(&Message::system("s"), &h, 1, 0);
        assert_eq!(t.turns, 2);
        assert_eq!(&msgs[1..], &h[8..]);
        assert!(msgs[0]
            .content
            .as_deref()
            .unwrap()
            .contains("[trimmed 2 older turns"));
    }

    #[test]
    fn fixed_tokens_such_as_tool_specs_count_against_the_budget() {
        let h = history(4);
        let sys = Message::system("s");
        let budget = estimate_message_tokens(&sys) + total(&h) + 10;
        assert_eq!(trim_to_budget(&sys, &h, budget, 0).1, Trimmed::default());
        let (_, t) = trim_to_budget(&sys, &h, budget, total(&h[..8]));
        assert!(t.turns >= 2, "{t:?}");
    }

    #[test]
    fn single_turn_history_is_never_trimmed() {
        let h = history(1);
        let (msgs, t) = trim_to_budget(&Message::system("s"), &h, 1, 0);
        assert_eq!(t, Trimmed::default());
        assert_eq!(msgs.len(), 5);
    }

    #[test]
    fn plan_and_assemble_match_trim_to_budget() {
        let h = history(6);
        let sys = Message::system("s");
        let budget = estimate_message_tokens(&sys) + total(&h[..4]) * 2 + 5;
        let w = plan_windows(&sys, &h, budget, 0, DEFAULT_PROTECT_LAST_N);
        assert_eq!(
            w,
            Windows {
                head_end: 4,
                tail_start: 20,
                dropped: Trimmed {
                    turns: 4,
                    messages: 16
                }
            },
            "the ask and the newest turn; the middle pays"
        );
        let note = compiled_tail(w.dropped);
        let msgs = assemble(&sys, &h, w, Some(&note));
        assert_eq!(&msgs[1..5], &h[..4]);
        assert_eq!(&msgs[5..], &h[20..]);
        let text = msgs[0].content.as_deref().unwrap();
        assert!(
            text.starts_with("s\n\n[compiled 4 older turns (16 messages)")
                && text.contains("one session_search away"),
            "{text}"
        );
        assert!(
            text.contains("one session_search away"),
            "the note says how to reach what was left out: {text}"
        );
        let off = plan_windows(&sys, &h, 0, 0, DEFAULT_PROTECT_LAST_N);
        assert_eq!(off, Windows::default());
        assert_eq!(assemble(&sys, &h, off, None)[0], sys);
        assert_eq!(assemble(&sys, &h, off, None).len(), h.len() + 1);
    }

    /// The ask survives when there is room for it: it is the goal, and a summary of a goal is
    /// a guess. The middle is what pays.
    #[test]
    fn the_first_turn_is_kept_when_the_tail_leaves_room_for_it() {
        let h = history(8);
        let sys = Message::system("s");
        // Room for the first turn plus four of the newest.
        let budget = estimate_message_tokens(&sys) + total(&h[..4]) * 5;
        let w = plan_windows(&sys, &h, budget, 0, DEFAULT_PROTECT_LAST_N);
        assert_eq!(w.head_end, 4, "the first turn, whole");
        assert_eq!(w.tail_start, 16, "four of the newest turns: {w:?}");
        assert!(w.dropped.turns >= 1 && w.dropped.messages >= 4, "{w:?}");
        let msgs = assemble(&sys, &h, w, None);
        assert_eq!(&msgs[1..5], &h[..4], "the ask is verbatim");
        assert_eq!(&msgs[5..], &h[w.tail_start..], "then the tail");
        assert!(total(&msgs[1..]) + estimate_message_tokens(&sys) <= budget);
        // The drop is in the middle, never a prefix of what is sent.
        assert_eq!(msgs[1].content, h[0].content);
        assert_eq!(msgs.last().unwrap().content, h.last().unwrap().content);
    }

    /// `protect_last_n` bounds the tail even when the budget would pay for more.
    #[test]
    fn the_tail_is_at_most_protect_last_n_turns() {
        let h = history(10);
        let sys = Message::system("s");
        let budget = estimate_message_tokens(&sys) + total(&h) + 10; // everything fits
        let w = plan_windows(&sys, &h, budget, 0, 20);
        assert_eq!(w, Windows::default(), "under budget nothing is dropped");

        let budget = estimate_message_tokens(&sys) + total(&h[..4]) * 5;
        let w = plan_windows(&sys, &h, budget, 0, 2);
        assert_eq!(
            w.tail_start, 32,
            "two turns, whatever the budget could hold: {w:?}"
        );
    }

    /// When the head cannot be paid for, the old behaviour is what is left: drop the oldest
    /// turns and say so. Never a half turn.
    #[test]
    fn the_head_gives_way_rather_than_a_turn_being_split() {
        let h = history(4);
        let sys = Message::system("s");
        let budget = estimate_message_tokens(&sys) + total(&h[..4]) + 1;
        let w = plan_windows(&sys, &h, budget, 0, DEFAULT_PROTECT_LAST_N);
        assert_eq!(w.head_end, 0, "{w:?}");
        assert_eq!(w.tail_start, 12, "one turn: the newest is never dropped");
        let calls: Vec<_> = assemble(&sys, &h, w, None)
            .iter()
            .flat_map(|m| m.tool_calls.iter().map(|c| c.id.clone()))
            .collect();
        let results: Vec<_> = assemble(&sys, &h, w, None)
            .iter()
            .filter_map(|m| m.tool_call_id.clone())
            .collect();
        assert_eq!(calls, results);
    }

    fn picture() -> crate::message::ImagePart {
        crate::message::ImagePart {
            name: "shot.png".into(),
            mime: "image/png".into(),
            url: "data:image/png;base64,AAAA".into(),
            seen: None,
        }
    }

    #[test]
    fn a_picture_is_charged_so_a_window_of_them_cannot_overflow_silently() {
        let mut with_picture = Message::user("q xxxx");
        let text_only = estimate_message_tokens(&with_picture);
        with_picture.images.push(picture());
        let charged = estimate_message_tokens(&with_picture);
        assert!(
            charged >= text_only + PICTURE_TOKENS,
            "a picture costs nothing, so a native turn full of them never plans a compaction: \
             {text_only} -> {charged}"
        );
        // A description that will be re-sent as text is charged on top of the pixels.
        let mut described = with_picture.clone();
        described.images[0].seen = Some("a screenshot of a dashboard ".repeat(10));
        assert!(estimate_message_tokens(&described) > charged);
    }

    #[test]
    fn a_history_of_pictures_plans_a_compaction_it_used_to_miss() {
        let mut h = history(16);
        for m in h.iter_mut().filter(|m| m.role == Role::User) {
            m.images.push(picture());
        }
        // The budget fits this history with the pictures free, which is what the estimator said
        // before: the plan was "send it all" and the request was refused instead of compacted.
        let text_chars: usize = total(&h) - 16 * PICTURE_TOKENS;
        let budget = text_chars + 200;
        let w = plan_windows(
            &Message::system("sys"),
            &h,
            budget,
            0,
            DEFAULT_PROTECT_LAST_N,
        );
        assert!(
            w.drops_anything(),
            "16 pictures were counted as free, so nothing was planned to be dropped"
        );
    }
}