1use std::collections::HashSet;
2
3use serde::{Deserialize, Serialize};
4
5use crate::types::{ChatMessage, ImageAttachment, Message, MessageRole, ToolCallMessage};
6
7use crate::types::SessionId;
8
9pub use crate::types::RunState;
13
14#[derive(Deserialize)]
22struct RawAgentSession {
23 id: Option<SessionId>,
24 chat_messages: Vec<ChatMessage>,
25 always_allowed_actions: HashSet<String>,
26 #[serde(default)]
30 total_tool_calls: Option<usize>,
31
32 run_state: Option<RunState>,
34
35 nudge_count: Option<usize>,
37 turn_tool_calls: Option<usize>,
38 reasoning_only_strikes: Option<usize>,
39 empty_response_strikes: Option<usize>,
40}
41
42impl From<RawAgentSession> for AgentSession {
43 fn from(raw: RawAgentSession) -> Self {
44 let mut run_state = raw.run_state.unwrap_or_else(|| RunState {
45 nudge_count: raw.nudge_count.unwrap_or(0),
46 turn_actions: raw.turn_tool_calls.unwrap_or(0),
47 reasoning_only_strikes: raw.reasoning_only_strikes.unwrap_or(0),
48 empty_response_strikes: raw.empty_response_strikes.unwrap_or(0),
49 ..RunState::default()
50 });
51 if let Some(total) = raw.total_tool_calls {
55 run_state.total_actions = total;
56 }
57 Self {
58 id: raw.id,
59 chat_messages: raw.chat_messages,
60 always_allowed_actions: raw.always_allowed_actions,
61 run_state,
62 }
63 }
64}
65
66#[derive(Clone, Debug, Default, Serialize, Deserialize)]
71#[serde(from = "RawAgentSession")]
72pub struct AgentSession {
73 id: Option<SessionId>,
74 chat_messages: Vec<ChatMessage>,
77 always_allowed_actions: HashSet<String>,
78 pub run_state: RunState,
82}
83
84impl AgentSession {
85 pub fn new(id: SessionId) -> Self {
86 Self {
87 id: Some(id),
88 chat_messages: Vec::new(),
89 always_allowed_actions: HashSet::new(),
90 run_state: RunState::default(),
91 }
92 }
93
94 pub fn id(&self) -> Option<SessionId> {
95 self.id.clone()
96 }
97
98 pub fn simple_messages(&self) -> Vec<Message> {
102 self.chat_messages
103 .iter()
104 .filter_map(|cm| match cm {
105 ChatMessage::Assistant { content: None, .. } => None,
106 ChatMessage::Assistant {
107 content: Some(c),
108 tool_calls: Some(tc),
109 ..
110 } if c.is_empty() && !tc.is_empty() => None,
111 _ => Some(Message::from(cm)),
112 })
113 .collect()
114 }
115
116 pub fn chat_messages(&self) -> &[ChatMessage] {
117 &self.chat_messages
118 }
119
120 pub fn chat_messages_mut(&mut self) -> &mut Vec<ChatMessage> {
122 &mut self.chat_messages
123 }
124
125 pub fn is_action_allowed(&self, action_key: &str) -> bool {
126 self.always_allowed_actions.contains(action_key)
127 }
128
129 pub fn allow_action(&mut self, action_key: impl Into<String>) {
130 self.always_allowed_actions.insert(action_key.into());
131 }
132
133 pub fn push_message(&mut self, role: MessageRole, content: impl Into<String>) {
134 let content = content.into();
135 let chat_msg = match role {
136 MessageRole::System => ChatMessage::system(content),
137 MessageRole::User => ChatMessage::user(content),
138 MessageRole::Assistant => ChatMessage::assistant(content),
139 MessageRole::Tool => ChatMessage::tool(String::new(), content),
140 };
141 self.chat_messages.push(chat_msg);
142 }
143
144 pub fn push_message_ephemeral(&mut self, role: MessageRole, content: impl Into<String>) {
148 let content = content.into();
149 let chat_msg = match role {
150 MessageRole::System => ChatMessage::system_ephemeral(content),
151 MessageRole::User => ChatMessage::user_ephemeral(content),
152 MessageRole::Assistant | MessageRole::Tool => {
153 self.push_message(role, content);
156 return;
157 }
158 };
159 self.chat_messages.push(chat_msg);
160 }
161
162 pub fn set_system_prompt(&mut self, content: impl Into<String>) {
167 let content = content.into();
168 if let Some(idx) = self.chat_messages.iter().position(|m| {
169 matches!(
170 m,
171 ChatMessage::System {
172 ephemeral: false,
173 ..
174 }
175 )
176 }) {
177 self.chat_messages[idx] = ChatMessage::system(content);
178 } else {
179 self.chat_messages.insert(0, ChatMessage::system(content));
180 }
181 }
182
183 pub fn push_assistant_with_reasoning(
187 &mut self,
188 content: impl Into<String>,
189 reasoning: impl Into<String>,
190 ) {
191 self.chat_messages
192 .push(ChatMessage::assistant_with_reasoning(content, reasoning));
193 }
194
195 pub fn push_user_message_with_images(
196 &mut self,
197 content: impl Into<String>,
198 images: Vec<ImageAttachment>,
199 ) {
200 self.chat_messages
201 .push(ChatMessage::user_with_images(content, images));
202 }
203
204 pub fn push_assistant_tool_call(
205 &mut self,
206 tool_call_id: &str,
207 tool_name: &str,
208 arguments_json: &str,
209 ) {
210 self.chat_messages.push(ChatMessage::assistant_tool_call(
211 tool_call_id,
212 tool_name,
213 arguments_json,
214 ));
215 }
216
217 fn preview_args(args: &str, max_chars: usize) -> String {
223 format!("{:?}", args.chars().take(max_chars).collect::<String>())
224 }
225
226 pub fn render_assistant_tool_calls(
232 tool_calls: &[(String, String, String)],
233 reasoning: Option<String>,
234 content: Option<String>,
235 ) -> ChatMessage {
236 let calls: Vec<ToolCallMessage> = tool_calls
237 .iter()
238 .map(|(id, name, args)| {
239 let valid_args = if serde_json::from_str::<serde_json::Value>(args).is_ok() {
249 args.clone()
250 } else {
251 tracing::warn!(
252 tool_name = %name,
253 args_len = args.len(),
254 args_preview = %Self::preview_args(args, 80),
255 "tool call arguments are not valid JSON (provider truncated them), \
256 sanitizing to empty object; re-issue instruction goes to the tool_result"
257 );
258 "{}".to_string()
259 };
260 ToolCallMessage {
261 id: id.clone(),
262 name: name.clone(),
263 arguments: valid_args,
264 }
265 })
266 .collect();
267 ChatMessage::Assistant {
268 content,
269 reasoning_content: reasoning,
270 tool_calls: Some(calls),
271 thinking_signature: None,
272 }
273 }
274
275 pub fn push_assistant_tool_calls(
276 &mut self,
277 tool_calls: &[(String, String, String)],
278 reasoning: Option<String>,
279 content: Option<String>,
280 ) {
281 self.push_chat_message(Self::render_assistant_tool_calls(
282 tool_calls, reasoning, content,
283 ));
284 }
285
286 pub fn push_chat_message(&mut self, message: ChatMessage) {
289 self.chat_messages.push(message);
290 }
291
292 pub fn push_tool_result(&mut self, tool_call_id: &str, content: impl Into<String>) {
293 self.chat_messages
294 .push(ChatMessage::tool(tool_call_id, content));
295 }
296
297 pub fn remove_ephemeral_messages(&mut self) {
301 let before = self.chat_messages.len();
302 self.chat_messages.retain(|m| !m.is_ephemeral());
303 let removed = before - self.chat_messages.len();
304 if removed > 0 {
305 tracing::debug!(
306 removed,
307 remaining = self.chat_messages.len(),
308 "ephemeral messages cleaned up"
309 );
310 }
311 }
312
313 pub fn turn_count(&self) -> usize {
316 self.chat_messages
317 .iter()
318 .filter(|m| matches!(m, ChatMessage::User { .. }))
319 .count()
320 }
321
322 pub fn trim_oldest_turns(&mut self, max_turns: usize) {
325 let current_turns = self.turn_count();
326 if current_turns <= max_turns {
327 return;
328 }
329 let turns_to_remove = current_turns - max_turns;
330
331 let user_positions: Vec<usize> = self
333 .chat_messages
334 .iter()
335 .enumerate()
336 .filter_map(|(i, m)| {
337 if matches!(m, ChatMessage::User { .. }) {
338 Some(i)
339 } else {
340 None
341 }
342 })
343 .collect();
344
345 if user_positions.len() <= turns_to_remove {
346 return;
347 }
348
349 let system_prefix = self
351 .chat_messages
352 .iter()
353 .take_while(|m| matches!(m, ChatMessage::System { .. }))
354 .count();
355
356 let drain_end = user_positions[turns_to_remove];
358 if system_prefix >= drain_end {
359 return; }
361
362 self.chat_messages.drain(system_prefix..drain_end);
363 }
364
365 pub fn pop_last_message(&mut self) {
368 self.chat_messages.pop();
369 }
370
371 pub fn close_dangling_tool_calls(&mut self, error_summary: &str) {
372 let assistant_idx = self.chat_messages.iter().rposition(
373 |m| matches!(m, ChatMessage::Assistant { tool_calls: Some(tc), .. } if !tc.is_empty()),
374 );
375
376 let Some(assistant_idx) = assistant_idx else {
377 return;
378 };
379
380 let ChatMessage::Assistant {
381 tool_calls: Some(tc),
382 ..
383 } = &self.chat_messages[assistant_idx]
384 else {
385 return;
386 };
387
388 let all_ids: Vec<String> = tc.iter().map(|t| t.id.clone()).collect();
389
390 let answered_ids: Vec<String> = self.chat_messages[assistant_idx + 1..]
391 .iter()
392 .filter_map(|m| match m {
393 ChatMessage::Tool { tool_call_id, .. } => Some(tool_call_id.clone()),
394 _ => None,
395 })
396 .collect();
397
398 for id in &all_ids {
399 if !answered_ids.iter().any(|a| a == id) {
400 self.push_tool_result(id, error_summary);
401 }
402 }
403 }
404
405 pub fn set_chat_messages(&mut self, messages: Vec<ChatMessage>) -> Result<(), String> {
415 validate_message_sequence(&messages)?;
416 self.chat_messages = messages;
417 Ok(())
418 }
419
420 pub fn recount_actions_from_messages(&mut self) {
426 self.run_state.total_actions = self
427 .chat_messages
428 .iter()
429 .filter_map(|m| match m {
430 ChatMessage::Assistant {
431 tool_calls: Some(tc),
432 ..
433 } => Some(tc.len()),
434 _ => None,
435 })
436 .sum();
437 }
438}
439
440pub fn validate_message_sequence(messages: &[ChatMessage]) -> Result<(), String> {
453 if !messages
454 .iter()
455 .any(|m| !matches!(m, ChatMessage::System { .. } | ChatMessage::Custom { .. }))
456 {
457 return Err(
458 "sequence contains no sendable message: System/Custom alone leave the \
459 provider `messages` array empty"
460 .to_string(),
461 );
462 }
463
464 let mut pending_tool_call_ids: HashSet<String> = HashSet::new();
465
466 for (i, msg) in messages.iter().enumerate() {
467 match msg {
468 ChatMessage::Tool { tool_call_id, .. } => {
469 if pending_tool_call_ids.is_empty() {
470 return Err(format!(
471 "message[{}]: Tool message with call_id '{}' has no preceding tool_call",
472 i, tool_call_id
473 ));
474 }
475 if !pending_tool_call_ids.remove(tool_call_id) {
477 return Err(format!(
478 "message[{}]: Tool message with call_id '{}' does not match any pending tool_call (already answered or unknown)",
479 i, tool_call_id
480 ));
481 }
482 }
483 ChatMessage::Assistant {
484 tool_calls: Some(tc),
485 ..
486 } => {
487 if !pending_tool_call_ids.is_empty() {
489 return Err(format!(
490 "message[{}]: Assistant message with new tool_calls appears before pending calls were answered: {:?}",
491 i, pending_tool_call_ids
492 ));
493 }
494 pending_tool_call_ids = tc.iter().map(|t| t.id.clone()).collect();
495 }
496 _ => {}
497 }
498 }
499
500 if !pending_tool_call_ids.is_empty() {
502 return Err(format!(
503 "message sequence ends with unanswered tool calls: {:?}",
504 pending_tool_call_ids
505 ));
506 }
507
508 Ok(())
509}
510
511#[cfg(test)]
512fn make_session() -> AgentSession {
513 AgentSession::new(SessionId::new(1))
514}
515
516#[cfg(test)]
517mod tests {
518 use super::*;
519
520 #[test]
521 fn test_turn_count_empty() {
522 let s = make_session();
523 assert_eq!(s.turn_count(), 0);
524 }
525
526 #[test]
527 fn test_turn_count_with_system_and_user() {
528 let mut s = make_session();
529 s.push_message(MessageRole::System, "system");
530 assert_eq!(s.turn_count(), 0);
531 s.push_message(MessageRole::User, "hello");
532 assert_eq!(s.turn_count(), 1);
533 s.push_message(MessageRole::Assistant, "hi");
534 assert_eq!(s.turn_count(), 1);
535 s.push_message(MessageRole::User, "bye");
536 assert_eq!(s.turn_count(), 2);
537 }
538
539 #[test]
540 fn test_turn_count_with_tool_calls() {
541 let mut s = make_session();
542 s.push_message(MessageRole::User, "do something");
543 s.push_assistant_tool_calls(&[("id1".into(), "tool".into(), "{}".into())], None, None);
544 s.push_tool_result("id1", "result");
545 s.push_message(MessageRole::Assistant, "done");
546 assert_eq!(s.turn_count(), 1);
548 }
549
550 #[test]
551 fn test_trim_oldest_turns_noop() {
552 let mut s = make_session();
553 s.push_message(MessageRole::User, "hello");
554 s.push_message(MessageRole::Assistant, "hi");
555 s.trim_oldest_turns(5);
556 assert_eq!(s.turn_count(), 1);
557 assert_eq!(s.chat_messages().len(), 2);
558 }
559
560 #[test]
561 fn test_trim_oldest_turns_removes_old() {
562 let mut s = make_session();
563 s.push_message(MessageRole::System, "sys");
564 s.push_message(MessageRole::User, "u1");
566 s.push_message(MessageRole::Assistant, "a1");
567 s.push_message(MessageRole::User, "u2");
569 s.push_message(MessageRole::Assistant, "a2");
570 s.push_message(MessageRole::User, "u3");
572 s.push_message(MessageRole::Assistant, "a3");
573
574 s.trim_oldest_turns(2);
575 assert_eq!(s.turn_count(), 2);
576 assert!(matches!(s.chat_messages()[0], ChatMessage::System { .. }));
578 assert!(
580 matches!(s.chat_messages()[1], ChatMessage::User { ref content, .. } if content == "u2")
581 );
582 }
583
584 #[test]
585 fn test_trim_oldest_turns_with_tool_calls() {
586 let mut s = make_session();
587 s.push_message(MessageRole::User, "u1");
589 s.push_assistant_tool_calls(&[("id1".into(), "t".into(), "{}".into())], None, None);
590 s.push_tool_result("id1", "r1");
591 s.push_message(MessageRole::Assistant, "a1");
592 s.push_message(MessageRole::User, "u2");
594 s.push_message(MessageRole::Assistant, "a2");
595
596 let msg_before = s.simple_messages().len();
597 let chat_before = s.chat_messages().len();
598 s.trim_oldest_turns(1);
599 assert_eq!(s.turn_count(), 1);
600 assert_eq!(s.chat_messages().len(), chat_before - 4);
602 assert_eq!(s.simple_messages().len(), msg_before - 3);
604 }
605
606 #[test]
607 fn test_pop_last_message_text() {
608 let mut s = make_session();
609 s.push_message(MessageRole::User, "hello");
610 s.push_message(MessageRole::Assistant, "hi");
611 assert_eq!(s.chat_messages().len(), 2);
612 s.pop_last_message();
613 assert_eq!(s.chat_messages().len(), 1);
614 assert_eq!(s.simple_messages().len(), 1);
615 }
616
617 #[test]
618 fn test_pop_last_message_tool_calls_only() {
619 let mut s = make_session();
620 s.push_message(MessageRole::User, "do it");
621 s.push_assistant_tool_calls(&[("id1".into(), "t".into(), "{}".into())], None, None);
622 assert_eq!(s.chat_messages().len(), 2);
623 assert_eq!(s.simple_messages().len(), 1); s.pop_last_message();
625 assert_eq!(s.chat_messages().len(), 1);
626 assert_eq!(s.simple_messages().len(), 1); }
628
629 #[test]
630 fn test_pop_last_message_empty_session() {
631 let mut s = make_session();
632 s.pop_last_message(); assert_eq!(s.chat_messages().len(), 0);
634 }
635
636 #[test]
639 fn test_id_and_action_allowlist() {
640 let mut s = make_session();
641 assert_eq!(s.id(), Some(SessionId::new(1)));
642 assert!(!s.is_action_allowed("approve:rm"));
643 s.allow_action("approve:rm");
644 assert!(s.is_action_allowed("approve:rm"));
645 assert!(!s.is_action_allowed("approve:shell"));
646 }
647
648 #[test]
649 fn test_chat_messages_mut() {
650 let mut s = make_session();
651 s.chat_messages_mut().push(ChatMessage::user("direct"));
652 assert_eq!(s.chat_messages().len(), 1);
653 }
654
655 #[test]
656 fn test_push_message_tool_role() {
657 let mut s = make_session();
658 s.push_message(MessageRole::Tool, "result");
659 assert!(matches!(s.chat_messages()[0], ChatMessage::Tool { .. }));
660 }
661
662 #[test]
663 fn test_push_assistant_with_reasoning() {
664 let mut s = make_session();
665 s.push_assistant_with_reasoning("answer", "thinking");
666 match &s.chat_messages()[0] {
667 ChatMessage::Assistant {
668 content,
669 reasoning_content,
670 ..
671 } => {
672 assert_eq!(content.as_deref(), Some("answer"));
673 assert_eq!(reasoning_content.as_deref(), Some("thinking"));
674 }
675 other => panic!("unexpected message: {other:?}"),
676 }
677 }
678
679 #[test]
680 fn test_push_user_message_with_images() {
681 let mut s = make_session();
682 s.push_user_message_with_images(
683 "look",
684 vec![ImageAttachment::Url {
685 url: "http://x".into(),
686 detail: None,
687 }],
688 );
689 match &s.chat_messages()[0] {
690 ChatMessage::User { images, .. } => assert_eq!(images.len(), 1),
691 other => panic!("unexpected message: {other:?}"),
692 }
693 }
694
695 #[test]
696 fn test_push_assistant_tool_call_singular() {
697 let mut s = make_session();
698 s.push_assistant_tool_call("call_1", "bash", "{}");
699 match &s.chat_messages()[0] {
700 ChatMessage::Assistant {
701 tool_calls: Some(tc),
702 ..
703 } => {
704 assert_eq!(tc.len(), 1);
705 assert_eq!(tc[0].id, "call_1");
706 assert_eq!(tc[0].name, "bash");
707 }
708 other => panic!("unexpected message: {other:?}"),
709 }
710 }
711
712 #[test]
713 fn test_simple_messages_filters_empty_content_tool_calls() {
714 let mut s = make_session();
715 s.chat_messages_mut().push(ChatMessage::Assistant {
716 content: Some(String::new()),
717 reasoning_content: None,
718 tool_calls: Some(vec![ToolCallMessage {
719 id: "c".into(),
720 name: "t".into(),
721 arguments: "{}".into(),
722 }]),
723 thinking_signature: None,
724 });
725 assert!(s.simple_messages().is_empty());
726 }
727
728 #[test]
729 fn test_remove_ephemeral_messages() {
730 let mut s = make_session();
731 s.push_message(MessageRole::System, "keep");
732 s.chat_messages_mut()
733 .push(ChatMessage::user_ephemeral("temp"));
734 s.chat_messages_mut()
735 .push(ChatMessage::system_ephemeral("temp2"));
736 s.push_message(MessageRole::User, "keep2");
737 assert_eq!(s.chat_messages().len(), 4);
738 s.remove_ephemeral_messages();
739 assert_eq!(s.chat_messages().len(), 2);
740 assert!(s.chat_messages().iter().all(|m| !m.is_ephemeral()));
741 }
742
743 #[test]
744 fn test_set_system_prompt_replaces_first_non_ephemeral_system() {
745 let mut s = make_session();
746 s.push_message(MessageRole::System, "old prompt");
747 s.push_message(MessageRole::User, "hi");
748 s.push_message(MessageRole::Assistant, "hello");
749
750 s.set_system_prompt("new prompt");
751
752 let msgs = s.chat_messages();
753 assert_eq!(msgs.len(), 3, "history length unchanged");
754 assert!(
755 matches!(&msgs[0], ChatMessage::System { content, ephemeral: false } if content == "new prompt")
756 );
757 assert!(matches!(&msgs[1], ChatMessage::User { content, .. } if content == "hi"));
758 assert!(
759 matches!(&msgs[2], ChatMessage::Assistant { content: Some(c), .. } if c == "hello")
760 );
761 }
762
763 #[test]
764 fn test_set_system_prompt_inserts_when_absent() {
765 let mut s = make_session();
766 s.push_message(MessageRole::User, "hi");
767
768 s.set_system_prompt("fresh prompt");
769
770 let msgs = s.chat_messages();
771 assert_eq!(msgs.len(), 2);
772 assert!(
773 matches!(&msgs[0], ChatMessage::System { content, ephemeral: false } if content == "fresh prompt")
774 );
775 assert!(matches!(&msgs[1], ChatMessage::User { .. }));
776 }
777
778 #[test]
779 fn test_set_system_prompt_skips_ephemeral_system_and_inserts() {
780 let mut s = make_session();
781 s.chat_messages_mut()
782 .push(ChatMessage::system_ephemeral("ephemeral nudge"));
783 s.push_message(MessageRole::User, "hi");
784
785 s.set_system_prompt("real prompt");
786
787 let msgs = s.chat_messages();
789 assert_eq!(msgs.len(), 3);
790 assert!(
791 matches!(&msgs[0], ChatMessage::System { content, ephemeral: false } if content == "real prompt")
792 );
793 assert!(matches!(
794 &msgs[1],
795 ChatMessage::System {
796 ephemeral: true,
797 ..
798 }
799 ));
800 assert!(matches!(&msgs[2], ChatMessage::User { .. }));
801 }
802
803 #[test]
804 fn test_close_dangling_tool_calls_noop_without_tool_call() {
805 let mut s = make_session();
806 s.push_message(MessageRole::User, "hi");
807 s.push_message(MessageRole::Assistant, "hi");
808 s.close_dangling_tool_calls("failed");
809 assert_eq!(s.chat_messages().len(), 2);
810 }
811
812 #[test]
813 fn test_close_dangling_tool_calls_adds_missing_results() {
814 let mut s = make_session();
815 s.push_message(MessageRole::User, "do");
816 s.push_assistant_tool_calls(
817 &[
818 ("c1".into(), "t".into(), "{}".into()),
819 ("c2".into(), "t".into(), "{}".into()),
820 ],
821 None,
822 None,
823 );
824 s.push_tool_result("c1", "ok"); s.close_dangling_tool_calls("failed");
826
827 let tool_results: Vec<(String, String)> = s
828 .chat_messages()
829 .iter()
830 .filter_map(|m| match m {
831 ChatMessage::Tool {
832 tool_call_id,
833 content,
834 ..
835 } => Some((tool_call_id.clone(), content.clone())),
836 _ => None,
837 })
838 .collect();
839 assert_eq!(tool_results.len(), 2);
840 assert!(
841 tool_results
842 .iter()
843 .any(|(id, c)| id == "c2" && c == "failed")
844 );
845 }
846
847 #[test]
848 fn set_chat_messages_leaves_counters_alone() {
849 let mut s = make_session();
853 s.run_state.record_actions(2);
854 let msgs = vec![
855 ChatMessage::user("do"),
856 ChatMessage::assistant_tool_call("c1", "t", "{}"),
857 ChatMessage::tool("c1", "result"),
858 ];
859 s.set_chat_messages(msgs).unwrap();
860 assert_eq!(s.run_state.total_actions, 2); assert_eq!(s.run_state.turn_actions, 2);
862 }
863
864 #[test]
865 fn recount_actions_from_messages_counts_the_assistant_lens() {
866 let mut s = make_session();
868 let msgs = vec![
869 ChatMessage::user("do"),
870 ChatMessage::assistant_tool_call("c1", "t", "{}"),
871 ChatMessage::tool("c1", "result"),
872 ];
873 s.set_chat_messages(msgs).unwrap();
874 s.recount_actions_from_messages();
875 assert_eq!(s.run_state.total_actions, 1);
876 }
877}
878
879#[cfg(test)]
880mod validate_tests {
881 use super::*;
882
883 #[test]
884 fn test_valid_simple_sequence() {
885 let msgs = vec![ChatMessage::user("hello"), ChatMessage::assistant("hi")];
886 assert!(validate_message_sequence(&msgs).is_ok());
887 }
888
889 #[test]
890 fn test_valid_tool_call_sequence() {
891 let msgs = vec![
892 ChatMessage::user("run command"),
893 ChatMessage::assistant_tool_call("call_1", "bash", r#"{"cmd":"ls"}"#),
894 ChatMessage::tool("call_1", "file1 file2"),
895 ChatMessage::assistant("done"),
896 ];
897 assert!(validate_message_sequence(&msgs).is_ok());
898 }
899
900 #[test]
901 fn test_valid_multi_tool_call_sequence() {
902 let msgs = vec![
903 ChatMessage::user("run commands"),
904 ChatMessage::Assistant {
905 content: None,
906 reasoning_content: None,
907 tool_calls: Some(vec![
908 crate::types::ToolCallMessage {
909 id: "call_1".into(),
910 name: "bash".into(),
911 arguments: "{}".into(),
912 },
913 crate::types::ToolCallMessage {
914 id: "call_2".into(),
915 name: "read".into(),
916 arguments: "{}".into(),
917 },
918 ]),
919 thinking_signature: None,
920 },
921 ChatMessage::tool("call_1", "result1"),
922 ChatMessage::tool("call_2", "result2"),
923 ChatMessage::assistant("done"),
924 ];
925 assert!(validate_message_sequence(&msgs).is_ok());
926 }
927
928 #[test]
929 fn test_orphaned_tool_result() {
930 let msgs = vec![
931 ChatMessage::user("hello"),
932 ChatMessage::tool("call_1", "orphaned result"),
933 ];
934 let err = validate_message_sequence(&msgs).unwrap_err();
935 assert!(err.contains("no preceding tool_call"));
936 }
937
938 #[test]
939 fn test_system_only_sequence_rejected() {
940 let msgs = vec![
944 ChatMessage::system("prompt"),
945 ChatMessage::system_ephemeral("reminder"),
946 ChatMessage::Custom {
947 role: "artifact".into(),
948 data: serde_json::json!({"id": "x"}),
949 },
950 ];
951 let err = validate_message_sequence(&msgs).unwrap_err();
952 assert!(err.contains("no sendable message"));
953 }
954
955 #[test]
956 fn test_system_plus_user_ok() {
957 let msgs = vec![ChatMessage::system("prompt"), ChatMessage::user("hi")];
958 assert!(validate_message_sequence(&msgs).is_ok());
959 }
960
961 #[test]
962 fn test_mismatched_tool_call_id() {
963 let msgs = vec![
964 ChatMessage::user("run"),
965 ChatMessage::assistant_tool_call("call_1", "bash", "{}"),
966 ChatMessage::tool("call_2", "wrong id"),
967 ];
968 let err = validate_message_sequence(&msgs).unwrap_err();
969 assert!(err.contains("does not match"));
970 }
971
972 #[test]
973 fn test_set_chat_messages_valid() {
974 let mut s = make_session();
975 let msgs = vec![ChatMessage::user("hello"), ChatMessage::assistant("hi")];
976 assert!(s.set_chat_messages(msgs.clone()).is_ok());
977 assert_eq!(s.chat_messages().len(), 2);
978 }
979
980 #[test]
981 fn test_set_chat_messages_invalid() {
982 let mut s = make_session();
983 let msgs = vec![ChatMessage::tool("call_1", "orphaned")];
984 assert!(s.set_chat_messages(msgs).is_err());
985 }
986
987 #[test]
990 fn deserialize_legacy_flat_fields() {
991 let json = r#"{
993 "id": null,
994 "chat_messages": [],
995 "always_allowed_actions": [],
996 "total_tool_calls": 5,
997 "nudge_count": 3,
998 "turn_tool_calls": 2,
999 "reasoning_only_strikes": 1,
1000 "empty_response_strikes": 0
1001 }"#;
1002 let session: AgentSession = serde_json::from_str(json).unwrap();
1003 assert_eq!(session.run_state.nudge_count, 3);
1004 assert_eq!(session.run_state.turn_actions, 2);
1005 assert_eq!(session.run_state.reasoning_only_strikes, 1);
1006 assert_eq!(session.run_state.empty_response_strikes, 0);
1007 assert!(!session.run_state.run_has_actions); }
1009
1010 #[test]
1011 fn deserialize_new_run_state_format() {
1012 let json = r#"{
1014 "id": null,
1015 "chat_messages": [],
1016 "always_allowed_actions": [],
1017 "total_tool_calls": 5,
1018 "run_state": {
1019 "turn_tool_calls": 4,
1020 "run_has_tool_calls": true,
1021 "reasoning_only_strikes": 0,
1022 "empty_response_strikes": 1,
1023 "nudge_count": 2
1024 }
1025 }"#;
1026 let session: AgentSession = serde_json::from_str(json).unwrap();
1027 assert_eq!(session.run_state.turn_actions, 4);
1028 assert!(session.run_state.run_has_actions);
1029 assert_eq!(session.run_state.empty_response_strikes, 1);
1030 assert_eq!(session.run_state.nudge_count, 2);
1031 }
1032
1033 #[test]
1034 fn deserialize_run_state_takes_precedence_over_flat() {
1035 let json = r#"{
1037 "id": null,
1038 "chat_messages": [],
1039 "always_allowed_actions": [],
1040 "total_tool_calls": 0,
1041 "run_state": {
1042 "turn_tool_calls": 10,
1043 "run_has_tool_calls": true,
1044 "reasoning_only_strikes": 0,
1045 "empty_response_strikes": 0,
1046 "nudge_count": 0
1047 },
1048 "nudge_count": 99,
1049 "turn_tool_calls": 99
1050 }"#;
1051 let session: AgentSession = serde_json::from_str(json).unwrap();
1052 assert_eq!(session.run_state.turn_actions, 10); assert_eq!(session.run_state.nudge_count, 0); }
1055
1056 #[test]
1057 fn deserialize_legacy_missing_optional_fields() {
1058 let json = r#"{
1060 "id": null,
1061 "chat_messages": [],
1062 "always_allowed_actions": [],
1063 "total_tool_calls": 0,
1064 "nudge_count": 1
1065 }"#;
1066 let session: AgentSession = serde_json::from_str(json).unwrap();
1067 assert_eq!(session.run_state.nudge_count, 1);
1068 assert_eq!(session.run_state.turn_actions, 0); assert_eq!(session.run_state.reasoning_only_strikes, 0);
1070 assert_eq!(session.run_state.empty_response_strikes, 0);
1071 }
1072
1073 #[test]
1074 fn roundtrip_preserves_run_state() {
1075 let mut session = AgentSession::new(SessionId::new(1));
1076 session.run_state.nudge_count = 5;
1077 session.run_state.turn_actions = 3;
1078 session.run_state.run_has_actions = true;
1079 session.run_state.reasoning_only_strikes = 2;
1080
1081 let json = serde_json::to_string(&session).unwrap();
1082 let restored: AgentSession = serde_json::from_str(&json).unwrap();
1083 assert_eq!(restored.run_state.nudge_count, 5);
1084 assert_eq!(restored.run_state.turn_actions, 3);
1085 assert!(restored.run_state.run_has_actions);
1086 assert_eq!(restored.run_state.reasoning_only_strikes, 2);
1087 }
1088
1089 #[test]
1090 fn deserialize_migrates_top_level_total_into_run_state() {
1091 let json = r#"{
1095 "id": null,
1096 "chat_messages": [],
1097 "always_allowed_actions": [],
1098 "total_tool_calls": 7,
1099 "run_state": {
1100 "turn_tool_calls": 4,
1101 "run_has_tool_calls": true,
1102 "reasoning_only_strikes": 0,
1103 "empty_response_strikes": 0,
1104 "nudge_count": 0
1105 }
1106 }"#;
1107 let session: AgentSession = serde_json::from_str(json).unwrap();
1108 assert_eq!(session.run_state.total_actions, 7);
1109 assert_eq!(session.run_state.turn_actions, 4);
1110
1111 let rewritten = serde_json::to_string(&session).unwrap();
1112 assert!(
1113 !rewritten.contains("total_tool_calls"),
1114 "new writes keep the total inside run_state: {rewritten}"
1115 );
1116 }
1117
1118 #[test]
1119 fn push_assistant_tool_calls_validates_json_args() {
1120 let mut s = make_session();
1121
1122 let valid_args = r#"{"path": "src/main.rs", "content": "fn main() {}"}"#;
1124 s.push_assistant_tool_calls(
1125 &[("id1".into(), "write_file".into(), valid_args.into())],
1126 None,
1127 None,
1128 );
1129 if let ChatMessage::Assistant {
1130 tool_calls: Some(ref tc),
1131 ..
1132 } = s.chat_messages[0]
1133 {
1134 assert_eq!(tc[0].arguments, valid_args);
1135 } else {
1136 panic!("expected Assistant message with tool_calls");
1137 }
1138
1139 let truncated_args = r#"{"path": "src/ui/markdown.rs", "content": "#;
1149 s.push_assistant_tool_calls(
1150 &[("id2".into(), "write_file".into(), truncated_args.into())],
1151 None,
1152 None,
1153 );
1154 if let ChatMessage::Assistant {
1155 tool_calls: Some(ref tc),
1156 ..
1157 } = s.chat_messages[1]
1158 {
1159 assert_eq!(tc[0].arguments, "{}");
1160 assert!(
1161 !tc[0].arguments.contains("tool_call_arguments_truncated"),
1162 "assistant arguments must not carry the poison wrapper object"
1163 );
1164 } else {
1165 panic!("expected Assistant message with tool_calls");
1166 }
1167 }
1168
1169 #[test]
1170 fn push_assistant_tool_calls_truncated_multibyte_no_panic() {
1171 let mut s = make_session();
1174
1175 let mut bad_args = "あ".repeat(70); bad_args.push_str("truncated"); s.push_assistant_tool_calls(&[("id1".into(), "tool".into(), bad_args)], None, None);
1183
1184 if let ChatMessage::Assistant {
1185 tool_calls: Some(ref tc),
1186 ..
1187 } = s.chat_messages[0]
1188 {
1189 assert_eq!(tc[0].arguments, "{}");
1190 } else {
1191 panic!("expected Assistant message with tool_calls");
1192 }
1193 }
1194
1195 #[test]
1196 fn push_assistant_tool_calls_then_tool_result_matches_anthropic_protocol() {
1197 let mut s = make_session();
1202
1203 let tool_calls = vec![
1205 (
1206 "call_00_VJtlnKha0ZZ2Yo8t5ysQ8883".to_string(),
1207 "write_file".to_string(),
1208 "{}".to_string(),
1209 ),
1210 (
1211 "call_01_abc123".to_string(),
1212 "bash".to_string(),
1213 r#"{"command": "ls"}"#.to_string(),
1214 ),
1215 ];
1216
1217 s.push_assistant_tool_calls(
1219 &tool_calls,
1220 Some("thinking...".to_string()),
1221 Some("I'll help you".to_string()),
1222 );
1223
1224 for (tc_id, _, _) in &tool_calls {
1226 s.push_tool_result(
1227 tc_id,
1228 "Tool call was not executed: the response hit the output token limit.",
1229 );
1230 }
1231
1232 if let ChatMessage::Assistant {
1235 tool_calls: Some(ref tc),
1236 ..
1237 } = s.chat_messages[0]
1238 {
1239 assert_eq!(tc.len(), 2);
1240 assert_eq!(tc[0].id, "call_00_VJtlnKha0ZZ2Yo8t5ysQ8883");
1241 assert_eq!(tc[0].name, "write_file");
1242 assert_eq!(tc[1].id, "call_01_abc123");
1243 assert_eq!(tc[1].name, "bash");
1244 } else {
1245 panic!("expected Assistant message with tool_calls");
1246 }
1247
1248 if let ChatMessage::Tool { tool_call_id, .. } = &s.chat_messages[1] {
1250 assert_eq!(tool_call_id, "call_00_VJtlnKha0ZZ2Yo8t5ysQ8883");
1251 } else {
1252 panic!("expected Tool message for first tool call");
1253 }
1254
1255 if let ChatMessage::Tool { tool_call_id, .. } = &s.chat_messages[2] {
1256 assert_eq!(tool_call_id, "call_01_abc123");
1257 } else {
1258 panic!("expected Tool message for second tool call");
1259 }
1260
1261 assert!(
1263 validate_message_sequence(&s.chat_messages).is_ok(),
1264 "message sequence should be valid with matching tool_use and tool_result"
1265 );
1266 }
1267}
1268
1269#[cfg(test)]
1270mod proptest_tests {
1271 use super::*;
1272 use proptest::prelude::*;
1273
1274 proptest! {
1275 #[test]
1278 fn push_assistant_tool_calls_valid_json_unchanged(args in r"\{[^{}]{0,200}\}") {
1279 if serde_json::from_str::<serde_json::Value>(&args).is_err() {
1281 return Ok(());
1282 }
1283 let mut s = make_session();
1284 s.push_assistant_tool_calls(
1285 &[("id".into(), "tool".into(), args.clone())],
1286 None,
1287 None,
1288 );
1289 if let ChatMessage::Assistant { tool_calls: Some(ref tc), .. } = s.chat_messages()[0] {
1290 assert_eq!(tc[0].arguments, args);
1291 } else {
1292 panic!("expected Assistant with tool_calls");
1293 }
1294 }
1295
1296 #[test]
1297 fn push_assistant_tool_calls_invalid_json_sanitized_to_empty(
1298 bad_args in "[a-z\u{4e00}-\u{9fff}]{0,300}"
1299 ) {
1300 if serde_json::from_str::<serde_json::Value>(&bad_args).is_ok() {
1302 return Ok(());
1303 }
1304 let mut s = make_session();
1305 s.push_assistant_tool_calls(
1306 &[("id".into(), "tool".into(), bad_args)],
1307 None,
1308 None,
1309 );
1310 if let ChatMessage::Assistant { tool_calls: Some(ref tc), .. } = s.chat_messages()[0] {
1311 serde_json::from_str::<serde_json::Value>(&tc[0].arguments)
1314 .expect("sanitized args must be valid JSON");
1315 assert_eq!(tc[0].arguments, "{}");
1316 } else {
1317 panic!("expected Assistant with tool_calls");
1318 }
1319 }
1320
1321 #[test]
1322 fn preview_args_escapes_and_caps_at_max_chars(payload in "[a-z\u{4e00}-\u{9fff}\n\t]{0,400}") {
1323 let preview = AgentSession::preview_args(&payload, 80);
1327 let expected_cap = 2 * payload.chars().count().min(80) + 2;
1328 assert!(
1329 preview.chars().count() <= expected_cap,
1330 "preview must cap at escaped length plus quotes: {preview}"
1331 );
1332 if payload.contains('\n') || payload.contains('\t') {
1333 assert!(
1334 preview.contains("\\n") || preview.contains("\\t"),
1335 "control chars must be escaped: {preview}"
1336 );
1337 }
1338 if payload.chars().count() <= 80 && !payload.contains('\n') && !payload.contains('\t') {
1339 assert_eq!(preview, format!("{payload:?}"));
1340 }
1341 }
1342
1343 #[test]
1346 fn trim_oldest_turns_never_exceeds_max(turns in 1usize..20, max in 1usize..20) {
1347 let mut s = make_session();
1348 for i in 0..turns {
1349 s.push_message(MessageRole::User, format!("u{}", i));
1350 s.push_message(MessageRole::Assistant, format!("a{}", i));
1351 }
1352 s.trim_oldest_turns(max);
1353 assert!(s.turn_count() <= max || turns <= max);
1354 }
1355
1356 #[test]
1359 fn validate_simple_user_assistant_always_passes(count in 1usize..20) {
1360 let mut msgs = Vec::new();
1361 for i in 0..count {
1362 msgs.push(ChatMessage::user(format!("msg{}", i)));
1363 msgs.push(ChatMessage::assistant(format!("reply{}", i)));
1364 }
1365 assert!(validate_message_sequence(&msgs).is_ok());
1366 }
1367 }
1368}