Skip to main content

sprite/models/
session.rs

1//! Session and tmux profile data structures for the Sprite multi-agent workflow toolkit.
2
3use super::{ConflictResolution, LogLevel};
4use chrono::{DateTime, Utc};
5use serde::{Deserialize, Serialize};
6use std::path::PathBuf;
7
8/// Represents the tmux session that hosts all agent panes and provides supervision interface.
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct Session {
11    /// Unique session identifier
12    pub name: String,
13
14    /// Current session status
15    pub status: SessionStatus,
16
17    /// Tmux profile being used
18    pub profile: String,
19
20    /// Active profile configuration
21    pub profile_config: TmuxProfile,
22
23    /// Creation timestamp
24    pub created_at: DateTime<Utc>,
25
26    /// Last activity timestamp
27    pub last_activity: Option<DateTime<Utc>>,
28
29    /// Session-specific settings
30    pub settings: SessionSettings,
31}
32
33#[allow(dead_code)]
34impl Session {
35    /// Create a new session with basic configuration.
36    pub fn new(name: impl Into<String>, profile: TmuxProfile) -> Self {
37        let name_str = name.into();
38        Self {
39            name: name_str.clone(),
40            status: SessionStatus::Creating,
41            profile: profile.name.clone(),
42            profile_config: profile,
43            created_at: Utc::now(),
44            last_activity: None,
45            settings: SessionSettings::default(),
46        }
47    }
48
49    /// Update the session's last activity timestamp.
50    pub fn update_activity(&mut self) {
51        self.last_activity = Some(Utc::now());
52    }
53
54    /// Check if the session is currently active.
55    pub fn is_active(&self) -> bool {
56        matches!(self.status, SessionStatus::Active | SessionStatus::Detached)
57    }
58
59    /// Check if the session is in an error state.
60    pub fn has_error(&self) -> bool {
61        matches!(self.status, SessionStatus::Error(_))
62    }
63
64    /// Get the error message if the session is in an error state.
65    pub fn error_message(&self) -> Option<&str> {
66        match &self.status {
67            SessionStatus::Error(msg) => Some(msg),
68            _ => None,
69        }
70    }
71
72    /// Get the duration since session creation.
73    pub fn duration(&self) -> chrono::Duration {
74        Utc::now() - self.created_at
75    }
76
77    /// Validate the session configuration.
78    pub fn validate(&self) -> Result<(), String> {
79        if self.name.is_empty() {
80            return Err("Session name cannot be empty".to_string());
81        }
82
83        // Validate session name format (alphanumeric with hyphens/underscores)
84        if !self
85            .name
86            .chars()
87            .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
88        {
89            return Err(
90                "Session name can only contain alphanumeric characters, hyphens, and underscores"
91                    .to_string(),
92            );
93        }
94
95        // Validate profile configuration
96        self.profile_config.validate()?;
97
98        Ok(())
99    }
100}
101
102/// Current status of a session.
103#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
104pub enum SessionStatus {
105    /// Session is being created
106    #[default]
107    Creating,
108    /// Session is active and running
109    Active,
110    /// Session is detached but still running
111    Detached,
112    /// Session is being terminated
113    Terminating,
114    /// Session encountered an error
115    Error(String),
116}
117
118/// Session-specific settings.
119#[derive(Debug, Clone, Serialize, Deserialize)]
120pub struct SessionSettings {
121    /// Whether to auto-sync agents
122    pub auto_sync: bool,
123
124    /// Sync interval in seconds
125    pub sync_interval_secs: Option<u64>,
126
127    /// Conflict resolution strategy
128    pub conflict_resolution: ConflictResolution,
129
130    /// Log level
131    pub log_level: LogLevel,
132
133    /// Whether to enable activity monitoring
134    pub enable_monitoring: bool,
135
136    /// Maximum session duration in seconds (None for unlimited)
137    pub max_duration_secs: Option<u64>,
138
139    /// Whether to automatically cleanup on termination
140    pub auto_cleanup: bool,
141}
142
143impl Default for SessionSettings {
144    fn default() -> Self {
145        Self {
146            auto_sync: false,
147            sync_interval_secs: Some(300), // 5 minutes
148            conflict_resolution: ConflictResolution::default(),
149            log_level: LogLevel::default(),
150            enable_monitoring: true,
151            max_duration_secs: None, // Unlimited
152            auto_cleanup: true,
153        }
154    }
155}
156
157/// Represents pre-configured tmux layout profiles for different agent arrangements.
158#[derive(Debug, Clone, Serialize, Deserialize)]
159pub struct TmuxProfile {
160    /// Profile identifier (profile0 - profile5)
161    pub name: String,
162
163    /// Profile description and use case
164    pub description: String,
165
166    /// Best for number of agents
167    pub best_for_agent_count: Option<u32>,
168
169    /// Layout type and configuration
170    pub layout: ProfileLayout,
171
172    /// Shell script path for this profile
173    pub script_path: PathBuf,
174
175    /// Whether this profile includes a supervisor pane
176    pub includes_supervisor: bool,
177
178    /// Supervisor configuration (if applicable)
179    pub supervisor_config: Option<SupervisorConfig>,
180}
181
182#[allow(dead_code)]
183impl TmuxProfile {
184    /// Validate the profile configuration.
185    pub fn validate(&self) -> Result<(), String> {
186        if self.name.is_empty() {
187            return Err("Profile name cannot be empty".to_string());
188        }
189
190        if self.script_path.as_os_str().is_empty() {
191            return Err("Profile script path cannot be empty".to_string());
192        }
193
194        self.layout.validate()?;
195
196        if let Some(ref supervisor) = self.supervisor_config {
197            supervisor.validate()?;
198        }
199
200        Ok(())
201    }
202
203    /// Check if this profile is suitable for the given number of agents.
204    pub fn is_suitable_for(&self, agent_count: u32) -> bool {
205        self.best_for_agent_count
206            .map(|best| agent_count <= best)
207            .unwrap_or(true)
208    }
209
210    /// Get the total number of panes this profile creates.
211    pub fn total_panes(&self) -> u32 {
212        let mut count = self.layout.pane_sizes.len() as u32;
213        if self.includes_supervisor {
214            count += 1;
215        }
216        count
217    }
218}
219
220/// Layout configuration for tmux profiles.
221#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct ProfileLayout {
223    /// Layout pattern: main-horizontal, main-vertical, even-horizontal, tiled
224    pub layout_type: String,
225
226    /// Pane size specifications
227    pub pane_sizes: Vec<PaneSize>,
228
229    /// Root pane configuration (main repository)
230    pub root_pane: Option<RootPaneConfig>,
231}
232
233#[allow(dead_code)]
234impl ProfileLayout {
235    /// Validate the layout configuration.
236    pub fn validate(&self) -> Result<(), String> {
237        if self.layout_type.is_empty() {
238            return Err("Layout type cannot be empty".to_string());
239        }
240
241        if self.pane_sizes.is_empty() {
242            return Err("Layout must have at least one pane size specification".to_string());
243        }
244
245        // Validate layout type
246        let valid_layouts = [
247            "main-horizontal",
248            "main-vertical",
249            "even-horizontal",
250            "tiled",
251        ];
252        if !valid_layouts.contains(&self.layout_type.as_str()) {
253            return Err(format!(
254                "Invalid layout type '{}'. Valid options: {}",
255                self.layout_type,
256                valid_layouts.join(", ")
257            ));
258        }
259
260        for (i, pane_size) in self.pane_sizes.iter().enumerate() {
261            if let Err(e) = pane_size.validate() {
262                return Err(format!("Pane size {} validation failed: {}", i + 1, e));
263            }
264        }
265
266        Ok(())
267    }
268}
269
270/// Size and position specification for a pane.
271#[derive(Debug, Clone, Serialize, Deserialize)]
272pub struct PaneSize {
273    /// Agent identifier
274    pub agent_id: String,
275
276    /// Percentage or size specification
277    pub size_spec: String,
278
279    /// Position in layout
280    pub position: LayoutPosition,
281}
282
283#[allow(dead_code)]
284impl PaneSize {
285    /// Validate the pane size specification.
286    pub fn validate(&self) -> Result<(), String> {
287        if self.agent_id.is_empty() {
288            return Err("Agent ID cannot be empty".to_string());
289        }
290
291        if self.size_spec.is_empty() {
292            return Err("Size specification cannot be empty".to_string());
293        }
294
295        // Validate size spec format (e.g., "50%", "80px", etc.)
296        if !self.size_spec.ends_with('%') && !self.size_spec.ends_with("px") {
297            return Err("Size specification must end with '%' or 'px'".to_string());
298        }
299
300        Ok(())
301    }
302}
303
304/// Position of a pane in the layout.
305#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
306pub enum LayoutPosition {
307    Top,
308    Bottom,
309    Left,
310    Right,
311    Center,
312}
313
314/// Configuration for the root pane (main repository).
315#[derive(Debug, Clone, Serialize, Deserialize)]
316pub struct RootPaneConfig {
317    /// Whether root pane is enabled
318    pub enabled: bool,
319
320    /// Root pane position
321    pub position: LayoutPosition,
322
323    /// Root pane size
324    pub size: String,
325
326    /// Default working directory
327    pub work_dir: PathBuf,
328}
329
330/// Supervisor configuration for session management.
331#[derive(Debug, Clone, Serialize, Deserialize)]
332pub struct SupervisorConfig {
333    /// Supervisor pane position
334    pub position: SupervisorPosition,
335
336    /// Supervisor pane size
337    pub size: SupervisorSize,
338
339    /// Default working directory for supervisor
340    pub work_dir: PathBuf,
341
342    /// Commands to run in supervisor pane on startup
343    pub startup_commands: Vec<String>,
344
345    /// Whether supervisor pane should be focused by default
346    pub focus_by_default: bool,
347}
348
349#[allow(dead_code)]
350impl SupervisorConfig {
351    /// Validate the supervisor configuration.
352    pub fn validate(&self) -> Result<(), String> {
353        if self.work_dir.as_os_str().is_empty() {
354            return Err("Supervisor work directory cannot be empty".to_string());
355        }
356
357        Ok(())
358    }
359}
360
361/// Position of the supervisor pane.
362#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
363pub enum SupervisorPosition {
364    Top,
365    Bottom,
366    Left,
367    Right,
368    Hidden,
369}
370
371/// Size specification for supervisor pane.
372#[derive(Debug, Clone, Serialize, Deserialize)]
373pub enum SupervisorSize {
374    /// Fixed size in pixels
375    Fixed(u32),
376    /// Percentage of available space
377    Percentage(u8),
378    /// Auto-size based on content
379    Auto,
380}
381
382/// Session layout configuration.
383#[derive(Debug, Clone, Serialize, Deserialize)]
384#[allow(dead_code)]
385pub struct SessionLayout {
386    /// Layout type: tiled, main-vertical, main-horizontal, custom
387    pub layout_type: LayoutType,
388
389    /// Pane arrangement specifications
390    pub pane_config: Vec<PaneConfig>,
391
392    /// Session dimensions
393    pub dimensions: Option<SessionDimensions>,
394}
395
396/// Layout type enumeration.
397#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
398#[allow(dead_code)]
399pub enum LayoutType {
400    /// All panes arranged in a grid
401    Tiled,
402    /// One main vertical pane with smaller panes on the side
403    MainVertical,
404    /// One main horizontal pane with smaller panes below
405    MainHorizontal,
406    /// Custom layout configuration
407    Custom(String),
408}
409
410/// Configuration for individual panes in a session.
411#[derive(Debug, Clone, Serialize, Deserialize)]
412#[allow(dead_code)]
413pub struct PaneConfig {
414    /// Agent name for this pane
415    pub agent_name: String,
416
417    /// Pane size/position specifications
418    pub size: PaneSize,
419
420    /// Pane index in layout
421    pub index: u32,
422}
423
424/// Session dimensions for layout calculations.
425#[derive(Debug, Clone, Serialize, Deserialize)]
426#[allow(dead_code)]
427pub struct SessionDimensions {
428    /// Width in characters
429    pub width: u32,
430
431    /// Height in characters
432    pub height: u32,
433}
434
435#[cfg(test)]
436mod tests {
437    use super::*;
438
439    #[test]
440    fn test_session_creation() {
441        let profile = TmuxProfile {
442            name: "test-profile".to_string(),
443            description: "Test profile".to_string(),
444            best_for_agent_count: Some(3),
445            layout: ProfileLayout {
446                layout_type: "tiled".to_string(),
447                pane_sizes: vec![PaneSize {
448                    agent_id: "agent-1".to_string(),
449                    size_spec: "50%".to_string(),
450                    position: LayoutPosition::Top,
451                }],
452                root_pane: None,
453            },
454            script_path: PathBuf::from("test.sh"),
455            includes_supervisor: false,
456            supervisor_config: None,
457        };
458
459        let session = Session::new("test-session", profile);
460        assert_eq!(session.name, "test-session");
461        assert_eq!(session.status, SessionStatus::Creating);
462        assert_eq!(session.profile, "test-profile");
463    }
464
465    #[test]
466    fn test_session_validation() {
467        let profile = TmuxProfile {
468            name: "test-profile".to_string(),
469            description: "Test profile".to_string(),
470            best_for_agent_count: Some(3),
471            layout: ProfileLayout {
472                layout_type: "tiled".to_string(),
473                pane_sizes: vec![PaneSize {
474                    agent_id: "agent-1".to_string(),
475                    size_spec: "50%".to_string(),
476                    position: LayoutPosition::Top,
477                }],
478                root_pane: None,
479            },
480            script_path: PathBuf::from("test.sh"),
481            includes_supervisor: false,
482            supervisor_config: None,
483        };
484
485        let session = Session::new("valid-session", profile.clone());
486        assert!(session.validate().is_ok());
487
488        // Test empty name
489        let mut invalid_session = Session::new("", profile.clone());
490        assert!(invalid_session.validate().is_err());
491
492        // Test invalid name format
493        invalid_session.name = "invalid session!".to_string();
494        assert!(invalid_session.validate().is_err());
495    }
496
497    #[test]
498    fn test_profile_validation() {
499        let valid_profile = TmuxProfile {
500            name: "profile0".to_string(),
501            description: "Valid profile".to_string(),
502            best_for_agent_count: Some(3),
503            layout: ProfileLayout {
504                layout_type: "tiled".to_string(),
505                pane_sizes: vec![PaneSize {
506                    agent_id: "agent-1".to_string(),
507                    size_spec: "50%".to_string(),
508                    position: LayoutPosition::Top,
509                }],
510                root_pane: None,
511            },
512            script_path: PathBuf::from("profile0.sh"),
513            includes_supervisor: false,
514            supervisor_config: None,
515        };
516
517        assert!(valid_profile.validate().is_ok());
518
519        // Test empty layout type
520        let mut invalid_profile = valid_profile.clone();
521        invalid_profile.layout.layout_type = "".to_string();
522        assert!(invalid_profile.validate().is_err());
523
524        // Test invalid layout type
525        invalid_profile.layout.layout_type = "invalid".to_string();
526        assert!(invalid_profile.validate().is_err());
527    }
528
529    #[test]
530    fn test_pane_size_validation() {
531        let valid_pane = PaneSize {
532            agent_id: "agent-1".to_string(),
533            size_spec: "50%".to_string(),
534            position: LayoutPosition::Top,
535        };
536
537        assert!(valid_pane.validate().is_ok());
538
539        // Test empty agent ID
540        let mut invalid_pane = valid_pane.clone();
541        invalid_pane.agent_id = "".to_string();
542        assert!(invalid_pane.validate().is_err());
543
544        // Test invalid size spec
545        invalid_pane.agent_id = "agent-1".to_string();
546        invalid_pane.size_spec = "50".to_string(); // Missing % or px
547        assert!(invalid_pane.validate().is_err());
548    }
549
550    #[test]
551    fn test_session_settings() {
552        let settings = SessionSettings::default();
553        assert!(!settings.auto_sync);
554        assert_eq!(settings.sync_interval_secs, Some(300));
555        assert_eq!(settings.conflict_resolution, ConflictResolution::Manual);
556        assert!(settings.enable_monitoring);
557        assert!(settings.auto_cleanup);
558    }
559}