ricecoder_sessions/history.rs
1//! History management for session conversations
2
3use crate::models::Message;
4
5/// Manages conversation history for a session
6#[derive(Debug, Clone)]
7pub struct HistoryManager {
8 /// Messages in the history, ordered by timestamp
9 messages: Vec<Message>,
10 /// Maximum number of messages to keep in history (None = unlimited)
11 max_size: Option<usize>,
12}
13
14impl HistoryManager {
15 /// Create a new history manager
16 pub fn new() -> Self {
17 Self {
18 messages: Vec::new(),
19 max_size: None,
20 }
21 }
22
23 /// Create a new history manager with a maximum size limit
24 pub fn with_max_size(max_size: usize) -> Self {
25 Self {
26 messages: Vec::new(),
27 max_size: Some(max_size),
28 }
29 }
30
31 /// Add a message to history
32 ///
33 /// Messages are automatically ordered by timestamp. If the history exceeds
34 /// the maximum size, the oldest message is removed.
35 pub fn add_message(&mut self, message: Message) {
36 self.messages.push(message);
37
38 // Sort by timestamp to maintain ordering
39 self.messages.sort_by_key(|m| m.timestamp);
40
41 // Enforce size limit if set
42 if let Some(max) = self.max_size {
43 if self.messages.len() > max {
44 // Remove oldest messages to stay within limit
45 let remove_count = self.messages.len() - max;
46 self.messages.drain(0..remove_count);
47 }
48 }
49 }
50
51 /// Get the most recent N messages
52 ///
53 /// Returns messages in chronological order (oldest first).
54 pub fn get_recent_messages(&self, count: usize) -> Vec<Message> {
55 if count == 0 {
56 return Vec::new();
57 }
58
59 let start = if self.messages.len() > count {
60 self.messages.len() - count
61 } else {
62 0
63 };
64
65 self.messages[start..].to_vec()
66 }
67
68 /// Search history by content
69 ///
70 /// Returns all messages whose content contains the query string (case-insensitive).
71 /// Results are returned in chronological order.
72 pub fn search_by_content(&self, query: &str) -> Vec<Message> {
73 let query_lower = query.to_lowercase();
74 self.messages
75 .iter()
76 .filter(|m| m.content.to_lowercase().contains(&query_lower))
77 .cloned()
78 .collect()
79 }
80
81 /// Get all messages in the history
82 ///
83 /// Returns messages in chronological order (oldest first).
84 pub fn get_all_messages(&self) -> Vec<Message> {
85 self.messages.clone()
86 }
87
88 /// Get the number of messages in the history
89 pub fn message_count(&self) -> usize {
90 self.messages.len()
91 }
92
93 /// Clear all messages from the history
94 pub fn clear(&mut self) {
95 self.messages.clear();
96 }
97
98 /// Get the maximum size limit (if set)
99 pub fn max_size(&self) -> Option<usize> {
100 self.max_size
101 }
102}
103
104impl Default for HistoryManager {
105 fn default() -> Self {
106 Self::new()
107 }
108}