1use std::collections::{HashMap, HashSet};
2use std::ops::Deref;
3use std::sync::{Arc, OnceLock};
4
5use chrono::Utc;
6
7use crate::session_model::{ConversationRecord, ProtocolEvent, SessionEventRecord};
8use crate::{BaseRenderCache, Message, MessageRole, PromptUsage, TokenUsage};
9
10#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
11pub struct SessionGraphData {
12 #[serde(default)]
13 pub nodes: Vec<SessionNodeRecord>,
14 #[serde(default, skip_serializing_if = "Option::is_none")]
15 pub leaf_node_id: Option<String>,
16}
17
18#[derive(Debug)]
19pub struct SessionGraph {
20 inner: Arc<SessionGraphData>,
21 cache: Arc<OnceLock<SessionGraphCache>>,
22}
23
24impl Default for SessionGraph {
25 fn default() -> Self {
26 Self {
27 inner: Arc::new(SessionGraphData::default()),
28 cache: Arc::new(OnceLock::new()),
29 }
30 }
31}
32
33impl Clone for SessionGraph {
34 fn clone(&self) -> Self {
35 Self {
36 inner: Arc::clone(&self.inner),
37 cache: Arc::clone(&self.cache),
38 }
39 }
40}
41
42impl serde::Serialize for SessionGraph {
43 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
44 where
45 S: serde::Serializer,
46 {
47 self.inner.serialize(serializer)
48 }
49}
50
51impl<'de> serde::Deserialize<'de> for SessionGraph {
52 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
53 where
54 D: serde::Deserializer<'de>,
55 {
56 let inner = SessionGraphData::deserialize(deserializer)?;
57 Ok(Self {
58 inner: Arc::new(inner),
59 cache: Arc::new(OnceLock::new()),
60 })
61 }
62}
63
64impl Deref for SessionGraph {
65 type Target = SessionGraphData;
66
67 fn deref(&self) -> &Self::Target {
68 self.inner.as_ref()
69 }
70}
71
72#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
73pub struct SessionNodeRecord {
74 pub node_id: String,
75 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub parent_node_id: Option<String>,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub caused_by: Option<crate::CausalRef>,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub agent_frame_id: Option<crate::AgentFrameId>,
81 pub timestamp: String,
82 #[serde(flatten)]
83 pub payload: SessionNodePayload,
84}
85
86#[derive(Clone, Debug)]
87pub(crate) struct SessionNodeDraft {
88 payload: SessionNodeDraftPayload,
89 caused_by: Option<crate::CausalRef>,
90}
91
92#[derive(Clone, Debug)]
93enum SessionNodeDraftPayload {
94 Message(Message),
95 Plugin {
96 plugin_type: String,
97 body: serde_json::Value,
98 },
99 ProtocolEvent(ProtocolEvent),
100}
101
102impl SessionNodeDraft {
103 pub(crate) fn message(message: Message) -> Self {
104 Self {
105 payload: SessionNodeDraftPayload::Message(message),
106 caused_by: None,
107 }
108 }
109
110 pub(crate) fn plugin(plugin_type: impl Into<String>, body: serde_json::Value) -> Self {
111 Self {
112 payload: SessionNodeDraftPayload::Plugin {
113 plugin_type: plugin_type.into(),
114 body,
115 },
116 caused_by: None,
117 }
118 }
119
120 pub(crate) fn protocol_event(event: ProtocolEvent) -> Self {
121 Self {
122 payload: SessionNodeDraftPayload::ProtocolEvent(event),
123 caused_by: None,
124 }
125 }
126
127 pub(crate) fn with_caused_by(mut self, caused_by: Option<crate::CausalRef>) -> Self {
128 self.caused_by = caused_by;
129 self
130 }
131}
132
133#[derive(Clone, Debug, Default, PartialEq)]
134pub struct SharedJsonValue(pub Arc<serde_json::Value>);
135
136impl SharedJsonValue {
137 pub fn new(value: serde_json::Value) -> Self {
138 Self(Arc::new(value))
139 }
140
141 pub fn to_owned(&self) -> serde_json::Value {
142 self.0.as_ref().clone()
143 }
144}
145
146impl AsRef<serde_json::Value> for SharedJsonValue {
147 fn as_ref(&self) -> &serde_json::Value {
148 self.0.as_ref()
149 }
150}
151
152impl serde::Serialize for SharedJsonValue {
153 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
154 where
155 S: serde::Serializer,
156 {
157 self.0.serialize(serializer)
158 }
159}
160
161impl<'de> serde::Deserialize<'de> for SharedJsonValue {
162 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
163 where
164 D: serde::Deserializer<'de>,
165 {
166 let value = serde_json::Value::deserialize(deserializer)?;
167 Ok(Self::new(value))
168 }
169}
170
171#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
172#[serde(tag = "kind", rename_all = "snake_case")]
173#[allow(clippy::large_enum_variant)]
174pub enum SessionNodePayload {
175 Event {
176 event: SessionEventRecord,
177 },
178 Plugin {
179 plugin_type: String,
180 body: SharedJsonValue,
181 },
182}
183
184#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
185pub struct PersistedSessionConfig {
186 pub provider_id: String,
187 pub model: crate::ModelSpec,
188}
189
190#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
191pub struct PersistedTurnState {
192 pub turn_index: usize,
193 #[serde(default)]
194 pub token_usage: TokenUsage,
195 #[serde(default, skip_serializing_if = "Option::is_none")]
196 pub last_prompt_usage: Option<PromptUsage>,
197 #[serde(default)]
198 pub protocol_turn_options: crate::ProtocolTurnOptions,
199}
200
201#[derive(Clone, Debug)]
202pub struct SessionMessageTreeNode {
203 pub node_id: String,
204 pub parent_message_node_id: Option<String>,
205 pub message: Message,
206 pub timestamp: String,
207 pub children: Vec<SessionMessageTreeNode>,
208 pub active: bool,
209}
210
211#[derive(Clone, Debug)]
212pub(crate) struct ActiveReadReplacement {
213 pub(crate) leaf_node_id: Option<String>,
214 pub(crate) new_tail_nodes: Vec<SessionNodeRecord>,
215 pub(crate) active_events: Vec<SessionEventRecord>,
216 pub(crate) active_messages: Vec<Message>,
217}
218
219#[derive(Clone, Debug)]
220pub(crate) struct SessionReadModel {
221 pub(crate) active_events: Arc<Vec<SessionEventRecord>>,
222 pub(crate) messages: Arc<Vec<Message>>,
223 pub(crate) prompt_render_cache: Arc<BaseRenderCache>,
224}
225
226#[derive(Clone, Debug)]
227pub(crate) struct SessionGraphAppendBuilder {
228 existing_ids: HashSet<String>,
229 leaf_node_id: Option<String>,
230 agent_frame_id: Option<crate::AgentFrameId>,
231}
232
233impl SessionGraphAppendBuilder {
234 pub(crate) fn with_agent_frame_id(
235 mut self,
236 agent_frame_id: impl Into<crate::AgentFrameId>,
237 ) -> Self {
238 self.agent_frame_id = Some(agent_frame_id.into());
239 self
240 }
241
242 pub(crate) fn agent_frame_id(&self) -> Option<&str> {
243 self.agent_frame_id.as_deref()
244 }
245
246 pub(crate) fn leaf_node_id(&self) -> Option<&String> {
247 self.leaf_node_id.as_ref()
248 }
249
250 pub(crate) fn set_leaf_node_id(&mut self, leaf_node_id: Option<String>) {
251 self.leaf_node_id = leaf_node_id;
252 }
253
254 pub(crate) fn register_existing_node_ids<'a>(
255 &mut self,
256 node_ids: impl IntoIterator<Item = &'a str>,
257 ) {
258 self.existing_ids
259 .extend(node_ids.into_iter().map(ToOwned::to_owned));
260 }
261
262 pub(crate) fn existing_node_ids(&self) -> &HashSet<String> {
263 &self.existing_ids
264 }
265
266 pub(crate) fn append_messages<I>(&mut self, messages: I) -> Vec<SessionNodeRecord>
267 where
268 I: IntoIterator<Item = Message>,
269 {
270 self.append_drafts(messages.into_iter().map(SessionNodeDraft::message))
271 }
272
273 pub(crate) fn append_protocol_events<I>(&mut self, events: I) -> Vec<SessionNodeRecord>
274 where
275 I: IntoIterator<Item = ProtocolEvent>,
276 {
277 self.append_drafts(events.into_iter().map(SessionNodeDraft::protocol_event))
278 }
279
280 pub(crate) fn append_drafts<I>(&mut self, drafts: I) -> Vec<SessionNodeRecord>
281 where
282 I: IntoIterator<Item = SessionNodeDraft>,
283 {
284 let mut nodes = Vec::new();
285 for draft in drafts {
286 let parent_node_id = self.leaf_node_id.clone();
287 let (node_id, caused_by, payload) = match draft.payload {
288 SessionNodeDraftPayload::Message(mut message) => {
289 if message.id.is_empty() {
290 message.id = fresh_node_id("m");
291 }
292 let node_id = unique_message_node_id(&message.id, &self.existing_ids);
293 let caused_by = draft
294 .caused_by
295 .or_else(|| causal_ref_from_message_origin(&message.origin));
296 (
297 node_id,
298 caused_by,
299 SessionNodePayload::Event {
300 event: SessionEventRecord::Conversation(
301 ConversationRecord::from_message(message),
302 ),
303 },
304 )
305 }
306 SessionNodeDraftPayload::Plugin { plugin_type, body } => {
307 let node_id = fresh_semantic_node_id("plugin", &self.existing_ids);
308 (
309 node_id,
310 draft.caused_by,
311 SessionNodePayload::Plugin {
312 plugin_type,
313 body: SharedJsonValue::new(body),
314 },
315 )
316 }
317 SessionNodeDraftPayload::ProtocolEvent(event) => {
318 let node_id = fresh_semantic_node_id("protocol", &self.existing_ids);
319 (
320 node_id,
321 draft.caused_by,
322 SessionNodePayload::Event {
323 event: SessionEventRecord::Protocol(event),
324 },
325 )
326 }
327 };
328 self.existing_ids.insert(node_id.clone());
329 self.leaf_node_id = Some(node_id.clone());
330 nodes.push(SessionNodeRecord {
331 node_id,
332 parent_node_id,
333 caused_by,
334 agent_frame_id: self.agent_frame_id.clone(),
335 timestamp: Utc::now().to_rfc3339(),
336 payload,
337 });
338 }
339 nodes
340 }
341}
342
343#[derive(Debug, Clone)]
344struct SessionGraphCache {
345 by_id: HashMap<String, usize>,
346 active_path_indices: Vec<usize>,
347 active_events: Arc<Vec<SessionEventRecord>>,
348 active_messages: Arc<Vec<Message>>,
349 active_message_ids: HashMap<String, usize>,
354 prompt_render_cache: Arc<BaseRenderCache>,
360}
361
362impl SessionGraphCache {
363 fn build(graph: &SessionGraph) -> Self {
364 let by_id = graph
365 .nodes
366 .iter()
367 .enumerate()
368 .map(|(idx, node)| (node.node_id.clone(), idx))
369 .collect::<HashMap<_, _>>();
370 let mut active_path_indices = Vec::new();
371 let mut current = graph
372 .leaf_node_id
373 .as_ref()
374 .and_then(|node_id| by_id.get(node_id).copied());
375 while let Some(idx) = current {
376 active_path_indices.push(idx);
377 current = graph.nodes[idx]
378 .parent_node_id
379 .as_ref()
380 .and_then(|node_id| by_id.get(node_id).copied());
381 }
382 active_path_indices.reverse();
383
384 let mut cache = Self {
385 by_id,
386 active_path_indices,
387 active_events: Arc::new(Vec::new()),
388 active_messages: Arc::new(Vec::new()),
389 active_message_ids: HashMap::new(),
390 prompt_render_cache: Arc::new(BaseRenderCache::new()),
391 };
392 cache.rebuild_read_model(graph);
393 cache
394 }
395
396 fn rebuild_read_model(&mut self, graph: &SessionGraph) {
397 let mut active_messages = Vec::with_capacity(self.active_path_indices.len());
398 let mut active_message_ids: HashMap<String, usize> =
399 HashMap::with_capacity(self.active_path_indices.len());
400 let mut active_events = Vec::with_capacity(self.active_path_indices.len());
401 for idx in &self.active_path_indices {
402 let node = &graph.nodes[*idx];
403 if let Some(event) = node.event() {
404 active_events.push(event.clone());
405 }
406 if let Some(message) = node.message() {
407 if !message.is_transient() && !active_message_ids.contains_key(&message.id) {
408 active_message_ids.insert(message.id.clone(), active_messages.len());
409 active_messages.push(message);
410 }
411 continue;
412 }
413 }
414 self.active_messages = Arc::new(active_messages);
415 self.active_message_ids = active_message_ids;
416 self.active_events = Arc::new(active_events);
417 self.prompt_render_cache = Arc::new(BaseRenderCache::new());
418 }
419
420 fn read_model_for_agent_frame(
421 &self,
422 graph: &SessionGraph,
423 frame_id: &str,
424 include_unscoped: bool,
425 ) -> SessionReadModel {
426 let mut active_messages = Vec::with_capacity(self.active_path_indices.len());
427 let mut active_message_ids = HashSet::new();
428 let mut active_events = Vec::with_capacity(self.active_path_indices.len());
429 for idx in &self.active_path_indices {
430 let node = &graph.nodes[*idx];
431 if !node_belongs_to_agent_frame(node, frame_id, include_unscoped) {
432 continue;
433 }
434 if let Some(event) = node.event() {
435 active_events.push(event.clone());
436 }
437 if let Some(message) = node.message() {
438 if !message.is_transient() && active_message_ids.insert(message.id.clone()) {
439 active_messages.push(message);
440 }
441 continue;
442 }
443 }
444 SessionReadModel {
445 active_events: Arc::new(active_events),
446 messages: Arc::new(active_messages),
447 prompt_render_cache: Arc::new(BaseRenderCache::new()),
448 }
449 }
450
451 fn append_node(
452 &mut self,
453 node_index: usize,
454 node: &SessionNodeRecord,
455 previous_leaf_node_id: Option<&str>,
456 ) {
457 self.by_id.insert(node.node_id.clone(), node_index);
458 let parent_matches_leaf = node.parent_node_id.as_deref() == previous_leaf_node_id;
459 if !parent_matches_leaf {
460 return;
461 }
462 self.active_path_indices.push(node_index);
463 if let Some(event) = node.event() {
464 Arc::make_mut(&mut self.active_events).push(event.clone());
465 }
466 if let Some(message) = node.message() {
467 if !message.is_transient() && !self.active_message_ids.contains_key(&message.id) {
468 let messages = Arc::make_mut(&mut self.active_messages);
469 self.active_message_ids
470 .insert(message.id.clone(), messages.len());
471 messages.push(message);
472 self.prompt_render_cache = Arc::new(BaseRenderCache::new());
473 }
474 }
475 }
476
477 fn reserve_append_capacity(&mut self, additional_nodes: usize, additional_messages: usize) {
478 self.by_id.reserve(additional_nodes);
479 self.active_path_indices.reserve(additional_nodes);
480 if additional_messages > 0 {
481 Arc::make_mut(&mut self.active_messages).reserve(additional_messages);
482 }
483 }
484}
485
486impl SessionNodeRecord {
487 pub fn event(&self) -> Option<&SessionEventRecord> {
488 match &self.payload {
489 SessionNodePayload::Event { event } => Some(event),
490 SessionNodePayload::Plugin { .. } => None,
491 }
492 }
493
494 pub fn message(&self) -> Option<Message> {
495 match self.event()? {
496 SessionEventRecord::Conversation(record) => Some(record.to_message()),
497 _ => None,
498 }
499 }
500
501 pub fn plugin(&self) -> Option<(&str, &serde_json::Value)> {
502 match &self.payload {
503 SessionNodePayload::Event { .. } => None,
504 SessionNodePayload::Plugin { plugin_type, body } => {
505 Some((plugin_type.as_str(), body.as_ref()))
506 }
507 }
508 }
509
510 pub fn plugin_body<T>(&self) -> Option<T>
511 where
512 T: for<'de> serde::Deserialize<'de>,
513 {
514 let (_, body) = self.plugin()?;
515 T::deserialize(body).ok()
516 }
517}
518
519impl SessionGraph {
520 pub fn append_active_read_delta(&mut self, messages: &[Message]) {
521 self.append_active_read_delta_scoped(None, messages);
522 }
523
524 pub fn append_active_read_delta_for_agent_frame(
525 &mut self,
526 agent_frame_id: &str,
527 messages: &[Message],
528 ) {
529 self.append_active_read_delta_scoped(Some(agent_frame_id), messages);
530 }
531
532 fn append_active_read_delta_scoped(
533 &mut self,
534 agent_frame_id: Option<&str>,
535 messages: &[Message],
536 ) {
537 let appendable_messages = {
538 let read_model = agent_frame_id
539 .map(|frame_id| self.read_model_for_agent_frame(frame_id, false))
540 .unwrap_or_else(|| self.read_model());
541 let mut seen_message_ids = read_model
542 .messages
543 .iter()
544 .map(|message| message.id.as_str())
545 .collect::<HashSet<_>>();
546 messages
547 .iter()
548 .filter(|message| {
549 !message.is_transient() && seen_message_ids.insert(message.id.as_str())
550 })
551 .cloned()
552 .collect::<Vec<_>>()
553 };
554
555 self.reserve_append_capacity(appendable_messages.len(), appendable_messages.len());
556 self.append_message_batch_scoped(agent_frame_id, appendable_messages);
557 }
558
559 pub(crate) fn append_active_conversation_messages_for_agent_frame(
560 &mut self,
561 agent_frame_id: &str,
562 messages: &[Message],
563 ) {
564 self.append_active_conversation_messages_scoped(Some(agent_frame_id), messages);
565 }
566
567 fn append_active_conversation_messages_scoped(
568 &mut self,
569 agent_frame_id: Option<&str>,
570 messages: &[Message],
571 ) {
572 let appendable_messages = messages
573 .iter()
574 .filter(|message| !message.is_transient())
575 .cloned()
576 .collect::<Vec<_>>();
577 self.reserve_append_capacity(appendable_messages.len(), appendable_messages.len());
578 self.append_message_batch_scoped(agent_frame_id, appendable_messages);
579 }
580
581 pub fn from_nodes(nodes: Vec<SessionNodeRecord>, leaf_node_id: Option<String>) -> Self {
582 Self {
583 inner: Arc::new(SessionGraphData {
584 nodes,
585 leaf_node_id,
586 }),
587 cache: Arc::new(OnceLock::new()),
588 }
589 }
590
591 pub(crate) fn append_builder(&self) -> SessionGraphAppendBuilder {
592 SessionGraphAppendBuilder {
593 existing_ids: self.nodes.iter().map(|node| node.node_id.clone()).collect(),
594 leaf_node_id: self.leaf_node_id.clone(),
595 agent_frame_id: None,
596 }
597 }
598
599 fn invalidate_cache(&mut self) {
600 self.cache = Arc::new(OnceLock::new());
601 }
602
603 fn data_mut(&mut self) -> &mut SessionGraphData {
604 self.invalidate_cache();
605 Arc::make_mut(&mut self.inner)
606 }
607
608 fn reserve_append_capacity(&mut self, additional_nodes: usize, additional_messages: usize) {
609 if additional_nodes == 0 {
610 return;
611 }
612 self.detach_initialized_cache_for_append();
613 Arc::make_mut(&mut self.inner)
614 .nodes
615 .reserve(additional_nodes);
616 if let Some(cache_lock) = Arc::get_mut(&mut self.cache)
617 && let Some(cache) = cache_lock.get_mut()
618 {
619 cache.reserve_append_capacity(additional_nodes, additional_messages);
620 }
621 }
622
623 fn detach_initialized_cache_for_append(&mut self) {
624 if Arc::get_mut(&mut self.cache).is_some() {
625 return;
626 }
627 let Some(cache) = self.cache.get().cloned() else {
628 self.invalidate_cache();
629 return;
630 };
631 let lock = OnceLock::new();
632 let _ = lock.set(cache);
633 self.cache = Arc::new(lock);
634 }
635
636 fn cache(&self) -> &SessionGraphCache {
637 self.cache.get_or_init(|| SessionGraphCache::build(self))
638 }
639
640 fn append_message_batch_scoped(
641 &mut self,
642 agent_frame_id: Option<&str>,
643 messages: Vec<Message>,
644 ) {
645 if messages.is_empty() {
646 return;
647 }
648 self.append_node_drafts_scoped(
649 agent_frame_id,
650 messages.into_iter().map(SessionNodeDraft::message),
651 );
652 }
653
654 fn append_prebuilt_nodes(&mut self, nodes: Vec<SessionNodeRecord>) {
655 if nodes.is_empty() {
656 return;
657 }
658
659 self.detach_initialized_cache_for_append();
660 if let Some(cache_lock) = Arc::get_mut(&mut self.cache)
661 && let Some(cache) = cache_lock.get_mut()
662 {
663 let data = Arc::make_mut(&mut self.inner);
664 for node in nodes {
665 let previous_leaf = data.leaf_node_id.clone();
666 let node_id = node.node_id.clone();
667 data.nodes.push(node);
668 cache.append_node(
669 data.nodes.len() - 1,
670 data.nodes.last().expect("just appended graph node"),
671 previous_leaf.as_deref(),
672 );
673 data.leaf_node_id = Some(node_id);
674 }
675 return;
676 }
677
678 let data = self.data_mut();
679 for node in nodes {
680 data.leaf_node_id = Some(node.node_id.clone());
681 data.nodes.push(node);
682 }
683 }
684
685 pub fn append_message(&mut self, message: Message) -> String {
686 self.append_node_draft(SessionNodeDraft::message(message))
687 }
688
689 pub fn append_plugin(
690 &mut self,
691 plugin_type: impl Into<String>,
692 body: serde_json::Value,
693 ) -> String {
694 self.append_node_draft(SessionNodeDraft::plugin(plugin_type, body))
695 }
696
697 pub fn active_path_nodes(&self) -> Vec<&SessionNodeRecord> {
698 self.cache()
699 .active_path_indices
700 .iter()
701 .map(|idx| &self.nodes[*idx])
702 .collect()
703 }
704
705 pub(crate) fn read_model(&self) -> SessionReadModel {
706 let cache = self.cache();
707 SessionReadModel {
708 active_events: Arc::clone(&cache.active_events),
709 messages: Arc::clone(&cache.active_messages),
710 prompt_render_cache: Arc::clone(&cache.prompt_render_cache),
711 }
712 }
713
714 pub(crate) fn read_model_for_agent_frame(
715 &self,
716 frame_id: &str,
717 include_unscoped: bool,
718 ) -> SessionReadModel {
719 if frame_id.is_empty() {
720 return self.read_model();
721 }
722 self.cache()
723 .read_model_for_agent_frame(self, frame_id, include_unscoped)
724 }
725
726 pub fn append_protocol_event(&mut self, event: ProtocolEvent) -> String {
727 self.append_node_draft(SessionNodeDraft::protocol_event(event))
728 }
729
730 pub(crate) fn append_node_draft(&mut self, draft: SessionNodeDraft) -> String {
731 self.append_node_drafts([draft])
732 .into_iter()
733 .next()
734 .expect("single draft append must create one node")
735 }
736
737 pub(crate) fn append_node_drafts<I>(&mut self, drafts: I) -> Vec<String>
738 where
739 I: IntoIterator<Item = SessionNodeDraft>,
740 {
741 self.append_node_drafts_scoped(None, drafts)
742 }
743
744 pub(crate) fn append_node_drafts_for_agent_frame<I>(
745 &mut self,
746 agent_frame_id: &str,
747 drafts: I,
748 ) -> Vec<String>
749 where
750 I: IntoIterator<Item = SessionNodeDraft>,
751 {
752 self.append_node_drafts_scoped(Some(agent_frame_id), drafts)
753 }
754
755 fn append_node_drafts_scoped<I>(
756 &mut self,
757 agent_frame_id: Option<&str>,
758 drafts: I,
759 ) -> Vec<String>
760 where
761 I: IntoIterator<Item = SessionNodeDraft>,
762 {
763 let mut builder = self.append_builder();
764 if let Some(agent_frame_id) = agent_frame_id {
765 builder = builder.with_agent_frame_id(agent_frame_id.to_string());
766 }
767 let nodes = builder.append_drafts(drafts);
768 let node_ids = nodes
769 .iter()
770 .map(|node| node.node_id.clone())
771 .collect::<Vec<_>>();
772 self.append_prebuilt_nodes(nodes);
773 node_ids
774 }
775
776 pub fn user_message_count(&self) -> usize {
777 self.nodes
778 .iter()
779 .filter_map(SessionNodeRecord::message)
780 .filter(|message| matches!(message.role, MessageRole::User))
781 .count()
782 }
783
784 pub fn first_user_message(&self) -> String {
785 self.nodes
786 .iter()
787 .filter_map(SessionNodeRecord::message)
788 .find(|message| matches!(message.role, MessageRole::User))
789 .map(|message| first_message_search_text(&message))
790 .unwrap_or_default()
791 }
792
793 pub fn branch_to(&mut self, node_id: Option<String>) {
794 self.data_mut().leaf_node_id = node_id;
795 }
796
797 pub fn set_leaf_node_id(&mut self, node_id: Option<String>) {
798 self.data_mut().leaf_node_id = node_id;
799 }
800
801 pub fn push_node_record(&mut self, node: SessionNodeRecord) {
802 self.data_mut().nodes.push(node);
803 }
804
805 pub fn extend_node_records<I>(&mut self, nodes: I)
806 where
807 I: IntoIterator<Item = SessionNodeRecord>,
808 {
809 self.data_mut().nodes.extend(nodes);
810 }
811
812 pub fn extend_active_path(&mut self, nodes: Vec<SessionNodeRecord>) {
820 self.append_prebuilt_nodes(nodes);
821 }
822
823 pub fn active_path_contains(&self, node_id: &str) -> bool {
824 self.active_path_nodes()
825 .into_iter()
826 .any(|node| node.node_id == node_id)
827 }
828
829 pub fn heal_orphaned_leaf(&mut self) -> bool {
837 if let Some(leaf) = self.leaf_node_id.as_ref()
838 && self.find_node(leaf).is_none()
839 {
840 let fallback = self
841 .nodes
842 .iter()
843 .rev()
844 .find(|node| node.message().is_some())
845 .map(|node| node.node_id.clone());
846 self.data_mut().leaf_node_id = fallback;
847 return true;
848 }
849 false
850 }
851
852 pub fn fork_current_path(&self) -> SessionGraph {
853 let path = self.active_path_nodes();
854 SessionGraph::from_nodes(
855 path.into_iter().cloned().collect(),
856 self.leaf_node_id.clone(),
857 )
858 }
859
860 pub fn find_node(&self, node_id: &str) -> Option<&SessionNodeRecord> {
861 self.cache()
862 .by_id
863 .get(node_id)
864 .and_then(|idx| self.nodes.get(*idx))
865 }
866
867 pub fn node_index(&self, node_id: &str) -> Option<usize> {
868 self.cache().by_id.get(node_id).copied()
869 }
870
871 pub fn replace_active_read_state(&mut self, messages: &[Message]) {
872 self.replace_active_read_state_scoped(None, messages);
873 }
874
875 pub fn replace_active_read_state_for_agent_frame(
876 &mut self,
877 agent_frame_id: &str,
878 messages: &[Message],
879 ) {
880 self.replace_active_read_state_scoped(Some(agent_frame_id), messages);
881 }
882
883 fn replace_active_read_state_scoped(
884 &mut self,
885 agent_frame_id: Option<&str>,
886 messages: &[Message],
887 ) {
888 let current_nodes = self.active_path_nodes();
889 let existing_ids = self
890 .nodes
891 .iter()
892 .map(|node| node.node_id.clone())
893 .collect::<HashSet<_>>();
894 let replacement =
895 build_active_read_replacement(current_nodes, &existing_ids, agent_frame_id, messages);
896 let data = self.data_mut();
897 data.leaf_node_id = replacement.leaf_node_id;
898 data.nodes.extend(replacement.new_tail_nodes);
899 }
900
901 pub fn from_active_read_state(messages: &[Message]) -> Self {
902 let mut graph = Self::default();
903 graph.replace_active_read_state(messages);
904 graph
905 }
906
907 pub fn message_tree(&self) -> Vec<SessionMessageTreeNode> {
908 let active_message_ids = self
909 .active_path_nodes()
910 .into_iter()
911 .filter_map(|node| node.message().map(|message| message.id.clone()))
912 .collect::<HashSet<_>>();
913
914 let message_nodes = self
915 .nodes
916 .iter()
917 .filter_map(|node| {
918 let message = node.message()?.clone();
919 let parent_message_node_id =
920 self.nearest_message_ancestor(node.parent_node_id.as_deref());
921 Some(SessionMessageTreeNode {
922 node_id: node.node_id.clone(),
923 parent_message_node_id,
924 message,
925 timestamp: node.timestamp.clone(),
926 children: Vec::new(),
927 active: active_message_ids.contains(&node.node_id),
928 })
929 })
930 .collect::<Vec<_>>();
931
932 build_tree(message_nodes)
933 }
934
935 fn nearest_message_ancestor(&self, node_id: Option<&str>) -> Option<String> {
936 let by_id = self
937 .nodes
938 .iter()
939 .map(|node| (node.node_id.as_str(), node))
940 .collect::<HashMap<_, _>>();
941 let mut current = node_id.and_then(|id| by_id.get(id).copied());
942 while let Some(node) = current {
943 if node.message().is_some() {
944 return Some(node.node_id.clone());
945 }
946 current = node
947 .parent_node_id
948 .as_deref()
949 .and_then(|parent| by_id.get(parent).copied());
950 }
951 None
952 }
953}
954
955fn build_tree(mut nodes: Vec<SessionMessageTreeNode>) -> Vec<SessionMessageTreeNode> {
956 let mut children_by_parent = HashMap::<Option<String>, Vec<SessionMessageTreeNode>>::new();
957 for node in nodes.drain(..) {
958 children_by_parent
959 .entry(node.parent_message_node_id.clone())
960 .or_default()
961 .push(node);
962 }
963 let mut roots = build_tree_children(None, &mut children_by_parent);
964 sort_tree(&mut roots);
965 roots
966}
967
968fn sort_tree(nodes: &mut [SessionMessageTreeNode]) {
969 nodes.sort_by(|a, b| a.timestamp.cmp(&b.timestamp));
970 for node in nodes {
971 sort_tree(&mut node.children);
972 }
973}
974
975fn build_tree_children(
976 parent_id: Option<String>,
977 children_by_parent: &mut HashMap<Option<String>, Vec<SessionMessageTreeNode>>,
978) -> Vec<SessionMessageTreeNode> {
979 let mut children = children_by_parent.remove(&parent_id).unwrap_or_default();
980 for child in &mut children {
981 child.children = build_tree_children(Some(child.node_id.clone()), children_by_parent);
982 }
983 children
984}
985
986fn node_belongs_to_agent_frame(
987 node: &SessionNodeRecord,
988 frame_id: &str,
989 include_unscoped: bool,
990) -> bool {
991 match node.agent_frame_id.as_deref() {
992 Some(node_frame_id) => node_frame_id == frame_id,
993 None => include_unscoped,
994 }
995}
996
997pub(crate) fn build_active_read_replacement<'a>(
998 current_nodes: impl IntoIterator<Item = &'a SessionNodeRecord>,
999 existing_node_ids: &HashSet<String>,
1000 agent_frame_id: Option<&str>,
1001 messages: &[Message],
1002) -> ActiveReadReplacement {
1003 let target = messages
1004 .iter()
1005 .filter(|message| !message.is_transient())
1006 .collect::<Vec<_>>();
1007
1008 let mut active_events = Vec::new();
1009 let mut active_messages = Vec::new();
1010 let mut active_message_ids = HashSet::new();
1011 let mut seen_active_read_keys = HashSet::new();
1012 let mut target_idx = 0usize;
1013 let mut leaf_node_id = None;
1014 for node in current_nodes {
1015 if node
1016 .message()
1017 .map(|message| message.is_transient())
1018 .unwrap_or(false)
1019 {
1020 continue;
1021 }
1022 if let Some(key) = recognized_active_read_key(node) {
1023 if !seen_active_read_keys.insert(key.clone()) {
1024 continue;
1025 }
1026 let Some(target_item) = target.get(target_idx) else {
1027 break;
1028 };
1029 if key != format!("message:{}", target_item.id) {
1030 break;
1031 }
1032 push_active_read_node(
1033 node,
1034 &mut active_events,
1035 &mut active_messages,
1036 &mut active_message_ids,
1037 );
1038 leaf_node_id = Some(node.node_id.clone());
1039 target_idx += 1;
1040 } else {
1041 push_active_read_node(
1042 node,
1043 &mut active_events,
1044 &mut active_messages,
1045 &mut active_message_ids,
1046 );
1047 leaf_node_id = Some(node.node_id.clone());
1048 }
1049 }
1050
1051 let mut new_node_ids = HashSet::new();
1052 let mut new_tail_nodes = Vec::new();
1053
1054 for message in target.into_iter().skip(target_idx) {
1055 let parent_node_id = leaf_node_id.clone();
1056 let node_id =
1057 unique_message_node_id_for_replacement(&message.id, existing_node_ids, &new_node_ids);
1058 let node = SessionNodeRecord {
1059 node_id,
1060 parent_node_id,
1061 caused_by: causal_ref_from_message_origin(&message.origin),
1062 agent_frame_id: agent_frame_id.map(ToOwned::to_owned),
1063 timestamp: Utc::now().to_rfc3339(),
1064 payload: SessionNodePayload::Event {
1065 event: SessionEventRecord::Conversation(ConversationRecord::from_message(
1066 message.clone(),
1067 )),
1068 },
1069 };
1070 new_node_ids.insert(node.node_id.clone());
1071 leaf_node_id = Some(node.node_id.clone());
1072 push_active_read_node(
1073 &node,
1074 &mut active_events,
1075 &mut active_messages,
1076 &mut active_message_ids,
1077 );
1078 new_tail_nodes.push(node);
1079 }
1080
1081 ActiveReadReplacement {
1082 leaf_node_id,
1083 new_tail_nodes,
1084 active_events,
1085 active_messages,
1086 }
1087}
1088
1089fn push_active_read_node(
1090 node: &SessionNodeRecord,
1091 active_events: &mut Vec<SessionEventRecord>,
1092 active_messages: &mut Vec<Message>,
1093 active_message_ids: &mut HashSet<String>,
1094) {
1095 if let Some(event) = node.event() {
1096 active_events.push(event.clone());
1097 }
1098 if let Some(message) = node.message() {
1099 if !message.is_transient() && active_message_ids.insert(message.id.clone()) {
1100 active_messages.push(message);
1101 }
1102 }
1103}
1104
1105fn recognized_active_read_key(node: &SessionNodeRecord) -> Option<String> {
1106 match &node.payload {
1107 SessionNodePayload::Event { event } => match event {
1108 SessionEventRecord::Conversation(record) => Some(format!("message:{}", record.id)),
1109 _ => None,
1110 },
1111 SessionNodePayload::Plugin { .. } => None,
1112 }
1113}
1114
1115fn causal_ref_from_message_origin(
1116 origin: &Option<crate::MessageOrigin>,
1117) -> Option<crate::CausalRef> {
1118 let Some(crate::MessageOrigin::Process {
1119 process_id,
1120 sequence,
1121 ..
1122 }) = origin
1123 else {
1124 return None;
1125 };
1126 Some(crate::CausalRef::ProcessEvent {
1127 process_id: process_id.clone(),
1128 sequence: *sequence,
1129 })
1130}
1131
1132fn fresh_semantic_node_id(prefix: &str, existing_ids: &HashSet<String>) -> String {
1133 loop {
1134 let candidate = format!("{prefix}:{}", uuid::Uuid::new_v4().simple());
1135 if !existing_ids.contains(&candidate) {
1136 return candidate;
1137 }
1138 }
1139}
1140
1141fn unique_message_node_id(message_id: &str, existing_ids: &HashSet<String>) -> String {
1142 if !existing_ids.contains(message_id) {
1143 return message_id.to_string();
1144 }
1145 let base = format!("message:{message_id}");
1146 if !existing_ids.contains(&base) {
1147 return base;
1148 }
1149 for suffix in 2.. {
1150 let candidate = format!("{base}:{suffix}");
1151 if !existing_ids.contains(&candidate) {
1152 return candidate;
1153 }
1154 }
1155 unreachable!("message node id space exhausted")
1156}
1157
1158fn unique_message_node_id_for_replacement(
1159 message_id: &str,
1160 existing_ids: &HashSet<String>,
1161 new_ids: &HashSet<String>,
1162) -> String {
1163 if !existing_ids.contains(message_id) && !new_ids.contains(message_id) {
1164 return message_id.to_string();
1165 }
1166 let base = format!("message:{message_id}");
1167 if !existing_ids.contains(&base) && !new_ids.contains(&base) {
1168 return base;
1169 }
1170 for suffix in 2.. {
1171 let candidate = format!("{base}:{suffix}");
1172 if !existing_ids.contains(&candidate) && !new_ids.contains(&candidate) {
1173 return candidate;
1174 }
1175 }
1176 unreachable!("message node id space exhausted")
1177}
1178
1179fn fresh_node_id(prefix: &str) -> String {
1180 format!("{prefix}{}", uuid::Uuid::new_v4().simple())
1181}
1182
1183fn first_message_search_text(message: &Message) -> String {
1184 message
1185 .parts
1186 .iter()
1187 .filter_map(|part| match part.kind {
1188 crate::PartKind::ToolCall | crate::PartKind::ToolResult => None,
1189 crate::PartKind::Image => Some("[Image attached]".to_string()),
1190 _ => (!part.content.trim().is_empty()).then(|| part.content.clone()),
1191 })
1192 .collect::<Vec<_>>()
1193 .join("\n\n")
1194 .trim()
1195 .to_string()
1196}
1197
1198#[cfg(test)]
1199mod tests {
1200 use super::*;
1201 use crate::{Part, PartKind, PruneState, shared_parts};
1202
1203 fn text_message(id: &str, role: MessageRole, content: &str) -> Message {
1204 Message {
1205 id: id.to_string(),
1206 role,
1207 parts: shared_parts(vec![Part {
1208 id: format!("{id}.p0"),
1209 kind: PartKind::Text,
1210 content: content.to_string(),
1211 attachment: None,
1212 tool_call_id: None,
1213 tool_name: None,
1214 tool_replay: None,
1215 prune_state: PruneState::Intact,
1216 reasoning_meta: None,
1217 response_meta: None,
1218 }]),
1219 origin: None,
1220 }
1221 }
1222
1223 fn protocol_event() -> ProtocolEvent {
1224 ProtocolEvent::typed("test_protocol", serde_json::json!({"step": "started"}))
1225 .expect("protocol event serializes")
1226 }
1227
1228 #[test]
1229 fn typed_append_node_ids_use_semantic_prefixes() {
1230 let mut graph = SessionGraph::default();
1231
1232 let message_id = graph.append_message(text_message("m1", MessageRole::User, "hello"));
1233 let protocol_id = graph.append_protocol_event(protocol_event());
1234 let plugin_id = graph.append_plugin("example", serde_json::json!({"ok": true}));
1235
1236 assert_eq!(message_id, "m1");
1237 assert!(protocol_id.starts_with("protocol:"));
1238 assert!(plugin_id.starts_with("plugin:"));
1239 }
1240
1241 #[test]
1242 fn active_read_replacement_persists_messages_only() {
1243 let message = text_message("m1", MessageRole::User, "hello");
1244 let graph = SessionGraph::from_active_read_state(&[message]);
1245
1246 assert_eq!(graph.nodes.len(), 1);
1247 assert!(matches!(
1248 graph.nodes[0].event(),
1249 Some(SessionEventRecord::Conversation(_))
1250 ));
1251 }
1252
1253 #[test]
1254 fn graph_writers_do_not_put_active_read_events_under_plugin_ids() {
1255 let mut graph = SessionGraph::default();
1256 graph.append_message(text_message("m1", MessageRole::User, "hello"));
1257 graph.append_protocol_event(protocol_event());
1258 graph.append_plugin("example", serde_json::json!({"ok": true}));
1259
1260 for node in &graph.nodes {
1261 match node.event() {
1262 Some(SessionEventRecord::Conversation(_)) => {
1263 assert!(!node.node_id.starts_with("plugin:"), "{:?}", node);
1264 }
1265 Some(SessionEventRecord::Protocol(_)) => {
1266 assert!(node.node_id.starts_with("protocol:"), "{:?}", node);
1267 }
1268 None => {
1269 assert!(node.node_id.starts_with("plugin:"), "{:?}", node);
1270 }
1271 }
1272 }
1273 }
1274}