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 should_check_topic_from_messages(turns: &[ConversationTurn], _min_turns: usize) -> bool {
136 if turns.len() < 4 {
138 return false;
139 }
140
141 let recent = &turns[turns.len() - 2..];
143 let previous = &turns[turns.len() - 4..turns.len() - 2];
144
145 let avg_recent =
146 recent.iter().map(|t| word_count(&t.user)).sum::<usize>() as f64 / recent.len() as f64;
147 let avg_prev =
148 previous.iter().map(|t| word_count(&t.user)).sum::<usize>() as f64 / previous.len() as f64;
149
150 let ratio = avg_recent / avg_prev.max(1.0);
151 !(0.5..=2.0).contains(&ratio)
152 }
153
154 pub fn pattern_changed(&self) -> bool {
159 if self.turns.len() < 4 {
160 return false;
161 }
162
163 let all_turns: Vec<_> = self.turns.iter().collect();
164
165 let recent = &all_turns[all_turns.len() - 2..];
167 let previous = &all_turns[all_turns.len() - 4..all_turns.len() - 2];
168
169 let avg_word_count_recent =
170 recent.iter().map(|t| word_count(&t.user)).sum::<usize>() as f64 / recent.len() as f64;
171
172 let avg_word_count_prev = previous.iter().map(|t| word_count(&t.user)).sum::<usize>()
173 as f64
174 / previous.len() as f64;
175
176 let ratio = avg_word_count_recent / avg_word_count_prev.max(1.0);
178 if !(0.5..=2.0).contains(&ratio) {
179 return true;
180 }
181
182 let domain_shift_keywords = [
184 ("code", "food"),
185 ("rust", "요리"),
186 ("bug", "저녁"),
187 ("file", "운동"),
188 ("import", "영화"),
189 ("commit", "음식"),
190 ("function", "게임"),
191 ("Cargo", "장보기"),
192 ];
193
194 let recent_text = recent
195 .iter()
196 .map(|t| t.user.to_lowercase())
197 .collect::<String>();
198 let prev_text = previous
199 .iter()
200 .map(|t| t.user.to_lowercase())
201 .collect::<String>();
202
203 for (prev_kw, recent_kw) in domain_shift_keywords {
204 let has_prev = prev_text.contains(prev_kw);
205 let has_recent = recent_text.contains(recent_kw);
206 if has_prev && !has_recent {
207 return true;
210 }
211 }
212
213 false
214 }
215
216 pub fn space_changed(&self) -> bool {
218 if self.turns.len() < 2 {
219 return false;
220 }
221
222 let all_turns: Vec<_> = self.turns.iter().collect();
223 let last = &all_turns[all_turns.len() - 1];
224 let prev = &all_turns[all_turns.len() - 2];
225
226 last.space_id != prev.space_id
227 }
228
229 pub fn last_space_id(&self) -> Option<SpaceId> {
231 self.last_space_id
232 }
233
234 pub fn clear(&mut self) {
236 self.turns.clear();
237 self.turns_since_topic_check = 0;
238 }
239}
240
241fn word_count(s: &str) -> usize {
243 s.split_whitespace().count()
244}
245
246fn truncate_response(response: &str, max_len: usize) -> String {
248 if response.len() <= max_len {
249 response.to_string()
250 } else {
251 let end = response.char_indices()
253 .take_while(|(idx, _)| *idx < max_len)
254 .last()
255 .map(|(idx, c)| idx + c.len_utf8())
256 .unwrap_or(0);
257 if end == 0 {
258 "...".to_string()
259 } else {
260 format!("{}...", &response[..end])
261 }
262 }
263}
264
265#[cfg(test)]
266mod tests {
267 use super::*;
268
269 #[test]
270 fn test_push_user_and_agent() {
271 let mut buf = ConversationBuffer::new(10);
272 assert!(buf.is_empty());
273
274 buf.push_user("Hello, how are you?");
275 assert_eq!(buf.len(), 1);
276 assert_eq!(buf.turns[0].user, "Hello, how are you?");
277 assert!(buf.turns[0].agent.is_empty());
278
279 buf.push_agent("I'm doing well!", &SpaceId::nil());
280 assert_eq!(buf.turns[0].agent, "I'm doing well!");
281 }
282
283 #[test]
284 fn test_max_capacity() {
285 let mut buf = ConversationBuffer::new(3);
286 let space = SpaceId::nil();
287
288 buf.push_user("msg1");
289 buf.push_agent("r1", &space);
290 buf.push_user("msg2");
291 buf.push_agent("r2", &space);
292 buf.push_user("msg3");
293 buf.push_agent("r3", &space);
294 buf.push_user("msg4");
295 buf.push_agent("r4", &space);
296 buf.push_user("msg5");
297 buf.push_agent("r5", &space);
298
299 assert_eq!(buf.len(), 3);
301 assert_eq!(buf.recent(1)[0].user, "msg5");
302 }
303
304 #[test]
305 fn test_should_check_topic() {
306 let mut buf = ConversationBuffer::new(10);
307 assert!(!buf.should_check_topic(3));
308
309 for _ in 0..3 {
310 buf.push_user("test");
311 buf.mark_topic_checked();
312 }
313 assert!(!buf.should_check_topic(3));
315 }
316
317 #[test]
318 fn test_pattern_changed_word_count() {
319 let mut buf = ConversationBuffer::new(10);
320 let space = SpaceId::nil();
321
322 for _ in 0..3 {
324 buf.push_user("hi");
325 buf.push_agent("hi", &space);
326 }
327
328 assert!(!buf.pattern_changed());
329
330 buf.push_user("This is a very long message that contains many many many many many words to trigger the pattern detection");
332 buf.push_agent("ok", &space);
333
334 assert!(buf.pattern_changed());
335 }
336
337 #[test]
338 fn test_truncate_response() {
339 let short = "Hello";
340 assert_eq!(truncate_response(short, 10), "Hello");
341
342 let long = "This is a very long response";
343 let truncated = truncate_response(long, 10);
344 assert_eq!(truncated.len(), 13); assert!(truncated.ends_with("..."));
346 }
347
348 #[test]
349 fn test_recent_turns() {
350 let mut buf = ConversationBuffer::new(10);
351 let space = SpaceId::nil();
352
353 for i in 0..5 {
354 buf.push_user(&format!("msg{}", i));
355 buf.push_agent(&format!("resp{}", i), &space);
356 }
357
358 let recent = buf.recent(3);
359 assert_eq!(recent.len(), 3);
360 assert_eq!(recent[0].user, "msg4"); assert_eq!(recent[2].user, "msg2");
362 }
363}