Skip to main content

agent_base/engine/
session.rs

1use std::collections::HashSet;
2
3use serde::{Deserialize, Serialize};
4
5use crate::types::{ChatMessage, ImageAttachment, Message, MessageRole, ToolCallMessage};
6
7use crate::types::SessionId;
8
9/// Run-level state tracking for the react loop.
10///
11/// Manages counters and flags that track the current run's progress.
12/// All fields are reset at the start of each run (when a new user message arrives).
13///
14/// # Backward compatibility
15///
16/// Before this struct existed, `nudge_count` and `turn_tool_calls` were flat
17/// fields on `AgentSession`.  The [`RawAgentSession`] deserialization shim
18/// migrates them automatically.
19#[derive(Clone, Debug, Default, Serialize, Deserialize)]
20pub struct RunState {
21    /// Number of tool calls already executed in the current turn.
22    /// Reset to 0 at the start of each turn (when a new user message arrives).
23    /// Used by `TurnToolLimitMiddleware` to enforce per-turn tool call limits.
24    pub turn_tool_calls: usize,
25    /// Whether any tools were called in the current run.
26    /// Reset to false at the start of each run. Used by the completion judge
27    /// to determine if tools were used before a text-only response.
28    pub run_has_tool_calls: bool,
29    /// Number of consecutive LLM turns that produced only reasoning_content
30    /// (no text, no tool call). Reset to 0 when a normal response or tool call
31    /// is produced. Used by the react loop to fail instead of looping forever
32    /// on a reasoning-model runaway.
33    pub reasoning_only_strikes: usize,
34    /// Number of consecutive LLM turns that produced a completely empty response
35    /// (no text, no reasoning, no tool call). Reset to 0 when a normal response
36    /// or tool call is produced. Used by the react loop to retry a bounded
37    /// number of times, then fail instead of looping forever.
38    pub empty_response_strikes: usize,
39    /// Number of tool-enforcement nudges issued in the current turn.
40    /// Reset to 0 at the start of each turn (when a new user message arrives).
41    /// Used by `ToolEnforcementMiddleware` to cap nudge attempts per turn.
42    pub nudge_count: usize,
43    /// Thinking is disabled for the rest of the current run.
44    /// Set to true when reasoning_only_strikes reaches the maximum (3).
45    /// Reset to false at the start of each new run (when a new user message arrives).
46    /// This allows the model to continue without thinking after too many
47    /// reasoning-only responses.
48    #[serde(default)]
49    pub thinking_disabled_for_rest_of_run: bool,
50
51    // ─── New fields for thinking guard ─────────────────────────────
52    /// Original thinking configuration (for restoration)
53    ///
54    /// Records whether thinking was originally enabled when the session started.
55    /// Used to restore thinking to its original state after DisableThinking → RestoreThinking cycle.
56    #[serde(default)]
57    pub original_thinking_enabled: bool,
58
59    /// Number of consecutive LLM turns where the truncation guard fired
60    /// (all tool_calls had invalid/truncated arguments). Reset to 0 when
61    /// at least one valid tool call executes successfully. Used to break
62    /// the re-issue death spiral: after N consecutive truncations, stop
63    /// retrying and fail with an actionable message.
64    #[serde(default)]
65    pub truncation_strikes: usize,
66
67    /// The latest tool batch parked on a human step (a design-canvas screen
68    /// awaiting a pick) and no tool ran after it. Overwritten per batch by
69    /// `handle_tool_calls`. When true at the end of a run, the run is
70    /// *waiting for the user* — the guard must complete instead of nudging
71    /// "continue working" over their pending answer.
72    #[serde(default)]
73    pub awaiting_human: bool,
74}
75
76impl RunState {
77    /// Reset all run-level state for a new run (when a new user message arrives).
78    pub fn reset_for_new_run(&mut self) {
79        self.turn_tool_calls = 0;
80        self.run_has_tool_calls = false;
81        self.reasoning_only_strikes = 0;
82        self.empty_response_strikes = 0;
83        self.nudge_count = 0;
84        self.thinking_disabled_for_rest_of_run = false;
85        self.truncation_strikes = 0;
86        self.awaiting_human = false;
87        // Note: original_thinking_enabled is NOT reset here
88        // It should be set once when the session starts
89    }
90
91    /// Record tool calls (branch 3: tool calls).
92    /// Resets reasoning_only_strikes, empty_response_strikes, and truncation_strikes.
93    pub fn record_tool_calls(&mut self, n: usize) {
94        self.turn_tool_calls += n;
95        self.run_has_tool_calls = true;
96        self.reasoning_only_strikes = 0;
97        self.empty_response_strikes = 0;
98        self.truncation_strikes = 0;
99    }
100
101    /// Record reasoning-only response (branch 1).
102    /// Resets empty_response_strikes.
103    /// Returns the new strike count.
104    /// If strikes reach 3, disables thinking for the rest of the run.
105    pub fn record_reasoning_only(&mut self) -> usize {
106        self.empty_response_strikes = 0;
107        self.reasoning_only_strikes += 1;
108        if self.reasoning_only_strikes >= 3 {
109            tracing::info!(
110                strikes = self.reasoning_only_strikes,
111                "reasoning_only_strikes reached 3, disabling thinking for rest of run"
112            );
113            self.thinking_disabled_for_rest_of_run = true;
114        }
115        self.reasoning_only_strikes
116    }
117
118    /// Record empty response (branch 2).
119    /// Resets reasoning_only_strikes.
120    /// Returns the new strike count.
121    pub fn record_empty_response(&mut self) -> usize {
122        self.reasoning_only_strikes = 0;
123        self.empty_response_strikes += 1;
124        self.empty_response_strikes
125    }
126
127    /// Record a truncation guard firing (all tool_calls had invalid arguments).
128    /// Returns the new strike count. Caller should check against threshold.
129    pub fn record_truncation(&mut self) -> usize {
130        self.truncation_strikes += 1;
131        self.truncation_strikes
132    }
133}
134
135/// Deserialization shim for backward compatibility.
136///
137/// Before `RunState` was introduced, `nudge_count`, `turn_tool_calls`,
138/// `reasoning_only_strikes`, and `empty_response_strikes` were flat fields
139/// on `AgentSession`.  This struct accepts **both** the old flat format and
140/// the new nested `run_state` format, migrating legacy data on the fly.
141#[derive(Deserialize)]
142struct RawAgentSession {
143    id: Option<SessionId>,
144    chat_messages: Vec<ChatMessage>,
145    always_allowed_actions: HashSet<String>,
146    total_tool_calls: usize,
147
148    // ── new format (preferred) ──
149    run_state: Option<RunState>,
150
151    // ── legacy flat fields (fallback) ──
152    nudge_count: Option<usize>,
153    turn_tool_calls: Option<usize>,
154    reasoning_only_strikes: Option<usize>,
155    empty_response_strikes: Option<usize>,
156}
157
158impl From<RawAgentSession> for AgentSession {
159    fn from(raw: RawAgentSession) -> Self {
160        let run_state = raw.run_state.unwrap_or_else(|| RunState {
161            nudge_count: raw.nudge_count.unwrap_or(0),
162            turn_tool_calls: raw.turn_tool_calls.unwrap_or(0),
163            reasoning_only_strikes: raw.reasoning_only_strikes.unwrap_or(0),
164            empty_response_strikes: raw.empty_response_strikes.unwrap_or(0),
165            ..RunState::default()
166        });
167        Self {
168            id: raw.id,
169            chat_messages: raw.chat_messages,
170            always_allowed_actions: raw.always_allowed_actions,
171            total_tool_calls: raw.total_tool_calls,
172            run_state,
173        }
174    }
175}
176
177/// Stable identity + rolling state of a single chat thread.
178///
179/// `Default` returns a fresh session; load persisted state via serde.
180/// Backward-compatible with the old flat-field format (pre-`RunState` migration).
181#[derive(Clone, Debug, Default, Serialize, Deserialize)]
182#[serde(from = "RawAgentSession")]
183pub struct AgentSession {
184    id: Option<SessionId>,
185    /// LLM API format messages, sent directly to the provider.
186    /// This is the single source of truth for the conversation state.
187    chat_messages: Vec<ChatMessage>,
188    always_allowed_actions: HashSet<String>,
189    /// Total number of tool calls made in this session (across all turns).
190    /// Used by middleware for decisions like "first_turn_only" enforcement.
191    pub total_tool_calls: usize,
192    /// Run-level state tracking for the react loop.
193    pub run_state: RunState,
194}
195
196impl AgentSession {
197    pub fn new(id: SessionId) -> Self {
198        Self {
199            id: Some(id),
200            chat_messages: Vec::new(),
201            always_allowed_actions: HashSet::new(),
202            total_tool_calls: 0,
203            run_state: RunState::default(),
204        }
205    }
206
207    pub fn id(&self) -> Option<SessionId> {
208        self.id.clone()
209    }
210
211    /// Derive a simplified `Vec<Message>` view from the canonical `chat_messages`.
212    /// Assistant messages that contain only tool_calls (no text content) are
213    /// skipped, since they have no corresponding simplified representation.
214    pub fn simple_messages(&self) -> Vec<Message> {
215        self.chat_messages
216            .iter()
217            .filter_map(|cm| match cm {
218                ChatMessage::Assistant { content: None, .. } => None,
219                ChatMessage::Assistant {
220                    content: Some(c),
221                    tool_calls: Some(tc),
222                    ..
223                } if c.is_empty() && !tc.is_empty() => None,
224                _ => Some(Message::from(cm)),
225            })
226            .collect()
227    }
228
229    pub fn chat_messages(&self) -> &[ChatMessage] {
230        &self.chat_messages
231    }
232
233    /// Mutable reference, for advanced scenarios that need to operate on messages directly.
234    pub fn chat_messages_mut(&mut self) -> &mut Vec<ChatMessage> {
235        &mut self.chat_messages
236    }
237
238    pub fn is_action_allowed(&self, action_key: &str) -> bool {
239        self.always_allowed_actions.contains(action_key)
240    }
241
242    pub fn allow_action(&mut self, action_key: impl Into<String>) {
243        self.always_allowed_actions.insert(action_key.into());
244    }
245
246    pub fn push_message(&mut self, role: MessageRole, content: impl Into<String>) {
247        let content = content.into();
248        let chat_msg = match role {
249            MessageRole::System => ChatMessage::system(content),
250            MessageRole::User => ChatMessage::user(content),
251            MessageRole::Assistant => ChatMessage::assistant(content),
252            MessageRole::Tool => ChatMessage::tool(String::new(), content),
253        };
254        self.chat_messages.push(chat_msg);
255    }
256
257    /// Push a message as ephemeral (user/system only): the LLM sees it this
258    /// turn, then `remove_ephemeral_messages` strips it at turn end — from
259    /// both memory and persistence.
260    pub fn push_message_ephemeral(&mut self, role: MessageRole, content: impl Into<String>) {
261        let content = content.into();
262        let chat_msg = match role {
263            MessageRole::System => ChatMessage::system_ephemeral(content),
264            MessageRole::User => ChatMessage::user_ephemeral(content),
265            MessageRole::Assistant | MessageRole::Tool => {
266                // Ephemeral assistant/tool messages are not a thing; fall back
267                // to a regular push rather than silently mis-marking.
268                self.push_message(role, content);
269                return;
270            }
271        };
272        self.chat_messages.push(chat_msg);
273    }
274
275    /// Replace the system prompt — the first **non-ephemeral** System message
276    /// (wherever it sits, matching how `context` locates it); inserted at
277    /// index 0 if none exists. All other messages are untouched. Hosts that
278    /// own prompt composition (e.g. skill activation) re-bake through this.
279    pub fn set_system_prompt(&mut self, content: impl Into<String>) {
280        let content = content.into();
281        if let Some(idx) = self.chat_messages.iter().position(|m| {
282            matches!(
283                m,
284                ChatMessage::System {
285                    ephemeral: false,
286                    ..
287                }
288            )
289        }) {
290            self.chat_messages[idx] = ChatMessage::system(content);
291        } else {
292            self.chat_messages.insert(0, ChatMessage::system(content));
293        }
294    }
295
296    /// Push an assistant message with reasoning/thinking content preserved.
297    /// This allows the LLM to see its own prior reasoning in subsequent turns,
298    /// preventing it from re-deriving the same conclusions every turn.
299    pub fn push_assistant_with_reasoning(
300        &mut self,
301        content: impl Into<String>,
302        reasoning: impl Into<String>,
303    ) {
304        self.chat_messages
305            .push(ChatMessage::assistant_with_reasoning(content, reasoning));
306    }
307
308    pub fn push_user_message_with_images(
309        &mut self,
310        content: impl Into<String>,
311        images: Vec<ImageAttachment>,
312    ) {
313        self.chat_messages
314            .push(ChatMessage::user_with_images(content, images));
315    }
316
317    pub fn push_assistant_tool_call(
318        &mut self,
319        tool_call_id: &str,
320        tool_name: &str,
321        arguments_json: &str,
322    ) {
323        self.chat_messages.push(ChatMessage::assistant_tool_call(
324            tool_call_id,
325            tool_name,
326            arguments_json,
327        ));
328    }
329
330    /// Escape and truncate the arguments to their first `max_chars` characters, so the
331    /// truncation WARN can display the raw content directly. Rust debug escaping keeps
332    /// unclosed JSON, control characters, and CJK boundaries clearly distinguishable, so
333    /// troubleshooting provider truncation in production no longer requires indirectly
334    /// reconstructing the content.
335    fn preview_args(args: &str, max_chars: usize) -> String {
336        format!("{:?}", args.chars().take(max_chars).collect::<String>())
337    }
338
339    pub fn push_assistant_tool_calls(
340        &mut self,
341        tool_calls: &[(String, String, String)],
342        reasoning: Option<String>,
343        content: Option<String>,
344    ) {
345        let calls: Vec<ToolCallMessage> = tool_calls
346            .iter()
347            .map(|(id, name, args)| {
348                // Invalid JSON args (provider truncated the stream mid-generation)
349                // are sanitized to an empty object. We deliberately do NOT wrap
350                // them in a descriptive `{error, original_args_preview, message}`
351                // object: "{}" is valid JSON so the next request is never rejected
352                // with 400, and — critically — a rich error object here becomes an
353                // imitation vector: the model replays it verbatim as the next
354                // call's arguments and, because it parses, it slips past the react
355                // truncation guard. The truncation explanation lives in the
356                // paired tool_result, which is where the model reads feedback.
357                let valid_args = if serde_json::from_str::<serde_json::Value>(args).is_ok() {
358                    args.clone()
359                } else {
360                    tracing::warn!(
361                        tool_name = %name,
362                        args_len = args.len(),
363                        args_preview = %Self::preview_args(args, 80),
364                        "tool call arguments are not valid JSON (provider truncated them), \
365                         sanitizing to empty object; re-issue instruction goes to the tool_result"
366                    );
367                    "{}".to_string()
368                };
369                ToolCallMessage {
370                    id: id.clone(),
371                    name: name.clone(),
372                    arguments: valid_args,
373                }
374            })
375            .collect();
376        self.chat_messages.push(ChatMessage::Assistant {
377            content,
378            reasoning_content: reasoning,
379            tool_calls: Some(calls),
380            thinking_signature: None,
381        });
382    }
383
384    pub fn push_tool_result(&mut self, tool_call_id: &str, content: impl Into<String>) {
385        self.chat_messages
386            .push(ChatMessage::tool(tool_call_id, content));
387    }
388
389    /// Remove all ephemeral messages (ephemeral=true).
390    ///
391    /// Called at the end of a turn to ensure injected ephemeral content does not linger into the next turn.
392    pub fn remove_ephemeral_messages(&mut self) {
393        let before = self.chat_messages.len();
394        self.chat_messages.retain(|m| !m.is_ephemeral());
395        let removed = before - self.chat_messages.len();
396        if removed > 0 {
397            tracing::debug!(
398                removed,
399                remaining = self.chat_messages.len(),
400                "ephemeral messages cleaned up"
401            );
402        }
403    }
404
405    /// Count the number of conversation turns.
406    /// A turn starts with a User message and includes subsequent Assistant/Tool messages.
407    pub fn turn_count(&self) -> usize {
408        self.chat_messages
409            .iter()
410            .filter(|m| matches!(m, ChatMessage::User { .. }))
411            .count()
412    }
413
414    /// Remove the oldest turns from the front until turn count ≤ max_turns.
415    /// Preserves the System message at index 0 if present.
416    pub fn trim_oldest_turns(&mut self, max_turns: usize) {
417        let current_turns = self.turn_count();
418        if current_turns <= max_turns {
419            return;
420        }
421        let turns_to_remove = current_turns - max_turns;
422
423        // Find User message positions (turn boundaries) in chat_messages
424        let user_positions: Vec<usize> = self
425            .chat_messages
426            .iter()
427            .enumerate()
428            .filter_map(|(i, m)| {
429                if matches!(m, ChatMessage::User { .. }) {
430                    Some(i)
431                } else {
432                    None
433                }
434            })
435            .collect();
436
437        if user_positions.len() <= turns_to_remove {
438            return;
439        }
440
441        // Preserve system prefix: count leading System messages
442        let system_prefix = self
443            .chat_messages
444            .iter()
445            .take_while(|m| matches!(m, ChatMessage::System { .. }))
446            .count();
447
448        // Drain from system_prefix up to the start of the (turns_to_remove + 1)-th turn
449        let drain_end = user_positions[turns_to_remove];
450        if system_prefix >= drain_end {
451            return; // nothing to drain after system messages
452        }
453
454        self.chat_messages.drain(system_prefix..drain_end);
455    }
456
457    /// Remove the last message from `chat_messages`.
458    /// Used by the max_message_tokens safety valve to discard oversized messages.
459    pub fn pop_last_message(&mut self) {
460        self.chat_messages.pop();
461    }
462
463    pub fn close_dangling_tool_calls(&mut self, error_summary: &str) {
464        let assistant_idx = self.chat_messages.iter().rposition(
465            |m| matches!(m, ChatMessage::Assistant { tool_calls: Some(tc), .. } if !tc.is_empty()),
466        );
467
468        let Some(assistant_idx) = assistant_idx else {
469            return;
470        };
471
472        let ChatMessage::Assistant {
473            tool_calls: Some(tc),
474            ..
475        } = &self.chat_messages[assistant_idx]
476        else {
477            return;
478        };
479
480        let all_ids: Vec<String> = tc.iter().map(|t| t.id.clone()).collect();
481
482        let answered_ids: Vec<String> = self.chat_messages[assistant_idx + 1..]
483            .iter()
484            .filter_map(|m| match m {
485                ChatMessage::Tool { tool_call_id, .. } => Some(tool_call_id.clone()),
486                _ => None,
487            })
488            .collect();
489
490        for id in &all_ids {
491            if !answered_ids.iter().any(|a| a == id) {
492                self.push_tool_result(id, error_summary);
493            }
494        }
495    }
496
497    /// Replace chat messages — only for persistence restore.
498    /// Validates message sequence before replacing.
499    ///
500    /// For persistence restore use only. Callers must ensure the `messages` sequence is valid.
501    pub fn set_chat_messages(&mut self, messages: Vec<ChatMessage>) -> Result<(), String> {
502        validate_message_sequence(&messages)?;
503        // Recalculate total_tool_calls from the incoming messages so middleware
504        // decisions (e.g. first_turn_only enforcement) see the correct count.
505        self.total_tool_calls = messages
506            .iter()
507            .filter_map(|m| match m {
508                ChatMessage::Assistant {
509                    tool_calls: Some(tc),
510                    ..
511                } => Some(tc.len()),
512                _ => None,
513            })
514            .sum();
515        self.chat_messages = messages;
516        Ok(())
517    }
518}
519
520/// Validate that a chat message sequence is well-formed for LLM API consumption.
521///
522/// Checks:
523/// - At least one non-System/non-Custom message (System maps to the
524///   top-level `system` parameter, Custom is stripped — a sequence of only
525///   those leaves an empty `messages` array, which providers reject with
526///   HTTP 400). Guards compaction outputs against producing an unsendable
527///   window.
528/// - No Tool message without a preceding Assistant with matching tool_call
529/// - No duplicate Tool messages for the same tool_call_id
530/// - All tool_calls in an Assistant batch must be answered before the next Assistant batch
531/// - No unanswered tool calls at the end of the sequence
532pub fn validate_message_sequence(messages: &[ChatMessage]) -> Result<(), String> {
533    if !messages
534        .iter()
535        .any(|m| !matches!(m, ChatMessage::System { .. } | ChatMessage::Custom { .. }))
536    {
537        return Err(
538            "sequence contains no sendable message: System/Custom alone leave the \
539             provider `messages` array empty"
540                .to_string(),
541        );
542    }
543
544    let mut pending_tool_call_ids: HashSet<String> = HashSet::new();
545
546    for (i, msg) in messages.iter().enumerate() {
547        match msg {
548            ChatMessage::Tool { tool_call_id, .. } => {
549                if pending_tool_call_ids.is_empty() {
550                    return Err(format!(
551                        "message[{}]: Tool message with call_id '{}' has no preceding tool_call",
552                        i, tool_call_id
553                    ));
554                }
555                // Remove the ID on match — also detects duplicates (second remove returns false)
556                if !pending_tool_call_ids.remove(tool_call_id) {
557                    return Err(format!(
558                        "message[{}]: Tool message with call_id '{}' does not match any pending tool_call (already answered or unknown)",
559                        i, tool_call_id
560                    ));
561                }
562            }
563            ChatMessage::Assistant {
564                tool_calls: Some(tc),
565                ..
566            } => {
567                // Previous batch must be fully answered before a new batch starts
568                if !pending_tool_call_ids.is_empty() {
569                    return Err(format!(
570                        "message[{}]: Assistant message with new tool_calls appears before pending calls were answered: {:?}",
571                        i, pending_tool_call_ids
572                    ));
573                }
574                pending_tool_call_ids = tc.iter().map(|t| t.id.clone()).collect();
575            }
576            _ => {}
577        }
578    }
579
580    // All tool calls must be answered by the end of the sequence
581    if !pending_tool_call_ids.is_empty() {
582        return Err(format!(
583            "message sequence ends with unanswered tool calls: {:?}",
584            pending_tool_call_ids
585        ));
586    }
587
588    Ok(())
589}
590
591#[cfg(test)]
592fn make_session() -> AgentSession {
593    AgentSession::new(SessionId::new(1))
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599
600    #[test]
601    fn test_turn_count_empty() {
602        let s = make_session();
603        assert_eq!(s.turn_count(), 0);
604    }
605
606    #[test]
607    fn test_turn_count_with_system_and_user() {
608        let mut s = make_session();
609        s.push_message(MessageRole::System, "system");
610        assert_eq!(s.turn_count(), 0);
611        s.push_message(MessageRole::User, "hello");
612        assert_eq!(s.turn_count(), 1);
613        s.push_message(MessageRole::Assistant, "hi");
614        assert_eq!(s.turn_count(), 1);
615        s.push_message(MessageRole::User, "bye");
616        assert_eq!(s.turn_count(), 2);
617    }
618
619    #[test]
620    fn test_turn_count_with_tool_calls() {
621        let mut s = make_session();
622        s.push_message(MessageRole::User, "do something");
623        s.push_assistant_tool_calls(&[("id1".into(), "tool".into(), "{}".into())], None, None);
624        s.push_tool_result("id1", "result");
625        s.push_message(MessageRole::Assistant, "done");
626        // One user turn: User -> Assistant(tool_calls) -> Tool -> Assistant(text)
627        assert_eq!(s.turn_count(), 1);
628    }
629
630    #[test]
631    fn test_trim_oldest_turns_noop() {
632        let mut s = make_session();
633        s.push_message(MessageRole::User, "hello");
634        s.push_message(MessageRole::Assistant, "hi");
635        s.trim_oldest_turns(5);
636        assert_eq!(s.turn_count(), 1);
637        assert_eq!(s.chat_messages().len(), 2);
638    }
639
640    #[test]
641    fn test_trim_oldest_turns_removes_old() {
642        let mut s = make_session();
643        s.push_message(MessageRole::System, "sys");
644        // Turn 1
645        s.push_message(MessageRole::User, "u1");
646        s.push_message(MessageRole::Assistant, "a1");
647        // Turn 2
648        s.push_message(MessageRole::User, "u2");
649        s.push_message(MessageRole::Assistant, "a2");
650        // Turn 3
651        s.push_message(MessageRole::User, "u3");
652        s.push_message(MessageRole::Assistant, "a3");
653
654        s.trim_oldest_turns(2);
655        assert_eq!(s.turn_count(), 2);
656        // System message preserved
657        assert!(matches!(s.chat_messages()[0], ChatMessage::System { .. }));
658        // Oldest user message is u2
659        assert!(
660            matches!(s.chat_messages()[1], ChatMessage::User { ref content, .. } if content == "u2")
661        );
662    }
663
664    #[test]
665    fn test_trim_oldest_turns_with_tool_calls() {
666        let mut s = make_session();
667        // Turn 1 with tool call
668        s.push_message(MessageRole::User, "u1");
669        s.push_assistant_tool_calls(&[("id1".into(), "t".into(), "{}".into())], None, None);
670        s.push_tool_result("id1", "r1");
671        s.push_message(MessageRole::Assistant, "a1");
672        // Turn 2
673        s.push_message(MessageRole::User, "u2");
674        s.push_message(MessageRole::Assistant, "a2");
675
676        let msg_before = s.simple_messages().len();
677        let chat_before = s.chat_messages().len();
678        s.trim_oldest_turns(1);
679        assert_eq!(s.turn_count(), 1);
680        // chat_messages should have lost 4 entries (User, Assistant(tool), Tool, Assistant(text))
681        assert_eq!(s.chat_messages().len(), chat_before - 4);
682        // simple_messages (derived from chat_messages, tool_calls-only filtered) loses 3 entries
683        assert_eq!(s.simple_messages().len(), msg_before - 3);
684    }
685
686    #[test]
687    fn test_pop_last_message_text() {
688        let mut s = make_session();
689        s.push_message(MessageRole::User, "hello");
690        s.push_message(MessageRole::Assistant, "hi");
691        assert_eq!(s.chat_messages().len(), 2);
692        s.pop_last_message();
693        assert_eq!(s.chat_messages().len(), 1);
694        assert_eq!(s.simple_messages().len(), 1);
695    }
696
697    #[test]
698    fn test_pop_last_message_tool_calls_only() {
699        let mut s = make_session();
700        s.push_message(MessageRole::User, "do it");
701        s.push_assistant_tool_calls(&[("id1".into(), "t".into(), "{}".into())], None, None);
702        assert_eq!(s.chat_messages().len(), 2);
703        assert_eq!(s.simple_messages().len(), 1); // only User in simple_messages (tool_calls-only filtered)
704        s.pop_last_message();
705        assert_eq!(s.chat_messages().len(), 1);
706        assert_eq!(s.simple_messages().len(), 1); // simple_messages unchanged (still just User)
707    }
708
709    #[test]
710    fn test_pop_last_message_empty_session() {
711        let mut s = make_session();
712        s.pop_last_message(); // should not panic
713        assert_eq!(s.chat_messages().len(), 0);
714    }
715
716    // ── B5: remaining session lifecycle paths ──────────────────────────────
717
718    #[test]
719    fn test_id_and_action_allowlist() {
720        let mut s = make_session();
721        assert_eq!(s.id(), Some(SessionId::new(1)));
722        assert!(!s.is_action_allowed("approve:rm"));
723        s.allow_action("approve:rm");
724        assert!(s.is_action_allowed("approve:rm"));
725        assert!(!s.is_action_allowed("approve:shell"));
726    }
727
728    #[test]
729    fn test_chat_messages_mut() {
730        let mut s = make_session();
731        s.chat_messages_mut().push(ChatMessage::user("direct"));
732        assert_eq!(s.chat_messages().len(), 1);
733    }
734
735    #[test]
736    fn test_push_message_tool_role() {
737        let mut s = make_session();
738        s.push_message(MessageRole::Tool, "result");
739        assert!(matches!(s.chat_messages()[0], ChatMessage::Tool { .. }));
740    }
741
742    #[test]
743    fn test_push_assistant_with_reasoning() {
744        let mut s = make_session();
745        s.push_assistant_with_reasoning("answer", "thinking");
746        match &s.chat_messages()[0] {
747            ChatMessage::Assistant {
748                content,
749                reasoning_content,
750                ..
751            } => {
752                assert_eq!(content.as_deref(), Some("answer"));
753                assert_eq!(reasoning_content.as_deref(), Some("thinking"));
754            }
755            other => panic!("unexpected message: {other:?}"),
756        }
757    }
758
759    #[test]
760    fn test_push_user_message_with_images() {
761        let mut s = make_session();
762        s.push_user_message_with_images(
763            "look",
764            vec![ImageAttachment::Url {
765                url: "http://x".into(),
766                detail: None,
767            }],
768        );
769        match &s.chat_messages()[0] {
770            ChatMessage::User { images, .. } => assert_eq!(images.len(), 1),
771            other => panic!("unexpected message: {other:?}"),
772        }
773    }
774
775    #[test]
776    fn test_push_assistant_tool_call_singular() {
777        let mut s = make_session();
778        s.push_assistant_tool_call("call_1", "bash", "{}");
779        match &s.chat_messages()[0] {
780            ChatMessage::Assistant {
781                tool_calls: Some(tc),
782                ..
783            } => {
784                assert_eq!(tc.len(), 1);
785                assert_eq!(tc[0].id, "call_1");
786                assert_eq!(tc[0].name, "bash");
787            }
788            other => panic!("unexpected message: {other:?}"),
789        }
790    }
791
792    #[test]
793    fn test_simple_messages_filters_empty_content_tool_calls() {
794        let mut s = make_session();
795        s.chat_messages_mut().push(ChatMessage::Assistant {
796            content: Some(String::new()),
797            reasoning_content: None,
798            tool_calls: Some(vec![ToolCallMessage {
799                id: "c".into(),
800                name: "t".into(),
801                arguments: "{}".into(),
802            }]),
803            thinking_signature: None,
804        });
805        assert!(s.simple_messages().is_empty());
806    }
807
808    #[test]
809    fn test_remove_ephemeral_messages() {
810        let mut s = make_session();
811        s.push_message(MessageRole::System, "keep");
812        s.chat_messages_mut()
813            .push(ChatMessage::user_ephemeral("temp"));
814        s.chat_messages_mut()
815            .push(ChatMessage::system_ephemeral("temp2"));
816        s.push_message(MessageRole::User, "keep2");
817        assert_eq!(s.chat_messages().len(), 4);
818        s.remove_ephemeral_messages();
819        assert_eq!(s.chat_messages().len(), 2);
820        assert!(s.chat_messages().iter().all(|m| !m.is_ephemeral()));
821    }
822
823    #[test]
824    fn test_set_system_prompt_replaces_first_non_ephemeral_system() {
825        let mut s = make_session();
826        s.push_message(MessageRole::System, "old prompt");
827        s.push_message(MessageRole::User, "hi");
828        s.push_message(MessageRole::Assistant, "hello");
829
830        s.set_system_prompt("new prompt");
831
832        let msgs = s.chat_messages();
833        assert_eq!(msgs.len(), 3, "history length unchanged");
834        assert!(
835            matches!(&msgs[0], ChatMessage::System { content, ephemeral: false } if content == "new prompt")
836        );
837        assert!(matches!(&msgs[1], ChatMessage::User { content, .. } if content == "hi"));
838        assert!(
839            matches!(&msgs[2], ChatMessage::Assistant { content: Some(c), .. } if c == "hello")
840        );
841    }
842
843    #[test]
844    fn test_set_system_prompt_inserts_when_absent() {
845        let mut s = make_session();
846        s.push_message(MessageRole::User, "hi");
847
848        s.set_system_prompt("fresh prompt");
849
850        let msgs = s.chat_messages();
851        assert_eq!(msgs.len(), 2);
852        assert!(
853            matches!(&msgs[0], ChatMessage::System { content, ephemeral: false } if content == "fresh prompt")
854        );
855        assert!(matches!(&msgs[1], ChatMessage::User { .. }));
856    }
857
858    #[test]
859    fn test_set_system_prompt_skips_ephemeral_system_and_inserts() {
860        let mut s = make_session();
861        s.chat_messages_mut()
862            .push(ChatMessage::system_ephemeral("ephemeral nudge"));
863        s.push_message(MessageRole::User, "hi");
864
865        s.set_system_prompt("real prompt");
866
867        // No non-ephemeral System exists → insert at the very front; the ephemeral nudge stays where it is.
868        let msgs = s.chat_messages();
869        assert_eq!(msgs.len(), 3);
870        assert!(
871            matches!(&msgs[0], ChatMessage::System { content, ephemeral: false } if content == "real prompt")
872        );
873        assert!(matches!(
874            &msgs[1],
875            ChatMessage::System {
876                ephemeral: true,
877                ..
878            }
879        ));
880        assert!(matches!(&msgs[2], ChatMessage::User { .. }));
881    }
882
883    #[test]
884    fn test_close_dangling_tool_calls_noop_without_tool_call() {
885        let mut s = make_session();
886        s.push_message(MessageRole::User, "hi");
887        s.push_message(MessageRole::Assistant, "hi");
888        s.close_dangling_tool_calls("failed");
889        assert_eq!(s.chat_messages().len(), 2);
890    }
891
892    #[test]
893    fn test_close_dangling_tool_calls_adds_missing_results() {
894        let mut s = make_session();
895        s.push_message(MessageRole::User, "do");
896        s.push_assistant_tool_calls(
897            &[
898                ("c1".into(), "t".into(), "{}".into()),
899                ("c2".into(), "t".into(), "{}".into()),
900            ],
901            None,
902            None,
903        );
904        s.push_tool_result("c1", "ok"); // only c1 answered
905        s.close_dangling_tool_calls("failed");
906
907        let tool_results: Vec<(String, String)> = s
908            .chat_messages()
909            .iter()
910            .filter_map(|m| match m {
911                ChatMessage::Tool {
912                    tool_call_id,
913                    name: _,
914                    content,
915                } => Some((tool_call_id.clone(), content.clone())),
916                _ => None,
917            })
918            .collect();
919        assert_eq!(tool_results.len(), 2);
920        assert!(
921            tool_results
922                .iter()
923                .any(|(id, c)| id == "c2" && c == "failed")
924        );
925    }
926
927    #[test]
928    fn test_set_chat_messages_recalculates_total_tool_calls() {
929        let mut s = make_session();
930        let msgs = vec![
931            ChatMessage::user("do"),
932            ChatMessage::assistant_tool_call("c1", "t", "{}"),
933            ChatMessage::tool("c1", "result"),
934        ];
935        s.set_chat_messages(msgs).unwrap();
936        assert_eq!(s.total_tool_calls, 1);
937    }
938}
939
940#[cfg(test)]
941mod validate_tests {
942    use super::*;
943
944    #[test]
945    fn test_valid_simple_sequence() {
946        let msgs = vec![ChatMessage::user("hello"), ChatMessage::assistant("hi")];
947        assert!(validate_message_sequence(&msgs).is_ok());
948    }
949
950    #[test]
951    fn test_valid_tool_call_sequence() {
952        let msgs = vec![
953            ChatMessage::user("run command"),
954            ChatMessage::assistant_tool_call("call_1", "bash", r#"{"cmd":"ls"}"#),
955            ChatMessage::tool("call_1", "file1 file2"),
956            ChatMessage::assistant("done"),
957        ];
958        assert!(validate_message_sequence(&msgs).is_ok());
959    }
960
961    #[test]
962    fn test_valid_multi_tool_call_sequence() {
963        let msgs = vec![
964            ChatMessage::user("run commands"),
965            ChatMessage::Assistant {
966                content: None,
967                reasoning_content: None,
968                tool_calls: Some(vec![
969                    crate::types::ToolCallMessage {
970                        id: "call_1".into(),
971                        name: "bash".into(),
972                        arguments: "{}".into(),
973                    },
974                    crate::types::ToolCallMessage {
975                        id: "call_2".into(),
976                        name: "read".into(),
977                        arguments: "{}".into(),
978                    },
979                ]),
980                thinking_signature: None,
981            },
982            ChatMessage::tool("call_1", "result1"),
983            ChatMessage::tool("call_2", "result2"),
984            ChatMessage::assistant("done"),
985        ];
986        assert!(validate_message_sequence(&msgs).is_ok());
987    }
988
989    #[test]
990    fn test_orphaned_tool_result() {
991        let msgs = vec![
992            ChatMessage::user("hello"),
993            ChatMessage::tool("call_1", "orphaned result"),
994        ];
995        let err = validate_message_sequence(&msgs).unwrap_err();
996        assert!(err.contains("no preceding tool_call"));
997    }
998
999    #[test]
1000    fn test_system_only_sequence_rejected() {
1001        // A compaction that leaves only System/Custom messages would send an
1002        // empty `messages` array (System maps to the `system` param) — the
1003        // contract rejects it.
1004        let msgs = vec![
1005            ChatMessage::system("prompt"),
1006            ChatMessage::system_ephemeral("reminder"),
1007            ChatMessage::Custom {
1008                role: "artifact".into(),
1009                data: serde_json::json!({"id": "x"}),
1010            },
1011        ];
1012        let err = validate_message_sequence(&msgs).unwrap_err();
1013        assert!(err.contains("no sendable message"));
1014    }
1015
1016    #[test]
1017    fn test_system_plus_user_ok() {
1018        let msgs = vec![ChatMessage::system("prompt"), ChatMessage::user("hi")];
1019        assert!(validate_message_sequence(&msgs).is_ok());
1020    }
1021
1022    #[test]
1023    fn test_mismatched_tool_call_id() {
1024        let msgs = vec![
1025            ChatMessage::user("run"),
1026            ChatMessage::assistant_tool_call("call_1", "bash", "{}"),
1027            ChatMessage::tool("call_2", "wrong id"),
1028        ];
1029        let err = validate_message_sequence(&msgs).unwrap_err();
1030        assert!(err.contains("does not match"));
1031    }
1032
1033    #[test]
1034    fn test_set_chat_messages_valid() {
1035        let mut s = make_session();
1036        let msgs = vec![ChatMessage::user("hello"), ChatMessage::assistant("hi")];
1037        assert!(s.set_chat_messages(msgs.clone()).is_ok());
1038        assert_eq!(s.chat_messages().len(), 2);
1039    }
1040
1041    #[test]
1042    fn test_set_chat_messages_invalid() {
1043        let mut s = make_session();
1044        let msgs = vec![ChatMessage::tool("call_1", "orphaned")];
1045        assert!(s.set_chat_messages(msgs).is_err());
1046    }
1047
1048    // ── RunState tests ────────────────────────────────────────────────────
1049
1050    #[test]
1051    fn run_state_default() {
1052        let rs = RunState::default();
1053        assert_eq!(rs.turn_tool_calls, 0);
1054        assert!(!rs.run_has_tool_calls);
1055        assert_eq!(rs.reasoning_only_strikes, 0);
1056        assert_eq!(rs.empty_response_strikes, 0);
1057        assert_eq!(rs.nudge_count, 0);
1058    }
1059
1060    #[test]
1061    fn run_state_reset_for_new_run() {
1062        let mut rs = RunState {
1063            turn_tool_calls: 5,
1064            run_has_tool_calls: true,
1065            reasoning_only_strikes: 2,
1066            empty_response_strikes: 1,
1067            nudge_count: 3,
1068            thinking_disabled_for_rest_of_run: true,
1069            original_thinking_enabled: true,
1070            truncation_strikes: 4,
1071            awaiting_human: true,
1072        };
1073
1074        rs.reset_for_new_run();
1075
1076        assert_eq!(rs.turn_tool_calls, 0);
1077        assert!(!rs.run_has_tool_calls);
1078        assert_eq!(rs.reasoning_only_strikes, 0);
1079        assert_eq!(rs.empty_response_strikes, 0);
1080        assert_eq!(rs.nudge_count, 0);
1081        assert_eq!(rs.truncation_strikes, 0);
1082        assert!(!rs.thinking_disabled_for_rest_of_run);
1083        assert!(!rs.awaiting_human);
1084        // original_thinking_enabled is NOT reset
1085        assert!(rs.original_thinking_enabled);
1086    }
1087
1088    #[test]
1089    fn run_state_record_tool_calls() {
1090        let mut rs = RunState {
1091            reasoning_only_strikes: 2,
1092            empty_response_strikes: 1,
1093            ..RunState::default()
1094        };
1095
1096        rs.record_tool_calls(3);
1097
1098        assert_eq!(rs.turn_tool_calls, 3);
1099        assert!(rs.run_has_tool_calls);
1100        assert_eq!(rs.reasoning_only_strikes, 0); // reset
1101        assert_eq!(rs.empty_response_strikes, 0); // reset
1102    }
1103
1104    #[test]
1105    fn run_state_record_tool_calls_accumulates() {
1106        let mut rs = RunState::default();
1107        rs.record_tool_calls(2);
1108        rs.record_tool_calls(3);
1109
1110        assert_eq!(rs.turn_tool_calls, 5);
1111        assert!(rs.run_has_tool_calls);
1112    }
1113
1114    #[test]
1115    fn run_state_record_reasoning_only() {
1116        let mut rs = RunState {
1117            empty_response_strikes: 2,
1118            ..RunState::default()
1119        };
1120
1121        let strikes = rs.record_reasoning_only();
1122
1123        assert_eq!(strikes, 1);
1124        assert_eq!(rs.reasoning_only_strikes, 1);
1125        assert_eq!(rs.empty_response_strikes, 0); // reset
1126    }
1127
1128    #[test]
1129    fn run_state_record_reasoning_only_consecutive() {
1130        let mut rs = RunState::default();
1131
1132        assert_eq!(rs.record_reasoning_only(), 1);
1133        assert_eq!(rs.record_reasoning_only(), 2);
1134        assert_eq!(rs.record_reasoning_only(), 3);
1135    }
1136
1137    #[test]
1138    fn run_state_record_empty_response() {
1139        let mut rs = RunState {
1140            reasoning_only_strikes: 2,
1141            ..RunState::default()
1142        };
1143
1144        let strikes = rs.record_empty_response();
1145
1146        assert_eq!(strikes, 1);
1147        assert_eq!(rs.empty_response_strikes, 1);
1148        assert_eq!(rs.reasoning_only_strikes, 0); // reset
1149    }
1150
1151    #[test]
1152    fn run_state_record_empty_response_consecutive() {
1153        let mut rs = RunState::default();
1154
1155        assert_eq!(rs.record_empty_response(), 1);
1156        assert_eq!(rs.record_empty_response(), 2);
1157        assert_eq!(rs.record_empty_response(), 3);
1158    }
1159
1160    #[test]
1161    fn run_state_branch_cross_reset() {
1162        // Simulate: reasoning only → tool calls → reasoning only
1163        let mut rs = RunState::default();
1164
1165        // Branch 1: reasoning only
1166        rs.record_reasoning_only();
1167        assert_eq!(rs.reasoning_only_strikes, 1);
1168
1169        // Branch 3: tool calls (should reset reasoning_only_strikes)
1170        rs.record_tool_calls(2);
1171        assert_eq!(rs.reasoning_only_strikes, 0);
1172        assert_eq!(rs.turn_tool_calls, 2);
1173
1174        // Branch 1 again: reasoning only (should start from 1, not 2)
1175        let strikes = rs.record_reasoning_only();
1176        assert_eq!(strikes, 1);
1177    }
1178
1179    #[test]
1180    fn run_state_empty_to_reasoning_reset() {
1181        // Simulate: empty → empty → reasoning only (should reset empty strikes)
1182        let mut rs = RunState::default();
1183
1184        rs.record_empty_response();
1185        rs.record_empty_response();
1186        assert_eq!(rs.empty_response_strikes, 2);
1187
1188        // Branch 1: reasoning only (should reset empty_response_strikes)
1189        rs.record_reasoning_only();
1190        assert_eq!(rs.empty_response_strikes, 0);
1191        assert_eq!(rs.reasoning_only_strikes, 1);
1192    }
1193
1194    #[test]
1195    fn run_state_thinking_disabled_default() {
1196        let rs = RunState::default();
1197        assert!(!rs.thinking_disabled_for_rest_of_run);
1198    }
1199
1200    #[test]
1201    fn run_state_thinking_disabled_after_3_strikes() {
1202        let mut rs = RunState::default();
1203
1204        // After 1st reasoning-only: not disabled
1205        rs.record_reasoning_only();
1206        assert!(!rs.thinking_disabled_for_rest_of_run);
1207        assert_eq!(rs.reasoning_only_strikes, 1);
1208
1209        // After 2nd reasoning-only: not disabled
1210        rs.record_reasoning_only();
1211        assert!(!rs.thinking_disabled_for_rest_of_run);
1212        assert_eq!(rs.reasoning_only_strikes, 2);
1213
1214        // After 3rd reasoning-only: disabled!
1215        rs.record_reasoning_only();
1216        assert!(rs.thinking_disabled_for_rest_of_run);
1217        assert_eq!(rs.reasoning_only_strikes, 3);
1218    }
1219
1220    #[test]
1221    fn run_state_thinking_disabled_resets_on_new_run() {
1222        let mut rs = RunState::default();
1223
1224        // Simulate 3 reasoning-only responses
1225        rs.record_reasoning_only();
1226        rs.record_reasoning_only();
1227        rs.record_reasoning_only();
1228        assert!(rs.thinking_disabled_for_rest_of_run);
1229        assert_eq!(rs.reasoning_only_strikes, 3);
1230
1231        // Reset for new run (new user message)
1232        rs.reset_for_new_run();
1233        assert!(!rs.thinking_disabled_for_rest_of_run);
1234        assert_eq!(rs.reasoning_only_strikes, 0);
1235    }
1236
1237    #[test]
1238    fn run_state_thinking_disabled_stays_after_tool_calls() {
1239        let mut rs = RunState::default();
1240
1241        // Simulate 3 reasoning-only responses
1242        rs.record_reasoning_only();
1243        rs.record_reasoning_only();
1244        rs.record_reasoning_only();
1245        assert!(rs.thinking_disabled_for_rest_of_run);
1246
1247        // Tool calls should NOT reset thinking_disabled_for_rest_of_run
1248        // (it should stay disabled for the rest of the run)
1249        rs.record_tool_calls(2);
1250        assert!(rs.thinking_disabled_for_rest_of_run);
1251        assert_eq!(rs.reasoning_only_strikes, 0); // strikes reset, but thinking stays disabled
1252    }
1253
1254    // ── Backward-compatible deserialization ────────────────────────────────
1255
1256    #[test]
1257    fn deserialize_legacy_flat_fields() {
1258        // Old format: nudge_count, turn_tool_calls, etc. as flat fields
1259        let json = r#"{
1260            "id": null,
1261            "chat_messages": [],
1262            "always_allowed_actions": [],
1263            "total_tool_calls": 5,
1264            "nudge_count": 3,
1265            "turn_tool_calls": 2,
1266            "reasoning_only_strikes": 1,
1267            "empty_response_strikes": 0
1268        }"#;
1269        let session: AgentSession = serde_json::from_str(json).unwrap();
1270        assert_eq!(session.run_state.nudge_count, 3);
1271        assert_eq!(session.run_state.turn_tool_calls, 2);
1272        assert_eq!(session.run_state.reasoning_only_strikes, 1);
1273        assert_eq!(session.run_state.empty_response_strikes, 0);
1274        assert!(!session.run_state.run_has_tool_calls); // default
1275    }
1276
1277    #[test]
1278    fn deserialize_new_run_state_format() {
1279        // New format: nested run_state
1280        let json = r#"{
1281            "id": null,
1282            "chat_messages": [],
1283            "always_allowed_actions": [],
1284            "total_tool_calls": 5,
1285            "run_state": {
1286                "turn_tool_calls": 4,
1287                "run_has_tool_calls": true,
1288                "reasoning_only_strikes": 0,
1289                "empty_response_strikes": 1,
1290                "nudge_count": 2
1291            }
1292        }"#;
1293        let session: AgentSession = serde_json::from_str(json).unwrap();
1294        assert_eq!(session.run_state.turn_tool_calls, 4);
1295        assert!(session.run_state.run_has_tool_calls);
1296        assert_eq!(session.run_state.empty_response_strikes, 1);
1297        assert_eq!(session.run_state.nudge_count, 2);
1298    }
1299
1300    #[test]
1301    fn deserialize_run_state_takes_precedence_over_flat() {
1302        // When both are present, run_state wins
1303        let json = r#"{
1304            "id": null,
1305            "chat_messages": [],
1306            "always_allowed_actions": [],
1307            "total_tool_calls": 0,
1308            "run_state": {
1309                "turn_tool_calls": 10,
1310                "run_has_tool_calls": true,
1311                "reasoning_only_strikes": 0,
1312                "empty_response_strikes": 0,
1313                "nudge_count": 0
1314            },
1315            "nudge_count": 99,
1316            "turn_tool_calls": 99
1317        }"#;
1318        let session: AgentSession = serde_json::from_str(json).unwrap();
1319        assert_eq!(session.run_state.turn_tool_calls, 10); // run_state wins
1320        assert_eq!(session.run_state.nudge_count, 0); // run_state wins
1321    }
1322
1323    #[test]
1324    fn deserialize_legacy_missing_optional_fields() {
1325        // Old format with some fields missing (defaults to 0)
1326        let json = r#"{
1327            "id": null,
1328            "chat_messages": [],
1329            "always_allowed_actions": [],
1330            "total_tool_calls": 0,
1331            "nudge_count": 1
1332        }"#;
1333        let session: AgentSession = serde_json::from_str(json).unwrap();
1334        assert_eq!(session.run_state.nudge_count, 1);
1335        assert_eq!(session.run_state.turn_tool_calls, 0); // missing → 0
1336        assert_eq!(session.run_state.reasoning_only_strikes, 0);
1337        assert_eq!(session.run_state.empty_response_strikes, 0);
1338    }
1339
1340    #[test]
1341    fn roundtrip_preserves_run_state() {
1342        let mut session = AgentSession::new(SessionId::new(1));
1343        session.run_state.nudge_count = 5;
1344        session.run_state.turn_tool_calls = 3;
1345        session.run_state.run_has_tool_calls = true;
1346        session.run_state.reasoning_only_strikes = 2;
1347
1348        let json = serde_json::to_string(&session).unwrap();
1349        let restored: AgentSession = serde_json::from_str(&json).unwrap();
1350        assert_eq!(restored.run_state.nudge_count, 5);
1351        assert_eq!(restored.run_state.turn_tool_calls, 3);
1352        assert!(restored.run_state.run_has_tool_calls);
1353        assert_eq!(restored.run_state.reasoning_only_strikes, 2);
1354    }
1355
1356    #[test]
1357    fn push_assistant_tool_calls_validates_json_args() {
1358        let mut s = make_session();
1359
1360        // Valid JSON args should pass through unchanged
1361        let valid_args = r#"{"path": "src/main.rs", "content": "fn main() {}"}"#;
1362        s.push_assistant_tool_calls(
1363            &[("id1".into(), "write_file".into(), valid_args.into())],
1364            None,
1365            None,
1366        );
1367        if let ChatMessage::Assistant {
1368            tool_calls: Some(ref tc),
1369            ..
1370        } = s.chat_messages[0]
1371        {
1372            assert_eq!(tc[0].arguments, valid_args);
1373        } else {
1374            panic!("expected Assistant message with tool_calls");
1375        }
1376
1377        // Truncated (invalid JSON) args must be sanitized to an empty object,
1378        // NOT wrapped in a descriptive error object. Two reasons:
1379        //   1. "{}" is valid JSON, so the next request is never rejected 400.
1380        //   2. a rich `{error, original_args_preview, message}` object in
1381        //      assistant history is an imitation vector — the model replays it
1382        //      verbatim as the next call's arguments, and because it parses as
1383        //      valid JSON it slips past the react truncation guard and resurfaces
1384        //      as a downstream ToolArgsInvalid. The truncation explanation
1385        //      belongs in the tool_result, not the assistant arguments.
1386        let truncated_args = r#"{"path": "src/ui/markdown.rs", "content": "#;
1387        s.push_assistant_tool_calls(
1388            &[("id2".into(), "write_file".into(), truncated_args.into())],
1389            None,
1390            None,
1391        );
1392        if let ChatMessage::Assistant {
1393            tool_calls: Some(ref tc),
1394            ..
1395        } = s.chat_messages[1]
1396        {
1397            assert_eq!(tc[0].arguments, "{}");
1398            assert!(
1399                !tc[0].arguments.contains("tool_call_arguments_truncated"),
1400                "assistant arguments must not carry the poison wrapper object"
1401            );
1402        } else {
1403            panic!("expected Assistant message with tool_calls");
1404        }
1405    }
1406
1407    #[test]
1408    fn push_assistant_tool_calls_truncated_multibyte_no_panic() {
1409        // Bug-2: Invalid JSON args with multi-byte UTF-8 chars near byte 200
1410        // cause a panic at char boundary when slicing &args[..args.len().min(200)].
1411        let mut s = make_session();
1412
1413        // Build invalid JSON with CJK chars that straddle the 200-byte boundary.
1414        // "あ" = 3 bytes in UTF-8. Repeating ~70 times = ~210 bytes, then add invalid suffix.
1415        let mut bad_args = "あ".repeat(70); // 70 * 3 = 210 bytes
1416        bad_args.push_str("truncated"); // makes it invalid JSON
1417
1418        // This must NOT panic. Invalid args are sanitized to "{}" (a fixed
1419        // literal), so no slicing of the multibyte string happens at all.
1420        s.push_assistant_tool_calls(&[("id1".into(), "tool".into(), bad_args)], None, None);
1421
1422        if let ChatMessage::Assistant {
1423            tool_calls: Some(ref tc),
1424            ..
1425        } = s.chat_messages[0]
1426        {
1427            assert_eq!(tc[0].arguments, "{}");
1428        } else {
1429            panic!("expected Assistant message with tool_calls");
1430        }
1431    }
1432
1433    #[test]
1434    fn push_assistant_tool_calls_then_tool_result_matches_anthropic_protocol() {
1435        // Regression test for: when LLM response is truncated (finish_reason=max_tokens),
1436        // the code must push assistant message WITH tool_use blocks (not plain text)
1437        // so that subsequent tool_result messages can match the tool_use_id.
1438        // This is required by Anthropic protocol.
1439        let mut s = make_session();
1440
1441        // Simulate truncated tool call response
1442        let tool_calls = vec![
1443            (
1444                "call_00_VJtlnKha0ZZ2Yo8t5ysQ8883".to_string(),
1445                "write_file".to_string(),
1446                "{}".to_string(),
1447            ),
1448            (
1449                "call_01_abc123".to_string(),
1450                "bash".to_string(),
1451                r#"{"command": "ls"}"#.to_string(),
1452            ),
1453        ];
1454
1455        // Push assistant message with tool_calls (as the fix does)
1456        s.push_assistant_tool_calls(
1457            &tool_calls,
1458            Some("thinking...".to_string()),
1459            Some("I'll help you".to_string()),
1460        );
1461
1462        // Push tool results for each tool call
1463        for (tc_id, _, _) in &tool_calls {
1464            s.push_tool_result(
1465                tc_id,
1466                "Tool call was not executed: the response hit the output token limit.",
1467            );
1468        }
1469
1470        // Verify the message sequence is valid
1471        // 1. Assistant message should have tool_calls
1472        if let ChatMessage::Assistant {
1473            tool_calls: Some(ref tc),
1474            ..
1475        } = s.chat_messages[0]
1476        {
1477            assert_eq!(tc.len(), 2);
1478            assert_eq!(tc[0].id, "call_00_VJtlnKha0ZZ2Yo8t5ysQ8883");
1479            assert_eq!(tc[0].name, "write_file");
1480            assert_eq!(tc[1].id, "call_01_abc123");
1481            assert_eq!(tc[1].name, "bash");
1482        } else {
1483            panic!("expected Assistant message with tool_calls");
1484        }
1485
1486        // 2. Tool result messages should have matching tool_use_id
1487        if let ChatMessage::Tool { tool_call_id, .. } = &s.chat_messages[1] {
1488            assert_eq!(tool_call_id, "call_00_VJtlnKha0ZZ2Yo8t5ysQ8883");
1489        } else {
1490            panic!("expected Tool message for first tool call");
1491        }
1492
1493        if let ChatMessage::Tool { tool_call_id, .. } = &s.chat_messages[2] {
1494            assert_eq!(tool_call_id, "call_01_abc123");
1495        } else {
1496            panic!("expected Tool message for second tool call");
1497        }
1498
1499        // 3. Validate message sequence (this would catch the bug)
1500        assert!(
1501            validate_message_sequence(&s.chat_messages).is_ok(),
1502            "message sequence should be valid with matching tool_use and tool_result"
1503        );
1504    }
1505}
1506
1507#[cfg(test)]
1508mod proptest_tests {
1509    use super::*;
1510    use proptest::prelude::*;
1511
1512    proptest! {
1513        // ── RunState property tests ─────────────────────────────────────────
1514
1515        #[test]
1516        fn reset_for_new_run_zeros_all_fields(
1517            turn_tool_calls in 0usize..1000,
1518            run_has_tool_calls in proptest::bool::ANY,
1519            reasoning_only_strikes in 0usize..100,
1520            empty_response_strikes in 0usize..100,
1521            nudge_count in 0usize..100,
1522        ) {
1523            let mut rs = RunState {
1524                turn_tool_calls,
1525                run_has_tool_calls,
1526                reasoning_only_strikes,
1527                empty_response_strikes,
1528                nudge_count,
1529                thinking_disabled_for_rest_of_run: true,
1530                original_thinking_enabled: true,
1531                truncation_strikes: 5,
1532                awaiting_human: true,
1533            };
1534            rs.reset_for_new_run();
1535            assert_eq!(rs.turn_tool_calls, 0);
1536            assert!(!rs.run_has_tool_calls);
1537            assert_eq!(rs.reasoning_only_strikes, 0);
1538            assert_eq!(rs.empty_response_strikes, 0);
1539            assert_eq!(rs.nudge_count, 0);
1540            assert_eq!(rs.truncation_strikes, 0);
1541            assert!(!rs.thinking_disabled_for_rest_of_run);
1542            assert!(!rs.awaiting_human);
1543            // original_thinking_enabled is NOT reset
1544            assert!(rs.original_thinking_enabled);
1545        }
1546
1547        #[test]
1548        fn record_tool_calls_accumulates(n in 0usize..100) {
1549            let mut rs = RunState::default();
1550            rs.record_tool_calls(n);
1551            assert_eq!(rs.turn_tool_calls, n);
1552            assert!(rs.run_has_tool_calls);
1553            assert_eq!(rs.reasoning_only_strikes, 0);
1554            assert_eq!(rs.empty_response_strikes, 0);
1555        }
1556
1557        #[test]
1558        fn record_reasoning_only_increments(count in 1usize..50) {
1559            let mut rs = RunState::default();
1560            for i in 1..=count {
1561                let strikes = rs.record_reasoning_only();
1562                assert_eq!(strikes, i);
1563                assert_eq!(rs.empty_response_strikes, 0);
1564            }
1565        }
1566
1567        #[test]
1568        fn record_empty_response_increments(count in 1usize..50) {
1569            let mut rs = RunState::default();
1570            for i in 1..=count {
1571                let strikes = rs.record_empty_response();
1572                assert_eq!(strikes, i);
1573                assert_eq!(rs.reasoning_only_strikes, 0);
1574            }
1575        }
1576
1577        // ── push_assistant_tool_calls property tests ────────────────────────
1578
1579        #[test]
1580        fn push_assistant_tool_calls_valid_json_unchanged(args in r"\{[^{}]{0,200}\}") {
1581            // Only test strings that are actually valid JSON objects
1582            if serde_json::from_str::<serde_json::Value>(&args).is_err() {
1583                return Ok(());
1584            }
1585            let mut s = make_session();
1586            s.push_assistant_tool_calls(
1587                &[("id".into(), "tool".into(), args.clone())],
1588                None,
1589                None,
1590            );
1591            if let ChatMessage::Assistant { tool_calls: Some(ref tc), .. } = s.chat_messages()[0] {
1592                assert_eq!(tc[0].arguments, args);
1593            } else {
1594                panic!("expected Assistant with tool_calls");
1595            }
1596        }
1597
1598        #[test]
1599        fn push_assistant_tool_calls_invalid_json_sanitized_to_empty(
1600            bad_args in "[a-z\u{4e00}-\u{9fff}]{0,300}"
1601        ) {
1602            // Skip if it happens to be valid JSON
1603            if serde_json::from_str::<serde_json::Value>(&bad_args).is_ok() {
1604                return Ok(());
1605            }
1606            let mut s = make_session();
1607            s.push_assistant_tool_calls(
1608                &[("id".into(), "tool".into(), bad_args)],
1609                None,
1610                None,
1611            );
1612            if let ChatMessage::Assistant { tool_calls: Some(ref tc), .. } = s.chat_messages()[0] {
1613                // Must be valid JSON (no 400 on replay) AND carry no poison
1614                // wrapper the model could echo back as arguments.
1615                serde_json::from_str::<serde_json::Value>(&tc[0].arguments)
1616                    .expect("sanitized args must be valid JSON");
1617                assert_eq!(tc[0].arguments, "{}");
1618            } else {
1619                panic!("expected Assistant with tool_calls");
1620            }
1621        }
1622
1623        #[test]
1624        fn preview_args_escapes_and_caps_at_max_chars(payload in "[a-z\u{4e00}-\u{9fff}\n\t]{0,400}") {
1625            // args_preview for the truncation WARN: truncate by characters (not bytes),
1626            // escape control characters in debug form (each input character expands to
1627            // at most 2 characters), with length capped at min(80, len) * 2 + the paired quotes.
1628            let preview = AgentSession::preview_args(&payload, 80);
1629            let expected_cap = 2 * payload.chars().count().min(80) + 2;
1630            assert!(
1631                preview.chars().count() <= expected_cap,
1632                "preview must cap at escaped length plus quotes: {preview}"
1633            );
1634            if payload.contains('\n') || payload.contains('\t') {
1635                assert!(
1636                    preview.contains("\\n") || preview.contains("\\t"),
1637                    "control chars must be escaped: {preview}"
1638                );
1639            }
1640            if payload.chars().count() <= 80 && !payload.contains('\n') && !payload.contains('\t') {
1641                assert_eq!(preview, format!("{payload:?}"));
1642            }
1643        }
1644
1645        // ── trim_oldest_turns property tests ────────────────────────────────
1646
1647        #[test]
1648        fn trim_oldest_turns_never_exceeds_max(turns in 1usize..20, max in 1usize..20) {
1649            let mut s = make_session();
1650            for i in 0..turns {
1651                s.push_message(MessageRole::User, format!("u{}", i));
1652                s.push_message(MessageRole::Assistant, format!("a{}", i));
1653            }
1654            s.trim_oldest_turns(max);
1655            assert!(s.turn_count() <= max || turns <= max);
1656        }
1657
1658        // ── validate_message_sequence property tests ────────────────────────
1659
1660        #[test]
1661        fn validate_simple_user_assistant_always_passes(count in 1usize..20) {
1662            let mut msgs = Vec::new();
1663            for i in 0..count {
1664                msgs.push(ChatMessage::user(format!("msg{}", i)));
1665                msgs.push(ChatMessage::assistant(format!("reply{}", i)));
1666            }
1667            assert!(validate_message_sequence(&msgs).is_ok());
1668        }
1669    }
1670}