use std::collections::VecDeque;
use rho_protocol::{SessionEvent as WireEvent, ToolCallUpdate, ToolStatus};
use super::FeedEvent;
#[derive(Default)]
pub(super) struct FinishedCalls {
held: VecDeque<Held>,
}
struct Held {
open: ToolCallUpdate,
at: Option<u64>,
}
impl FinishedCalls {
pub(super) fn push(&mut self, event: FeedEvent, sent: &mut VecDeque<FeedEvent>) {
let FeedEvent {
event: WireEvent::ToolCall(update),
at,
notification: None,
} = event
else {
self.finish(sent);
sent.push_back(event);
return;
};
if opens(&update) {
self.held.push_back(Held { open: *update, at });
return;
}
let goes_with_open = self
.held
.front()
.is_some_and(|held| held.open.id == update.id && self.finishes(&update));
let held = if goes_with_open {
self.held.pop_front()
} else {
None
};
if let Some(held) = held {
sent.push_back(FeedEvent {
at: held.at,
..WireEvent::tool_call(joined(held.open, *update)).into()
});
return;
}
self.finish(sent);
sent.push_back(FeedEvent {
at,
..WireEvent::ToolCall(update).into()
});
}
pub(super) fn finish(&mut self, sent: &mut VecDeque<FeedEvent>) {
sent.extend(self.held.drain(..).map(|Held { open, at }| FeedEvent {
at,
..WireEvent::tool_call(open).into()
}));
}
fn finishes(&self, result: &ToolCallUpdate) -> bool {
let finished = match result.status {
Some(ToolStatus::Completed) => true,
Some(ToolStatus::Failed) => self.held.len() == 1,
Some(ToolStatus::Cancelled) => false,
Some(ToolStatus::Pending | ToolStatus::InProgress) | None => false,
Some(ToolStatus::Unknown) => false,
Some(_) => false,
};
finished && result.display.is_some()
}
}
pub(super) struct JoinedEvents<I> {
events: I,
finished_calls: FinishedCalls,
ready: VecDeque<FeedEvent>,
expected: usize,
sent: usize,
}
impl<I> JoinedEvents<I> {
pub(super) fn new(events: I, expected: usize) -> Self {
Self {
events,
finished_calls: FinishedCalls::default(),
ready: VecDeque::new(),
expected,
sent: 0,
}
}
}
impl<I: Iterator<Item = FeedEvent>> Iterator for JoinedEvents<I> {
type Item = FeedEvent;
fn next(&mut self) -> Option<FeedEvent> {
loop {
if let Some(event) = self.ready.pop_front() {
self.sent += 1;
return Some(event);
}
match self.events.next() {
Some(event) => self.finished_calls.push(event, &mut self.ready),
None if !self.finished_calls.held.is_empty() => {
self.finished_calls.finish(&mut self.ready);
}
None => {
debug_assert_eq!(self.sent, self.expected);
return None;
}
}
}
}
}
fn opens(update: &ToolCallUpdate) -> bool {
update.status == Some(ToolStatus::InProgress) && update.content.is_none()
}
fn joined(open: ToolCallUpdate, result: ToolCallUpdate) -> ToolCallUpdate {
let ToolCallUpdate {
id,
title,
kind,
status,
raw_input,
content,
locations,
display,
} = result;
ToolCallUpdate {
id,
title: title.or(open.title),
kind: kind.or(open.kind),
status: status.or(open.status),
raw_input: raw_input.or(open.raw_input),
content: content.or(open.content),
locations: locations.or(open.locations),
display: display.or(open.display),
}
}