Skip to main content

rhema_transcript/
zoom.rs

1//! The `zoom` tool: the model's way back to any original message.
2//!
3//! The view summarizes old ranges; zoom opens them. It reads the same
4//! mirror the decorator refreshes, so what it returns is the log as the
5//! last request carried it, which is every message the model has been
6//! shown an id for. Read-only: a `Safe` replay, per the resolver
7//! contract.
8
9use std::sync::{Arc, Mutex, PoisonError};
10
11use async_trait::async_trait;
12use rhema_core::{Content, Image, ReplaySafety, ToolCall, ToolContext, ToolResult, ToolSpec};
13
14use crate::summary;
15use crate::tree::Range;
16use crate::view::Transcript;
17
18/// Bytes one zoom call returns before cutting; the cut names the
19/// total and the `at` to resume at. The same cap and path at every
20/// `n`, so paging a range and paging a message are one call shape.
21pub const ZOOM_MAX_BYTES: usize = 8 * 1024;
22
23/// The most bytes one zoom call renders before it refuses. A range
24/// bigger than this cannot be paged, paging needs the bytes before
25/// `at` rendered too, and a narrower `n` is the way. Sixty-four
26/// pages: no honest range comes near it, and a model asking for the
27/// whole log in one call stops here instead of holding the mirror's
28/// lock while it all renders.
29const ZOOM_RENDER_CEILING: usize = 64 * ZOOM_MAX_BYTES;
30
31/// The `zoom` resolver over a shared mirror.
32#[derive(Debug, Clone)]
33pub struct Zoom {
34    transcript: Arc<Mutex<Transcript>>,
35}
36
37impl Zoom {
38    /// The resolver reading `transcript`, the mirror the view
39    /// decorator refreshes. Build both sides with [`crate::attach`].
40    pub fn new(transcript: Arc<Mutex<Transcript>>) -> Self {
41        Self { transcript }
42    }
43
44    /// The spec advertised to the model. Its description is the view's
45    /// contract: how the lines read and when to zoom.
46    pub fn spec() -> ToolSpec {
47        ToolSpec::new(
48            "zoom",
49            "Read older messages of this conversation whole. The \
50             <transcript> block in the context summarizes old ranges as \
51             `id+n|text` lines; zoom opens them. zoom(id, n) returns the \
52             n messages from id whole, a wide range with each message \
53             headed by its id+1| address. Long output is cut: pass at (a \
54             byte offset) to page on. Images the range holds ride the \
55             result as image blocks: zoom is the way back to pixels \
56             too. Before you guess, ask, or re-run a command: if a \
57             summary line omits what you need, the \
58             original is here.",
59            serde_json::json!({
60                "type": "object",
61                "properties": {
62                    "id": {
63                        "type": "integer",
64                        "description": "index of the range's first message"
65                    },
66                    "n": {
67                        "type": "integer",
68                        "description": "how many messages the range covers; the messages come back whole",
69                        "default": 1
70                    },
71                    "at": {
72                        "type": "integer",
73                        "description": "byte offset into the output, to page through a long message",
74                        "default": 0
75                    }
76                },
77                "required": ["id"]
78            }),
79        )
80    }
81
82    /// Resolves one zoom call; the in-band form of
83    /// [`rhema_core::ToolResolver::resolve`], public for tests and
84    /// embedders.
85    ///
86    /// `id`, `n`, and `at` arrive from the model and are trusted for
87    /// nothing: an out-of-range value is an in-band failure, and `at` is
88    /// snapped down to a char boundary before any slice.
89    pub fn zoom(&self, call: &ToolCall) -> ToolResult {
90        let Some(id) = call.args.get("id").and_then(|v| v.as_u64()) else {
91            return ToolResult::failure(&call.id, "zoom needs an integer `id`");
92        };
93        let n = call
94            .args
95            .get("n")
96            .and_then(|v| v.as_u64())
97            .unwrap_or(1)
98            .max(1) as usize;
99        let at = call.args.get("at").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
100
101        let transcript = self
102            .transcript
103            .lock()
104            .unwrap_or_else(PoisonError::into_inner);
105        let len = transcript.len();
106        let range = Range { id: id as usize, n };
107        if range.id >= len {
108            return ToolResult::failure(
109                &call.id,
110                format!("zoom: message {id} is past the log ({len} messages)"),
111            );
112        }
113        // Saturating: `n` is model-supplied and unbounded; the wrapped
114        // sum of a plain add could land inside the log.
115        if range.id.saturating_add(range.n) > len {
116            return ToolResult::failure(
117                &call.id,
118                format!(
119                    "zoom: {id}+{} reaches past the log ({len} messages); \
120                     the last message is {}",
121                    range.n,
122                    len - 1
123                ),
124            );
125        }
126
127        // Render only what the requested page needs: everything up to
128        // one byte past `at + ZOOM_MAX_BYTES`, which is all the offset
129        // math reads. A page-1 call stops one message past its page
130        // instead of rendering the whole range under the lock.
131        let needed = at.saturating_add(ZOOM_MAX_BYTES).saturating_add(1);
132        let range_end = range.id + range.n;
133        let mut text = String::new();
134        let mut covered = range.id;
135        for i in range.id..range_end {
136            if !text.is_empty() {
137                text.push('\n');
138            }
139            if range.n > 1 {
140                // The addresses are the map: a page of content also
141                // names the messages it holds, so the model can zoom a
142                // neighbor or a narrower range without recomputing.
143                text.push_str(&format!("{i}+1|"));
144            }
145            let message = transcript.message(i).expect("the range was checked");
146            text.push_str(&summary::render_message(message));
147            covered = i + 1;
148            if text.len() >= needed && covered < range_end {
149                break;
150            }
151        }
152        let truncated = covered < range_end;
153        if truncated && text.len() > ZOOM_RENDER_CEILING {
154            return ToolResult::failure(
155                &call.id,
156                format!(
157                    "zoom: {id}+{} renders past the byte budget, \
158                     zoom a narrower range (smaller n)",
159                    range.n
160                ),
161            );
162        }
163
164        if at >= text.len() {
165            if truncated {
166                return ToolResult::failure(
167                    &call.id,
168                    format!(
169                        "zoom: `at` {at} lands past what was rendered \
170                         ({} bytes); zoom a narrower range (smaller n)",
171                        text.len()
172                    ),
173                );
174            }
175            let mut msg = format!("zoom: `at` {at} is past the end ({} bytes)", text.len());
176            // Only a render bigger than one page has a tail worth
177            // pointing at.
178            if text.len() > ZOOM_MAX_BYTES {
179                msg.push_str(&format!("; page from {}", text.len() - ZOOM_MAX_BYTES));
180            }
181            return ToolResult::failure(&call.id, msg);
182        }
183        // The pixels the rendered messages hold ride the result: the
184        // `[image: ...]` lines in the text only name them, and zoom
185        // is the way back. Newest first past the cap, the same bound
186        // the band obeys, so one zoom cannot smuggle more images
187        // than a view itself may send; the note names the rest.
188        let mut images: Vec<Image> = Vec::new();
189        let shown = Range {
190            id: range.id,
191            n: covered - range.id,
192        };
193        for message in transcript.range(shown).unwrap_or(&[]) {
194            for part in &message.content {
195                match part {
196                    Content::ToolResult(result) => images.extend(result.images.iter().cloned()),
197                    Content::Image(image) => images.push(image.clone()),
198                    _ => {}
199                }
200            }
201        }
202        let mut image_note = String::new();
203        let cap = transcript.max_view_images();
204        if images.len() > cap {
205            let omitted = images.len() - cap;
206            let noun = if omitted == 1 { "image" } else { "images" };
207            image_note = format!("\n\n[{omitted} older {noun} omitted]");
208            images = images.split_off(omitted);
209        }
210
211        let start = snapped_back(&text, at);
212        if text.len() <= ZOOM_MAX_BYTES {
213            return ToolResult::success(&call.id, format!("{}{}", &text[start..], image_note))
214                .with_images(images);
215        }
216        let mut end = start.saturating_add(ZOOM_MAX_BYTES).min(text.len());
217        while end < text.len() && !text.is_char_boundary(end) {
218            end -= 1;
219        }
220        // The total is only known when the render reached the range's
221        // end; a page cut short of it reports its own size instead.
222        let note = if end < text.len() {
223            if truncated {
224                format!("\n\n[{} bytes; zoom again with at={end}]", end - start)
225            } else {
226                format!(
227                    "\n\n[{} of {} bytes; zoom again with at={}]",
228                    end - start,
229                    text.len(),
230                    end
231                )
232            }
233        } else {
234            String::new()
235        };
236        ToolResult::success(
237            &call.id,
238            format!("{}{}{}", &text[start..end], note, image_note),
239        )
240        .with_images(images)
241    }
242}
243
244/// The largest char boundary at or below `at`, the model supplies raw
245/// byte offsets, and UTF-8 cannot be cut mid-character.
246fn snapped_back(text: &str, at: usize) -> usize {
247    let mut at = at.min(text.len());
248    while at > 0 && !text.is_char_boundary(at) {
249        at -= 1;
250    }
251    at
252}
253
254#[async_trait]
255impl rhema_core::ToolResolver for Zoom {
256    fn specs(&self) -> Vec<ToolSpec> {
257        vec![Self::spec()]
258    }
259
260    fn replay_safety(&self, name: &str) -> ReplaySafety {
261        if name == "zoom" {
262            ReplaySafety::Safe
263        } else {
264            ReplaySafety::Unsafe
265        }
266    }
267
268    async fn resolve(&self, call: ToolCall, _ctx: &ToolContext) -> ToolResult {
269        self.zoom(&call)
270    }
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276    use rhema_core::{Message, Role, ToolResolver};
277
278    fn transcript_with(messages: Vec<Message>) -> Arc<Mutex<Transcript>> {
279        let mut transcript = Transcript::new(crate::view::TranscriptSettings::default());
280        transcript.observe(&messages);
281        Arc::new(Mutex::new(transcript))
282    }
283
284    fn call(args: serde_json::Value) -> ToolCall {
285        ToolCall {
286            id: "z1".into(),
287            name: "zoom".into(),
288            args,
289            provider_data: serde_json::Value::Null,
290        }
291    }
292
293    fn history() -> Vec<Message> {
294        vec![
295            Message::text(Role::User, "fix the login bug"),
296            Message::text(Role::Assistant, "checking auth.rs"),
297            Message::text(Role::User, "the session one, not the api key"),
298        ]
299    }
300
301    #[test]
302    fn zoom_one_returns_the_message_whole() {
303        let zoom = Zoom::new(transcript_with(history()));
304        let out = zoom.zoom(&call(serde_json::json!({ "id": 1 })));
305        assert!(!out.is_error);
306        assert_eq!(out.content, "checking auth.rs");
307    }
308
309    /// One tool result holding images, at index 4 of a
310    /// user-assistant-user-user-result log.
311    fn image_history(count: usize) -> Vec<Message> {
312        let mut messages = history();
313        messages.push(Message::text(Role::User, "the screenshot"));
314        messages.push(Message {
315            annotations: Default::default(),
316            role: Role::Tool,
317            content: vec![rhema_core::Content::ToolResult(
318                rhema_core::ToolResult::success("c1", "shot").with_images(
319                    (0..count)
320                        .map(|i| {
321                            rhema_core::Image::new(rhema_core::ImageMediaType::Png, format!("Z{i}"))
322                        })
323                        .collect(),
324                ),
325            )],
326        });
327        messages
328    }
329
330    /// The pixels ride the result: the text still names them, and
331    /// zoom is the way back past the view's stand-ins.
332    #[test]
333    fn zoom_returns_the_range_s_images() {
334        let zoom = Zoom::new(transcript_with(image_history(2)));
335        let out = zoom.zoom(&call(serde_json::json!({ "id": 4, "n": 1 })));
336        assert!(!out.is_error);
337        assert_eq!(out.images.len(), 2);
338        assert!(
339            out.content.contains("[image: image/png]"),
340            "{}",
341            out.content
342        );
343        assert!(
344            out.images
345                .iter()
346                .all(|image| image.data == "Z0" || image.data == "Z1")
347        );
348    }
349
350    /// Past the cap the newest ride and the note names the rest; the
351    /// omitted images are one narrower range away.
352    #[test]
353    fn zoom_caps_its_images_to_the_newest() {
354        let mut transcript = Transcript::new(crate::view::TranscriptSettings {
355            max_view_images: 2,
356            ..Default::default()
357        });
358        transcript.observe(&image_history(3));
359        let zoom = Zoom::new(Arc::new(Mutex::new(transcript)));
360        let out = zoom.zoom(&call(serde_json::json!({ "id": 4, "n": 1 })));
361        assert!(!out.is_error);
362        assert_eq!(out.images.len(), 2);
363        assert!(
364            out.content.contains("1 older image omitted"),
365            "{}",
366            out.content
367        );
368        assert!(out.images.iter().all(|image| image.data != "Z0"));
369    }
370
371    #[test]
372    fn zoom_many_returns_the_messages_whole_and_addressed() {
373        let zoom = Zoom::new(transcript_with(history()));
374        let out = zoom.zoom(&call(serde_json::json!({ "id": 0, "n": 3 })));
375        assert!(!out.is_error);
376        assert!(
377            out.content.contains("0+1|fix the login bug")
378                && out.content.contains("1+1|checking auth.rs")
379                && out.content.contains("2+1|the session one, not the api key"),
380            "{}",
381            out.content
382        );
383    }
384
385    #[test]
386    fn a_wide_range_pages_the_same_way_a_message_does() {
387        // Three messages of half the cap each: the range's content
388        // cannot fit one page, and the second page begins inside the
389        // second message, so the third one's address lands on it.
390        let chunk = "y".repeat(ZOOM_MAX_BYTES / 2);
391        let transcript = transcript_with(vec![
392            Message::text(Role::User, chunk.clone()),
393            Message::text(Role::Assistant, chunk.clone()),
394            Message::text(Role::User, chunk),
395        ]);
396        let zoom = Zoom::new(Arc::clone(&transcript));
397        let first = zoom.zoom(&call(serde_json::json!({ "id": 0, "n": 3 })));
398        assert!(first.content.contains("at="), "{}", first.content);
399        let resume_at: usize = first
400            .content
401            .split("at=")
402            .nth(1)
403            .unwrap()
404            .trim_end_matches(']')
405            .parse()
406            .unwrap();
407        let rest = zoom.zoom(&call(
408            serde_json::json!({ "id": 0, "n": 3, "at": resume_at }),
409        ));
410        assert!(!rest.is_error, "{:?}", rest);
411        // The last page reaches the range's final message and needs
412        // no further cut.
413        assert!(rest.content.contains("2+1|"), "{}", rest.content);
414        assert!(!rest.content.contains("at="), "{}", rest.content);
415    }
416
417    #[test]
418    fn bad_ids_are_in_band_errors() {
419        let zoom = Zoom::new(transcript_with(history()));
420        let past = zoom.zoom(&call(serde_json::json!({ "id": 3 })));
421        assert!(past.is_error);
422        assert!(past.content.contains("past the log (3 messages)"));
423        let over = zoom.zoom(&call(serde_json::json!({ "id": 1, "n": 9 })));
424        assert!(over.is_error);
425        let no_id = zoom.zoom(&call(serde_json::json!({ "n": 1 })));
426        assert!(no_id.is_error);
427    }
428
429    #[test]
430    fn a_long_message_pages_at_the_offset() {
431        let big = "y".repeat(ZOOM_MAX_BYTES + 500);
432        let zoom = Zoom::new(transcript_with(vec![Message::text(Role::User, big)]));
433        let first = zoom.zoom(&call(serde_json::json!({ "id": 0 })));
434        assert!(first.content.len() <= ZOOM_MAX_BYTES + 100);
435        assert!(first.content.contains("at="), "{}", first.content);
436        let resume_at: usize = first
437            .content
438            .split("at=")
439            .nth(1)
440            .unwrap()
441            .trim_end_matches(']')
442            .parse()
443            .unwrap();
444        let rest = zoom.zoom(&call(serde_json::json!({ "id": 0, "at": resume_at })));
445        assert!(!rest.is_error, "{:?}", rest);
446        assert!(
447            rest.content.len() <= 500 + 100,
448            "{} bytes",
449            rest.content.len()
450        );
451    }
452
453    #[test]
454    fn a_wide_range_renders_one_page_and_names_its_own_size() {
455        let line = "x".repeat(600);
456        let messages: Vec<Message> = (0..200)
457            .map(|i| Message::text(Role::User, format!("msg {i} {line}")))
458            .collect();
459        let zoom = Zoom::new(transcript_with(messages));
460        let out = zoom.zoom(&call(serde_json::json!({ "id": 0, "n": 200 })));
461        assert!(!out.is_error, "{:?}", out);
462        // One page, not two hundred messages.
463        assert!(
464            out.content.len() < ZOOM_MAX_BYTES + 2048,
465            "{} bytes",
466            out.content.len()
467        );
468        // The render stopped early: the note carries no grand total.
469        assert!(
470            out.content.contains("zoom again with at="),
471            "{}",
472            out.content
473        );
474        assert!(!out.content.contains(" of "), "{}", out.content);
475        // Paging continues from the named offset.
476        let at: usize = out
477            .content
478            .rsplit("at=")
479            .next()
480            .unwrap()
481            .trim_end_matches(']')
482            .parse()
483            .unwrap();
484        let rest = zoom.zoom(&call(serde_json::json!({ "id": 0, "n": 200, "at": at })));
485        assert!(!rest.is_error, "{:?}", rest);
486    }
487
488    #[test]
489    fn a_range_past_the_ceiling_refuses_with_a_direction() {
490        let line = "x".repeat(2000);
491        let messages: Vec<Message> = (0..400)
492            .map(|i| Message::text(Role::User, format!("msg {i} {line}")))
493            .collect();
494        let zoom = Zoom::new(transcript_with(messages));
495        // Early pages are honest work: the ceiling refuses the deep
496        // ones, where honoring `at` means rendering half a megabyte to
497        // hand back eight kilobytes.
498        let deep = ZOOM_RENDER_CEILING - 2000;
499        let out = zoom.zoom(&call(serde_json::json!({ "id": 0, "n": 400, "at": deep })));
500        assert!(
501            out.is_error,
502            "the deep page does not render: {}",
503            &out.content[..200]
504        );
505        assert!(out.content.contains("narrower range"), "{}", out.content);
506        // A single message still reads: the ceiling is for ranges.
507        let one = zoom.zoom(&call(serde_json::json!({ "id": 399 })));
508        assert!(!one.is_error, "{:?}", one);
509    }
510
511    #[test]
512    fn the_spec_advertises_zoom_and_only_zoom() {
513        let zoom = Zoom::new(transcript_with(history()));
514        let names: Vec<String> = zoom.specs().iter().map(|s| s.name.clone()).collect();
515        assert_eq!(names, vec!["zoom".to_owned()]);
516        let spec = Zoom::spec();
517        assert!(spec.description.contains("id+n|text"));
518        assert_eq!(zoom.replay_safety("zoom"), ReplaySafety::Safe);
519        assert_eq!(zoom.replay_safety("other"), ReplaySafety::Unsafe);
520    }
521
522    #[test]
523    fn a_text_block_only_history_renders_verbatim() {
524        let zoom = Zoom::new(transcript_with(history()));
525        let out = zoom.zoom(&call(serde_json::json!({ "id": 2 })));
526        assert_eq!(out.content, "the session one, not the api key");
527    }
528
529    #[test]
530    fn an_absurd_n_is_an_in_band_error_not_an_overflow() {
531        // id=1 with n=u64::MAX wrapped to `id + n == 0` under a plain
532        // add, walking past the bounds check into the expects.
533        let zoom = Zoom::new(transcript_with(history()));
534        let out = zoom.zoom(&call(serde_json::json!({ "id": 1, "n": u64::MAX })));
535        assert!(out.is_error);
536        assert!(out.content.contains("past the log"), "{}", out.content);
537    }
538
539    #[test]
540    fn an_at_past_the_end_names_the_content_size() {
541        // The render is the content, so the byte count in the error
542        // must equal what a successful call over the same range
543        // returns, not the size of some condensation of it.
544        let zoom = Zoom::new(transcript_with(history()));
545        let whole = zoom.zoom(&call(serde_json::json!({ "id": 0, "n": 3 })));
546        assert!(!whole.is_error);
547        let out = zoom.zoom(&call(serde_json::json!({ "id": 0, "n": 3, "at": 10_000 })));
548        assert!(out.is_error);
549        let size: usize = out
550            .content
551            .split('(')
552            .nth(1)
553            .unwrap()
554            .split(" bytes")
555            .next()
556            .unwrap()
557            .parse()
558            .unwrap();
559        assert_eq!(size, whole.content.len(), "{}", out.content);
560    }
561
562    #[test]
563    fn an_at_inside_a_character_snaps_back_instead_of_panic() {
564        // Byte 1 sits inside the two-byte leading `é`: the raw slice
565        // used to panic here.
566        let zoom = Zoom::new(transcript_with(vec![Message::text(
567            Role::User,
568            "éa long enough message to hold a paging cut",
569        )]));
570        let out = zoom.zoom(&call(serde_json::json!({ "id": 0, "at": 1 })));
571        assert!(!out.is_error, "{out:?}");
572        assert!(out.content.starts_with('é'), "{}", out.content);
573    }
574}