oxios_kernel/space/
conversation_buffer.rs1use chrono::{DateTime, Utc};
8use serde::{Deserialize, Serialize};
9use std::collections::VecDeque;
10
11use super::SpaceId;
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct ConversationTurn {
16 pub user: String,
18 pub agent: String,
20 pub space_id: SpaceId,
22 pub timestamp: DateTime<Utc>,
24}
25
26#[derive(Debug, Clone)]
28pub struct ConversationBuffer {
29 turns: VecDeque<ConversationTurn>,
31 max_turns: usize,
33 turns_since_topic_check: usize,
35 last_space_id: Option<SpaceId>,
37}
38
39impl Default for ConversationBuffer {
40 fn default() -> Self {
41 Self::new(50)
42 }
43}
44
45impl ConversationBuffer {
46 pub fn new(max_turns: usize) -> Self {
48 Self {
49 turns: VecDeque::with_capacity(max_turns),
50 max_turns,
51 turns_since_topic_check: 0,
52 last_space_id: None,
53 }
54 }
55
56 pub fn push_user(&mut self, message: &str) {
58 let turn = ConversationTurn {
59 user: message.to_string(),
60 agent: String::new(), space_id: SpaceId::nil(), timestamp: Utc::now(),
63 };
64
65 if let Some(last) = self.turns.back_mut() {
67 if last.agent.is_empty() && last.space_id == SpaceId::nil() {
68 last.user = message.to_string();
69 last.timestamp = Utc::now();
70 return;
71 }
72 }
73
74 self.turns.push_back(turn);
75
76 while self.turns.len() > self.max_turns {
78 self.turns.pop_front();
79 }
80 }
81
82 pub fn push_agent(&mut self, response: &str, space_id: &SpaceId) {
84 if let Some(last) = self.turns.back_mut() {
85 last.agent = truncate_response(response, 200);
86 last.space_id = *space_id;
87 self.last_space_id = Some(*space_id);
88 }
89 }
90
91 pub fn recent(&self, n: usize) -> Vec<&ConversationTurn> {
93 self.turns.iter().rev().take(n).collect()
94 }
95
96 pub fn turns(&self) -> std::collections::VecDeque<ConversationTurn> {
98 self.turns.clone()
99 }
100
101 pub fn len(&self) -> usize {
103 self.turns.len()
104 }
105
106 pub fn is_empty(&self) -> bool {
108 self.turns.is_empty()
109 }
110
111 pub fn should_check_topic(&self, min_turns: usize) -> bool {
116 self.turns_since_topic_check >= min_turns || self.pattern_changed()
117 }
118
119 pub fn mark_topic_checked(&mut self) {
121 self.turns_since_topic_check = 0;
122 }
123
124 pub fn record_turn(&mut self, min_turns: usize) -> bool {
126 self.turns_since_topic_check += 1;
127 self.should_check_topic(min_turns)
128 }
129
130 pub fn pattern_changed(&self) -> bool {
135 if self.turns.len() < 4 {
136 return false;
137 }
138
139 let all_turns: Vec<_> = self.turns.iter().collect();
140
141 let recent = &all_turns[all_turns.len() - 2..];
143 let previous = &all_turns[all_turns.len() - 4..all_turns.len() - 2];
144
145 let avg_word_count_recent =
146 recent.iter().map(|t| word_count(&t.user)).sum::<usize>() as f64 / recent.len() as f64;
147
148 let avg_word_count_prev = previous.iter().map(|t| word_count(&t.user)).sum::<usize>()
149 as f64
150 / previous.len() as f64;
151
152 let ratio = avg_word_count_recent / avg_word_count_prev.max(1.0);
154 if !(0.5..=2.0).contains(&ratio) {
155 return true;
156 }
157
158 let domain_shift_keywords = [
160 ("code", "food"),
161 ("rust", "요리"),
162 ("bug", "저녁"),
163 ("file", "운동"),
164 ("import", "영화"),
165 ("commit", "음식"),
166 ("function", "게임"),
167 ("Cargo", "장보기"),
168 ];
169
170 let recent_text = recent
171 .iter()
172 .map(|t| t.user.to_lowercase())
173 .collect::<String>();
174 let prev_text = previous
175 .iter()
176 .map(|t| t.user.to_lowercase())
177 .collect::<String>();
178
179 for (prev_kw, recent_kw) in domain_shift_keywords {
180 let has_prev = prev_text.contains(prev_kw);
181 let has_recent = recent_text.contains(recent_kw);
182 if has_prev && !has_recent {
183 return true;
186 }
187 }
188
189 false
190 }
191
192 pub fn space_changed(&self) -> bool {
194 if self.turns.len() < 2 {
195 return false;
196 }
197
198 let all_turns: Vec<_> = self.turns.iter().collect();
199 let last = &all_turns[all_turns.len() - 1];
200 let prev = &all_turns[all_turns.len() - 2];
201
202 last.space_id != prev.space_id
203 }
204
205 pub fn last_space_id(&self) -> Option<SpaceId> {
207 self.last_space_id
208 }
209
210 pub fn clear(&mut self) {
212 self.turns.clear();
213 self.turns_since_topic_check = 0;
214 }
215}
216
217fn word_count(s: &str) -> usize {
219 s.split_whitespace().count()
220}
221
222fn truncate_response(response: &str, max_len: usize) -> String {
224 if response.len() <= max_len {
225 response.to_string()
226 } else {
227 format!("{}...", &response[..max_len])
228 }
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234
235 #[test]
236 fn test_push_user_and_agent() {
237 let mut buf = ConversationBuffer::new(10);
238 assert!(buf.is_empty());
239
240 buf.push_user("Hello, how are you?");
241 assert_eq!(buf.len(), 1);
242 assert_eq!(buf.turns[0].user, "Hello, how are you?");
243 assert!(buf.turns[0].agent.is_empty());
244
245 buf.push_agent("I'm doing well!", &SpaceId::nil());
246 assert_eq!(buf.turns[0].agent, "I'm doing well!");
247 }
248
249 #[test]
250 fn test_max_capacity() {
251 let mut buf = ConversationBuffer::new(3);
252 let space = SpaceId::nil();
253
254 buf.push_user("msg1");
255 buf.push_agent("r1", &space);
256 buf.push_user("msg2");
257 buf.push_agent("r2", &space);
258 buf.push_user("msg3");
259 buf.push_agent("r3", &space);
260 buf.push_user("msg4");
261 buf.push_agent("r4", &space);
262 buf.push_user("msg5");
263 buf.push_agent("r5", &space);
264
265 assert_eq!(buf.len(), 3);
267 assert_eq!(buf.recent(1)[0].user, "msg5");
268 }
269
270 #[test]
271 fn test_should_check_topic() {
272 let mut buf = ConversationBuffer::new(10);
273 assert!(!buf.should_check_topic(3));
274
275 for _ in 0..3 {
276 buf.push_user("test");
277 buf.mark_topic_checked();
278 }
279 assert!(!buf.should_check_topic(3));
281 }
282
283 #[test]
284 fn test_pattern_changed_word_count() {
285 let mut buf = ConversationBuffer::new(10);
286 let space = SpaceId::nil();
287
288 for _ in 0..3 {
290 buf.push_user("hi");
291 buf.push_agent("hi", &space);
292 }
293
294 assert!(!buf.pattern_changed());
295
296 buf.push_user("This is a very long message that contains many many many many many words to trigger the pattern detection");
298 buf.push_agent("ok", &space);
299
300 assert!(buf.pattern_changed());
301 }
302
303 #[test]
304 fn test_truncate_response() {
305 let short = "Hello";
306 assert_eq!(truncate_response(short, 10), "Hello");
307
308 let long = "This is a very long response";
309 let truncated = truncate_response(long, 10);
310 assert_eq!(truncated.len(), 13); assert!(truncated.ends_with("..."));
312 }
313
314 #[test]
315 fn test_recent_turns() {
316 let mut buf = ConversationBuffer::new(10);
317 let space = SpaceId::nil();
318
319 for i in 0..5 {
320 buf.push_user(&format!("msg{}", i));
321 buf.push_agent(&format!("resp{}", i), &space);
322 }
323
324 let recent = buf.recent(3);
325 assert_eq!(recent.len(), 3);
326 assert_eq!(recent[0].user, "msg4"); assert_eq!(recent[2].user, "msg2");
328 }
329}