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// RunState moved to agent-types (D5+OV-11): the counting state rides in
10// `CheckpointData`, so it must live where the checkpoint payload lives.
11// Re-exported here so existing `engine::session::RunState` imports keep working.
12pub use crate::types::RunState;
13
14/// Deserialization shim for backward compatibility.
15///
16/// Before `RunState` was introduced, `nudge_count`, `turn_tool_calls`,
17/// `reasoning_only_strikes`, and `empty_response_strikes` were flat fields
18/// on `AgentSession` — and the session-lifetime total lived at the top level
19/// as `total_tool_calls`. This struct accepts **both** the old flat format and
20/// the new nested `run_state` format, migrating legacy data on the fly.
21#[derive(Deserialize)]
22struct RawAgentSession {
23    id: Option<SessionId>,
24    chat_messages: Vec<ChatMessage>,
25    always_allowed_actions: HashSet<String>,
26    /// Pre-T7 session total (D5 moved it into `RunState::total_actions`).
27    /// Optional so new-format payloads omit it; when present it migrates into
28    /// the counting state — the one counting home.
29    #[serde(default)]
30    total_tool_calls: Option<usize>,
31
32    // ── new format (preferred) ──
33    run_state: Option<RunState>,
34
35    // ── legacy flat fields (fallback) ──
36    nudge_count: Option<usize>,
37    turn_tool_calls: Option<usize>,
38    reasoning_only_strikes: Option<usize>,
39    empty_response_strikes: Option<usize>,
40}
41
42impl From<RawAgentSession> for AgentSession {
43    fn from(raw: RawAgentSession) -> Self {
44        let mut run_state = raw.run_state.unwrap_or_else(|| RunState {
45            nudge_count: raw.nudge_count.unwrap_or(0),
46            turn_actions: raw.turn_tool_calls.unwrap_or(0),
47            reasoning_only_strikes: raw.reasoning_only_strikes.unwrap_or(0),
48            empty_response_strikes: raw.empty_response_strikes.unwrap_or(0),
49            ..RunState::default()
50        });
51        // Pre-T7 wire kept the session total at the top level; migrate it into
52        // the counting state (D5: one counting home). New-format payloads omit
53        // the top-level key and keep the total already inside `run_state`.
54        if let Some(total) = raw.total_tool_calls {
55            run_state.total_actions = total;
56        }
57        Self {
58            id: raw.id,
59            chat_messages: raw.chat_messages,
60            always_allowed_actions: raw.always_allowed_actions,
61            run_state,
62        }
63    }
64}
65
66/// Stable identity + rolling state of a single chat thread.
67///
68/// `Default` returns a fresh session; load persisted state via serde.
69/// Backward-compatible with the old flat-field format (pre-`RunState` migration).
70#[derive(Clone, Debug, Default, Serialize, Deserialize)]
71#[serde(from = "RawAgentSession")]
72pub struct AgentSession {
73    id: Option<SessionId>,
74    /// LLM API format messages, sent directly to the provider.
75    /// This is the single source of truth for the conversation state.
76    chat_messages: Vec<ChatMessage>,
77    always_allowed_actions: HashSet<String>,
78    /// Run-level state tracking for the react loop. Holds ALL counting state
79    /// (D5): `run_state.total_actions` is the session-lifetime total middleware
80    /// decisions like "first_turn_only" read.
81    pub run_state: RunState,
82}
83
84impl AgentSession {
85    pub fn new(id: SessionId) -> Self {
86        Self {
87            id: Some(id),
88            chat_messages: Vec::new(),
89            always_allowed_actions: HashSet::new(),
90            run_state: RunState::default(),
91        }
92    }
93
94    pub fn id(&self) -> Option<SessionId> {
95        self.id.clone()
96    }
97
98    /// Derive a simplified `Vec<Message>` view from the canonical `chat_messages`.
99    /// Assistant messages that contain only tool_calls (no text content) are
100    /// skipped, since they have no corresponding simplified representation.
101    pub fn simple_messages(&self) -> Vec<Message> {
102        self.chat_messages
103            .iter()
104            .filter_map(|cm| match cm {
105                ChatMessage::Assistant { content: None, .. } => None,
106                ChatMessage::Assistant {
107                    content: Some(c),
108                    tool_calls: Some(tc),
109                    ..
110                } if c.is_empty() && !tc.is_empty() => None,
111                _ => Some(Message::from(cm)),
112            })
113            .collect()
114    }
115
116    pub fn chat_messages(&self) -> &[ChatMessage] {
117        &self.chat_messages
118    }
119
120    /// Mutable reference, for advanced scenarios that need to operate on messages directly.
121    pub fn chat_messages_mut(&mut self) -> &mut Vec<ChatMessage> {
122        &mut self.chat_messages
123    }
124
125    pub fn is_action_allowed(&self, action_key: &str) -> bool {
126        self.always_allowed_actions.contains(action_key)
127    }
128
129    pub fn allow_action(&mut self, action_key: impl Into<String>) {
130        self.always_allowed_actions.insert(action_key.into());
131    }
132
133    pub fn push_message(&mut self, role: MessageRole, content: impl Into<String>) {
134        let content = content.into();
135        let chat_msg = match role {
136            MessageRole::System => ChatMessage::system(content),
137            MessageRole::User => ChatMessage::user(content),
138            MessageRole::Assistant => ChatMessage::assistant(content),
139            MessageRole::Tool => ChatMessage::tool(String::new(), content),
140        };
141        self.chat_messages.push(chat_msg);
142    }
143
144    /// Push a message as ephemeral (user/system only): the LLM sees it this
145    /// turn, then `remove_ephemeral_messages` strips it at turn end — from
146    /// both memory and persistence.
147    pub fn push_message_ephemeral(&mut self, role: MessageRole, content: impl Into<String>) {
148        let content = content.into();
149        let chat_msg = match role {
150            MessageRole::System => ChatMessage::system_ephemeral(content),
151            MessageRole::User => ChatMessage::user_ephemeral(content),
152            MessageRole::Assistant | MessageRole::Tool => {
153                // Ephemeral assistant/tool messages are not a thing; fall back
154                // to a regular push rather than silently mis-marking.
155                self.push_message(role, content);
156                return;
157            }
158        };
159        self.chat_messages.push(chat_msg);
160    }
161
162    /// Replace the system prompt — the first **non-ephemeral** System message
163    /// (wherever it sits, matching how `context` locates it); inserted at
164    /// index 0 if none exists. All other messages are untouched. Hosts that
165    /// own prompt composition (e.g. skill activation) re-bake through this.
166    pub fn set_system_prompt(&mut self, content: impl Into<String>) {
167        let content = content.into();
168        if let Some(idx) = self.chat_messages.iter().position(|m| {
169            matches!(
170                m,
171                ChatMessage::System {
172                    ephemeral: false,
173                    ..
174                }
175            )
176        }) {
177            self.chat_messages[idx] = ChatMessage::system(content);
178        } else {
179            self.chat_messages.insert(0, ChatMessage::system(content));
180        }
181    }
182
183    /// Push an assistant message with reasoning/thinking content preserved.
184    /// This allows the LLM to see its own prior reasoning in subsequent turns,
185    /// preventing it from re-deriving the same conclusions every turn.
186    pub fn push_assistant_with_reasoning(
187        &mut self,
188        content: impl Into<String>,
189        reasoning: impl Into<String>,
190    ) {
191        self.chat_messages
192            .push(ChatMessage::assistant_with_reasoning(content, reasoning));
193    }
194
195    pub fn push_user_message_with_images(
196        &mut self,
197        content: impl Into<String>,
198        images: Vec<ImageAttachment>,
199    ) {
200        self.chat_messages
201            .push(ChatMessage::user_with_images(content, images));
202    }
203
204    pub fn push_assistant_tool_call(
205        &mut self,
206        tool_call_id: &str,
207        tool_name: &str,
208        arguments_json: &str,
209    ) {
210        self.chat_messages.push(ChatMessage::assistant_tool_call(
211            tool_call_id,
212            tool_name,
213            arguments_json,
214        ));
215    }
216
217    /// Escape and truncate the arguments to their first `max_chars` characters, so the
218    /// truncation WARN can display the raw content directly. Rust debug escaping keeps
219    /// unclosed JSON, control characters, and CJK boundaries clearly distinguishable, so
220    /// troubleshooting provider truncation in production no longer requires indirectly
221    /// reconstructing the content.
222    fn preview_args(args: &str, max_chars: usize) -> String {
223        format!("{:?}", args.chars().take(max_chars).collect::<String>())
224    }
225
226    /// Render one assistant message carrying tool calls — the tool backend's
227    /// history protocol (invalid-JSON sanitization included). Split out of
228    /// [`Self::push_assistant_tool_calls`] so the backend can both push the
229    /// message and carry it in `Observation::history_messages` for checkpoint
230    /// replay (M3 seam).
231    pub fn render_assistant_tool_calls(
232        tool_calls: &[(String, String, String)],
233        reasoning: Option<String>,
234        content: Option<String>,
235    ) -> ChatMessage {
236        let calls: Vec<ToolCallMessage> = tool_calls
237            .iter()
238            .map(|(id, name, args)| {
239                // Invalid JSON args (provider truncated the stream mid-generation)
240                // are sanitized to an empty object. We deliberately do NOT wrap
241                // them in a descriptive `{error, original_args_preview, message}`
242                // object: "{}" is valid JSON so the next request is never rejected
243                // with 400, and — critically — a rich error object here becomes an
244                // imitation vector: the model replays it verbatim as the next
245                // call's arguments and, because it parses, it slips past the react
246                // truncation guard. The truncation explanation lives in the
247                // paired tool_result, which is where the model reads feedback.
248                let valid_args = if serde_json::from_str::<serde_json::Value>(args).is_ok() {
249                    args.clone()
250                } else {
251                    tracing::warn!(
252                        tool_name = %name,
253                        args_len = args.len(),
254                        args_preview = %Self::preview_args(args, 80),
255                        "tool call arguments are not valid JSON (provider truncated them), \
256                         sanitizing to empty object; re-issue instruction goes to the tool_result"
257                    );
258                    "{}".to_string()
259                };
260                ToolCallMessage {
261                    id: id.clone(),
262                    name: name.clone(),
263                    arguments: valid_args,
264                }
265            })
266            .collect();
267        ChatMessage::Assistant {
268            content,
269            reasoning_content: reasoning,
270            tool_calls: Some(calls),
271            thinking_signature: None,
272        }
273    }
274
275    pub fn push_assistant_tool_calls(
276        &mut self,
277        tool_calls: &[(String, String, String)],
278        reasoning: Option<String>,
279        content: Option<String>,
280    ) {
281        self.push_chat_message(Self::render_assistant_tool_calls(
282            tool_calls, reasoning, content,
283        ));
284    }
285
286    /// Push one already-built message — the kernel's verbatim push for
287    /// backend-rendered history ([`crate::types::Observation::history_messages`]).
288    pub fn push_chat_message(&mut self, message: ChatMessage) {
289        self.chat_messages.push(message);
290    }
291
292    pub fn push_tool_result(&mut self, tool_call_id: &str, content: impl Into<String>) {
293        self.chat_messages
294            .push(ChatMessage::tool(tool_call_id, content));
295    }
296
297    /// Remove all ephemeral messages (ephemeral=true).
298    ///
299    /// Called at the end of a turn to ensure injected ephemeral content does not linger into the next turn.
300    pub fn remove_ephemeral_messages(&mut self) {
301        let before = self.chat_messages.len();
302        self.chat_messages.retain(|m| !m.is_ephemeral());
303        let removed = before - self.chat_messages.len();
304        if removed > 0 {
305            tracing::debug!(
306                removed,
307                remaining = self.chat_messages.len(),
308                "ephemeral messages cleaned up"
309            );
310        }
311    }
312
313    /// Count the number of conversation turns.
314    /// A turn starts with a User message and includes subsequent Assistant/Tool messages.
315    pub fn turn_count(&self) -> usize {
316        self.chat_messages
317            .iter()
318            .filter(|m| matches!(m, ChatMessage::User { .. }))
319            .count()
320    }
321
322    /// Remove the oldest turns from the front until turn count ≤ max_turns.
323    /// Preserves the System message at index 0 if present.
324    pub fn trim_oldest_turns(&mut self, max_turns: usize) {
325        let current_turns = self.turn_count();
326        if current_turns <= max_turns {
327            return;
328        }
329        let turns_to_remove = current_turns - max_turns;
330
331        // Find User message positions (turn boundaries) in chat_messages
332        let user_positions: Vec<usize> = self
333            .chat_messages
334            .iter()
335            .enumerate()
336            .filter_map(|(i, m)| {
337                if matches!(m, ChatMessage::User { .. }) {
338                    Some(i)
339                } else {
340                    None
341                }
342            })
343            .collect();
344
345        if user_positions.len() <= turns_to_remove {
346            return;
347        }
348
349        // Preserve system prefix: count leading System messages
350        let system_prefix = self
351            .chat_messages
352            .iter()
353            .take_while(|m| matches!(m, ChatMessage::System { .. }))
354            .count();
355
356        // Drain from system_prefix up to the start of the (turns_to_remove + 1)-th turn
357        let drain_end = user_positions[turns_to_remove];
358        if system_prefix >= drain_end {
359            return; // nothing to drain after system messages
360        }
361
362        self.chat_messages.drain(system_prefix..drain_end);
363    }
364
365    /// Remove the last message from `chat_messages`.
366    /// Used by the max_message_tokens safety valve to discard oversized messages.
367    pub fn pop_last_message(&mut self) {
368        self.chat_messages.pop();
369    }
370
371    pub fn close_dangling_tool_calls(&mut self, error_summary: &str) {
372        let assistant_idx = self.chat_messages.iter().rposition(
373            |m| matches!(m, ChatMessage::Assistant { tool_calls: Some(tc), .. } if !tc.is_empty()),
374        );
375
376        let Some(assistant_idx) = assistant_idx else {
377            return;
378        };
379
380        let ChatMessage::Assistant {
381            tool_calls: Some(tc),
382            ..
383        } = &self.chat_messages[assistant_idx]
384        else {
385            return;
386        };
387
388        let all_ids: Vec<String> = tc.iter().map(|t| t.id.clone()).collect();
389
390        let answered_ids: Vec<String> = self.chat_messages[assistant_idx + 1..]
391            .iter()
392            .filter_map(|m| match m {
393                ChatMessage::Tool { tool_call_id, .. } => Some(tool_call_id.clone()),
394                _ => None,
395            })
396            .collect();
397
398        for id in &all_ids {
399            if !answered_ids.iter().any(|a| a == id) {
400                self.push_tool_result(id, error_summary);
401            }
402        }
403    }
404
405    /// Replace chat messages — for persistence restore and window compaction.
406    /// Validates message sequence before replacing.
407    ///
408    /// Counters are NOT touched (D5): the counting source is explicit. A
409    /// checkpoint restore trusts the persisted `RunState` (co-written with the
410    /// checkpoint/journal — OV-11); only a messages-only restore — the
411    /// old-format corpus — recounts via [`Self::recount_actions_from_messages`].
412    /// Recounting here would also deflate the total after compaction and lie
413    /// for restored histories that carry synthesized "已中断/未执行" results.
414    pub fn set_chat_messages(&mut self, messages: Vec<ChatMessage>) -> Result<(), String> {
415        validate_message_sequence(&messages)?;
416        self.chat_messages = messages;
417        Ok(())
418    }
419
420    /// Old-format compatibility (D5: 消息重算只做旧格式兼容): rebuild the
421    /// session-lifetime action total from the history's assistant tool-call
422    /// lens. Call ONLY on restores that carry no persisted counting state —
423    /// the lens counts call attempts, not executed actions, so it is a
424    /// fallback, never the primary source.
425    pub fn recount_actions_from_messages(&mut self) {
426        self.run_state.total_actions = self
427            .chat_messages
428            .iter()
429            .filter_map(|m| match m {
430                ChatMessage::Assistant {
431                    tool_calls: Some(tc),
432                    ..
433                } => Some(tc.len()),
434                _ => None,
435            })
436            .sum();
437    }
438}
439
440/// Validate that a chat message sequence is well-formed for LLM API consumption.
441///
442/// Checks:
443/// - At least one non-System/non-Custom message (System maps to the
444///   top-level `system` parameter, Custom is stripped — a sequence of only
445///   those leaves an empty `messages` array, which providers reject with
446///   HTTP 400). Guards compaction outputs against producing an unsendable
447///   window.
448/// - No Tool message without a preceding Assistant with matching tool_call
449/// - No duplicate Tool messages for the same tool_call_id
450/// - All tool_calls in an Assistant batch must be answered before the next Assistant batch
451/// - No unanswered tool calls at the end of the sequence
452pub fn validate_message_sequence(messages: &[ChatMessage]) -> Result<(), String> {
453    if !messages
454        .iter()
455        .any(|m| !matches!(m, ChatMessage::System { .. } | ChatMessage::Custom { .. }))
456    {
457        return Err(
458            "sequence contains no sendable message: System/Custom alone leave the \
459             provider `messages` array empty"
460                .to_string(),
461        );
462    }
463
464    let mut pending_tool_call_ids: HashSet<String> = HashSet::new();
465
466    for (i, msg) in messages.iter().enumerate() {
467        match msg {
468            ChatMessage::Tool { tool_call_id, .. } => {
469                if pending_tool_call_ids.is_empty() {
470                    return Err(format!(
471                        "message[{}]: Tool message with call_id '{}' has no preceding tool_call",
472                        i, tool_call_id
473                    ));
474                }
475                // Remove the ID on match — also detects duplicates (second remove returns false)
476                if !pending_tool_call_ids.remove(tool_call_id) {
477                    return Err(format!(
478                        "message[{}]: Tool message with call_id '{}' does not match any pending tool_call (already answered or unknown)",
479                        i, tool_call_id
480                    ));
481                }
482            }
483            ChatMessage::Assistant {
484                tool_calls: Some(tc),
485                ..
486            } => {
487                // Previous batch must be fully answered before a new batch starts
488                if !pending_tool_call_ids.is_empty() {
489                    return Err(format!(
490                        "message[{}]: Assistant message with new tool_calls appears before pending calls were answered: {:?}",
491                        i, pending_tool_call_ids
492                    ));
493                }
494                pending_tool_call_ids = tc.iter().map(|t| t.id.clone()).collect();
495            }
496            _ => {}
497        }
498    }
499
500    // All tool calls must be answered by the end of the sequence
501    if !pending_tool_call_ids.is_empty() {
502        return Err(format!(
503            "message sequence ends with unanswered tool calls: {:?}",
504            pending_tool_call_ids
505        ));
506    }
507
508    Ok(())
509}
510
511#[cfg(test)]
512fn make_session() -> AgentSession {
513    AgentSession::new(SessionId::new(1))
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519
520    #[test]
521    fn test_turn_count_empty() {
522        let s = make_session();
523        assert_eq!(s.turn_count(), 0);
524    }
525
526    #[test]
527    fn test_turn_count_with_system_and_user() {
528        let mut s = make_session();
529        s.push_message(MessageRole::System, "system");
530        assert_eq!(s.turn_count(), 0);
531        s.push_message(MessageRole::User, "hello");
532        assert_eq!(s.turn_count(), 1);
533        s.push_message(MessageRole::Assistant, "hi");
534        assert_eq!(s.turn_count(), 1);
535        s.push_message(MessageRole::User, "bye");
536        assert_eq!(s.turn_count(), 2);
537    }
538
539    #[test]
540    fn test_turn_count_with_tool_calls() {
541        let mut s = make_session();
542        s.push_message(MessageRole::User, "do something");
543        s.push_assistant_tool_calls(&[("id1".into(), "tool".into(), "{}".into())], None, None);
544        s.push_tool_result("id1", "result");
545        s.push_message(MessageRole::Assistant, "done");
546        // One user turn: User -> Assistant(tool_calls) -> Tool -> Assistant(text)
547        assert_eq!(s.turn_count(), 1);
548    }
549
550    #[test]
551    fn test_trim_oldest_turns_noop() {
552        let mut s = make_session();
553        s.push_message(MessageRole::User, "hello");
554        s.push_message(MessageRole::Assistant, "hi");
555        s.trim_oldest_turns(5);
556        assert_eq!(s.turn_count(), 1);
557        assert_eq!(s.chat_messages().len(), 2);
558    }
559
560    #[test]
561    fn test_trim_oldest_turns_removes_old() {
562        let mut s = make_session();
563        s.push_message(MessageRole::System, "sys");
564        // Turn 1
565        s.push_message(MessageRole::User, "u1");
566        s.push_message(MessageRole::Assistant, "a1");
567        // Turn 2
568        s.push_message(MessageRole::User, "u2");
569        s.push_message(MessageRole::Assistant, "a2");
570        // Turn 3
571        s.push_message(MessageRole::User, "u3");
572        s.push_message(MessageRole::Assistant, "a3");
573
574        s.trim_oldest_turns(2);
575        assert_eq!(s.turn_count(), 2);
576        // System message preserved
577        assert!(matches!(s.chat_messages()[0], ChatMessage::System { .. }));
578        // Oldest user message is u2
579        assert!(
580            matches!(s.chat_messages()[1], ChatMessage::User { ref content, .. } if content == "u2")
581        );
582    }
583
584    #[test]
585    fn test_trim_oldest_turns_with_tool_calls() {
586        let mut s = make_session();
587        // Turn 1 with tool call
588        s.push_message(MessageRole::User, "u1");
589        s.push_assistant_tool_calls(&[("id1".into(), "t".into(), "{}".into())], None, None);
590        s.push_tool_result("id1", "r1");
591        s.push_message(MessageRole::Assistant, "a1");
592        // Turn 2
593        s.push_message(MessageRole::User, "u2");
594        s.push_message(MessageRole::Assistant, "a2");
595
596        let msg_before = s.simple_messages().len();
597        let chat_before = s.chat_messages().len();
598        s.trim_oldest_turns(1);
599        assert_eq!(s.turn_count(), 1);
600        // chat_messages should have lost 4 entries (User, Assistant(tool), Tool, Assistant(text))
601        assert_eq!(s.chat_messages().len(), chat_before - 4);
602        // simple_messages (derived from chat_messages, tool_calls-only filtered) loses 3 entries
603        assert_eq!(s.simple_messages().len(), msg_before - 3);
604    }
605
606    #[test]
607    fn test_pop_last_message_text() {
608        let mut s = make_session();
609        s.push_message(MessageRole::User, "hello");
610        s.push_message(MessageRole::Assistant, "hi");
611        assert_eq!(s.chat_messages().len(), 2);
612        s.pop_last_message();
613        assert_eq!(s.chat_messages().len(), 1);
614        assert_eq!(s.simple_messages().len(), 1);
615    }
616
617    #[test]
618    fn test_pop_last_message_tool_calls_only() {
619        let mut s = make_session();
620        s.push_message(MessageRole::User, "do it");
621        s.push_assistant_tool_calls(&[("id1".into(), "t".into(), "{}".into())], None, None);
622        assert_eq!(s.chat_messages().len(), 2);
623        assert_eq!(s.simple_messages().len(), 1); // only User in simple_messages (tool_calls-only filtered)
624        s.pop_last_message();
625        assert_eq!(s.chat_messages().len(), 1);
626        assert_eq!(s.simple_messages().len(), 1); // simple_messages unchanged (still just User)
627    }
628
629    #[test]
630    fn test_pop_last_message_empty_session() {
631        let mut s = make_session();
632        s.pop_last_message(); // should not panic
633        assert_eq!(s.chat_messages().len(), 0);
634    }
635
636    // ── B5: remaining session lifecycle paths ──────────────────────────────
637
638    #[test]
639    fn test_id_and_action_allowlist() {
640        let mut s = make_session();
641        assert_eq!(s.id(), Some(SessionId::new(1)));
642        assert!(!s.is_action_allowed("approve:rm"));
643        s.allow_action("approve:rm");
644        assert!(s.is_action_allowed("approve:rm"));
645        assert!(!s.is_action_allowed("approve:shell"));
646    }
647
648    #[test]
649    fn test_chat_messages_mut() {
650        let mut s = make_session();
651        s.chat_messages_mut().push(ChatMessage::user("direct"));
652        assert_eq!(s.chat_messages().len(), 1);
653    }
654
655    #[test]
656    fn test_push_message_tool_role() {
657        let mut s = make_session();
658        s.push_message(MessageRole::Tool, "result");
659        assert!(matches!(s.chat_messages()[0], ChatMessage::Tool { .. }));
660    }
661
662    #[test]
663    fn test_push_assistant_with_reasoning() {
664        let mut s = make_session();
665        s.push_assistant_with_reasoning("answer", "thinking");
666        match &s.chat_messages()[0] {
667            ChatMessage::Assistant {
668                content,
669                reasoning_content,
670                ..
671            } => {
672                assert_eq!(content.as_deref(), Some("answer"));
673                assert_eq!(reasoning_content.as_deref(), Some("thinking"));
674            }
675            other => panic!("unexpected message: {other:?}"),
676        }
677    }
678
679    #[test]
680    fn test_push_user_message_with_images() {
681        let mut s = make_session();
682        s.push_user_message_with_images(
683            "look",
684            vec![ImageAttachment::Url {
685                url: "http://x".into(),
686                detail: None,
687            }],
688        );
689        match &s.chat_messages()[0] {
690            ChatMessage::User { images, .. } => assert_eq!(images.len(), 1),
691            other => panic!("unexpected message: {other:?}"),
692        }
693    }
694
695    #[test]
696    fn test_push_assistant_tool_call_singular() {
697        let mut s = make_session();
698        s.push_assistant_tool_call("call_1", "bash", "{}");
699        match &s.chat_messages()[0] {
700            ChatMessage::Assistant {
701                tool_calls: Some(tc),
702                ..
703            } => {
704                assert_eq!(tc.len(), 1);
705                assert_eq!(tc[0].id, "call_1");
706                assert_eq!(tc[0].name, "bash");
707            }
708            other => panic!("unexpected message: {other:?}"),
709        }
710    }
711
712    #[test]
713    fn test_simple_messages_filters_empty_content_tool_calls() {
714        let mut s = make_session();
715        s.chat_messages_mut().push(ChatMessage::Assistant {
716            content: Some(String::new()),
717            reasoning_content: None,
718            tool_calls: Some(vec![ToolCallMessage {
719                id: "c".into(),
720                name: "t".into(),
721                arguments: "{}".into(),
722            }]),
723            thinking_signature: None,
724        });
725        assert!(s.simple_messages().is_empty());
726    }
727
728    #[test]
729    fn test_remove_ephemeral_messages() {
730        let mut s = make_session();
731        s.push_message(MessageRole::System, "keep");
732        s.chat_messages_mut()
733            .push(ChatMessage::user_ephemeral("temp"));
734        s.chat_messages_mut()
735            .push(ChatMessage::system_ephemeral("temp2"));
736        s.push_message(MessageRole::User, "keep2");
737        assert_eq!(s.chat_messages().len(), 4);
738        s.remove_ephemeral_messages();
739        assert_eq!(s.chat_messages().len(), 2);
740        assert!(s.chat_messages().iter().all(|m| !m.is_ephemeral()));
741    }
742
743    #[test]
744    fn test_set_system_prompt_replaces_first_non_ephemeral_system() {
745        let mut s = make_session();
746        s.push_message(MessageRole::System, "old prompt");
747        s.push_message(MessageRole::User, "hi");
748        s.push_message(MessageRole::Assistant, "hello");
749
750        s.set_system_prompt("new prompt");
751
752        let msgs = s.chat_messages();
753        assert_eq!(msgs.len(), 3, "history length unchanged");
754        assert!(
755            matches!(&msgs[0], ChatMessage::System { content, ephemeral: false } if content == "new prompt")
756        );
757        assert!(matches!(&msgs[1], ChatMessage::User { content, .. } if content == "hi"));
758        assert!(
759            matches!(&msgs[2], ChatMessage::Assistant { content: Some(c), .. } if c == "hello")
760        );
761    }
762
763    #[test]
764    fn test_set_system_prompt_inserts_when_absent() {
765        let mut s = make_session();
766        s.push_message(MessageRole::User, "hi");
767
768        s.set_system_prompt("fresh prompt");
769
770        let msgs = s.chat_messages();
771        assert_eq!(msgs.len(), 2);
772        assert!(
773            matches!(&msgs[0], ChatMessage::System { content, ephemeral: false } if content == "fresh prompt")
774        );
775        assert!(matches!(&msgs[1], ChatMessage::User { .. }));
776    }
777
778    #[test]
779    fn test_set_system_prompt_skips_ephemeral_system_and_inserts() {
780        let mut s = make_session();
781        s.chat_messages_mut()
782            .push(ChatMessage::system_ephemeral("ephemeral nudge"));
783        s.push_message(MessageRole::User, "hi");
784
785        s.set_system_prompt("real prompt");
786
787        // No non-ephemeral System exists → insert at the very front; the ephemeral nudge stays where it is.
788        let msgs = s.chat_messages();
789        assert_eq!(msgs.len(), 3);
790        assert!(
791            matches!(&msgs[0], ChatMessage::System { content, ephemeral: false } if content == "real prompt")
792        );
793        assert!(matches!(
794            &msgs[1],
795            ChatMessage::System {
796                ephemeral: true,
797                ..
798            }
799        ));
800        assert!(matches!(&msgs[2], ChatMessage::User { .. }));
801    }
802
803    #[test]
804    fn test_close_dangling_tool_calls_noop_without_tool_call() {
805        let mut s = make_session();
806        s.push_message(MessageRole::User, "hi");
807        s.push_message(MessageRole::Assistant, "hi");
808        s.close_dangling_tool_calls("failed");
809        assert_eq!(s.chat_messages().len(), 2);
810    }
811
812    #[test]
813    fn test_close_dangling_tool_calls_adds_missing_results() {
814        let mut s = make_session();
815        s.push_message(MessageRole::User, "do");
816        s.push_assistant_tool_calls(
817            &[
818                ("c1".into(), "t".into(), "{}".into()),
819                ("c2".into(), "t".into(), "{}".into()),
820            ],
821            None,
822            None,
823        );
824        s.push_tool_result("c1", "ok"); // only c1 answered
825        s.close_dangling_tool_calls("failed");
826
827        let tool_results: Vec<(String, String)> = s
828            .chat_messages()
829            .iter()
830            .filter_map(|m| match m {
831                ChatMessage::Tool {
832                    tool_call_id,
833                    content,
834                    ..
835                } => Some((tool_call_id.clone(), content.clone())),
836                _ => None,
837            })
838            .collect();
839        assert_eq!(tool_results.len(), 2);
840        assert!(
841            tool_results
842                .iter()
843                .any(|(id, c)| id == "c2" && c == "failed")
844        );
845    }
846
847    #[test]
848    fn set_chat_messages_leaves_counters_alone() {
849        // D5: the counting source is explicit — a messages replace must not
850        // recount. (Replaces `test_set_chat_messages_recalculates_total_tool_calls`,
851        // a named D13 exception: the demotion is the designed behavior change.)
852        let mut s = make_session();
853        s.run_state.record_actions(2);
854        let msgs = vec![
855            ChatMessage::user("do"),
856            ChatMessage::assistant_tool_call("c1", "t", "{}"),
857            ChatMessage::tool("c1", "result"),
858        ];
859        s.set_chat_messages(msgs).unwrap();
860        assert_eq!(s.run_state.total_actions, 2); // untouched, not 1
861        assert_eq!(s.run_state.turn_actions, 2);
862    }
863
864    #[test]
865    fn recount_actions_from_messages_counts_the_assistant_lens() {
866        // The old-format entry point keeps the previous rebuild behavior.
867        let mut s = make_session();
868        let msgs = vec![
869            ChatMessage::user("do"),
870            ChatMessage::assistant_tool_call("c1", "t", "{}"),
871            ChatMessage::tool("c1", "result"),
872        ];
873        s.set_chat_messages(msgs).unwrap();
874        s.recount_actions_from_messages();
875        assert_eq!(s.run_state.total_actions, 1);
876    }
877}
878
879#[cfg(test)]
880mod validate_tests {
881    use super::*;
882
883    #[test]
884    fn test_valid_simple_sequence() {
885        let msgs = vec![ChatMessage::user("hello"), ChatMessage::assistant("hi")];
886        assert!(validate_message_sequence(&msgs).is_ok());
887    }
888
889    #[test]
890    fn test_valid_tool_call_sequence() {
891        let msgs = vec![
892            ChatMessage::user("run command"),
893            ChatMessage::assistant_tool_call("call_1", "bash", r#"{"cmd":"ls"}"#),
894            ChatMessage::tool("call_1", "file1 file2"),
895            ChatMessage::assistant("done"),
896        ];
897        assert!(validate_message_sequence(&msgs).is_ok());
898    }
899
900    #[test]
901    fn test_valid_multi_tool_call_sequence() {
902        let msgs = vec![
903            ChatMessage::user("run commands"),
904            ChatMessage::Assistant {
905                content: None,
906                reasoning_content: None,
907                tool_calls: Some(vec![
908                    crate::types::ToolCallMessage {
909                        id: "call_1".into(),
910                        name: "bash".into(),
911                        arguments: "{}".into(),
912                    },
913                    crate::types::ToolCallMessage {
914                        id: "call_2".into(),
915                        name: "read".into(),
916                        arguments: "{}".into(),
917                    },
918                ]),
919                thinking_signature: None,
920            },
921            ChatMessage::tool("call_1", "result1"),
922            ChatMessage::tool("call_2", "result2"),
923            ChatMessage::assistant("done"),
924        ];
925        assert!(validate_message_sequence(&msgs).is_ok());
926    }
927
928    #[test]
929    fn test_orphaned_tool_result() {
930        let msgs = vec![
931            ChatMessage::user("hello"),
932            ChatMessage::tool("call_1", "orphaned result"),
933        ];
934        let err = validate_message_sequence(&msgs).unwrap_err();
935        assert!(err.contains("no preceding tool_call"));
936    }
937
938    #[test]
939    fn test_system_only_sequence_rejected() {
940        // A compaction that leaves only System/Custom messages would send an
941        // empty `messages` array (System maps to the `system` param) — the
942        // contract rejects it.
943        let msgs = vec![
944            ChatMessage::system("prompt"),
945            ChatMessage::system_ephemeral("reminder"),
946            ChatMessage::Custom {
947                role: "artifact".into(),
948                data: serde_json::json!({"id": "x"}),
949            },
950        ];
951        let err = validate_message_sequence(&msgs).unwrap_err();
952        assert!(err.contains("no sendable message"));
953    }
954
955    #[test]
956    fn test_system_plus_user_ok() {
957        let msgs = vec![ChatMessage::system("prompt"), ChatMessage::user("hi")];
958        assert!(validate_message_sequence(&msgs).is_ok());
959    }
960
961    #[test]
962    fn test_mismatched_tool_call_id() {
963        let msgs = vec![
964            ChatMessage::user("run"),
965            ChatMessage::assistant_tool_call("call_1", "bash", "{}"),
966            ChatMessage::tool("call_2", "wrong id"),
967        ];
968        let err = validate_message_sequence(&msgs).unwrap_err();
969        assert!(err.contains("does not match"));
970    }
971
972    #[test]
973    fn test_set_chat_messages_valid() {
974        let mut s = make_session();
975        let msgs = vec![ChatMessage::user("hello"), ChatMessage::assistant("hi")];
976        assert!(s.set_chat_messages(msgs.clone()).is_ok());
977        assert_eq!(s.chat_messages().len(), 2);
978    }
979
980    #[test]
981    fn test_set_chat_messages_invalid() {
982        let mut s = make_session();
983        let msgs = vec![ChatMessage::tool("call_1", "orphaned")];
984        assert!(s.set_chat_messages(msgs).is_err());
985    }
986
987    // ── Backward-compatible deserialization ────────────────────────────────
988
989    #[test]
990    fn deserialize_legacy_flat_fields() {
991        // Old format: nudge_count, turn_tool_calls, etc. as flat fields
992        let json = r#"{
993            "id": null,
994            "chat_messages": [],
995            "always_allowed_actions": [],
996            "total_tool_calls": 5,
997            "nudge_count": 3,
998            "turn_tool_calls": 2,
999            "reasoning_only_strikes": 1,
1000            "empty_response_strikes": 0
1001        }"#;
1002        let session: AgentSession = serde_json::from_str(json).unwrap();
1003        assert_eq!(session.run_state.nudge_count, 3);
1004        assert_eq!(session.run_state.turn_actions, 2);
1005        assert_eq!(session.run_state.reasoning_only_strikes, 1);
1006        assert_eq!(session.run_state.empty_response_strikes, 0);
1007        assert!(!session.run_state.run_has_actions); // default
1008    }
1009
1010    #[test]
1011    fn deserialize_new_run_state_format() {
1012        // New format: nested run_state
1013        let json = r#"{
1014            "id": null,
1015            "chat_messages": [],
1016            "always_allowed_actions": [],
1017            "total_tool_calls": 5,
1018            "run_state": {
1019                "turn_tool_calls": 4,
1020                "run_has_tool_calls": true,
1021                "reasoning_only_strikes": 0,
1022                "empty_response_strikes": 1,
1023                "nudge_count": 2
1024            }
1025        }"#;
1026        let session: AgentSession = serde_json::from_str(json).unwrap();
1027        assert_eq!(session.run_state.turn_actions, 4);
1028        assert!(session.run_state.run_has_actions);
1029        assert_eq!(session.run_state.empty_response_strikes, 1);
1030        assert_eq!(session.run_state.nudge_count, 2);
1031    }
1032
1033    #[test]
1034    fn deserialize_run_state_takes_precedence_over_flat() {
1035        // When both are present, run_state wins
1036        let json = r#"{
1037            "id": null,
1038            "chat_messages": [],
1039            "always_allowed_actions": [],
1040            "total_tool_calls": 0,
1041            "run_state": {
1042                "turn_tool_calls": 10,
1043                "run_has_tool_calls": true,
1044                "reasoning_only_strikes": 0,
1045                "empty_response_strikes": 0,
1046                "nudge_count": 0
1047            },
1048            "nudge_count": 99,
1049            "turn_tool_calls": 99
1050        }"#;
1051        let session: AgentSession = serde_json::from_str(json).unwrap();
1052        assert_eq!(session.run_state.turn_actions, 10); // run_state wins
1053        assert_eq!(session.run_state.nudge_count, 0); // run_state wins
1054    }
1055
1056    #[test]
1057    fn deserialize_legacy_missing_optional_fields() {
1058        // Old format with some fields missing (defaults to 0)
1059        let json = r#"{
1060            "id": null,
1061            "chat_messages": [],
1062            "always_allowed_actions": [],
1063            "total_tool_calls": 0,
1064            "nudge_count": 1
1065        }"#;
1066        let session: AgentSession = serde_json::from_str(json).unwrap();
1067        assert_eq!(session.run_state.nudge_count, 1);
1068        assert_eq!(session.run_state.turn_actions, 0); // missing → 0
1069        assert_eq!(session.run_state.reasoning_only_strikes, 0);
1070        assert_eq!(session.run_state.empty_response_strikes, 0);
1071    }
1072
1073    #[test]
1074    fn roundtrip_preserves_run_state() {
1075        let mut session = AgentSession::new(SessionId::new(1));
1076        session.run_state.nudge_count = 5;
1077        session.run_state.turn_actions = 3;
1078        session.run_state.run_has_actions = true;
1079        session.run_state.reasoning_only_strikes = 2;
1080
1081        let json = serde_json::to_string(&session).unwrap();
1082        let restored: AgentSession = serde_json::from_str(&json).unwrap();
1083        assert_eq!(restored.run_state.nudge_count, 5);
1084        assert_eq!(restored.run_state.turn_actions, 3);
1085        assert!(restored.run_state.run_has_actions);
1086        assert_eq!(restored.run_state.reasoning_only_strikes, 2);
1087    }
1088
1089    #[test]
1090    fn deserialize_migrates_top_level_total_into_run_state() {
1091        // Pre-T7 wire: the session total lived at the top level. It migrates
1092        // into the one counting home (D5), and the old top-level field is gone
1093        // from new writes.
1094        let json = r#"{
1095            "id": null,
1096            "chat_messages": [],
1097            "always_allowed_actions": [],
1098            "total_tool_calls": 7,
1099            "run_state": {
1100                "turn_tool_calls": 4,
1101                "run_has_tool_calls": true,
1102                "reasoning_only_strikes": 0,
1103                "empty_response_strikes": 0,
1104                "nudge_count": 0
1105            }
1106        }"#;
1107        let session: AgentSession = serde_json::from_str(json).unwrap();
1108        assert_eq!(session.run_state.total_actions, 7);
1109        assert_eq!(session.run_state.turn_actions, 4);
1110
1111        let rewritten = serde_json::to_string(&session).unwrap();
1112        assert!(
1113            !rewritten.contains("total_tool_calls"),
1114            "new writes keep the total inside run_state: {rewritten}"
1115        );
1116    }
1117
1118    #[test]
1119    fn push_assistant_tool_calls_validates_json_args() {
1120        let mut s = make_session();
1121
1122        // Valid JSON args should pass through unchanged
1123        let valid_args = r#"{"path": "src/main.rs", "content": "fn main() {}"}"#;
1124        s.push_assistant_tool_calls(
1125            &[("id1".into(), "write_file".into(), valid_args.into())],
1126            None,
1127            None,
1128        );
1129        if let ChatMessage::Assistant {
1130            tool_calls: Some(ref tc),
1131            ..
1132        } = s.chat_messages[0]
1133        {
1134            assert_eq!(tc[0].arguments, valid_args);
1135        } else {
1136            panic!("expected Assistant message with tool_calls");
1137        }
1138
1139        // Truncated (invalid JSON) args must be sanitized to an empty object,
1140        // NOT wrapped in a descriptive error object. Two reasons:
1141        //   1. "{}" is valid JSON, so the next request is never rejected 400.
1142        //   2. a rich `{error, original_args_preview, message}` object in
1143        //      assistant history is an imitation vector — the model replays it
1144        //      verbatim as the next call's arguments, and because it parses as
1145        //      valid JSON it slips past the react truncation guard and resurfaces
1146        //      as a downstream ToolArgsInvalid. The truncation explanation
1147        //      belongs in the tool_result, not the assistant arguments.
1148        let truncated_args = r#"{"path": "src/ui/markdown.rs", "content": "#;
1149        s.push_assistant_tool_calls(
1150            &[("id2".into(), "write_file".into(), truncated_args.into())],
1151            None,
1152            None,
1153        );
1154        if let ChatMessage::Assistant {
1155            tool_calls: Some(ref tc),
1156            ..
1157        } = s.chat_messages[1]
1158        {
1159            assert_eq!(tc[0].arguments, "{}");
1160            assert!(
1161                !tc[0].arguments.contains("tool_call_arguments_truncated"),
1162                "assistant arguments must not carry the poison wrapper object"
1163            );
1164        } else {
1165            panic!("expected Assistant message with tool_calls");
1166        }
1167    }
1168
1169    #[test]
1170    fn push_assistant_tool_calls_truncated_multibyte_no_panic() {
1171        // Bug-2: Invalid JSON args with multi-byte UTF-8 chars near byte 200
1172        // cause a panic at char boundary when slicing &args[..args.len().min(200)].
1173        let mut s = make_session();
1174
1175        // Build invalid JSON with CJK chars that straddle the 200-byte boundary.
1176        // "あ" = 3 bytes in UTF-8. Repeating ~70 times = ~210 bytes, then add invalid suffix.
1177        let mut bad_args = "あ".repeat(70); // 70 * 3 = 210 bytes
1178        bad_args.push_str("truncated"); // makes it invalid JSON
1179
1180        // This must NOT panic. Invalid args are sanitized to "{}" (a fixed
1181        // literal), so no slicing of the multibyte string happens at all.
1182        s.push_assistant_tool_calls(&[("id1".into(), "tool".into(), bad_args)], None, None);
1183
1184        if let ChatMessage::Assistant {
1185            tool_calls: Some(ref tc),
1186            ..
1187        } = s.chat_messages[0]
1188        {
1189            assert_eq!(tc[0].arguments, "{}");
1190        } else {
1191            panic!("expected Assistant message with tool_calls");
1192        }
1193    }
1194
1195    #[test]
1196    fn push_assistant_tool_calls_then_tool_result_matches_anthropic_protocol() {
1197        // Regression test for: when LLM response is truncated (finish_reason=max_tokens),
1198        // the code must push assistant message WITH tool_use blocks (not plain text)
1199        // so that subsequent tool_result messages can match the tool_use_id.
1200        // This is required by Anthropic protocol.
1201        let mut s = make_session();
1202
1203        // Simulate truncated tool call response
1204        let tool_calls = vec![
1205            (
1206                "call_00_VJtlnKha0ZZ2Yo8t5ysQ8883".to_string(),
1207                "write_file".to_string(),
1208                "{}".to_string(),
1209            ),
1210            (
1211                "call_01_abc123".to_string(),
1212                "bash".to_string(),
1213                r#"{"command": "ls"}"#.to_string(),
1214            ),
1215        ];
1216
1217        // Push assistant message with tool_calls (as the fix does)
1218        s.push_assistant_tool_calls(
1219            &tool_calls,
1220            Some("thinking...".to_string()),
1221            Some("I'll help you".to_string()),
1222        );
1223
1224        // Push tool results for each tool call
1225        for (tc_id, _, _) in &tool_calls {
1226            s.push_tool_result(
1227                tc_id,
1228                "Tool call was not executed: the response hit the output token limit.",
1229            );
1230        }
1231
1232        // Verify the message sequence is valid
1233        // 1. Assistant message should have tool_calls
1234        if let ChatMessage::Assistant {
1235            tool_calls: Some(ref tc),
1236            ..
1237        } = s.chat_messages[0]
1238        {
1239            assert_eq!(tc.len(), 2);
1240            assert_eq!(tc[0].id, "call_00_VJtlnKha0ZZ2Yo8t5ysQ8883");
1241            assert_eq!(tc[0].name, "write_file");
1242            assert_eq!(tc[1].id, "call_01_abc123");
1243            assert_eq!(tc[1].name, "bash");
1244        } else {
1245            panic!("expected Assistant message with tool_calls");
1246        }
1247
1248        // 2. Tool result messages should have matching tool_use_id
1249        if let ChatMessage::Tool { tool_call_id, .. } = &s.chat_messages[1] {
1250            assert_eq!(tool_call_id, "call_00_VJtlnKha0ZZ2Yo8t5ysQ8883");
1251        } else {
1252            panic!("expected Tool message for first tool call");
1253        }
1254
1255        if let ChatMessage::Tool { tool_call_id, .. } = &s.chat_messages[2] {
1256            assert_eq!(tool_call_id, "call_01_abc123");
1257        } else {
1258            panic!("expected Tool message for second tool call");
1259        }
1260
1261        // 3. Validate message sequence (this would catch the bug)
1262        assert!(
1263            validate_message_sequence(&s.chat_messages).is_ok(),
1264            "message sequence should be valid with matching tool_use and tool_result"
1265        );
1266    }
1267}
1268
1269#[cfg(test)]
1270mod proptest_tests {
1271    use super::*;
1272    use proptest::prelude::*;
1273
1274    proptest! {
1275        // ── push_assistant_tool_calls property tests ────────────────────────
1276
1277        #[test]
1278        fn push_assistant_tool_calls_valid_json_unchanged(args in r"\{[^{}]{0,200}\}") {
1279            // Only test strings that are actually valid JSON objects
1280            if serde_json::from_str::<serde_json::Value>(&args).is_err() {
1281                return Ok(());
1282            }
1283            let mut s = make_session();
1284            s.push_assistant_tool_calls(
1285                &[("id".into(), "tool".into(), args.clone())],
1286                None,
1287                None,
1288            );
1289            if let ChatMessage::Assistant { tool_calls: Some(ref tc), .. } = s.chat_messages()[0] {
1290                assert_eq!(tc[0].arguments, args);
1291            } else {
1292                panic!("expected Assistant with tool_calls");
1293            }
1294        }
1295
1296        #[test]
1297        fn push_assistant_tool_calls_invalid_json_sanitized_to_empty(
1298            bad_args in "[a-z\u{4e00}-\u{9fff}]{0,300}"
1299        ) {
1300            // Skip if it happens to be valid JSON
1301            if serde_json::from_str::<serde_json::Value>(&bad_args).is_ok() {
1302                return Ok(());
1303            }
1304            let mut s = make_session();
1305            s.push_assistant_tool_calls(
1306                &[("id".into(), "tool".into(), bad_args)],
1307                None,
1308                None,
1309            );
1310            if let ChatMessage::Assistant { tool_calls: Some(ref tc), .. } = s.chat_messages()[0] {
1311                // Must be valid JSON (no 400 on replay) AND carry no poison
1312                // wrapper the model could echo back as arguments.
1313                serde_json::from_str::<serde_json::Value>(&tc[0].arguments)
1314                    .expect("sanitized args must be valid JSON");
1315                assert_eq!(tc[0].arguments, "{}");
1316            } else {
1317                panic!("expected Assistant with tool_calls");
1318            }
1319        }
1320
1321        #[test]
1322        fn preview_args_escapes_and_caps_at_max_chars(payload in "[a-z\u{4e00}-\u{9fff}\n\t]{0,400}") {
1323            // args_preview for the truncation WARN: truncate by characters (not bytes),
1324            // escape control characters in debug form (each input character expands to
1325            // at most 2 characters), with length capped at min(80, len) * 2 + the paired quotes.
1326            let preview = AgentSession::preview_args(&payload, 80);
1327            let expected_cap = 2 * payload.chars().count().min(80) + 2;
1328            assert!(
1329                preview.chars().count() <= expected_cap,
1330                "preview must cap at escaped length plus quotes: {preview}"
1331            );
1332            if payload.contains('\n') || payload.contains('\t') {
1333                assert!(
1334                    preview.contains("\\n") || preview.contains("\\t"),
1335                    "control chars must be escaped: {preview}"
1336                );
1337            }
1338            if payload.chars().count() <= 80 && !payload.contains('\n') && !payload.contains('\t') {
1339                assert_eq!(preview, format!("{payload:?}"));
1340            }
1341        }
1342
1343        // ── trim_oldest_turns property tests ────────────────────────────────
1344
1345        #[test]
1346        fn trim_oldest_turns_never_exceeds_max(turns in 1usize..20, max in 1usize..20) {
1347            let mut s = make_session();
1348            for i in 0..turns {
1349                s.push_message(MessageRole::User, format!("u{}", i));
1350                s.push_message(MessageRole::Assistant, format!("a{}", i));
1351            }
1352            s.trim_oldest_turns(max);
1353            assert!(s.turn_count() <= max || turns <= max);
1354        }
1355
1356        // ── validate_message_sequence property tests ────────────────────────
1357
1358        #[test]
1359        fn validate_simple_user_assistant_always_passes(count in 1usize..20) {
1360            let mut msgs = Vec::new();
1361            for i in 0..count {
1362                msgs.push(ChatMessage::user(format!("msg{}", i)));
1363                msgs.push(ChatMessage::assistant(format!("reply{}", i)));
1364            }
1365            assert!(validate_message_sequence(&msgs).is_ok());
1366        }
1367    }
1368}