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, responses_continuation_key};
9use crate::llm::providers::gemini::wire::{Content, FunctionResponse, Part};
10use crate::llm::request_gap::RequestGapTracker;
11use hashbrown::HashMap;
12use parking_lot::Mutex;
13use std::collections::VecDeque;
14use std::sync::Arc;
15use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
16use vtcode_commons::ErrorCategory;
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: HashMap<(String, String), ResponsesContinuationState>,
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: HashMap::new(),
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 responses_continuation_key(provider, model).and_then(|key| self.previous_response_chains.get(&key))
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 let Some(key) = responses_continuation_key(provider, model) else {
327 return;
328 };
329 let Some(response_id) = response_id.map(str::trim).filter(|value| !value.is_empty()) else {
330 self.previous_response_chains.remove(&key);
331 return;
332 };
333
334 self.previous_response_chains
335 .insert(key, ResponsesContinuationState { response_id: response_id.to_string(), messages });
336 }
337
338 pub fn clear_previous_response_chain_for(&mut self, provider: &str, model: &str) {
339 if let Some(key) = responses_continuation_key(provider, model) {
340 self.previous_response_chains.remove(&key);
341 }
342 }
343
344 pub fn clear_previous_response_chain(&mut self) {
345 self.previous_response_chains.clear();
346 }
347
348 pub fn mark_tool_loop_limit_hit(&mut self) {
349 if self.tool_loop_limit_hit {
350 return;
351 }
352 self.tool_loop_limit_hit = true;
353 self.outcome =
354 TaskOutcome::tool_loop_limit_reached(self.constraints.max_tool_loops, self.consecutive_tool_loops);
355 }
356
357 #[inline]
361 pub fn messages_mut(&mut self) -> &mut Vec<Message> {
362 Arc::make_mut(&mut self.messages)
363 }
364
365 pub fn add_user_message(&mut self, text: String) {
367 self.add_user_message_with_intent(text, None);
368 }
369
370 pub fn add_synthetic_user_message(&mut self, text: String) {
376 let metadata = Self::user_message_metadata(&text, None, true);
377 self.push_user_message(text, metadata);
378 }
379
380 pub fn add_user_message_with_intent(&mut self, text: String, intent_id: Option<String>) {
383 let metadata = Self::user_message_metadata(&text, intent_id, false);
384 self.push_user_message(text, metadata);
385 }
386
387 fn user_message_metadata(
388 text: &str,
389 intent_id: Option<String>,
390 synthetic: bool,
391 ) -> crate::core::message_metadata::MessageMetadata {
392 let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
393 let tokens = text.len().saturating_div(4); let metadata = if synthetic {
395 crate::core::message_metadata::MessageMetadata::harness_notice(now, tokens)
396 } else {
397 crate::core::message_metadata::MessageMetadata::user_input(now, tokens)
398 };
399 match intent_id {
400 Some(id) => metadata.with_intent_id(id),
401 None => metadata,
402 }
403 }
404
405 fn push_user_message(&mut self, text: String, metadata: crate::core::message_metadata::MessageMetadata) {
406 self.conversation.push(Content::user_text(text.as_str()));
407 let msg = Message::user(text).with_metadata(metadata);
408 let msg_tokens = msg.estimate_tokens();
410 self.cached_total_tokens = self.cached_total_tokens.saturating_add(msg_tokens);
411 self.messages_mut().push(msg);
412 }
413
414 const PROGRESS_STAGNATION_THRESHOLD: usize = 4;
416
417 fn assistant_response_hash(&self) -> Option<u64> {
419 use crate::llm::provider::{MessageContent, MessageRole};
420 let last_assistant = self.messages.iter().rev().find(|m| m.role == MessageRole::Assistant)?;
421 use std::hash::{Hash, Hasher};
422 let mut hasher = std::collections::hash_map::DefaultHasher::new();
423 match &last_assistant.content {
424 MessageContent::Text(t) => t.hash(&mut hasher),
425 MessageContent::Parts(parts) => {
426 for part in parts {
427 if let crate::llm::provider::ContentPart::Text { text, .. } = part {
428 text.hash(&mut hasher);
429 }
430 }
431 }
432 }
433 Some(hasher.finish())
434 }
435
436 pub fn record_progress_hash_and_check_stagnation(&mut self) -> bool {
438 let Some(hash) = self.assistant_response_hash() else {
439 self.stagnant_turns = 0;
440 return false;
441 };
442 if self.progress_hashes.back() == Some(&hash) {
443 self.stagnant_turns += 1;
444 } else {
445 self.stagnant_turns = 0;
446 }
447 self.progress_hashes.push_back(hash);
448 if self.progress_hashes.len() > 16 {
449 self.progress_hashes.pop_front();
450 }
451 self.stagnant_turns >= Self::PROGRESS_STAGNATION_THRESHOLD
452 }
453
454 pub fn attach_metadata_to_last(&mut self, source: &str, estimated_tokens: usize) {
457 if let Some(last) = self.messages_mut().last_mut() {
458 let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
459 let metadata = match source {
460 "llm_response" => crate::core::message_metadata::MessageMetadata::llm_response(now, estimated_tokens),
461 "tool_result" => crate::core::message_metadata::MessageMetadata::tool_result(now, estimated_tokens),
462 "system" => crate::core::message_metadata::MessageMetadata::system(now, estimated_tokens),
463 "synthetic" => crate::core::message_metadata::MessageMetadata::synthetic(now, estimated_tokens),
464 _ => crate::core::message_metadata::MessageMetadata::user_input(now, estimated_tokens),
465 };
466 last.metadata = Some(metadata);
467 }
468 }
469
470 pub fn utilization(&self) -> f64 {
472 if self.constraints.max_context_tokens == 0 {
473 return 0.0;
474 }
475 self.total_tokens() as f64 / self.constraints.max_context_tokens as f64
476 }
477
478 #[inline]
482 pub fn total_tokens(&self) -> usize {
483 self.cached_total_tokens
484 }
485
486 pub fn reconcile_token_count(&mut self) {
490 self.cached_total_tokens = self.messages.iter().map(|m| m.estimate_tokens()).sum();
491 }
492
493 #[inline]
496 pub fn adjust_token_count(&mut self, delta: isize) {
497 if delta >= 0 {
498 self.cached_total_tokens = self
500 .cached_total_tokens
501 .saturating_add(usize::try_from(delta).expect("delta >= 0 checked above"));
502 } else {
503 self.cached_total_tokens = self.cached_total_tokens.saturating_sub(delta.unsigned_abs());
504 }
505 }
506
507 pub fn preflight_token_check(
515 &self,
516 system_prompt_tokens: usize,
517 tool_def_tokens: usize,
518 reserved_output_tokens: usize,
519 ) -> (bool, usize, usize) {
520 let budget = self.constraints.max_context_tokens.saturating_sub(reserved_output_tokens);
521 let estimated = self
522 .total_tokens()
523 .saturating_add(system_prompt_tokens)
524 .saturating_add(tool_def_tokens);
525 (estimated <= budget, estimated, budget)
526 }
527
528 pub fn find_safe_split_point(&self, preferred_split_at: usize) -> usize {
530 crate::core::agent::state::safe_history_split_point(&self.messages, self.conversation.len(), preferred_split_at)
531 }
532
533 pub fn normalize(&mut self) {
535 crate::core::agent::state::normalize_history(self.messages_mut());
536 self.reconcile_token_count();
537 }
538
539 pub fn clear_conversation_history(&mut self) {
551 self.messages_mut().clear();
552 self.conversation.clear();
553 self.cached_total_tokens = 0;
554 self.last_processed_message_idx = 0;
555 self.previous_response_chains.clear();
556 self.consecutive_tool_loops = 0;
557 self.tool_loop_limit_hit = false;
558 self.consecutive_escalations = 0;
559 self.progress_hashes.clear();
560 self.stagnant_turns = 0;
561 self.pending_actions = PendingActions::new(100);
562 self.consecutive_idle_turns = 0;
563 self.max_tool_loop_streak = 0;
564 self.turn_tool_observations.clear();
565 self.current_stage = None;
566 self.auto_compact_suppressed = crate::compaction::SUPPRESS_NONE;
567 self.error_recovery.lock().reset();
568 }
569
570 pub fn into_results(
571 self,
572 summary: String,
573 thread_events: Vec<ThreadEvent>,
574 total_duration_ms: u128,
575 ) -> TaskResults {
576 let average_turn_duration_ms = if self.turn_count > 0 {
577 Some(self.turn_total_ms as f64 / self.turn_count as f64)
578 } else {
579 None
580 };
581 let max_turn_duration_ms = if self.turn_count > 0 {
582 Some(self.turn_max_ms)
583 } else {
584 None
585 };
586
587 TaskResults {
588 created_contexts: self.created_contexts,
589 modified_files: self.modified_files,
590 executed_commands: self.executed_commands,
591 summary,
592 stop_reason: self.stop_reason,
593 total_cost_usd: self.total_cost_usd,
594 warnings: self.warnings,
595 thread_events,
596 outcome: self.outcome,
597 turns_executed: self.stats.turns_executed,
598 total_duration_ms,
599 average_turn_duration_ms,
600 max_turn_duration_ms,
601 turn_durations_ms: self.turn_durations_ms,
602 }
603 }
604
605 fn push_tool_event(&mut self, call_id: String, tool_name: &str, value: &serde_json::Value, is_gemini: bool) {
610 if is_gemini {
611 self.conversation.push(Content {
612 role: "function".to_string(),
613 parts: vec![Part::FunctionResponse {
614 function_response: FunctionResponse {
615 name: tool_name.to_string(),
616 response: value.clone(),
617 id: Some(call_id.clone()),
618 },
619 thought_signature: None,
620 }],
621 });
622 }
623 let serialized = serde_json::to_string(value).expect("Value serialization is infallible");
624 let msg = Message::tool_response(call_id, serialized);
625 let tokens = msg.estimate_tokens();
626 self.cached_total_tokens = self.cached_total_tokens.saturating_add(tokens);
627 self.messages_mut().push(msg);
628 }
629
630 pub fn push_tool_result(&mut self, call_id: String, tool_name: &str, result: &serde_json::Value, is_gemini: bool) {
632 self.push_tool_event(call_id, tool_name, result, is_gemini);
633 let tool_name_owned = tool_name.to_owned();
636 if !self.executed_commands.contains(&tool_name_owned) {
637 self.executed_commands.push(tool_name_owned);
638 }
639 }
640
641 pub fn push_tool_error(
643 &mut self,
644 call_id: String,
645 tool_name: &str,
646 error_payload: &serde_json::Value,
647 is_gemini: bool,
648 ) {
649 self.push_tool_event(call_id, tool_name, error_payload, is_gemini);
650 }
651
652 pub fn push_warning(&mut self, warning: impl Into<String>) {
663 let warning = warning.into();
664 if self.warnings.contains(&warning) {
665 return;
666 }
667 if self.warnings.len() < MAX_SESSION_WARNINGS {
668 self.warnings.push(warning);
669 } else if self.warnings.last().is_none_or(|w| w != WARNINGS_ELIDED_MARKER) {
670 self.warnings.push(WARNINGS_ELIDED_MARKER.to_string());
671 }
672 }
673}
674
675const MAX_SESSION_WARNINGS: usize = 200;
679const WARNINGS_ELIDED_MARKER: &str = "[Additional unique warnings elided — session warning cap reached]";
680
681#[cfg(test)]
682mod tests {
683 use super::AgentSessionState;
684 use crate::config::types::ReasoningEffortLevel;
685 use crate::llm::provider::Message;
686 use crate::llm::providers::gemini::wire::Part;
687 use std::sync::Arc;
688 use std::thread;
689 use std::time::Duration;
690
691 #[test]
695 fn cache_gap_exceeds_delegates_to_request_gap_tracker() {
696 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
697 assert_eq!(state.cache_gap_exceeds(Duration::from_millis(1)), None);
698
699 state.note_request_sent();
700 thread::sleep(Duration::from_millis(15));
701 let gap = state.cache_gap_exceeds(Duration::from_millis(5));
702 assert!(gap.is_some_and(|elapsed| elapsed >= Duration::from_millis(15)));
703 }
704
705 #[test]
706 fn note_reasoning_effort_change_is_false_on_first_request() {
707 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
708 assert!(!state.note_reasoning_effort_change(Some(ReasoningEffortLevel::Medium)));
709 }
710
711 #[test]
712 fn note_reasoning_effort_change_is_false_when_unchanged() {
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::Medium)));
716 }
717
718 #[test]
719 fn note_reasoning_effort_change_is_true_when_changed() {
720 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
721 assert!(!state.note_reasoning_effort_change(Some(ReasoningEffortLevel::Medium)));
722 assert!(state.note_reasoning_effort_change(Some(ReasoningEffortLevel::High)));
723 assert!(!state.note_reasoning_effort_change(Some(ReasoningEffortLevel::High)));
725 }
726
727 #[test]
728 fn note_model_change_is_false_on_first_request() {
729 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
730 assert!(!state.note_model_change("gpt-5.6"));
731 }
732
733 #[test]
734 fn note_model_change_is_false_when_unchanged() {
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("gpt-5.6"));
738 }
739
740 #[test]
741 fn note_model_change_is_true_when_changed() {
742 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
743 assert!(!state.note_model_change("gpt-5.6"));
744 assert!(state.note_model_change("claude-opus-4-6"));
745 assert!(!state.note_model_change("claude-opus-4-6"));
747 }
748
749 #[test]
750 fn previous_response_chain_is_scoped_to_provider_and_model() {
751 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
752 let messages_52 = vec![Message::user("hello".to_string())];
753 let messages_54 = vec![Message::user("continue".to_string())];
754
755 state.set_previous_response_chain("openai", "gpt-5.6", Some("resp_123"), messages_52.clone());
756 state.set_previous_response_chain("openai", "gpt-5.6-sol", Some("resp_456"), messages_54.clone());
757
758 assert_eq!(state.previous_response_id_for("openai", "gpt-5.6"), Some("resp_123".to_string()));
759 assert_eq!(state.previous_response_id_for("openai", "gpt-5.6-sol"), Some("resp_456".to_string()));
760 assert_eq!(state.previous_response_id_for("gemini", "gpt-5.6"), None);
761
762 state.clear_previous_response_chain_for("openai", "gpt-5.6");
763
764 assert_eq!(state.previous_response_id_for("openai", "gpt-5.6"), None);
765 assert_eq!(state.previous_response_chain_for("openai", "gpt-5.6"), None);
766 assert_eq!(state.previous_response_id_for("openai", "gpt-5.6-sol"), Some("resp_456".to_string()));
767 assert_eq!(
768 state
769 .previous_response_chain_for("openai", "gpt-5.6-sol")
770 .map(|chain| chain.messages.as_slice()),
771 Some(messages_54.as_slice())
772 );
773
774 state.clear_previous_response_chain();
775 assert_eq!(state.previous_response_id_for("openai", "gpt-5.6-sol"), None);
776 assert_eq!(state.previous_response_chain_for("openai", "gpt-5.6-sol"), None);
777 }
778
779 #[test]
780 fn shared_previous_response_chain_reuses_history_arc() {
781 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
782 let messages = Arc::new(vec![Message::user("hello".to_string())]);
783
784 state.set_previous_response_chain_shared("openai", "gpt-5.6-sol", Some("resp_123"), Arc::clone(&messages));
785
786 let stored = &state
787 .previous_response_chain_for("openai", "gpt-5.6-sol")
788 .expect("continuation state")
789 .messages;
790 assert!(Arc::ptr_eq(&messages, stored));
791 }
792
793 #[test]
794 fn register_tool_loop_tracks_current_and_max_streak() {
795 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
796
797 assert_eq!(state.register_tool_loop(), 1);
798 assert_eq!(state.register_tool_loop(), 2);
799 assert_eq!(state.consecutive_tool_loops, 2);
800 assert_eq!(state.max_tool_loop_streak, 2);
801
802 state.reset_tool_loop_guard();
803 assert_eq!(state.register_tool_loop(), 1);
804 assert_eq!(state.max_tool_loop_streak, 2);
805 }
806
807 #[test]
808 fn push_tool_error_preserves_structured_json_for_gemini() {
809 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
810 let payload = serde_json::json!({
811 "error": {
812 "tool_name": "read_file",
813 "message": "missing file",
814 "category": "ResourceNotFound"
815 }
816 });
817
818 state.push_tool_error("call_1".to_string(), "read_file", &payload, true);
819
820 match &state.conversation[0].parts[0] {
821 Part::FunctionResponse { function_response, .. } => {
822 assert_eq!(function_response.response["error"]["message"], "missing file");
823 }
824 other => panic!("expected function response, got {other:?}"),
825 }
826 let expected_serialized = serde_json::to_string(&payload).unwrap();
827 assert_eq!(state.messages[0], Message::tool_response("call_1".to_string(), expected_serialized));
828 }
829
830 #[test]
831 fn harness_notices_are_tagged_synthetic_while_user_messages_are_not() {
832 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
833 state.add_user_message("fix the flaky test".to_string());
834 state.add_synthetic_user_message("It looks like you're repeating the same response.".to_string());
835 state.add_user_message_with_intent("steer: stop after this".to_string(), Some("intent-1".to_string()));
836
837 let sources: Vec<Option<&str>> = state
838 .messages
839 .iter()
840 .map(|message| message.metadata.as_ref().and_then(|metadata| metadata.source()))
841 .collect();
842 assert_eq!(sources, vec![Some("user_input"), Some("synthetic"), Some("user_input")]);
843 assert!(
844 state.messages[1]
845 .metadata
846 .as_ref()
847 .is_some_and(vtcode_commons::message_metadata::MessageMetadata::is_synthetic)
848 );
849 let archived: Vec<crate::utils::session_archive::SessionMessage> =
851 state.messages.iter().map(Into::into).collect();
852 assert!(
853 archived[1]
854 .metadata
855 .as_deref()
856 .is_some_and(vtcode_commons::message_metadata::MessageMetadata::is_synthetic)
857 );
858 assert!(archived[0].metadata.as_deref().is_some_and(|m| !m.is_synthetic()));
859 }
860
861 #[test]
862 fn cached_total_tokens_matches_direct_computation() {
863 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
864
865 state.add_user_message("Hello, how are you?".to_string());
867 state.push_tool_result(
868 "call_1".to_string(),
869 "read_file",
870 &serde_json::json!({"content": "test file content"}),
871 false,
872 );
873 state.push_tool_error(
874 "call_2".to_string(),
875 "write_file",
876 &serde_json::json!({"error": "permission denied"}),
877 false,
878 );
879
880 let direct = state.messages.iter().map(|m| m.estimate_tokens()).sum::<usize>();
882 assert_eq!(state.total_tokens(), direct);
883 assert!(state.total_tokens() > 0);
884 }
885
886 #[test]
887 fn reconcile_token_count_resyncs_after_external_mutation() {
888 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
889 state.add_user_message("test message".to_string());
890 let before = state.total_tokens();
891
892 state.messages_mut().push(Message::assistant("extra response".to_string()));
894 assert_ne!(state.total_tokens(), before + Message::assistant("extra response".to_string()).estimate_tokens());
895
896 state.reconcile_token_count();
898 let expected = state.messages.iter().map(|m| m.estimate_tokens()).sum::<usize>();
899 assert_eq!(state.total_tokens(), expected);
900 }
901
902 #[test]
903 fn clear_conversation_history_resets_all_state() {
904 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
905 state.messages_mut().push(Message::user("hello".to_string()));
906 state.messages_mut().push(Message::assistant("hi".to_string()));
907 state.conversation.push(crate::llm::providers::gemini::wire::Content {
908 role: "user".to_string(),
909 parts: vec![Part::Text { text: "hello".to_string(), thought_signature: None }],
910 });
911 state.reconcile_token_count();
912 state.last_processed_message_idx = 2;
913 state.progress_hashes.push_back(123);
914 state.stagnant_turns = 3;
915 state.set_previous_response_chain("openai", "gpt-5", Some("resp_1"), vec![]);
916
917 assert!(!state.messages.is_empty());
918 assert!(!state.conversation.is_empty());
919 assert!(state.total_tokens() > 0);
920
921 state.clear_conversation_history();
922
923 assert!(state.messages.is_empty());
924 assert!(state.conversation.is_empty());
925 assert_eq!(state.total_tokens(), 0);
926 assert_eq!(state.last_processed_message_idx, 0);
927 assert!(state.progress_hashes.is_empty());
928 assert_eq!(state.stagnant_turns, 0);
929 assert!(state.previous_response_chains.is_empty());
930 }
931
932 #[test]
933 fn push_warning_skips_exact_duplicates() {
934 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
935 state.push_warning("rate limited");
936 state.push_warning("rate limited");
937 state.push_warning("rate limited");
938 assert_eq!(state.warnings.len(), 1);
939 assert_eq!(state.warnings[0], "rate limited");
940 }
941
942 #[test]
943 fn push_warning_retains_distinct_warnings() {
944 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
945 state.push_warning("first warning");
946 state.push_warning("second warning");
947 state.push_warning("third warning");
948 assert_eq!(state.warnings.len(), 3);
949 assert_eq!(state.warnings[0], "first warning");
950 assert_eq!(state.warnings[1], "second warning");
951 assert_eq!(state.warnings[2], "third warning");
952 }
953
954 #[test]
955 fn push_warning_inserts_elision_marker_at_cap() {
956 let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
957 for i in 0..super::MAX_SESSION_WARNINGS {
959 state.push_warning(format!("warning {i}"));
960 }
961 assert_eq!(state.warnings.len(), super::MAX_SESSION_WARNINGS);
962 assert!(!state.warnings.iter().any(|w| w == super::WARNINGS_ELIDED_MARKER));
963
964 state.push_warning("overflow A");
966 assert_eq!(state.warnings.len(), super::MAX_SESSION_WARNINGS + 1);
967 assert_eq!(state.warnings.last().unwrap(), super::WARNINGS_ELIDED_MARKER);
968
969 state.push_warning("overflow B");
972 state.push_warning("overflow C");
973 assert_eq!(state.warnings.len(), super::MAX_SESSION_WARNINGS + 1);
974 assert_eq!(state.warnings.last().unwrap(), super::WARNINGS_ELIDED_MARKER);
975 assert!(!state.warnings.iter().any(|w| w == "overflow A"));
977 assert!(!state.warnings.iter().any(|w| w == "overflow B"));
978 }
979}