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