ag_ui/client/thread/merge.rs
1//! Two threads on one conversation: bringing together what each of them added.
2
3use std::collections::{HashMap, HashSet, hash_map::Entry};
4
5use crate::client::error::{Error, Result};
6use crate::client::transport::Transport;
7use crate::{Message, MessageId, ToolCallId};
8
9use super::Thread;
10
11/// What [`Thread::merge_messages_from`] added to a thread, and what it left
12/// as it was.
13#[derive(Clone, Debug, Default, PartialEq, Eq)]
14#[non_exhaustive]
15#[must_use = "`differing` names the messages of the other thread that were not taken"]
16pub struct MergeReport {
17 /// The messages added, in the order the other thread holds them. Each is
18 /// in [`Thread::messages`] now: a tool result behind the message that
19 /// holds its call, every other message at the end.
20 pub added: Vec<MessageId>,
21 /// The ids both threads hold as different messages. This thread's copy
22 /// was kept, and the other thread's was not taken. Empty when the two
23 /// threads started from the same messages and each only added its own.
24 pub differing: Vec<MessageId>,
25 /// The tool messages of the other thread that
26 /// [`abandon_tool_call`](Thread::abandon_tool_call) made there for a call
27 /// this thread holds an answer to, in the order the other thread holds
28 /// them. Each stood in for a result the other thread never got, and was
29 /// not taken: the call keeps the answer this thread has.
30 pub superseded: Vec<MessageId>,
31}
32
33/// Merges two copies of one conversation's messages, by message id.
34///
35/// AG-UI 1.0 makes a message id unique within its thread, so two lists that
36/// hold the same conversation agree on which message is which. They differ in
37/// what each holds that the other lacks, and that is all this adds: the
38/// result is `ours` with the messages of `theirs` it does not hold.
39///
40/// | A message | In the result |
41/// | --- | --- |
42/// | only `ours` holds | as it is, in the order `ours` has them |
43/// | both hold, the copies equal | once, in the place `ours` gives it |
44/// | both hold, the copies different | the copy of `ours`, in the place `ours` gives it |
45/// | only `theirs` holds | after every message of `ours`, in the order `theirs` has them |
46/// | a tool result, of either list, whose call a message before it holds | directly behind that message, after the tool results and activity messages already behind it |
47///
48/// Two lists that started from the same messages and each grew at the end
49/// therefore merge to: the common start, what `ours` added, what `theirs`
50/// added. The result depends on the two lists and nothing else, so the same
51/// arguments always give the same list. It is not symmetric: with the
52/// arguments swapped, the other list's additions come first and the other
53/// list's copies are the ones kept.
54///
55/// No message of `ours` is changed or left out, so a message one list saw
56/// complete and the other only in part stays as `ours` has it. Pass as `ours`
57/// the list whose copies should stand.
58///
59/// The last row is the one rule about a role. A tool result is placed by the
60/// call it answers and not by where a list kept it, so that in the result it
61/// follows the message that holds its call whichever way the two lists were
62/// built: one that arrived after other messages and was kept at the end is
63/// put behind its call, in `ours` as in `theirs`. A list whose results stand
64/// behind their calls already comes through in its own order. The message
65/// that holds a call is the assistant message with that call among its
66/// `tool_calls`. Where several hold the id, as with a provider that numbers
67/// its calls from zero in every turn, it is the newest one whose call has no
68/// result yet, or the newest one when each has. A result whose call no
69/// earlier message holds stays in the order of its list.
70///
71/// A reasoning message stays in front of the reply it led to because the
72/// order of each list is kept, and an activity message is merged like any
73/// other.
74///
75/// The function reads ids and nothing else. It does not know which
76/// conversation a list belongs to, and it does not refuse a tool call both
77/// lists answered: both results are in the list. Use it for a view of two
78/// threads while either is still running. For the thread that will send the
79/// next request, [`Thread::merge_messages_from`] applies the same rules and
80/// checks what a list cannot say.
81///
82/// Each list is expected to hold an id once, as [`Thread::messages`] does. Of
83/// a repeated id the first message is kept.
84///
85/// ```
86/// use ag_ui::Message;
87/// use ag_ui::client::merge_messages;
88///
89/// let start = vec![Message::user("u-1", "Hello"), Message::assistant("a-1", "Hi")];
90/// // Two copies of the conversation, each of which went on by itself.
91/// let mut ours = start.clone();
92/// ours.push(Message::user("u-2", "Write the report"));
93/// ours.push(Message::assistant("a-2", "Here it is."));
94/// let mut theirs = start.clone();
95/// theirs.push(Message::user("u-3", "What time is it?"));
96/// theirs.push(Message::assistant("a-3", "Noon."));
97///
98/// let merged = merge_messages(&ours, &theirs);
99/// let ids: Vec<_> = merged.iter().map(|message| message.id().as_str()).collect();
100/// assert_eq!(ids, ["u-1", "a-1", "u-2", "a-2", "u-3", "a-3"]);
101/// ```
102#[must_use]
103pub fn merge_messages(ours: &[Message], theirs: &[Message]) -> Vec<Message> {
104 merge(ours, theirs, &HashSet::new()).messages
105}
106
107/// One merge, worked out before anything is changed.
108struct Merge {
109 messages: Vec<Message>,
110 added: Vec<MessageId>,
111 differing: Vec<MessageId>,
112 /// Tool calls that had a result before the merge added another from the
113 /// other list: the call, the result that was there, and the one added.
114 answered_twice: Vec<(ToolCallId, MessageId, MessageId)>,
115}
116
117/// Merges `theirs` into `ours`, leaving out the messages of `theirs` named in
118/// `skip`.
119fn merge(ours: &[Message], theirs: &[Message], skip: &HashSet<&MessageId>) -> Merge {
120 let mut merged = Merge {
121 messages: Vec::with_capacity(ours.len() + theirs.len()),
122 added: Vec::new(),
123 differing: Vec::new(),
124 answered_twice: Vec::new(),
125 };
126 // The calls some message of the result holds, so that a result with no
127 // such message is placed without a search.
128 let mut issued = HashSet::new();
129 let mut held: HashMap<&MessageId, &Message> = HashMap::with_capacity(ours.len());
130 for message in ours {
131 if let Entry::Vacant(first) = held.entry(message.id()) {
132 first.insert(message);
133 place(&mut merged.messages, &mut issued, message);
134 }
135 }
136 let mut met = HashSet::with_capacity(theirs.len());
137 for message in theirs {
138 if !met.insert(message.id()) || skip.contains(message.id()) {
139 continue;
140 }
141 if let Some(mine) = held.get(message.id()) {
142 if *mine != message {
143 merged.differing.push(message.id().clone());
144 }
145 continue;
146 }
147 merged.added.push(message.id().clone());
148 if let Some((call, answer)) = place(&mut merged.messages, &mut issued, message) {
149 merged
150 .answered_twice
151 .push((call, answer, message.id().clone()));
152 }
153 }
154 merged
155}
156
157/// Adds `message` to `messages` the way a client adds one it receives: a tool
158/// result behind the message that holds its call, anything else at the end.
159/// For a result whose call already had one, returns the call and that result.
160fn place<'a>(
161 messages: &mut Vec<Message>,
162 issued: &mut HashSet<&'a ToolCallId>,
163 message: &'a Message,
164) -> Option<(ToolCallId, MessageId)> {
165 issued.extend(calls_of(message));
166 let call = match message {
167 Message::Tool(result) if issued.contains(&result.tool_call_id) => &result.tool_call_id,
168 _ => {
169 messages.push(message.clone());
170 return None;
171 }
172 };
173 let (at, answer) = place_of_result(messages, call);
174 let answer = answer.map(|index| (call.clone(), messages[index].id().clone()));
175 messages.insert(at, message.clone());
176 answer
177}
178
179/// The ids of the tool calls a message holds.
180fn calls_of(message: &Message) -> impl Iterator<Item = &ToolCallId> {
181 let calls = match message {
182 Message::Assistant(assistant) => assistant.tool_calls.as_deref(),
183 _ => None,
184 };
185 calls.into_iter().flatten().map(|call| &call.id)
186}
187
188/// Where a result for `call` goes in `messages`, and the index of the result
189/// the call already has there, if it has one.
190///
191/// The reference client's placement for a `TOOL_CALL_RESULT`
192/// (`client/src/apply/default.ts`): behind the newest message holding the
193/// call that has no result for it yet, or behind the newest holder when each
194/// has one; then past the tool and activity messages directly behind that
195/// message, so results keep the order they came in. With no holder, the end.
196fn place_of_result(messages: &[Message], call: &ToolCallId) -> (usize, Option<usize>) {
197 let behind = |holder: usize| {
198 let mut at = holder + 1;
199 while matches!(
200 messages.get(at),
201 Some(Message::Tool(_) | Message::Activity(_))
202 ) {
203 at += 1;
204 }
205 at
206 };
207 // Read from the end: the first result met after a holder is the one
208 // standing closest behind it.
209 let mut answer = None;
210 let mut newest = None;
211 for (index, message) in messages.iter().enumerate().rev() {
212 match message {
213 Message::Tool(result) if result.tool_call_id == *call => answer = Some(index),
214 _ if calls_of(message).any(|id| id == call) => {
215 if answer.is_none() {
216 return (behind(index), None);
217 }
218 newest.get_or_insert((index, answer.take()));
219 }
220 _ => {}
221 }
222 }
223 match newest {
224 Some((holder, answer)) => (behind(holder), answer),
225 None => (messages.len(), None),
226 }
227}
228
229/// Providers may reuse a tool-call ID in a later assistant message.
230#[derive(Debug, PartialEq, Eq, Hash)]
231struct IssuedCall<'a> {
232 assistant_id: &'a MessageId,
233 call_id: &'a ToolCallId,
234}
235
236/// Index each tool result by its message ID. A result before its call has no entry.
237fn calls_by_result(messages: &[Message]) -> HashMap<&MessageId, IssuedCall<'_>> {
238 #[derive(Default)]
239 struct Issuers<'a> {
240 latest: Option<&'a MessageId>,
241 unanswered: Vec<&'a MessageId>,
242 }
243
244 let mut issuers: HashMap<&ToolCallId, Issuers<'_>> = HashMap::new();
245 let mut results = HashMap::new();
246 for message in messages {
247 for call_id in calls_of(message) {
248 let history = issuers.entry(call_id).or_default();
249 history.latest = Some(message.id());
250 history.unanswered.push(message.id());
251 }
252 if let Message::Tool(result) = message {
253 let call_id = &result.tool_call_id;
254 let history = issuers.entry(call_id).or_default();
255 // Answer the newest outstanding call first, then fall back to the
256 // latest issuer if every occurrence already has a result.
257 if let Some(assistant_id) = history.unanswered.pop().or(history.latest) {
258 results.insert(
259 &result.id,
260 IssuedCall {
261 assistant_id,
262 call_id,
263 },
264 );
265 }
266 }
267 }
268 results
269}
270
271/// Ids, for an error message.
272fn list<'a>(ids: impl Iterator<Item = &'a str>) -> String {
273 ids.collect::<Vec<_>>().join(", ")
274}
275
276impl<T: Transport, S> Thread<T, S> {
277 /// Adds the messages another thread of the same conversation holds and
278 /// this one lacks, by the rules of [`merge_messages`]: this thread's
279 /// messages are kept as they are, the other's follow them in the other
280 /// thread's order, and a tool result stands behind the message that holds
281 /// its call.
282 ///
283 /// This is how two runs that were in flight together on one conversation
284 /// come back to one thread, which then sends the next request; see the
285 /// [module docs](super#two-runs-at-once). Nothing is sent, and `other` is
286 /// not changed. Draw the conversation again afterwards, as after
287 /// [`Update::Messages`](super::Update::Messages): a message may have been
288 /// added between two this thread held.
289 ///
290 /// # What the merge takes, leaves and refuses
291 ///
292 /// | Of the other thread | After the merge |
293 /// | --- | --- |
294 /// | a message this thread lacks | added |
295 /// | a message both hold | this thread's copy; an id whose copies differ is in [`MergeReport::differing`] |
296 /// | a tool message [`abandon_tool_call`](Thread::abandon_tool_call) made there, for a call this thread holds an answer to | left out, and named in [`MergeReport::superseded`] |
297 /// | the subagents it lists ([`subagents`](Thread::subagents)) | added where this thread lacks the invocation |
298 /// | the run ids it used | refused for a run of this thread too |
299 /// | a tool call an interrupt decided there | stays decided here, when its message was added |
300 /// | its state | not read: this thread's [`raw_state`](Thread::raw_state) is unchanged |
301 /// | pending interrupts, a resume submission, unanswered tool calls, a request in flight | the merge is refused, and likewise when this thread has any |
302 ///
303 /// State is the application's to settle. AG-UI 1.0 does not say what two
304 /// runs open at once on one thread do to the state they share, so nothing
305 /// here chooses: read [`raw_state`](Thread::raw_state) of both threads and
306 /// call [`set_state`](Thread::set_state) with the value the next run
307 /// should start from.
308 ///
309 /// Both threads must be at rest, each able to start a run of its own.
310 /// What a thread still owes belongs to the thread that owes it: an
311 /// interrupt is answered where its submission is tracked, and a tool call
312 /// is answered before another turn stands between the call and its
313 /// result. Settle those first, on the thread that has them, with
314 /// [`resume`](Thread::resume), a tool message or
315 /// [`abandon_tool_call`](Thread::abandon_tool_call). Both threads were at
316 /// rest, so the merged one can take the next request, and
317 /// [`send`](Thread::send) checks it as it checks any other.
318 ///
319 /// A tool call that both threads answered, each with a message of its
320 /// own, is refused as well: a call has one result, and choosing between
321 /// two is not this method's to do. A stand-in is not a result. A thread
322 /// remembers the tool messages its `abandon_tool_call` made, and so does
323 /// its [snapshot](Thread::snapshot), so a stand-in on the other thread
324 /// gives way to the answer this thread holds. The other way round, a
325 /// stand-in here and a result there, is refused, because a merge
326 /// changes and removes nothing of this thread's: merge this thread into
327 /// the other one instead, where the result stands and the stand-in gives
328 /// way.
329 ///
330 /// ```
331 /// use ag_ui::Message;
332 /// use ag_ui::client::{Thread, transport::ReplayTransport};
333 ///
334 /// let start = vec![Message::user("u-1", "Hello"), Message::assistant("a-1", "Hi")];
335 /// let thread = |added: [Message; 2]| {
336 /// let mut messages = start.clone();
337 /// messages.extend(added);
338 /// Thread::<_>::builder(ReplayTransport::new([]), "thread-1")
339 /// .messages(messages)
340 /// .build()
341 /// };
342 /// let mut main = thread([
343 /// Message::user("u-2", "Write the report"),
344 /// Message::assistant("a-2", "Here it is."),
345 /// ])?;
346 /// let side = thread([
347 /// Message::user("u-3", "What time is it?"),
348 /// Message::assistant("a-3", "Noon."),
349 /// ])?;
350 ///
351 /// let merged = main.merge_messages_from(&side)?;
352 /// assert_eq!(merged.added, ["u-3", "a-3"]);
353 /// assert!(merged.differing.is_empty());
354 /// let ids: Vec<_> = main.messages().iter().map(|message| message.id().as_str()).collect();
355 /// assert_eq!(ids, ["u-1", "a-1", "u-2", "a-2", "u-3", "a-3"]);
356 /// // Merging again adds nothing: every message is held now.
357 /// assert!(main.merge_messages_from(&side)?.added.is_empty());
358 /// # Ok::<(), ag_ui::client::Error>(())
359 /// ```
360 ///
361 /// # Errors
362 ///
363 /// [`Error::Merge`], with nothing changed, when the two threads have
364 /// different thread ids, when either is not at rest, when a tool call
365 /// has a result on each thread, when this thread gave up a call the
366 /// other holds a result for, or when keeping this thread's message
367 /// would detach an incoming result from its call or leave the merged
368 /// conversation with an unanswered call.
369 pub fn merge_messages_from<U: Transport, R>(
370 &mut self,
371 other: &Thread<U, R>,
372 ) -> Result<MergeReport> {
373 if self.thread_id != other.thread_id {
374 return Err(Error::Merge(format!(
375 "thread {:?} is another conversation than thread {:?}",
376 other.thread_id.as_str(),
377 self.thread_id.as_str()
378 )));
379 }
380 self.at_rest("this thread")?;
381 other.at_rest("the other thread")?;
382
383 // A stand-in the other thread made for a call this thread holds an
384 // answer to is left out: the call has its answer here. Told from a
385 // result by the record `abandon_tool_call` keeps, not by what the
386 // message says.
387 let answered: HashSet<_> = calls_by_result(self.messages()).into_values().collect();
388 let incoming_calls = calls_by_result(other.messages());
389 let superseded: Vec<&MessageId> = other
390 .messages()
391 .iter()
392 .map(Message::id)
393 .filter(|id| {
394 other.abandoned.contains(*id)
395 && self.applier.message(id).is_none()
396 && incoming_calls
397 .get(*id)
398 .is_some_and(|call| answered.contains(call))
399 })
400 .collect();
401 let skip: HashSet<&MessageId> = superseded.iter().copied().collect();
402
403 let merged = merge(self.messages(), other.messages(), &skip);
404 if let Some((call, here, there)) = merged
405 .answered_twice
406 .iter()
407 .find(|(_, here, _)| self.applier.message(here).is_some())
408 {
409 // Giving a call up here does not undo a result there, and a merge
410 // changes and removes nothing of this thread's: the result is
411 // merged the other way.
412 if self.abandoned.contains(here) {
413 return Err(Error::Merge(format!(
414 "tool call {call} was given up on this thread, with message {here}, and has \
415 a result on the other thread, message {there}: merge this thread into the \
416 one that holds the result"
417 )));
418 }
419 return Err(Error::Merge(format!(
420 "tool call {call} has a result on each thread, message {here} on this one and \
421 message {there} on the other"
422 )));
423 }
424
425 // A conflicting retained message can discard the assistant's call
426 // while its result is still added. Check the settled transcript
427 // before mutating either the messages or the thread's bookkeeping.
428 let merged_calls = calls_by_result(&merged.messages);
429 for id in &merged.added {
430 let Some(call) = incoming_calls.get(id) else {
431 continue;
432 };
433 if merged_calls.get(id) != Some(call) {
434 return Err(Error::Merge(format!(
435 "tool result {id} would no longer answer call {} on message {}",
436 call.call_id, call.assistant_id
437 )));
438 }
439 }
440
441 // A retained message can also displace the incoming result itself.
442 // Project the decisions first: an interrupt may already have settled
443 // that call, even if no tool message survives for it.
444 let mut decided = self.decided_interrupt_tool_call_ids.clone();
445 for id in &merged.added {
446 let Some(message) = other.applier.message(id) else {
447 continue;
448 };
449 for call in calls_of(message) {
450 if other.decided_interrupt_tool_call_ids.contains(call)
451 && other.applier.tool_call_holder(call) == Some(id)
452 {
453 decided.insert(call.clone());
454 } else {
455 decided.remove(call);
456 }
457 }
458 }
459 let pending = self.unanswered_tool_calls_in(&merged.messages, &decided);
460 if !pending.is_empty() {
461 return Err(Error::Merge(format!(
462 "the merged history would have unanswered tool calls {}",
463 list(pending.iter().map(ToolCallId::as_str))
464 )));
465 }
466
467 let superseded = superseded.into_iter().cloned().collect();
468 self.decided_interrupt_tool_call_ids = decided;
469 self.abandoned.extend(
470 merged
471 .added
472 .iter()
473 .filter(|id| other.abandoned.contains(*id))
474 .cloned(),
475 );
476 self.applier = std::mem::take(&mut self.applier).with_messages(merged.messages);
477 self.run_ids.extend(other.run_ids.iter().cloned());
478 let announced: Vec<_> = other
479 .subagents()
480 .iter()
481 .filter(|subagent| self.subagent(&subagent.run_id).is_none())
482 .cloned()
483 .collect();
484 if !announced.is_empty() {
485 let mut subagents = self.subagents().to_vec();
486 subagents.extend(announced);
487 let interrupts = self.applier.interrupts().to_vec();
488 self.applier.restore_auxiliary(subagents, interrupts);
489 }
490 Ok(MergeReport {
491 added: merged.added,
492 differing: merged.differing,
493 superseded,
494 })
495 }
496
497 /// Refuses a merge while this thread owes something only it can settle.
498 fn at_rest(&self, which: &str) -> Result<()> {
499 let owes = if self.active_run_id.is_some() {
500 "has a request in flight, and is merged once its stream has ended".to_owned()
501 } else if self.submission.is_some() {
502 "holds an unconfirmed resume submission, which is reconciled with the server before \
503 the thread is merged"
504 .to_owned()
505 } else if !self.interrupts.is_empty() {
506 format!(
507 "is paused on interrupts {}, which are answered on the thread that holds them \
508 before it is merged",
509 list(
510 self.interrupts
511 .iter()
512 .map(|interrupt| interrupt.id.as_str())
513 )
514 )
515 } else {
516 let calls = self.unanswered_tool_calls();
517 if calls.is_empty() {
518 return Ok(());
519 }
520 format!(
521 "has unanswered tool calls {}, which are answered or abandoned on the thread \
522 that holds them before it is merged",
523 list(calls.iter().map(ToolCallId::as_str))
524 )
525 };
526 Err(Error::Merge(format!("{which} {owes}")))
527 }
528}
529
530#[cfg(test)]
531mod tests {
532 use super::*;
533 use crate::{AssistantMessage, ToolCall};
534
535 #[test]
536 fn reused_call_ids_match_outstanding_calls_before_falling_back_to_the_latest_issuer() {
537 let issue = |id: &str| {
538 Message::Assistant(AssistantMessage {
539 id: id.into(),
540 tool_calls: Some(vec![ToolCall::new("c", "lookup", "{}")]),
541 ..Default::default()
542 })
543 };
544 let result = |id: &str| Message::tool(id, "c", "answer");
545 let messages = [
546 result("early"),
547 issue("a"),
548 issue("b"),
549 result("first"),
550 result("second"),
551 result("extra"),
552 ];
553 let calls = calls_by_result(&messages);
554 let issuer = |result: &str| {
555 calls
556 .get(&MessageId::new(result))
557 .map(|call| call.assistant_id.as_str())
558 };
559
560 assert_eq!(issuer("early"), None);
561 assert_eq!(issuer("first"), Some("b"));
562 assert_eq!(issuer("second"), Some("a"));
563 assert_eq!(issuer("extra"), Some("b"));
564 }
565}