Skip to main content

ag_ui/client/thread/
snapshot.rs

1//! Saving a conversation, and restoring one.
2
3use std::collections::{HashMap, HashSet};
4use std::sync::Arc;
5
6use crate::client::{
7    agent::RemoteAgent,
8    apply::{Applier, Subagent},
9    error::{Error, Result},
10    transport::Transport,
11};
12use crate::{Interrupt, Message, MessageId, ReasoningMessage, RunId, ThreadId, ToolCallId};
13use serde::{Deserialize, Serialize, de::DeserializeOwned};
14use serde_json::Value;
15
16use super::pending::{ResumeSubmission, SubmissionStatus, validate_responses};
17use super::run::RunEnd;
18use super::{Thread, random_id, unique};
19
20/// The format [`Thread::snapshot`] writes. Version 1 kept reasoning in a list
21/// of its own; [`Thread::restore`] still reads it.
22const VERSION: u32 = 2;
23
24fn current_protocol_version() -> Option<String> {
25    Some(crate::input::PROTOCOL_VERSION.to_owned())
26}
27
28/// A versioned local snapshot. It contains conversation data, never a transport,
29/// observer or running future. Validate it through `restore` before using it.
30///
31/// The fields are public: an application that reconciles a conversation with
32/// its server edits a snapshot and restores it. The struct is
33/// `#[non_exhaustive]`, so one is made by [`Thread::snapshot`], by
34/// deserializing, or by [`ThreadSnapshot::new`], and not by a struct literal.
35///
36/// ```
37/// use ag_ui::Message;
38/// use ag_ui::client::{Thread, ThreadSnapshot, transport::ReplayTransport};
39///
40/// let mut snapshot = ThreadSnapshot::new("thread-1");
41/// snapshot.messages = vec![Message::user("u-1", "Hello")];
42/// let thread = Thread::<_>::restore(ReplayTransport::new([]), snapshot)?;
43/// assert_eq!(thread.messages().len(), 1);
44/// # Ok::<(), ag_ui::client::Error>(())
45/// ```
46///
47/// A struct literal does not compile outside this crate, so a field added
48/// later breaks no caller:
49///
50/// ```compile_fail,E0639
51/// use ag_ui::client::ThreadSnapshot;
52///
53/// let snapshot = ThreadSnapshot {
54///     version: 2,
55///     thread_id: "thread-1".into(),
56///     protocol_version: None,
57///     messages: Vec::new(),
58///     state: serde_json::json!({}),
59///     reasoning: Vec::new(),
60///     subagents: Vec::new(),
61///     interrupts: Vec::new(),
62///     decided_interrupt_tool_call_ids: Vec::new(),
63///     abandoned: Vec::new(),
64///     submission: None,
65///     run_ids: Vec::new(),
66///     last_run_end: None,
67///     active_run_id: None,
68/// };
69/// ```
70#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
71#[non_exhaustive]
72pub struct ThreadSnapshot {
73    /// Snapshot format version (currently 2). Version 1 is still restored.
74    pub version: u32,
75    /// The remote conversation identifier.
76    pub thread_id: ThreadId,
77    /// Protocol version this thread declares to its peer. `None` pins a
78    /// legacy peer; snapshots predating this field restore the current version.
79    #[serde(default = "current_protocol_version")]
80    pub protocol_version: Option<String>,
81    /// Materialized conversation, reasoning and activity messages included.
82    pub messages: Vec<Message>,
83    /// Current raw shared state.
84    pub state: Value,
85    /// Version 1 only: the reasoning that format kept apart from `messages`.
86    /// A snapshot of the current version leaves it empty and does not write
87    /// it. [`Thread::restore`] moves a version 1 list into the conversation.
88    #[serde(default, skip_serializing_if = "Vec::is_empty")]
89    pub reasoning: Vec<ReasoningMessage>,
90    /// Announced subagent lifecycle state.
91    pub subagents: Vec<Subagent>,
92    /// Questions which have not been confirmed as answered.
93    pub interrupts: Vec<Interrupt>,
94    /// Tool calls whose interrupt decisions were accepted by a later run.
95    #[serde(default, skip_serializing_if = "Vec::is_empty")]
96    pub decided_interrupt_tool_call_ids: Vec<ToolCallId>,
97    /// The tool messages [`Thread::abandon_tool_call`] made: each stands in
98    /// for a result nobody produced.
99    /// [`Thread::merge_messages_from`] reads it to tell such a message from a
100    /// result. Not written when empty.
101    ///
102    /// The field is optional and the format version stays 2. A version 1
103    /// snapshot, and a version 2 snapshot written before the field existed,
104    /// restore with nothing recorded, so every tool message they hold counts
105    /// as a result. An id that names no tool message of `messages` is
106    /// dropped on restore.
107    #[serde(default, skip_serializing_if = "Vec::is_empty")]
108    pub abandoned: Vec<MessageId>,
109    /// A submitted decision whose acceptance has not been confirmed.
110    pub submission: Option<ResumeSubmission>,
111    /// Previously dispatched local run IDs, used to prevent reuse.
112    pub run_ids: Vec<RunId>,
113    /// The last locally observed termination, if any.
114    pub last_run_end: Option<RunEnd>,
115    /// A dispatched local run which had not ended when this snapshot was taken.
116    pub active_run_id: Option<RunId>,
117}
118
119impl ThreadSnapshot {
120    /// The snapshot of a conversation on which nothing has happened: no
121    /// messages, `{}` for state, the current format and protocol versions.
122    /// Set the fields that differ.
123    pub fn new(thread_id: impl Into<ThreadId>) -> Self {
124        Self {
125            version: VERSION,
126            thread_id: thread_id.into(),
127            protocol_version: current_protocol_version(),
128            messages: Vec::new(),
129            state: serde_json::json!({}),
130            reasoning: Vec::new(),
131            subagents: Vec::new(),
132            interrupts: Vec::new(),
133            decided_interrupt_tool_call_ids: Vec::new(),
134            abandoned: Vec::new(),
135            submission: None,
136            run_ids: Vec::new(),
137            last_run_end: None,
138            active_run_id: None,
139        }
140    }
141}
142
143impl<T, S> Thread<T, S> {
144    /// Save local conversation data. Transport settings and callbacks are excluded.
145    ///
146    /// What a run leaves can be restored: [`Thread::restore`] accepts the
147    /// snapshot of a thread whatever the streams it read carried.
148    pub fn snapshot(&self) -> ThreadSnapshot {
149        let mut run_ids: Vec<_> = self.run_ids.iter().cloned().collect();
150        run_ids.sort_by(|a, b| a.as_str().cmp(b.as_str()));
151        let mut decided_interrupt_tool_call_ids: Vec<_> = self
152            .decided_interrupt_tool_call_ids
153            .iter()
154            .cloned()
155            .collect();
156        decided_interrupt_tool_call_ids.sort_by(|a, b| a.as_str().cmp(b.as_str()));
157        // A stand-in a `MESSAGES_SNAPSHOT` removed since is not one any more.
158        let mut abandoned: Vec<_> = self
159            .abandoned
160            .iter()
161            .filter(|id| matches!(self.applier.message(id), Some(Message::Tool(_))))
162            .cloned()
163            .collect();
164        abandoned.sort_by(|a, b| a.as_str().cmp(b.as_str()));
165        ThreadSnapshot {
166            version: VERSION,
167            thread_id: self.thread_id.clone(),
168            protocol_version: self.protocol_version.clone(),
169            messages: self.messages().to_vec(),
170            state: self.raw_state().clone(),
171            reasoning: Vec::new(),
172            subagents: self.subagents().to_vec(),
173            interrupts: self.interrupts.clone(),
174            decided_interrupt_tool_call_ids,
175            abandoned,
176            submission: self.submission.clone(),
177            run_ids,
178            last_run_end: self.last_run_end.clone(),
179            active_run_id: self.active_run_id.clone(),
180        }
181    }
182}
183
184impl<T, S: DeserializeOwned> Thread<T, S> {
185    /// Restore local state using a new transport. No server query is performed.
186    ///
187    /// A version 1 snapshot kept reasoning in a list of its own, and nothing
188    /// in it says where a reasoning message stood among the others. Its
189    /// entries are put before every message of the conversation, in the
190    /// order the list held them. Reasoning comes before the reply it led to,
191    /// and there each entry still does; after the messages, each would follow
192    /// its own reply and stand in front of whatever the agent says next. From
193    /// there they are sent with the next run, like any other reasoning
194    /// message.
195    ///
196    /// Two kinds of entry are not moved. One whose id a message of the
197    /// conversation already has, because an id names one message. And one
198    /// with no content, encrypted value or metadata: that is what version 1
199    /// kept for a `REASONING_START` whose id no reasoning message shared, and
200    /// it holds no reasoning.
201    ///
202    /// # Errors
203    ///
204    /// [`Error::Snapshot`] for a version this build does not read, an empty
205    /// thread id, an id a list holds twice, a subagent whose parent is not
206    /// listed or is one of its own descendants, and a submission that does
207    /// not fit the rest; [`Error::State`] for a state that does not fit `S`.
208    /// An id may be the empty string: AG-UI 1.0 sets no minimum length for
209    /// one.
210    pub fn restore(transport: T, snapshot: ThreadSnapshot) -> Result<Self>
211    where
212        T: Transport,
213    {
214        Self::restore_shared(Arc::new(transport), snapshot)
215    }
216
217    pub(crate) fn restore_shared(transport: Arc<T>, mut snapshot: ThreadSnapshot) -> Result<Self> {
218        validate_snapshot(&snapshot)?;
219        if snapshot.active_run_id.take().is_some() {
220            snapshot.last_run_end = Some(RunEnd::Aborted);
221        }
222        let typed = S::deserialize(&snapshot.state).map_err(Error::State)?;
223        if let Some(submission) = &mut snapshot.submission {
224            submission.status = SubmissionStatus::Unconfirmed;
225        }
226        for subagent in &mut snapshot.subagents {
227            if subagent.status == crate::client::SubagentStatus::Running {
228                subagent.status = crate::client::SubagentStatus::Aborted;
229            }
230        }
231        let mut applier = Applier::new()
232            .with_messages(conversation(snapshot.messages, snapshot.reasoning))
233            .with_state(snapshot.state);
234        applier.restore_auxiliary(snapshot.subagents, snapshot.interrupts.clone());
235        let abandoned = snapshot
236            .abandoned
237            .into_iter()
238            .filter(|id| matches!(applier.message(id), Some(Message::Tool(_))))
239            .collect();
240        Ok(Self {
241            agent: RemoteAgent::new(transport),
242            thread_id: snapshot.thread_id,
243            applier,
244            state: Ok(typed),
245            tools: Vec::new(),
246            context: Vec::new(),
247            forwarded_props: Value::Null,
248            protocol_version: snapshot.protocol_version,
249            verify: true,
250            interrupts: snapshot.interrupts,
251            decided_interrupt_tool_call_ids: snapshot
252                .decided_interrupt_tool_call_ids
253                .into_iter()
254                .collect(),
255            abandoned,
256            submission: snapshot.submission,
257            run_ids: snapshot.run_ids.into_iter().collect(),
258            next_run_id: None,
259            last_run_end: snapshot.last_run_end,
260            active_run_id: None,
261            observer: None,
262            id_generator: Box::new(random_id),
263            diagnostic_limit: 100,
264        })
265    }
266}
267
268/// The messages of a snapshot with a version 1 reasoning list put in front of
269/// them; see [`Thread::restore`] for why there, and for the two kinds of
270/// entry left behind.
271fn conversation(messages: Vec<Message>, reasoning: Vec<ReasoningMessage>) -> Vec<Message> {
272    if reasoning.is_empty() {
273        return messages;
274    }
275    let taken: HashSet<&MessageId> = messages.iter().map(Message::id).collect();
276    let mut conversation: Vec<Message> = reasoning
277        .into_iter()
278        .filter(|entry| {
279            let holds_nothing = entry.content.is_empty()
280                && entry.encrypted_value.is_none()
281                && entry.metadata.is_none();
282            !holds_nothing && !taken.contains(&entry.id)
283        })
284        .map(Message::Reasoning)
285        .collect();
286    conversation.extend(messages);
287    conversation
288}
289
290fn validate_snapshot(snapshot: &ThreadSnapshot) -> Result<()> {
291    match snapshot.version {
292        1 => unique(
293            snapshot.reasoning.iter().map(|message| message.id.as_str()),
294            "reasoning",
295        )?,
296        // One store: a second list could only disagree with the first.
297        VERSION if snapshot.reasoning.is_empty() => {}
298        VERSION => {
299            return Err(Error::Snapshot(
300                "a version 2 snapshot holds reasoning in `messages`, so `reasoning` must be empty"
301                    .into(),
302            ));
303        }
304        other => return Err(Error::Snapshot(format!("unsupported version {other}"))),
305    }
306    if snapshot.thread_id.as_str().is_empty() {
307        return Err(Error::Snapshot("empty thread ID".into()));
308    }
309    unique(
310        snapshot
311            .messages
312            .iter()
313            .map(|message| message.id().as_str()),
314        "message",
315    )?;
316    unique(
317        snapshot
318            .subagents
319            .iter()
320            .map(|subagent| subagent.run_id.as_str()),
321        "subagent",
322    )?;
323    unique(
324        snapshot
325            .interrupts
326            .iter()
327            .map(|interrupt| interrupt.id.as_str()),
328        "interrupt",
329    )?;
330    unique(
331        snapshot
332            .decided_interrupt_tool_call_ids
333            .iter()
334            .map(ToolCallId::as_str),
335        "decided interrupt tool call",
336    )?;
337    unique(snapshot.run_ids.iter().map(|id| id.as_str()), "run")?;
338    let run_ids: HashSet<&RunId> = snapshot.run_ids.iter().collect();
339    if let Some(id) = &snapshot.active_run_id {
340        if !run_ids.contains(id) {
341            return Err(Error::Snapshot(
342                "active run refers to an unknown run ID".into(),
343            ));
344        }
345    }
346    ancestry(&snapshot.subagents)?;
347    if let Some(submission) = &snapshot.submission {
348        if submission.status == SubmissionStatus::InFlight
349            && snapshot.active_run_id.as_ref() != Some(&submission.run_id)
350        {
351            return Err(Error::Snapshot(
352                "in-flight submission must reference the active run".into(),
353            ));
354        }
355        if !run_ids.contains(&submission.run_id) {
356            return Err(Error::Snapshot(
357                "submission refers to an unknown run ID".into(),
358            ));
359        }
360        validate_responses(&snapshot.interrupts, &submission.entries, false)
361            .map_err(|error| Error::Snapshot(error.to_string()))?;
362    }
363    Ok(())
364}
365
366/// Checks that every subagent's parent is listed and that no subagent is its
367/// own ancestor, and returns how many parent links it followed.
368///
369/// Each subagent is walked from once, and a walk stops at the first one
370/// already known to reach a root, so the links followed never outnumber the
371/// subagents: a chain of any depth is checked in one pass.
372fn ancestry(subagents: &[Subagent]) -> Result<usize> {
373    /// Where the check stands on one subagent.
374    #[derive(Clone, Copy, PartialEq)]
375    enum Seen {
376        No,
377        /// On the walk in progress: reaching it again closes a cycle.
378        Walking,
379        /// Its ancestors end at a root.
380        Rooted,
381    }
382    let index: HashMap<&str, usize> = subagents
383        .iter()
384        .enumerate()
385        .map(|(index, subagent)| (subagent.run_id.as_str(), index))
386        .collect();
387    let mut seen = vec![Seen::No; subagents.len()];
388    let mut walk = Vec::new();
389    let mut followed = 0;
390    for start in 0..subagents.len() {
391        let mut at = start;
392        loop {
393            match seen[at] {
394                Seen::Rooted => break,
395                Seen::Walking => return Err(Error::Snapshot("cyclic subagent ancestry".into())),
396                Seen::No => {}
397            }
398            seen[at] = Seen::Walking;
399            walk.push(at);
400            let Some(parent) = &subagents[at].parent_subagent_run_id else {
401                break;
402            };
403            at = *index
404                .get(parent.as_str())
405                .ok_or_else(|| Error::Snapshot(format!("unknown parent subagent {parent}")))?;
406            followed += 1;
407        }
408        for walked in walk.drain(..) {
409            seen[walked] = Seen::Rooted;
410        }
411    }
412    Ok(followed)
413}
414
415#[cfg(test)]
416mod tests {
417    use super::*;
418
419    fn subagent(id: &str, parent: Option<&str>) -> Subagent {
420        Subagent {
421            run_id: id.into(),
422            name: "worker".into(),
423            description: None,
424            parent_subagent_run_id: parent.map(Into::into),
425            parent_tool_call_id: None,
426            parent_message_id: None,
427            status: crate::client::SubagentStatus::Finished { result: None },
428        }
429    }
430
431    /// The reviewer measured 1.5 s to restore 2,000 nested subagents: each
432    /// was walked to the root, and each step searched the list. The links
433    /// followed are counted here and not timed: one per subagent, whichever
434    /// end of the chain is listed first.
435    #[test]
436    fn a_chain_of_nested_subagents_is_checked_in_one_pass() {
437        const DEPTH: usize = 20_000;
438        let id = |depth: usize| format!("s-{depth}");
439        let mut chain: Vec<Subagent> = (0..DEPTH)
440            .map(|depth| {
441                let parent = depth.checked_sub(1).map(id);
442                subagent(&id(depth), parent.as_deref())
443            })
444            .collect();
445        assert_eq!(ancestry(&chain).unwrap(), DEPTH - 1);
446        chain.reverse();
447        assert_eq!(ancestry(&chain).unwrap(), DEPTH - 1);
448    }
449
450    #[test]
451    fn a_cycle_and_an_unlisted_parent_are_refused() {
452        let cycle = [
453            subagent("a", Some("c")),
454            subagent("b", Some("a")),
455            subagent("c", Some("b")),
456            subagent("d", Some("a")),
457        ];
458        assert_eq!(
459            ancestry(&cycle).unwrap_err().to_string(),
460            "invalid thread snapshot: cyclic subagent ancestry"
461        );
462        assert_eq!(
463            ancestry(&[subagent("a", Some("a"))])
464                .unwrap_err()
465                .to_string(),
466            "invalid thread snapshot: cyclic subagent ancestry"
467        );
468        assert_eq!(
469            ancestry(&[subagent("a", Some("gone"))])
470                .unwrap_err()
471                .to_string(),
472            "invalid thread snapshot: unknown parent subagent gone"
473        );
474        // A tree is neither.
475        let tree = [
476            subagent("root", None),
477            subagent("left", Some("root")),
478            subagent("right", Some("root")),
479            subagent("leaf", Some("left")),
480        ];
481        assert_eq!(ancestry(&tree).unwrap(), 3);
482    }
483}