Skip to main content

eclipse_core/
context.rs

1//! Context-window management: bound what is sent to the model per request.
2//!
3//! Sizes are **estimates** (characters / 4, rounded up, plus a few tokens of per-message
4//! framing). Real tokenizers differ by model and language (CJK text and code are usually
5//! far more tokens per character), so treat the budget as a coarse safety rail, not a
6//! guarantee that the endpoint will accept the request.
7//!
8//! Trimming drops whole *turns* (a user message and everything the agent did in answer,
9//! tool calls and their results included) from the oldest end, so a tool call is never
10//! separated from its result. The system prompt and the tool definitions are always
11//! sent, and the latest turn is always kept, even if it alone exceeds the budget. The
12//! stored session is not modified; only the request is shortened.
13//!
14//! What replaces the dropped turns in the system prompt is the compiled handoff
15//! ([`crate::compact`]) and, under it, [`compiled_tail`]'s note about what was left out. The
16//! budget itself uses a character heuristic, so it is a rail rather than a promise: the
17//! handoff's own size is bounded separately by `[context] handoff_chars`.
18
19use crate::message::{Message, Role};
20
21/// Rough per-message overhead (role, separators) in tokens.
22const MESSAGE_OVERHEAD: usize = 4;
23
24/// What one picture costs, before its description is counted.
25///
26/// A picture is not characters. The wire carries a data URL whose base64 length says nothing about
27/// the tokens a model spends on the pixels — a 2 MB JPEG is 2.7 M characters and roughly a thousand
28/// tokens — so counting the URL would overcharge by three orders of magnitude while counting nothing
29/// (which is what this did) lets a native turn grow the window past the budget with no compaction
30/// planned. A flat charge is coarse on purpose and errs high: the estimate only has to plan a
31/// compaction before a request is refused.
32const PICTURE_TOKENS: usize = 900;
33
34pub fn estimate_text_tokens(text: &str) -> usize {
35    text.chars().count().div_ceil(4)
36}
37
38pub fn estimate_message_tokens(m: &Message) -> usize {
39    let mut chars = m.content.as_deref().map_or(0, |c| c.chars().count());
40    for call in &m.tool_calls {
41        chars += call.id.chars().count()
42            + call.function.name.chars().count()
43            + call.function.arguments.chars().count();
44    }
45    let mut tokens = chars.div_ceil(4) + MESSAGE_OVERHEAD;
46    for picture in &m.images {
47        tokens += PICTURE_TOKENS;
48        // The name rides in the request beside the picture, and a stored description is re-sent as
49        // text on a turn that reads it (`#346`) — both are charged where they are spent.
50        tokens += estimate_text_tokens(&picture.name);
51        if let Some(seen) = &picture.seen {
52            tokens += estimate_text_tokens(seen);
53        }
54    }
55    tokens
56}
57
58/// What [`trim_to_budget`] did.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub struct Trimmed {
61    pub turns: usize,
62    pub messages: usize,
63}
64
65/// The note placed in the system prompt in place of dropped turns.
66pub fn trim_note(t: Trimmed) -> String {
67    format!(
68        "[trimmed {} older turn{} ({} message{}) to fit the context budget; \
69         earlier conversation is not shown]",
70        t.turns,
71        if t.turns == 1 { "" } else { "s" },
72        t.messages,
73        if t.messages == 1 { "" } else { "s" },
74    )
75}
76
77/// The line under a compiled handoff: how much it stands in for, and that the handoff itself is
78/// what replaced it — "earlier conversation is not shown" would be a lie once it is.
79pub fn compiled_tail(t: Trimmed) -> String {
80    format!(
81        "[compiled {} older turn{} ({} message{}) into the handoff above; every [#N] row is still \
82         in the session and one session_search away]",
83        t.turns,
84        if t.turns == 1 { "" } else { "s" },
85        t.messages,
86        if t.messages == 1 { "" } else { "s" },
87    )
88}
89
90/// How many turns stay verbatim at the tail when a request has to be shortened. A turn is
91/// a user message and everything the agent did in answer, so twenty is a lot of live state.
92pub const DEFAULT_PROTECT_LAST_N: usize = 20;
93
94/// Which parts of the history a request keeps once it no longer fits: the first turn
95/// (the ask, verbatim — it is the goal, and a summary of it is a guess), the last
96/// `protect_last_n` turns (the live state), and nothing in between.
97///
98/// `history[..head_end]` and `history[tail_start..]` are sent; `history[head_end..tail_start]`
99/// is what does not fit — dropped by [`trim_to_budget`], compiled by the compaction pass.
100/// Nothing is dropped when `tail_start == head_end` (including both zero, which is how "the
101/// whole history fits" is spelled).
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
103pub struct Windows {
104    pub head_end: usize,
105    pub tail_start: usize,
106    pub dropped: Trimmed,
107}
108
109impl Windows {
110    /// True when a request would leave something out.
111    pub fn drops_anything(&self) -> bool {
112        self.tail_start > self.head_end
113    }
114
115    /// The turns that are not sent verbatim.
116    pub fn dropped(&self) -> std::ops::Range<usize> {
117        self.head_end..self.tail_start
118    }
119}
120
121/// Turn starts: the index of every user message, and 0 if the history does not begin with
122/// one (anything before the first user message belongs to the first turn).
123fn turn_starts(history: &[Message]) -> Vec<usize> {
124    let mut starts: Vec<usize> = history
125        .iter()
126        .enumerate()
127        .filter(|(_, m)| m.role == Role::User)
128        .map(|(i, _)| i)
129        .collect();
130    if starts.first() != Some(&0) {
131        starts.insert(0, 0);
132    }
133    starts
134}
135
136fn turn_cost(history: &[Message], starts: &[usize], n: usize) -> usize {
137    let end = starts.get(n + 1).copied().unwrap_or(history.len());
138    history[starts[n]..end]
139        .iter()
140        .map(estimate_message_tokens)
141        .sum()
142}
143
144/// Plan the three windows for one request. Pure arithmetic, no messages are built.
145///
146/// A `budget_tokens` of 0 disables it all; `fixed_tokens` (the tool definitions) counts
147/// against the budget. A history that fits is sent untouched. Past the budget the tail is
148/// filled newest-first — at most `protect_last_n` turns — and the first turn is kept when
149/// there is room for both.
150///
151/// The tail has priority, with one reservation: when the first turn costs no more than half
152/// the budget it is paid for first, so a conversation with slack keeps its goal instead of
153/// spending the last of it on one more recent turn. A first turn that costs more than half
154/// the budget is not reserved for — an enormous pasted prompt is not worth starving the live
155/// state for — and the tail then takes what it can, which is the oldest-turns-go behaviour
156/// this replaced. A turn is never split, so a tool call cannot be separated from its result.
157/// The plan a manual compaction asks for: keep the first turn and the newest `protect_last_n`
158/// turns verbatim and replace everything between them with the handoff, whether or not the
159/// request would have fitted. It is the same calculation with the budget taken out of the
160/// decision, which is why it cannot drift from [`plan_windows`].
161pub fn plan_forced(system: &Message, history: &[Message], protect_last_n: usize) -> Windows {
162    // No budget at all, rather than an enormous one: the planner answers "drop nothing" when the
163    // history fits, and half of `usize::MAX` is a number no real history reaches — which is how a
164    // forced compaction came to be a no-op (`#562`).
165    plan(system, history, 0, 0, protect_last_n, true)
166}
167
168pub fn plan_windows(
169    system: &Message,
170    history: &[Message],
171    budget_tokens: usize,
172    fixed_tokens: usize,
173    protect_last_n: usize,
174) -> Windows {
175    plan(
176        system,
177        history,
178        budget_tokens,
179        fixed_tokens,
180        protect_last_n,
181        false,
182    )
183}
184
185/// The one planner, with `forced` as the only difference between the two callers.
186///
187/// `forced` is a manual compaction: the person asked for it, so the budget does not get a vote —
188/// the head and the newest `protect_last_n` turns are kept and everything between them goes,
189/// whatever the history costs. Everything else (which turns count as a turn, that a turn is never
190/// split, that a `protect_last_n` of 0 still keeps one) is shared, which is what keeps the two
191/// paths from drifting.
192fn plan(
193    system: &Message,
194    history: &[Message],
195    budget_tokens: usize,
196    fixed_tokens: usize,
197    protect_last_n: usize,
198    forced: bool,
199) -> Windows {
200    let nothing = Windows::default();
201    if history.is_empty() || (!forced && budget_tokens == 0) {
202        return nothing;
203    }
204    let used = estimate_message_tokens(system) + fixed_tokens;
205    let total: usize = history.iter().map(estimate_message_tokens).sum();
206    if !forced && used + total <= budget_tokens {
207        return nothing;
208    }
209    let starts = turn_starts(history);
210    // One turn is the whole conversation: the latest turn is never sacrificed, so there is
211    // nothing to choose between.
212    if starts.len() < 2 {
213        return nothing;
214    }
215
216    let first_end = starts[1];
217    let head_cost: usize = history[..first_end]
218        .iter()
219        .map(estimate_message_tokens)
220        .sum();
221    // The ask is paid for first only when it is not the whole point of the budget — and always,
222    // when a person asked for the compaction instead of the budget.
223    let reserve = if forced || head_cost * 2 <= budget_tokens {
224        head_cost
225    } else {
226        0
227    };
228
229    let mut tail_start = history.len();
230    let mut tail_used = used;
231    let keep = protect_last_n.max(1);
232    for n in (0..starts.len()).rev() {
233        if starts.len() - n > keep {
234            break;
235        }
236        let cost = turn_cost(history, &starts, n);
237        // The newest turn is kept unconditionally; older ones only while they fit — and all
238        // `protect_last_n` of them when the compaction is a forced one.
239        if !forced && tail_start != history.len() && tail_used + cost + reserve > budget_tokens {
240            break;
241        }
242        tail_used += cost;
243        tail_start = starts[n];
244    }
245
246    let head_end = if reserve > 0
247        && first_end <= tail_start
248        && (forced || head_cost + tail_used <= budget_tokens)
249    {
250        first_end
251    } else {
252        0
253    };
254    if head_end >= tail_start {
255        return nothing;
256    }
257    Windows {
258        head_end,
259        tail_start,
260        dropped: Trimmed {
261            turns: starts
262                .iter()
263                .filter(|&&s| s >= head_end && s < tail_start)
264                .count(),
265            messages: tail_start - head_end,
266        },
267    }
268}
269
270/// The request messages: `system` (with `note` appended when given), the head of the history
271/// and then the tail, with the dropped middle left out.
272pub fn assemble(
273    system: &Message,
274    history: &[Message],
275    windows: Windows,
276    note: Option<&str>,
277) -> Vec<Message> {
278    let mut sys = system.clone();
279    if let Some(note) = note {
280        sys.content = Some(match sys.content.take() {
281            Some(c) if !c.is_empty() => format!("{c}\n\n{note}"),
282            _ => note.to_string(),
283        });
284    }
285    let head = &history[..windows.head_end.min(history.len())];
286    let tail = &history[windows.tail_start.min(history.len())..];
287    let mut v = Vec::with_capacity(1 + head.len() + tail.len());
288    v.push(sys);
289    v.extend_from_slice(head);
290    v.extend_from_slice(tail);
291    v
292}
293
294/// Build the request messages: `system`, then as many of the most recent turns of
295/// `history` as fit in `budget_tokens` (after `fixed_tokens`, e.g. the tool definitions).
296/// A `budget_tokens` of 0 disables trimming. When turns are dropped the system message
297/// gets a [`trim_note`] appended, so the model knows the conversation is incomplete.
298pub fn trim_to_budget(
299    system: &Message,
300    history: &[Message],
301    budget_tokens: usize,
302    fixed_tokens: usize,
303) -> (Vec<Message>, Trimmed) {
304    let windows = plan_windows(
305        system,
306        history,
307        budget_tokens,
308        fixed_tokens,
309        DEFAULT_PROTECT_LAST_N,
310    );
311    let note = windows.drops_anything().then(|| trim_note(windows.dropped));
312    (
313        assemble(system, history, windows, note.as_deref()),
314        windows.dropped,
315    )
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321    use crate::message::{FunctionCall, ToolCall};
322
323    fn call(id: &str) -> Message {
324        Message::assistant_tool_calls(
325            None,
326            vec![ToolCall {
327                id: id.into(),
328                kind: "function".into(),
329                function: FunctionCall {
330                    name: "shell".into(),
331                    arguments: "{}".into(),
332                },
333            }],
334        )
335    }
336
337    /// `n` turns of user / tool call / tool result / assistant, each text 40 chars.
338    fn history(n: usize) -> Vec<Message> {
339        let pad = "x".repeat(40);
340        (0..n)
341            .flat_map(|i| {
342                [
343                    Message::user(format!("q{i} {pad}")),
344                    call(&format!("c{i}")),
345                    Message::tool_result(format!("c{i}"), format!("r{i} {pad}")),
346                    Message::assistant(format!("a{i} {pad}")),
347                ]
348            })
349            .collect()
350    }
351
352    fn total(msgs: &[Message]) -> usize {
353        msgs.iter().map(estimate_message_tokens).sum()
354    }
355
356    /// `#562`: a manual compaction was a no-op. `plan_forced` handed the planner a budget of
357    /// `usize::MAX / 2`, and the planner answers "drop nothing" when the history fits — which every
358    /// real history does at half of `usize::MAX` — so `/compress` and the dashboard's compaction
359    /// threw nothing away. There was no test on the forced path at all, which is why the gate could
360    /// not see it.
361    #[test]
362    fn a_forced_plan_drops_the_middle_of_a_history_that_fits_any_budget() {
363        let history = history(4);
364        let system = Message::system("sys");
365
366        // The ordinary plan on a budget this history fits: nothing to do.
367        assert!(!plan_windows(&system, &history, 1_000_000, 0, 2).drops_anything());
368
369        // Forced: the first turn and the newest two are kept, the turn between them goes.
370        let forced = plan_forced(&system, &history, 2);
371        assert!(forced.drops_anything(), "a forced plan drops: {forced:?}");
372        assert_eq!(forced.head_end, 4, "the first turn is kept whole");
373        assert_eq!(forced.tail_start, 8, "the newest two turns are kept");
374        assert_eq!(forced.dropped.turns, 1);
375        assert_eq!(forced.dropped.messages, 4, "one turn is four messages");
376
377        let kept = assemble(&system, &history, forced, None);
378        assert_eq!(kept.len(), 1 + 4 + 8, "system, head, tail");
379        assert!(kept[1].content.as_deref().unwrap_or("").starts_with("q0"));
380        assert!(kept[5].content.as_deref().unwrap_or("").starts_with("q2"));
381    }
382
383    /// A forced plan on a history with nothing between the head and the tail has nothing to do, and
384    /// says so rather than reporting a compaction that did not happen.
385    #[test]
386    fn a_forced_plan_of_two_turns_drops_nothing() {
387        let history = history(2);
388        let system = Message::system("sys");
389        let forced = plan_forced(&system, &history, 2);
390        assert!(!forced.drops_anything(), "{forced:?}");
391        assert_eq!(assemble(&system, &history, forced, None).len(), 1 + 8);
392    }
393
394    #[test]
395    fn a_forced_plan_of_an_empty_history_is_empty() {
396        let system = Message::system("sys");
397        assert!(!plan_forced(&system, &[], 3).drops_anything());
398    }
399
400    #[test]
401    fn estimate_is_chars_over_four() {
402        assert_eq!(estimate_text_tokens(""), 0);
403        assert_eq!(estimate_text_tokens("abcd"), 1);
404        assert_eq!(estimate_text_tokens("abcde"), 2);
405        assert_eq!(estimate_text_tokens("ééééé"), 2, "counts chars, not bytes");
406        let m = Message::user("a".repeat(40));
407        assert_eq!(estimate_message_tokens(&m), 10 + MESSAGE_OVERHEAD);
408        assert!(estimate_message_tokens(&call("c1")) > MESSAGE_OVERHEAD);
409    }
410
411    #[test]
412    fn disabled_budget_sends_everything() {
413        let h = history(5);
414        let (msgs, t) = trim_to_budget(&Message::system("sys"), &h, 0, 0);
415        assert_eq!(t, Trimmed::default());
416        assert_eq!(msgs.len(), h.len() + 1);
417        assert_eq!(msgs[0].content.as_deref(), Some("sys"));
418    }
419
420    #[test]
421    fn within_budget_is_untouched() {
422        let h = history(2);
423        let (msgs, t) = trim_to_budget(&Message::system("sys"), &h, 100_000, 0);
424        assert_eq!(t, Trimmed::default());
425        assert_eq!(msgs[0].content.as_deref(), Some("sys"));
426        assert_eq!(&msgs[1..], &h[..]);
427    }
428
429    /// Over budget, the middle goes: the ask stays (it is the goal), the newest turn stays
430    /// (it is the live state), and the drops are named in the system prompt.
431    #[test]
432    fn the_middle_is_dropped_and_named_and_the_system_prompt_stays() {
433        let h = history(6);
434        let sys = Message::system("be helpful");
435        let per_turn = total(&h[..4]);
436        let budget = estimate_message_tokens(&sys) + per_turn * 2 + 5;
437        let (msgs, t) = trim_to_budget(&sys, &h, budget, 0);
438        assert_eq!(
439            t,
440            Trimmed {
441                turns: 4,
442                messages: 16
443            }
444        );
445        assert_eq!(msgs.len(), 1 + 4 + 4, "the ask, then the newest turn");
446        let sys_text = msgs[0].content.as_deref().unwrap();
447        assert!(sys_text.starts_with("be helpful\n\n[trimmed 4 older turns (16 messages)"));
448        assert_eq!(&msgs[1..5], &h[..4], "the ask, verbatim and whole");
449        assert_eq!(&msgs[5..], &h[20..], "the newest turn, in order");
450        assert_eq!(msgs[1].role, Role::User, "never starts mid-turn");
451        assert_eq!(
452            msgs[5].role,
453            Role::User,
454            "and never resumes mid-turn either"
455        );
456        assert!(total(&msgs[1..]) + estimate_message_tokens(&sys) <= budget);
457    }
458
459    #[test]
460    fn tool_calls_stay_paired_with_their_results() {
461        let h = history(8);
462        for budget in (10..400).step_by(7) {
463            let (msgs, _) = trim_to_budget(&Message::system("s"), &h, budget, 0);
464            let calls: Vec<_> = msgs
465                .iter()
466                .flat_map(|m| m.tool_calls.iter().map(|c| c.id.clone()))
467                .collect();
468            let results: Vec<_> = msgs.iter().filter_map(|m| m.tool_call_id.clone()).collect();
469            assert_eq!(calls, results, "budget {budget}");
470        }
471    }
472
473    #[test]
474    fn latest_turn_is_kept_even_when_over_budget() {
475        let h = history(3);
476        let (msgs, t) = trim_to_budget(&Message::system("s"), &h, 1, 0);
477        assert_eq!(t.turns, 2);
478        assert_eq!(&msgs[1..], &h[8..]);
479        assert!(msgs[0]
480            .content
481            .as_deref()
482            .unwrap()
483            .contains("[trimmed 2 older turns"));
484    }
485
486    #[test]
487    fn fixed_tokens_such_as_tool_specs_count_against_the_budget() {
488        let h = history(4);
489        let sys = Message::system("s");
490        let budget = estimate_message_tokens(&sys) + total(&h) + 10;
491        assert_eq!(trim_to_budget(&sys, &h, budget, 0).1, Trimmed::default());
492        let (_, t) = trim_to_budget(&sys, &h, budget, total(&h[..8]));
493        assert!(t.turns >= 2, "{t:?}");
494    }
495
496    #[test]
497    fn single_turn_history_is_never_trimmed() {
498        let h = history(1);
499        let (msgs, t) = trim_to_budget(&Message::system("s"), &h, 1, 0);
500        assert_eq!(t, Trimmed::default());
501        assert_eq!(msgs.len(), 5);
502    }
503
504    #[test]
505    fn plan_and_assemble_match_trim_to_budget() {
506        let h = history(6);
507        let sys = Message::system("s");
508        let budget = estimate_message_tokens(&sys) + total(&h[..4]) * 2 + 5;
509        let w = plan_windows(&sys, &h, budget, 0, DEFAULT_PROTECT_LAST_N);
510        assert_eq!(
511            w,
512            Windows {
513                head_end: 4,
514                tail_start: 20,
515                dropped: Trimmed {
516                    turns: 4,
517                    messages: 16
518                }
519            },
520            "the ask and the newest turn; the middle pays"
521        );
522        let note = compiled_tail(w.dropped);
523        let msgs = assemble(&sys, &h, w, Some(&note));
524        assert_eq!(&msgs[1..5], &h[..4]);
525        assert_eq!(&msgs[5..], &h[20..]);
526        let text = msgs[0].content.as_deref().unwrap();
527        assert!(
528            text.starts_with("s\n\n[compiled 4 older turns (16 messages)")
529                && text.contains("one session_search away"),
530            "{text}"
531        );
532        assert!(
533            text.contains("one session_search away"),
534            "the note says how to reach what was left out: {text}"
535        );
536        let off = plan_windows(&sys, &h, 0, 0, DEFAULT_PROTECT_LAST_N);
537        assert_eq!(off, Windows::default());
538        assert_eq!(assemble(&sys, &h, off, None)[0], sys);
539        assert_eq!(assemble(&sys, &h, off, None).len(), h.len() + 1);
540    }
541
542    /// The ask survives when there is room for it: it is the goal, and a summary of a goal is
543    /// a guess. The middle is what pays.
544    #[test]
545    fn the_first_turn_is_kept_when_the_tail_leaves_room_for_it() {
546        let h = history(8);
547        let sys = Message::system("s");
548        // Room for the first turn plus four of the newest.
549        let budget = estimate_message_tokens(&sys) + total(&h[..4]) * 5;
550        let w = plan_windows(&sys, &h, budget, 0, DEFAULT_PROTECT_LAST_N);
551        assert_eq!(w.head_end, 4, "the first turn, whole");
552        assert_eq!(w.tail_start, 16, "four of the newest turns: {w:?}");
553        assert!(w.dropped.turns >= 1 && w.dropped.messages >= 4, "{w:?}");
554        let msgs = assemble(&sys, &h, w, None);
555        assert_eq!(&msgs[1..5], &h[..4], "the ask is verbatim");
556        assert_eq!(&msgs[5..], &h[w.tail_start..], "then the tail");
557        assert!(total(&msgs[1..]) + estimate_message_tokens(&sys) <= budget);
558        // The drop is in the middle, never a prefix of what is sent.
559        assert_eq!(msgs[1].content, h[0].content);
560        assert_eq!(msgs.last().unwrap().content, h.last().unwrap().content);
561    }
562
563    /// `protect_last_n` bounds the tail even when the budget would pay for more.
564    #[test]
565    fn the_tail_is_at_most_protect_last_n_turns() {
566        let h = history(10);
567        let sys = Message::system("s");
568        let budget = estimate_message_tokens(&sys) + total(&h) + 10; // everything fits
569        let w = plan_windows(&sys, &h, budget, 0, 20);
570        assert_eq!(w, Windows::default(), "under budget nothing is dropped");
571
572        let budget = estimate_message_tokens(&sys) + total(&h[..4]) * 5;
573        let w = plan_windows(&sys, &h, budget, 0, 2);
574        assert_eq!(
575            w.tail_start, 32,
576            "two turns, whatever the budget could hold: {w:?}"
577        );
578    }
579
580    /// When the head cannot be paid for, the old behaviour is what is left: drop the oldest
581    /// turns and say so. Never a half turn.
582    #[test]
583    fn the_head_gives_way_rather_than_a_turn_being_split() {
584        let h = history(4);
585        let sys = Message::system("s");
586        let budget = estimate_message_tokens(&sys) + total(&h[..4]) + 1;
587        let w = plan_windows(&sys, &h, budget, 0, DEFAULT_PROTECT_LAST_N);
588        assert_eq!(w.head_end, 0, "{w:?}");
589        assert_eq!(w.tail_start, 12, "one turn: the newest is never dropped");
590        let calls: Vec<_> = assemble(&sys, &h, w, None)
591            .iter()
592            .flat_map(|m| m.tool_calls.iter().map(|c| c.id.clone()))
593            .collect();
594        let results: Vec<_> = assemble(&sys, &h, w, None)
595            .iter()
596            .filter_map(|m| m.tool_call_id.clone())
597            .collect();
598        assert_eq!(calls, results);
599    }
600
601    fn picture() -> crate::message::ImagePart {
602        crate::message::ImagePart {
603            name: "shot.png".into(),
604            mime: "image/png".into(),
605            url: "data:image/png;base64,AAAA".into(),
606            seen: None,
607        }
608    }
609
610    #[test]
611    fn a_picture_is_charged_so_a_window_of_them_cannot_overflow_silently() {
612        let mut with_picture = Message::user("q xxxx");
613        let text_only = estimate_message_tokens(&with_picture);
614        with_picture.images.push(picture());
615        let charged = estimate_message_tokens(&with_picture);
616        assert!(
617            charged >= text_only + PICTURE_TOKENS,
618            "a picture costs nothing, so a native turn full of them never plans a compaction: \
619             {text_only} -> {charged}"
620        );
621        // A description that will be re-sent as text is charged on top of the pixels.
622        let mut described = with_picture.clone();
623        described.images[0].seen = Some("a screenshot of a dashboard ".repeat(10));
624        assert!(estimate_message_tokens(&described) > charged);
625    }
626
627    #[test]
628    fn a_history_of_pictures_plans_a_compaction_it_used_to_miss() {
629        let mut h = history(16);
630        for m in h.iter_mut().filter(|m| m.role == Role::User) {
631            m.images.push(picture());
632        }
633        // The budget fits this history with the pictures free, which is what the estimator said
634        // before: the plan was "send it all" and the request was refused instead of compacted.
635        let text_chars: usize = total(&h) - 16 * PICTURE_TOKENS;
636        let budget = text_chars + 200;
637        let w = plan_windows(
638            &Message::system("sys"),
639            &h,
640            budget,
641            0,
642            DEFAULT_PROTECT_LAST_N,
643        );
644        assert!(
645            w.drops_anything(),
646            "16 pictures were counted as free, so nothing was planned to be dropped"
647        );
648    }
649}