Skip to main content

codive_core/
session.rs

1//! Session management for the Agent system
2//!
3//! This module defines types for managing conversation sessions.
4//! A session represents an ongoing conversation between a user and the agent.
5//!
6//! # Architecture
7//!
8//! ```text
9//! Session
10//!    ├── id (unique identifier)
11//!    ├── title (display name)
12//!    ├── messages[] (conversation history)
13//!    ├── status (active/completed/error)
14//!    └── timestamps (created/updated)
15//! ```
16//!
17//! # Example
18//!
19//! ```rust
20//! use codive_core::session::Session;
21//! use codive_core::Message;
22//!
23//! let mut session = Session::new();
24//! session.add_message(Message::user("Hello!"));
25//! session.add_message(Message::assistant_text("Hi there!"));
26//!
27//! assert_eq!(session.message_count(), 2);
28//! ```
29
30use crate::message::Message;
31use chrono::{DateTime, Utc};
32use serde::{Deserialize, Serialize};
33use std::sync::atomic::{AtomicU64, Ordering};
34
35// ============================================================================
36// SessionId
37// ============================================================================
38
39/// A unique identifier for a session
40pub type SessionId = String;
41
42/// Generate a unique session ID
43fn generate_session_id() -> SessionId {
44    static COUNTER: AtomicU64 = AtomicU64::new(0);
45    let timestamp = Utc::now().timestamp_millis() as u64;
46    let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
47    format!("sess_{}_{}", timestamp, counter)
48}
49
50// ============================================================================
51// SessionStatus
52// ============================================================================
53
54/// The current status of a session
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum SessionStatus {
58    /// Session is active and can accept messages
59    Active,
60    /// Session is currently processing a request
61    Processing,
62    /// Session completed normally
63    Completed,
64    /// Session ended due to an error
65    Error,
66}
67
68impl Default for SessionStatus {
69    fn default() -> Self {
70        Self::Active
71    }
72}
73
74impl SessionStatus {
75    /// Check if the session can accept new messages
76    pub fn can_accept_messages(&self) -> bool {
77        matches!(self, Self::Active)
78    }
79
80    /// Check if the session is in a terminal state
81    pub fn is_terminal(&self) -> bool {
82        matches!(self, Self::Completed | Self::Error)
83    }
84}
85
86// ============================================================================
87// Session
88// ============================================================================
89
90/// A conversation session between user and agent
91///
92/// Sessions track the full conversation history and metadata.
93/// They are the primary unit of state in the agent system.
94///
95/// # Ownership
96///
97/// The session owns its messages (`Vec<Message>`). When you add a message,
98/// ownership transfers to the session. This is Rust's ownership model in action.
99///
100/// # Mutability
101///
102/// Methods that modify the session take `&mut self`:
103/// - `add_message()` - adds to the messages vec
104/// - `set_title()` - changes the title
105///
106/// Methods that only read take `&self`:
107/// - `last_message()` - returns a reference
108/// - `message_count()` - returns a count
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct Session {
111    /// Unique identifier for this session
112    pub id: SessionId,
113
114    /// Human-readable title (can be auto-generated)
115    pub title: String,
116
117    /// Current status of the session
118    pub status: SessionStatus,
119
120    /// The conversation messages
121    pub messages: Vec<Message>,
122
123    /// When the session was created
124    pub created_at: DateTime<Utc>,
125
126    /// When the session was last modified
127    pub updated_at: DateTime<Utc>,
128
129    /// Optional metadata (for extensions)
130    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
131    pub metadata: serde_json::Map<String, serde_json::Value>,
132}
133
134impl Session {
135    /// Create a new empty session
136    pub fn new() -> Self {
137        let now = Utc::now();
138        Self {
139            id: generate_session_id(),
140            title: "New Session".to_string(),
141            status: SessionStatus::Active,
142            messages: Vec::new(),
143            created_at: now,
144            updated_at: now,
145            metadata: serde_json::Map::new(),
146        }
147    }
148
149    /// Create a session with a specific ID (for restoration)
150    pub fn with_id(id: impl Into<String>) -> Self {
151        let now = Utc::now();
152        Self {
153            id: id.into(),
154            title: "New Session".to_string(),
155            status: SessionStatus::Active,
156            messages: Vec::new(),
157            created_at: now,
158            updated_at: now,
159            metadata: serde_json::Map::new(),
160        }
161    }
162
163    /// Set the session title
164    pub fn with_title(mut self, title: impl Into<String>) -> Self {
165        self.title = title.into();
166        self
167    }
168
169    /// Add a message to the session
170    ///
171    /// This transfers ownership of the message to the session.
172    /// The session's `updated_at` timestamp is also updated.
173    pub fn add_message(&mut self, message: Message) {
174        self.messages.push(message);
175        self.updated_at = Utc::now();
176    }
177
178    /// Add multiple messages at once
179    pub fn add_messages(&mut self, messages: impl IntoIterator<Item = Message>) {
180        self.messages.extend(messages);
181        self.updated_at = Utc::now();
182    }
183
184    /// Get the last message, if any
185    pub fn last_message(&self) -> Option<&Message> {
186        self.messages.last()
187    }
188
189    /// Get the last N messages
190    pub fn last_n_messages(&self, n: usize) -> &[Message] {
191        let len = self.messages.len();
192        if n >= len {
193            &self.messages
194        } else {
195            &self.messages[len - n..]
196        }
197    }
198
199    /// Get all messages from a specific role
200    pub fn messages_by_role(&self, role: crate::message::Role) -> Vec<&Message> {
201        self.messages.iter().filter(|m| m.role == role).collect()
202    }
203
204    /// Get the number of messages
205    pub fn message_count(&self) -> usize {
206        self.messages.len()
207    }
208
209    /// Check if the session is empty (no messages)
210    pub fn is_empty(&self) -> bool {
211        self.messages.is_empty()
212    }
213
214    /// Set the session title
215    pub fn set_title(&mut self, title: impl Into<String>) {
216        self.title = title.into();
217        self.updated_at = Utc::now();
218    }
219
220    /// Set the session status
221    pub fn set_status(&mut self, status: SessionStatus) {
222        self.status = status;
223        self.updated_at = Utc::now();
224    }
225
226    /// Mark session as processing
227    pub fn start_processing(&mut self) {
228        self.set_status(SessionStatus::Processing);
229    }
230
231    /// Mark session as active (done processing)
232    pub fn finish_processing(&mut self) {
233        self.set_status(SessionStatus::Active);
234    }
235
236    /// Mark session as completed
237    pub fn complete(&mut self) {
238        self.set_status(SessionStatus::Completed);
239    }
240
241    /// Mark session as errored
242    pub fn mark_error(&mut self) {
243        self.set_status(SessionStatus::Error);
244    }
245
246    /// Check if the session can accept new messages
247    pub fn can_accept_messages(&self) -> bool {
248        self.status.can_accept_messages()
249    }
250
251    /// Add metadata to the session
252    pub fn set_metadata(&mut self, key: impl Into<String>, value: serde_json::Value) {
253        self.metadata.insert(key.into(), value);
254        self.updated_at = Utc::now();
255    }
256
257    /// Get metadata value
258    pub fn get_metadata(&self, key: &str) -> Option<&serde_json::Value> {
259        self.metadata.get(key)
260    }
261
262    /// Generate a title from the first user message
263    ///
264    /// Useful for auto-generating session titles from conversation content.
265    pub fn auto_title(&mut self) {
266        if let Some(first_user_msg) = self.messages.iter().find(|m| m.is_user()) {
267            let text = first_user_msg.text_content();
268            // Take first 50 chars, trim to word boundary
269            let title: String = text.chars().take(50).collect();
270            let title = title
271                .rsplit_once(' ')
272                .map(|(s, _)| s)
273                .unwrap_or(&title)
274                .trim();
275            if !title.is_empty() {
276                self.title = if title.len() < text.len() {
277                    format!("{}...", title)
278                } else {
279                    title.to_string()
280                };
281                self.updated_at = Utc::now();
282            }
283        }
284    }
285
286    /// Get conversation duration
287    pub fn duration(&self) -> chrono::Duration {
288        self.updated_at - self.created_at
289    }
290}
291
292impl Default for Session {
293    fn default() -> Self {
294        Self::new()
295    }
296}
297
298// ============================================================================
299// SessionSummary
300// ============================================================================
301
302/// A lightweight summary of a session (for listings)
303///
304/// Used when you need to display a list of sessions without
305/// loading all messages.
306#[derive(Debug, Clone, Serialize, Deserialize)]
307pub struct SessionSummary {
308    /// Session ID
309    pub id: SessionId,
310    /// Session title
311    pub title: String,
312    /// Current status
313    pub status: SessionStatus,
314    /// Number of messages
315    pub message_count: usize,
316    /// When created
317    pub created_at: DateTime<Utc>,
318    /// When last updated
319    pub updated_at: DateTime<Utc>,
320}
321
322impl From<&Session> for SessionSummary {
323    fn from(session: &Session) -> Self {
324        Self {
325            id: session.id.clone(),
326            title: session.title.clone(),
327            status: session.status,
328            message_count: session.message_count(),
329            created_at: session.created_at,
330            updated_at: session.updated_at,
331        }
332    }
333}
334
335// ============================================================================
336// RUST CONCEPTS EXPLAINED (for learning)
337// ============================================================================
338//
339// 1. `Vec<T>` - Growable array
340//    - Like ArrayList in Java or std::vector in C++
341//    - Owns its elements (when Vec is dropped, elements are dropped)
342//    - `push()` adds to end, `last()` gets last element
343//
344// 2. `&self` vs `&mut self`
345//    - `&self` - immutable borrow, can only read
346//    - `&mut self` - mutable borrow, can modify
347//    - Rust enforces: many readers OR one writer (not both)
348//
349// 3. `Option<&Message>` return
350//    - `last_message()` returns reference to message owned by session
351//    - `Option` because the vec might be empty
352//    - Caller cannot outlive the session (borrow checker ensures this)
353//
354// 4. `chrono::DateTime<Utc>`
355//    - `DateTime` is generic over timezone
356//    - `Utc` is the UTC timezone type
357//    - `Utc::now()` gets current time
358//    - Built-in serde support with `features = ["serde"]`
359//
360// 5. Ownership transfer in `add_message`
361//    - Takes `message: Message` (not `&Message`)
362//    - Ownership moves from caller to session
363//    - Caller can't use the message after passing it
364//
365// 6. `impl Default`
366//    - Allows `Session::default()` as alternative to `Session::new()`
367//    - Required for some generic code
368//    - Convention: `new()` and `default()` should be equivalent
369//
370// 7. `&[Message]` return type
371//    - Slice - a view into a contiguous sequence
372//    - Doesn't own the data, just references it
373//    - More flexible than `&Vec<Message>`
374//
375// **📚 Read:**
376// - [Rust Book Ch 4 - Ownership](https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html)
377// - [Rust Book Ch 8.1 - Vectors](https://doc.rust-lang.org/book/ch08-01-vectors.html)
378
379// ============================================================================
380// Tests
381// ============================================================================
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386    use crate::message::Role;
387
388    #[test]
389    fn test_session_new() {
390        let session = Session::new();
391        assert!(session.id.starts_with("sess_"));
392        assert_eq!(session.title, "New Session");
393        assert_eq!(session.status, SessionStatus::Active);
394        assert!(session.messages.is_empty());
395    }
396
397    #[test]
398    fn test_session_with_id() {
399        let session = Session::with_id("custom_id");
400        assert_eq!(session.id, "custom_id");
401    }
402
403    #[test]
404    fn test_session_with_title() {
405        let session = Session::new().with_title("My Chat");
406        assert_eq!(session.title, "My Chat");
407    }
408
409    #[test]
410    fn test_add_message() {
411        let mut session = Session::new();
412        let initial_updated = session.updated_at;
413
414        // Small delay to ensure timestamp changes
415        std::thread::sleep(std::time::Duration::from_millis(1));
416
417        session.add_message(Message::user("Hello"));
418        assert_eq!(session.message_count(), 1);
419        assert!(session.updated_at > initial_updated);
420    }
421
422    #[test]
423    fn test_add_messages() {
424        let mut session = Session::new();
425        session.add_messages(vec![
426            Message::user("Hello"),
427            Message::assistant_text("Hi!"),
428            Message::user("How are you?"),
429        ]);
430        assert_eq!(session.message_count(), 3);
431    }
432
433    #[test]
434    fn test_last_message() {
435        let mut session = Session::new();
436        assert!(session.last_message().is_none());
437
438        session.add_message(Message::user("First"));
439        session.add_message(Message::user("Second"));
440
441        let last = session.last_message().unwrap();
442        assert_eq!(last.text_content(), "Second");
443    }
444
445    #[test]
446    fn test_last_n_messages() {
447        let mut session = Session::new();
448        session.add_messages(vec![
449            Message::user("1"),
450            Message::user("2"),
451            Message::user("3"),
452            Message::user("4"),
453        ]);
454
455        let last_2 = session.last_n_messages(2);
456        assert_eq!(last_2.len(), 2);
457        assert_eq!(last_2[0].text_content(), "3");
458        assert_eq!(last_2[1].text_content(), "4");
459
460        // Request more than available
461        let all = session.last_n_messages(10);
462        assert_eq!(all.len(), 4);
463    }
464
465    #[test]
466    fn test_messages_by_role() {
467        let mut session = Session::new();
468        session.add_messages(vec![
469            Message::user("User 1"),
470            Message::assistant_text("Assistant 1"),
471            Message::user("User 2"),
472            Message::assistant_text("Assistant 2"),
473        ]);
474
475        let user_msgs = session.messages_by_role(Role::User);
476        assert_eq!(user_msgs.len(), 2);
477
478        let assistant_msgs = session.messages_by_role(Role::Assistant);
479        assert_eq!(assistant_msgs.len(), 2);
480    }
481
482    #[test]
483    fn test_session_status() {
484        let mut session = Session::new();
485        assert!(session.can_accept_messages());
486
487        session.start_processing();
488        assert_eq!(session.status, SessionStatus::Processing);
489        assert!(!session.can_accept_messages());
490
491        session.finish_processing();
492        assert_eq!(session.status, SessionStatus::Active);
493        assert!(session.can_accept_messages());
494
495        session.complete();
496        assert_eq!(session.status, SessionStatus::Completed);
497        assert!(session.status.is_terminal());
498    }
499
500    #[test]
501    fn test_auto_title() {
502        let mut session = Session::new();
503        session.add_message(Message::user("How do I write a Rust function?"));
504        session.auto_title();
505        assert!(session.title.contains("Rust"));
506    }
507
508    #[test]
509    fn test_auto_title_long() {
510        let mut session = Session::new();
511        session.add_message(Message::user(
512            "This is a very long message that should be truncated when used as a title",
513        ));
514        session.auto_title();
515        assert!(session.title.len() <= 55); // 50 chars + "..."
516        assert!(session.title.ends_with("..."));
517    }
518
519    #[test]
520    fn test_metadata() {
521        let mut session = Session::new();
522        session.set_metadata("key", serde_json::json!("value"));
523        assert_eq!(
524            session.get_metadata("key"),
525            Some(&serde_json::json!("value"))
526        );
527        assert!(session.get_metadata("nonexistent").is_none());
528    }
529
530    #[test]
531    fn test_session_serialization() {
532        let mut session = Session::new().with_title("Test Session");
533        session.add_message(Message::user("Hello"));
534
535        let json = serde_json::to_string(&session).unwrap();
536        let restored: Session = serde_json::from_str(&json).unwrap();
537
538        assert_eq!(session.id, restored.id);
539        assert_eq!(session.title, restored.title);
540        assert_eq!(session.message_count(), restored.message_count());
541    }
542
543    #[test]
544    fn test_session_summary() {
545        let mut session = Session::new().with_title("My Session");
546        session.add_messages(vec![Message::user("1"), Message::user("2")]);
547
548        let summary = SessionSummary::from(&session);
549        assert_eq!(summary.id, session.id);
550        assert_eq!(summary.title, "My Session");
551        assert_eq!(summary.message_count, 2);
552    }
553
554    #[test]
555    fn test_session_id_uniqueness() {
556        let s1 = Session::new();
557        let s2 = Session::new();
558        assert_ne!(s1.id, s2.id);
559    }
560
561    #[test]
562    fn test_session_status_serialization() {
563        assert_eq!(
564            serde_json::to_string(&SessionStatus::Active).unwrap(),
565            "\"active\""
566        );
567        assert_eq!(
568            serde_json::to_string(&SessionStatus::Processing).unwrap(),
569            "\"processing\""
570        );
571    }
572}