1use super::{ConflictResolution, LogLevel};
4use chrono::{DateTime, Utc};
5use serde::{Deserialize, Serialize};
6use std::path::PathBuf;
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct Session {
11 pub name: String,
13
14 pub status: SessionStatus,
16
17 pub profile: String,
19
20 pub profile_config: TmuxProfile,
22
23 pub created_at: DateTime<Utc>,
25
26 pub last_activity: Option<DateTime<Utc>>,
28
29 pub settings: SessionSettings,
31}
32
33#[allow(dead_code)]
34impl Session {
35 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 pub fn update_activity(&mut self) {
51 self.last_activity = Some(Utc::now());
52 }
53
54 pub fn is_active(&self) -> bool {
56 matches!(self.status, SessionStatus::Active | SessionStatus::Detached)
57 }
58
59 pub fn has_error(&self) -> bool {
61 matches!(self.status, SessionStatus::Error(_))
62 }
63
64 pub fn error_message(&self) -> Option<&str> {
66 match &self.status {
67 SessionStatus::Error(msg) => Some(msg),
68 _ => None,
69 }
70 }
71
72 pub fn duration(&self) -> chrono::Duration {
74 Utc::now() - self.created_at
75 }
76
77 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 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 self.profile_config.validate()?;
97
98 Ok(())
99 }
100}
101
102#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
104pub enum SessionStatus {
105 #[default]
107 Creating,
108 Active,
110 Detached,
112 Terminating,
114 Error(String),
116}
117
118#[derive(Debug, Clone, Serialize, Deserialize)]
120pub struct SessionSettings {
121 pub auto_sync: bool,
123
124 pub sync_interval_secs: Option<u64>,
126
127 pub conflict_resolution: ConflictResolution,
129
130 pub log_level: LogLevel,
132
133 pub enable_monitoring: bool,
135
136 pub max_duration_secs: Option<u64>,
138
139 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), conflict_resolution: ConflictResolution::default(),
149 log_level: LogLevel::default(),
150 enable_monitoring: true,
151 max_duration_secs: None, auto_cleanup: true,
153 }
154 }
155}
156
157#[derive(Debug, Clone, Serialize, Deserialize)]
159pub struct TmuxProfile {
160 pub name: String,
162
163 pub description: String,
165
166 pub best_for_agent_count: Option<u32>,
168
169 pub layout: ProfileLayout,
171
172 pub script_path: PathBuf,
174
175 pub includes_supervisor: bool,
177
178 pub supervisor_config: Option<SupervisorConfig>,
180}
181
182#[allow(dead_code)]
183impl TmuxProfile {
184 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 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct ProfileLayout {
223 pub layout_type: String,
225
226 pub pane_sizes: Vec<PaneSize>,
228
229 pub root_pane: Option<RootPaneConfig>,
231}
232
233#[allow(dead_code)]
234impl ProfileLayout {
235 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
272pub struct PaneSize {
273 pub agent_id: String,
275
276 pub size_spec: String,
278
279 pub position: LayoutPosition,
281}
282
283#[allow(dead_code)]
284impl PaneSize {
285 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 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#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
306pub enum LayoutPosition {
307 Top,
308 Bottom,
309 Left,
310 Right,
311 Center,
312}
313
314#[derive(Debug, Clone, Serialize, Deserialize)]
316pub struct RootPaneConfig {
317 pub enabled: bool,
319
320 pub position: LayoutPosition,
322
323 pub size: String,
325
326 pub work_dir: PathBuf,
328}
329
330#[derive(Debug, Clone, Serialize, Deserialize)]
332pub struct SupervisorConfig {
333 pub position: SupervisorPosition,
335
336 pub size: SupervisorSize,
338
339 pub work_dir: PathBuf,
341
342 pub startup_commands: Vec<String>,
344
345 pub focus_by_default: bool,
347}
348
349#[allow(dead_code)]
350impl SupervisorConfig {
351 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#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
363pub enum SupervisorPosition {
364 Top,
365 Bottom,
366 Left,
367 Right,
368 Hidden,
369}
370
371#[derive(Debug, Clone, Serialize, Deserialize)]
373pub enum SupervisorSize {
374 Fixed(u32),
376 Percentage(u8),
378 Auto,
380}
381
382#[derive(Debug, Clone, Serialize, Deserialize)]
384#[allow(dead_code)]
385pub struct SessionLayout {
386 pub layout_type: LayoutType,
388
389 pub pane_config: Vec<PaneConfig>,
391
392 pub dimensions: Option<SessionDimensions>,
394}
395
396#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
398#[allow(dead_code)]
399pub enum LayoutType {
400 Tiled,
402 MainVertical,
404 MainHorizontal,
406 Custom(String),
408}
409
410#[derive(Debug, Clone, Serialize, Deserialize)]
412#[allow(dead_code)]
413pub struct PaneConfig {
414 pub agent_name: String,
416
417 pub size: PaneSize,
419
420 pub index: u32,
422}
423
424#[derive(Debug, Clone, Serialize, Deserialize)]
426#[allow(dead_code)]
427pub struct SessionDimensions {
428 pub width: u32,
430
431 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 let mut invalid_session = Session::new("", profile.clone());
490 assert!(invalid_session.validate().is_err());
491
492 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 let mut invalid_profile = valid_profile.clone();
521 invalid_profile.layout.layout_type = "".to_string();
522 assert!(invalid_profile.validate().is_err());
523
524 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 let mut invalid_pane = valid_pane.clone();
541 invalid_pane.agent_id = "".to_string();
542 assert!(invalid_pane.validate().is_err());
543
544 invalid_pane.agent_id = "agent-1".to_string();
546 invalid_pane.size_spec = "50".to_string(); 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}