1use crate::core::agent::error_recovery::ErrorRecoveryState;
4use crate::core::agent::task::{TaskOutcome, TaskResults};
5use crate::core::pending_actions::PendingActions;
6use crate::core::state_schema::SchemaVersion;
7use crate::exec::events::Usage;
8use crate::llm::provider::{Message, ResponsesContinuationState, ResponsesContinuationStore};
9use crate::llm::providers::gemini::wire::{Content, FunctionResponse, Part};
10use crate::llm::request_gap::RequestGapTracker;
11use parking_lot::Mutex;
12use std::collections::VecDeque;
13use std::sync::Arc;
14use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
15use vtcode_commons::ErrorCategory;
16use vtcode_exec_events::ThreadEvent;
17
18#[derive(Debug, Clone)]
19pub struct ToolExecutionObservation {
20 pub tool_name: String,
21 pub attempts: u32,
22 pub duration_ms: u64,
23 pub error_category: Option<ErrorCategory>,
24}
25
26pub struct AgentSessionState {
29 pub session_id: String,
31
32 pub conversation: Vec<Content>,
34
35 pub messages: Arc<Vec<Message>>,
41
42 pub schema_version: SchemaVersion,
44
45 pub stats: SessionStats,
47 pub auto_compact_suppressed: u8,
51
52 pub constraints: SessionConstraints,
54
55 pub outcome: TaskOutcome,
57 pub stop_reason: Option<String>,
59 pub total_cost_usd: Option<f64>,
61
62 pub is_completed: bool,
64
65 pub current_stage: Option<String>,
67
68 pub created_contexts: Vec<String>,
70 pub modified_files: Vec<String>,
71 pub executed_commands: Vec<String>,
72 pub warnings: Vec<String>,
73 pub last_file_path: Option<String>,
74 pub last_dir_path: Option<String>,
75
76 pub consecutive_tool_loops: usize,
78 pub tool_loop_limit_hit: bool,
79 pub consecutive_escalations: u32,
82 pub progress_hashes: VecDeque<u64>,
85 pub stagnant_turns: usize,
87 pub last_processed_message_idx: usize,
88 pub previous_response_chains: ResponsesContinuationStore,
90 pub error_recovery: Arc<Mutex<ErrorRecoveryState>>,
92 pub pending_actions: PendingActions,
94
95 pub consecutive_idle_turns: usize,
97 pub max_tool_loop_streak: usize,
98 pub turn_count: usize,
99 pub turn_total_ms: u128,
100 pub turn_max_ms: u128,
101 pub turn_durations_ms: Vec<u128>,
102 pub turn_tool_observations: Vec<ToolExecutionObservation>,
104 cached_total_tokens: usize,
107
108 request_gap: RequestGapTracker,
113
114 last_reasoning_effort: Option<crate::config::types::ReasoningEffortLevel>,
117 last_model: Option<String>,
122}
123
124#[derive(Debug, Default, Clone)]
126pub struct SessionStats {
127 pub turns_executed: usize,
128 pub total_duration: Duration,
129 pub turn_durations: Vec<Duration>,
130 pub total_usage: Usage,
131 pub provider_name: String,
136 pub prompt_cache_health: super::cache_health::PromptCacheHealthMonitor,
140}
141
142impl SessionStats {
143 pub fn merge_usage(
147 &mut self,
148 usage: &crate::llm::provider::Usage,
149 ) -> Option<super::cache_health::CacheHealthAlert> {
150 let normalized = crate::llm::usage_cost::normalized_turn_usage(&self.provider_name, usage);
151 self.total_usage.add(&normalized);
152 self.prompt_cache_health.record_turn(&normalized)
153 }
154}
155
156#[derive(Debug, Clone)]
158pub struct SessionConstraints {
159 pub max_turns: usize,
160 pub max_tool_loops: usize,
161 pub max_context_tokens: usize,
162}
163
164impl AgentSessionState {
165 pub fn new(session_id: String, max_turns: usize, max_tool_loops: usize, max_context_tokens: usize) -> Self {
166 Self {
167 session_id,
168 schema_version: SchemaVersion::CURRENT,
169 conversation: Vec::new(),
170 messages: Arc::new(Vec::new()),
171 stats: SessionStats::default(),
172 auto_compact_suppressed: crate::compaction::SUPPRESS_NONE,
173 constraints: SessionConstraints { max_turns, max_tool_loops, max_context_tokens },
174 outcome: TaskOutcome::Unknown,
175 stop_reason: None,
176 total_cost_usd: None,
177 is_completed: false,
178 current_stage: None,
179 created_contexts: Vec::with_capacity(16),
180 modified_files: Vec::with_capacity(32),
181 executed_commands: Vec::with_capacity(64),
182 warnings: Vec::with_capacity(16),
183 last_file_path: None,
184 last_dir_path: None,
185 consecutive_tool_loops: 0,
186 tool_loop_limit_hit: false,
187 consecutive_escalations: 0,
188 progress_hashes: VecDeque::with_capacity(16),
189 stagnant_turns: 0,
190 last_processed_message_idx: 0,
191 previous_response_chains: ResponsesContinuationStore::default(),
192 error_recovery: Arc::new(Mutex::new(ErrorRecoveryState::default())),
193 pending_actions: PendingActions::new(100),
194 consecutive_idle_turns: 0,
195 max_tool_loop_streak: 0,
196 turn_count: 0,
197 turn_total_ms: 0,
198 turn_max_ms: 0,
199 turn_durations_ms: Vec::with_capacity(max_turns),
200 turn_tool_observations: Vec::with_capacity(32),
201 cached_total_tokens: 0,
202 request_gap: RequestGapTracker::default(),
203 last_reasoning_effort: None,
204 last_model: None,
205 }
206 }
207
208 pub fn note_request_sent(&mut self) {
211 self.request_gap.note_request_sent();
212 }
213
214 pub fn cache_gap_exceeds(&self, threshold: Duration) -> Option<Duration> {
220 self.request_gap.cache_gap_exceeds(threshold)
221 }
222
223 pub fn note_reasoning_effort_change(&mut self, effort: Option<crate::config::types::ReasoningEffortLevel>) -> bool {
229 let changed = matches!(
230 (self.last_reasoning_effort, effort),
231 (Some(previous), Some(current)) if previous != current
232 );
233 self.last_reasoning_effort = effort;
234 changed
235 }
236
237 pub fn note_model_change(&mut self, model: &str) -> bool {
244 let changed = self.last_model.as_deref().is_some_and(|previous| previous != model);
245 self.last_model = Some(model.to_string());
246 changed
247 }
248
249 pub fn record_turn(&mut self, start: &Instant, recorded: &mut bool) {
251 if *recorded {
252 return;
253 }
254 let duration = start.elapsed();
255 let ms = duration.as_millis() as u64;
256
257 self.stats.turns_executed += 1;
258 self.stats.total_duration += duration;
259 self.stats.turn_durations.push(duration);
260
261 self.turn_count += 1;
263 self.turn_total_ms += ms as u128;
264 self.turn_max_ms = self.turn_max_ms.max(ms as u128);
265 self.turn_durations_ms.push(ms as u128);
266
267 *recorded = true;
268 }
269
270 pub fn finalize_outcome(&mut self, max_turns: usize) {
271 if self.outcome != TaskOutcome::Unknown {
272 return;
273 }
274 if self.tool_loop_limit_hit {
276 self.outcome =
277 TaskOutcome::tool_loop_limit_reached(self.constraints.max_tool_loops, self.consecutive_tool_loops);
278 } else if self.is_completed {
279 self.outcome = TaskOutcome::Success;
280 } else if self.stats.turns_executed >= max_turns {
281 self.outcome = TaskOutcome::turn_limit_reached(max_turns, self.stats.turns_executed);
282 }
283 }
284
285 pub fn register_tool_loop(&mut self) -> usize {
286 self.consecutive_tool_loops += 1;
287 self.max_tool_loop_streak = self.max_tool_loop_streak.max(self.consecutive_tool_loops);
288 self.consecutive_tool_loops
289 }
290
291 pub fn reset_tool_loop_guard(&mut self) {
292 self.consecutive_tool_loops = 0;
293 }
294
295 pub fn previous_response_id_for(&self, provider: &str, model: &str) -> Option<String> {
296 self.previous_response_chain_for(provider, model)
297 .map(|chain| chain.response_id.clone())
298 }
299
300 pub fn previous_response_chain_for(&self, provider: &str, model: &str) -> Option<&ResponsesContinuationState> {
301 self.previous_response_chains.get(provider, model)
302 }
303
304 pub fn set_previous_response_chain(
305 &mut self,
306 provider: &str,
307 model: &str,
308 response_id: Option<&str>,
309 messages: Vec<Message>,
310 ) {
311 self.set_previous_response_chain_shared(provider, model, response_id, Arc::new(messages));
312 }
313
314 pub(crate) fn set_previous_response_chain_shared(
319 &mut self,
320 provider: &str,
321 model: &str,
322 response_id: Option<&str>,
323 messages: Arc<Vec<Message>>,
324 ) {
325 self.previous_response_chains.set(provider, model, response_id, messages);
326 }
327
328 pub fn clear_previous_response_chain_for(&mut self, provider: &str, model: &str) {
329 self.previous_response_chains.clear_for(provider, model);
330 }
331
332 pub fn clear_previous_response_chain(&mut self) {
333 self.previous_response_chains.clear();
334 }
335
336 pub fn mark_tool_loop_limit_hit(&mut self) {
337 if self.tool_loop_limit_hit {
338 return;
339 }
340 self.tool_loop_limit_hit = true;
341 self.outcome =
342 TaskOutcome::tool_loop_limit_reached(self.constraints.max_tool_loops, self.consecutive_tool_loops);
343 }
344
345 #[inline]
349 pub fn messages_mut(&mut self) -> &mut Vec<Message> {
350 Arc::make_mut(&mut self.messages)
351 }
352
353 pub fn add_user_message(&mut self, text: String) {
355 self.add_user_message_with_intent(text, None);
356 }
357
358 pub fn add_synthetic_user_message(&mut self, text: String) {
364 self.add_synthetic_user_message_with_intent(text, None);
365 }
366
367 pub fn add_synthetic_user_message_with_intent(&mut self, text: String, intent_id: Option<String>) {
369 let metadata = Self::user_message_metadata(&text, intent_id, true);
370 self.push_user_message(text, metadata);
371 }
372
373 pub fn add_user_message_with_intent(&mut self, text: String, intent_id: Option<String>) {
376 let metadata = Self::user_message_metadata(&text, intent_id, false);
377 self.push_user_message(text, metadata);
378 }
379
380 fn user_message_metadata(
381 text: &str,
382 intent_id: Option<String>,
383 synthetic: bool,
384 ) -> crate::core::message_metadata::MessageMetadata {
385 let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
386 let tokens = text.len().saturating_div(4); let metadata = if synthetic {
388 crate::core::message_metadata::MessageMetadata::harness_notice(now, tokens)
389 } else {
390 crate::core::message_metadata::MessageMetadata::user_input(now, tokens)
391 };
392 match intent_id {
393 Some(id) => metadata.with_intent_id(id),
394 None => metadata,
395 }
396 }
397
398 fn push_user_message(&mut self, text: String, metadata: crate::core::message_metadata::MessageMetadata) {
399 self.conversation.push(Content::user_text(text.as_str()));
400 let msg = Message::user(text).with_metadata(metadata);
401 let msg_tokens = msg.estimate_tokens();
403 self.cached_total_tokens = self.cached_total_tokens.saturating_add(msg_tokens);
404 self.messages_mut().push(msg);
405 }
406
407 const PROGRESS_STAGNATION_THRESHOLD: usize = 4;
409
410 fn assistant_response_hash(&self) -> Option<u64> {
412 use crate::llm::provider::{MessageContent, MessageRole};
413 let last_assistant = self.messages.iter().rev().find(|m| m.role == MessageRole::Assistant)?;
414 use std::hash::{Hash, Hasher};
415 let mut hasher = std::collections::hash_map::DefaultHasher::new();
416 match &last_assistant.content {
417 MessageContent::Text(t) => t.hash(&mut hasher),
418 MessageContent::Parts(parts) => {
419 for part in parts {
420 if let crate::llm::provider::ContentPart::Text { text, .. } = part {
421 text.hash(&mut hasher);
422 }
423 }
424 }
425 }
426 Some(hasher.finish())
427 }
428
429 pub fn record_progress_hash_and_check_stagnation(&mut self) -> bool {
431 let Some(hash) = self.assistant_response_hash() else {
432 self.stagnant_turns = 0;
433 return false;
434 };
435 if self.progress_hashes.back() == Some(&hash) {
436 self.stagnant_turns += 1;
437 } else {
438 self.stagnant_turns = 0;
439 }
440 self.progress_hashes.push_back(hash);
441 if self.progress_hashes.len() > 16 {
442 self.progress_hashes.pop_front();
443 }
444 self.stagnant_turns >= Self::PROGRESS_STAGNATION_THRESHOLD
445 }
446
447 pub fn attach_metadata_to_last(&mut self, source: &str, estimated_tokens: usize) {
450 if let Some(last) = self.messages_mut().last_mut() {
451 let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
452 let metadata = match source {
453 "llm_response" => crate::core::message_metadata::MessageMetadata::llm_response(now, estimated_tokens),
454 "tool_result" => crate::core::message_metadata::MessageMetadata::tool_result(now, estimated_tokens),
455 "system" => crate::core::message_metadata::MessageMetadata::system(now, estimated_tokens),
456 "synthetic" => crate::core::message_metadata::MessageMetadata::synthetic(now, estimated_tokens),
457 _ => crate::core::message_metadata::MessageMetadata::user_input(now, estimated_tokens),
458 };
459 last.metadata = Some(metadata);
460 }
461 }
462
463 pub fn utilization(&self) -> f64 {
465 if self.constraints.max_context_tokens == 0 {
466 return 0.0;
467 }
468 self.total_tokens() as f64 / self.constraints.max_context_tokens as f64
469 }
470
471 #[inline]
475 pub fn total_tokens(&self) -> usize {
476 self.cached_total_tokens
477 }
478
479 pub fn reconcile_token_count(&mut self) {
483 self.cached_total_tokens = self.messages.iter().map(|m| m.estimate_tokens()).sum();
484 }
485
486 #[inline]
489 pub fn adjust_token_count(&mut self, delta: isize) {
490 if delta >= 0 {
491 self.cached_total_tokens = self
493 .cached_total_tokens
494 .saturating_add(usize::try_from(delta).expect("delta >= 0 checked above"));
495 } else {
496 self.cached_total_tokens = self.cached_total_tokens.saturating_sub(delta.unsigned_abs());
497 }
498 }
499
500 pub fn preflight_token_check(
508 &self,
509 system_prompt_tokens: usize,
510 tool_def_tokens: usize,
511 reserved_output_tokens: usize,
512 ) -> (bool, usize, usize) {
513 let budget = self.constraints.max_context_tokens.saturating_sub(reserved_output_tokens);
514 let estimated = self
515 .total_tokens()
516 .saturating_add(system_prompt_tokens)
517 .saturating_add(tool_def_tokens);
518 (estimated <= budget, estimated, budget)
519 }
520
521 pub fn find_safe_split_point(&self, preferred_split_at: usize) -> usize {
523 crate::core::agent::state::safe_history_split_point(&self.messages, self.conversation.len(), preferred_split_at)
524 }
525
526 pub fn normalize(&mut self) {
528 crate::core::agent::state::normalize_history(self.messages_mut());
529 self.reconcile_token_count();
530 }
531
532 pub fn clear_conversation_history(&mut self) {
544 self.messages_mut().clear();
545 self.conversation.clear();
546 self.cached_total_tokens = 0;
547 self.last_processed_message_idx = 0;
548 self.previous_response_chains.clear();
549 self.consecutive_tool_loops = 0;
550 self.tool_loop_limit_hit = false;
551 self.consecutive_escalations = 0;
552 self.progress_hashes.clear();
553 self.stagnant_turns = 0;
554 self.pending_actions = PendingActions::new(100);
555 self.consecutive_idle_turns = 0;
556 self.max_tool_loop_streak = 0;
557 self.turn_tool_observations.clear();
558 self.current_stage = None;
559 self.auto_compact_suppressed = crate::compaction::SUPPRESS_NONE;
560 self.error_recovery.lock().reset();
561 }
562
563 pub fn into_results(
564 self,
565 summary: String,
566 thread_events: Vec<ThreadEvent>,
567 total_duration_ms: u128,
568 ) -> TaskResults {
569 let average_turn_duration_ms = if self.turn_count > 0 {
570 Some(self.turn_total_ms as f64 / self.turn_count as f64)
571 } else {
572 None
573 };
574 let max_turn_duration_ms = if self.turn_count > 0 {
575 Some(self.turn_max_ms)
576 } else {
577 None
578 };
579
580 TaskResults {
581 created_contexts: self.created_contexts,
582 modified_files: self.modified_files,
583 executed_commands: self.executed_commands,
584 summary,
585 stop_reason: self.stop_reason,
586 total_cost_usd: self.total_cost_usd,
587 warnings: self.warnings,
588 thread_events,
589 outcome: self.outcome,
590 turns_executed: self.stats.turns_executed,
591 total_duration_ms,
592 average_turn_duration_ms,
593 max_turn_duration_ms,
594 turn_durations_ms: self.turn_durations_ms,
595 }
596 }
597
598 fn push_tool_event(&mut self, call_id: String, tool_name: &str, value: &serde_json::Value, is_gemini: bool) {
603 if is_gemini {
604 self.conversation.push(Content {
605 role: "function".to_string(),
606 parts: vec![Part::FunctionResponse {
607 function_response: FunctionResponse {
608 name: tool_name.to_string(),
609 response: value.clone(),
610 id: Some(call_id.clone()),
611 },
612 thought_signature: None,
613 }],
614 });
615 }
616 let serialized = serde_json::to_string(value).expect("Value serialization is infallible");
617 let msg = Message::tool_response(call_id, serialized);
618 let tokens = msg.estimate_tokens();
619 self.cached_total_tokens = self.cached_total_tokens.saturating_add(tokens);
620 self.messages_mut().push(msg);
621 }
622
623 pub fn push_tool_result(&mut self, call_id: String, tool_name: &str, result: &serde_json::Value, is_gemini: bool) {
625 self.push_tool_event(call_id, tool_name, result, is_gemini);
626 let tool_name_owned = tool_name.to_owned();
629 if !self.executed_commands.contains(&tool_name_owned) {
630 self.executed_commands.push(tool_name_owned);
631 }
632 }
633
634 pub fn push_tool_error(
636 &mut self,
637 call_id: String,
638 tool_name: &str,
639 error_payload: &serde_json::Value,
640 is_gemini: bool,
641 ) {
642 self.push_tool_event(call_id, tool_name, error_payload, is_gemini);
643 }
644
645 pub fn push_warning(&mut self, warning: impl Into<String>) {
656 let warning = warning.into();
657 if self.warnings.contains(&warning) {
658 return;
659 }
660 if self.warnings.len() < MAX_SESSION_WARNINGS {
661 self.warnings.push(warning);
662 } else if self.warnings.last().is_none_or(|w| w != WARNINGS_ELIDED_MARKER) {
663 self.warnings.push(WARNINGS_ELIDED_MARKER.to_string());
664 }
665 }
666}
667
668const MAX_SESSION_WARNINGS: usize = 200;
672const WARNINGS_ELIDED_MARKER: &str = "[Additional unique warnings elided — session warning cap reached]";
673
674#[cfg(test)]
675mod tests {
676 use super::AgentSessionState;
677 use crate::config::types::ReasoningEffortLevel;
678 use crate::llm::provider::Message;
679 use crate::llm::providers::gemini::wire::Part;
680 use std::sync::Arc;
681 use std::thread;
682 use std::time::Duration;
683
684 #[test]
688 fn cache_gap_exceeds_delegates_to_request_gap_tracker() {
689 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
690 assert_eq!(state.cache_gap_exceeds(Duration::from_millis(1)), None);
691
692 state.note_request_sent();
693 thread::sleep(Duration::from_millis(15));
694 let gap = state.cache_gap_exceeds(Duration::from_millis(5));
695 assert!(gap.is_some_and(|elapsed| elapsed >= Duration::from_millis(15)));
696 }
697
698 #[test]
699 fn note_reasoning_effort_change_is_false_on_first_request() {
700 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
701 assert!(!state.note_reasoning_effort_change(Some(ReasoningEffortLevel::Medium)));
702 }
703
704 #[test]
705 fn note_reasoning_effort_change_is_false_when_unchanged() {
706 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
707 assert!(!state.note_reasoning_effort_change(Some(ReasoningEffortLevel::Medium)));
708 assert!(!state.note_reasoning_effort_change(Some(ReasoningEffortLevel::Medium)));
709 }
710
711 #[test]
712 fn note_reasoning_effort_change_is_true_when_changed() {
713 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
714 assert!(!state.note_reasoning_effort_change(Some(ReasoningEffortLevel::Medium)));
715 assert!(state.note_reasoning_effort_change(Some(ReasoningEffortLevel::High)));
716 assert!(!state.note_reasoning_effort_change(Some(ReasoningEffortLevel::High)));
718 }
719
720 #[test]
721 fn note_model_change_is_false_on_first_request() {
722 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
723 assert!(!state.note_model_change("gpt-5.6"));
724 }
725
726 #[test]
727 fn note_model_change_is_false_when_unchanged() {
728 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
729 assert!(!state.note_model_change("gpt-5.6"));
730 assert!(!state.note_model_change("gpt-5.6"));
731 }
732
733 #[test]
734 fn note_model_change_is_true_when_changed() {
735 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
736 assert!(!state.note_model_change("gpt-5.6"));
737 assert!(state.note_model_change("claude-opus-4-6"));
738 assert!(!state.note_model_change("claude-opus-4-6"));
740 }
741
742 #[test]
743 fn previous_response_chain_is_scoped_to_provider_and_model() {
744 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
745 let messages_52 = vec![Message::user("hello".to_string())];
746 let messages_54 = vec![Message::user("continue".to_string())];
747
748 state.set_previous_response_chain("openai", "gpt-5.6", Some("resp_123"), messages_52.clone());
749 state.set_previous_response_chain("openai", "gpt-5.6-sol", Some("resp_456"), messages_54.clone());
750
751 assert_eq!(state.previous_response_id_for("openai", "gpt-5.6"), Some("resp_123".to_string()));
752 assert_eq!(state.previous_response_id_for("openai", "gpt-5.6-sol"), Some("resp_456".to_string()));
753 assert_eq!(state.previous_response_id_for("gemini", "gpt-5.6"), None);
754
755 state.clear_previous_response_chain_for("openai", "gpt-5.6");
756
757 assert_eq!(state.previous_response_id_for("openai", "gpt-5.6"), None);
758 assert_eq!(state.previous_response_chain_for("openai", "gpt-5.6"), None);
759 assert_eq!(state.previous_response_id_for("openai", "gpt-5.6-sol"), Some("resp_456".to_string()));
760 assert_eq!(
761 state
762 .previous_response_chain_for("openai", "gpt-5.6-sol")
763 .map(|chain| chain.messages.as_slice()),
764 Some(messages_54.as_slice())
765 );
766
767 state.clear_previous_response_chain();
768 assert_eq!(state.previous_response_id_for("openai", "gpt-5.6-sol"), None);
769 assert_eq!(state.previous_response_chain_for("openai", "gpt-5.6-sol"), None);
770 }
771
772 #[test]
773 fn shared_previous_response_chain_reuses_history_arc() {
774 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
775 let messages = Arc::new(vec![Message::user("hello".to_string())]);
776
777 state.set_previous_response_chain_shared("openai", "gpt-5.6-sol", Some("resp_123"), Arc::clone(&messages));
778
779 let stored = &state
780 .previous_response_chain_for("openai", "gpt-5.6-sol")
781 .expect("continuation state")
782 .messages;
783 assert!(Arc::ptr_eq(&messages, stored));
784 }
785
786 #[test]
787 fn register_tool_loop_tracks_current_and_max_streak() {
788 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
789
790 assert_eq!(state.register_tool_loop(), 1);
791 assert_eq!(state.register_tool_loop(), 2);
792 assert_eq!(state.consecutive_tool_loops, 2);
793 assert_eq!(state.max_tool_loop_streak, 2);
794
795 state.reset_tool_loop_guard();
796 assert_eq!(state.register_tool_loop(), 1);
797 assert_eq!(state.max_tool_loop_streak, 2);
798 }
799
800 #[test]
801 fn push_tool_error_preserves_structured_json_for_gemini() {
802 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
803 let payload = serde_json::json!({
804 "error": {
805 "tool_name": "read_file",
806 "message": "missing file",
807 "category": "ResourceNotFound"
808 }
809 });
810
811 state.push_tool_error("call_1".to_string(), "read_file", &payload, true);
812
813 match &state.conversation[0].parts[0] {
814 Part::FunctionResponse { function_response, .. } => {
815 assert_eq!(function_response.response["error"]["message"], "missing file");
816 }
817 other => panic!("expected function response, got {other:?}"),
818 }
819 let expected_serialized = serde_json::to_string(&payload).unwrap();
820 assert_eq!(state.messages[0], Message::tool_response("call_1".to_string(), expected_serialized));
821 }
822
823 #[test]
824 fn harness_notices_are_tagged_synthetic_while_user_messages_are_not() {
825 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
826 state.add_user_message("fix the flaky test".to_string());
827 state.add_synthetic_user_message("It looks like you're repeating the same response.".to_string());
828 state.add_user_message_with_intent("steer: stop after this".to_string(), Some("intent-1".to_string()));
829
830 let sources: Vec<Option<&str>> = state
831 .messages
832 .iter()
833 .map(|message| message.metadata.as_ref().and_then(|metadata| metadata.source()))
834 .collect();
835 assert_eq!(sources, vec![Some("user_input"), Some("synthetic"), Some("user_input")]);
836 assert!(
837 state.messages[1]
838 .metadata
839 .as_ref()
840 .is_some_and(vtcode_commons::message_metadata::MessageMetadata::is_synthetic)
841 );
842 let archived: Vec<crate::utils::session_archive::SessionMessage> =
844 state.messages.iter().map(Into::into).collect();
845 assert!(
846 archived[1]
847 .metadata
848 .as_deref()
849 .is_some_and(vtcode_commons::message_metadata::MessageMetadata::is_synthetic)
850 );
851 assert!(archived[0].metadata.as_deref().is_some_and(|m| !m.is_synthetic()));
852 }
853
854 #[test]
855 fn cached_total_tokens_matches_direct_computation() {
856 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
857
858 state.add_user_message("Hello, how are you?".to_string());
860 state.push_tool_result(
861 "call_1".to_string(),
862 "read_file",
863 &serde_json::json!({"content": "test file content"}),
864 false,
865 );
866 state.push_tool_error(
867 "call_2".to_string(),
868 "write_file",
869 &serde_json::json!({"error": "permission denied"}),
870 false,
871 );
872
873 let direct = state.messages.iter().map(|m| m.estimate_tokens()).sum::<usize>();
875 assert_eq!(state.total_tokens(), direct);
876 assert!(state.total_tokens() > 0);
877 }
878
879 #[test]
880 fn reconcile_token_count_resyncs_after_external_mutation() {
881 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
882 state.add_user_message("test message".to_string());
883 let before = state.total_tokens();
884
885 state.messages_mut().push(Message::assistant("extra response".to_string()));
887 assert_ne!(state.total_tokens(), before + Message::assistant("extra response".to_string()).estimate_tokens());
888
889 state.reconcile_token_count();
891 let expected = state.messages.iter().map(|m| m.estimate_tokens()).sum::<usize>();
892 assert_eq!(state.total_tokens(), expected);
893 }
894
895 #[test]
896 fn clear_conversation_history_resets_all_state() {
897 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
898 state.messages_mut().push(Message::user("hello".to_string()));
899 state.messages_mut().push(Message::assistant("hi".to_string()));
900 state.conversation.push(crate::llm::providers::gemini::wire::Content {
901 role: "user".to_string(),
902 parts: vec![Part::Text { text: "hello".to_string(), thought_signature: None }],
903 });
904 state.reconcile_token_count();
905 state.last_processed_message_idx = 2;
906 state.progress_hashes.push_back(123);
907 state.stagnant_turns = 3;
908 state.set_previous_response_chain("openai", "gpt-5", Some("resp_1"), vec![]);
909
910 assert!(!state.messages.is_empty());
911 assert!(!state.conversation.is_empty());
912 assert!(state.total_tokens() > 0);
913
914 state.clear_conversation_history();
915
916 assert!(state.messages.is_empty());
917 assert!(state.conversation.is_empty());
918 assert_eq!(state.total_tokens(), 0);
919 assert_eq!(state.last_processed_message_idx, 0);
920 assert!(state.progress_hashes.is_empty());
921 assert_eq!(state.stagnant_turns, 0);
922 assert!(state.previous_response_chains.is_empty());
923 }
924
925 #[test]
926 fn push_warning_skips_exact_duplicates() {
927 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
928 state.push_warning("rate limited");
929 state.push_warning("rate limited");
930 state.push_warning("rate limited");
931 assert_eq!(state.warnings.len(), 1);
932 assert_eq!(state.warnings[0], "rate limited");
933 }
934
935 #[test]
936 fn push_warning_retains_distinct_warnings() {
937 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
938 state.push_warning("first warning");
939 state.push_warning("second warning");
940 state.push_warning("third warning");
941 assert_eq!(state.warnings.len(), 3);
942 assert_eq!(state.warnings[0], "first warning");
943 assert_eq!(state.warnings[1], "second warning");
944 assert_eq!(state.warnings[2], "third warning");
945 }
946
947 #[test]
948 fn push_warning_inserts_elision_marker_at_cap() {
949 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
950 for i in 0..super::MAX_SESSION_WARNINGS {
952 state.push_warning(format!("warning {i}"));
953 }
954 assert_eq!(state.warnings.len(), super::MAX_SESSION_WARNINGS);
955 assert!(!state.warnings.iter().any(|w| w == super::WARNINGS_ELIDED_MARKER));
956
957 state.push_warning("overflow A");
959 assert_eq!(state.warnings.len(), super::MAX_SESSION_WARNINGS + 1);
960 assert_eq!(state.warnings.last().unwrap(), super::WARNINGS_ELIDED_MARKER);
961
962 state.push_warning("overflow B");
965 state.push_warning("overflow C");
966 assert_eq!(state.warnings.len(), super::MAX_SESSION_WARNINGS + 1);
967 assert_eq!(state.warnings.last().unwrap(), super::WARNINGS_ELIDED_MARKER);
968 assert!(!state.warnings.iter().any(|w| w == "overflow A"));
970 assert!(!state.warnings.iter().any(|w| w == "overflow B"));
971 }
972}