use rho_protocol::MessageId;
use crate::{app::session_runtime::TurnKeys, session::tree::MessageKey};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum KeyedPart {
Whole,
Thought,
Agent(u32),
}
pub(super) fn keyed_message_id(key: &MessageKey, part: KeyedPart) -> MessageId {
let key = key.as_str();
MessageId::new(match part {
KeyedPart::Whole => format!("msg-{key}"),
KeyedPart::Thought => format!("msg-{key}-thought"),
KeyedPart::Agent(n) => format!("msg-{key}-agent-{n}"),
})
}
pub(crate) fn user_message_id(key: &MessageKey) -> MessageId {
keyed_message_id(key, KeyedPart::Whole)
}
pub(super) fn fresh_message_id() -> MessageId {
MessageId::new(format!("msg-{}", uuid::Uuid::new_v4()))
}
#[derive(Clone, Copy, PartialEq)]
pub(super) enum ChunkKind {
Agent,
Thought,
}
#[derive(Default)]
pub(super) struct MessageStream {
open: Option<(ChunkKind, MessageId)>,
keys: Option<TurnKeys>,
steps: u32,
discarded: bool,
stretch: u32,
stretch_state: Stretch,
steers: u32,
}
#[derive(Clone, Copy, Default, PartialEq)]
enum Stretch {
#[default]
Empty,
Open,
Closed,
}
impl MessageStream {
pub(super) fn run_started(&mut self, keys: TurnKeys) {
*self = Self {
keys: Some(keys),
..Self::default()
};
}
pub(super) fn run_ended(&mut self) {
self.keys = None;
}
pub(super) fn interrupt(&mut self) {
self.open = None;
}
pub(super) fn step_started(&mut self) {
self.steps += 1;
self.discarded = false;
self.new_response();
}
pub(super) fn response_reset(&mut self, discarded: bool) {
self.discarded |= discarded;
self.new_response();
}
fn new_response(&mut self) {
self.open = None;
self.stretch = 0;
self.stretch_state = Stretch::Empty;
}
pub(super) fn call_seen(&mut self) {
if self.stretch_state == Stretch::Open {
self.stretch_state = Stretch::Closed;
if matches!(self.open, Some((ChunkKind::Agent, _))) {
self.open = None;
}
}
}
pub(super) fn chunk(&mut self, kind: ChunkKind) -> MessageId {
if let Some((open, id)) = &self.open {
if *open == kind {
return id.clone();
}
}
let part = match kind {
ChunkKind::Thought => KeyedPart::Thought,
ChunkKind::Agent => {
if self.stretch_state == Stretch::Closed {
self.stretch += 1;
}
self.stretch_state = Stretch::Open;
KeyedPart::Agent(self.stretch)
}
};
let id = self
.reply()
.map_or_else(fresh_message_id, |reply| keyed_message_id(&reply, part));
self.open = Some((kind, id.clone()));
id
}
pub(super) fn steer(&mut self) -> MessageId {
self.steers += 1;
self.keys.as_ref().map_or_else(fresh_message_id, |keys| {
keyed_message_id(&keys.steer(self.steers), KeyedPart::Whole)
})
}
fn reply(&self) -> Option<MessageKey> {
let keys = self.keys.as_ref()?;
(self.steps > 0 && !self.discarded).then(|| keys.reply(self.steps))
}
}