use super::{ConflictResolution, LogLevel};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
pub name: String,
pub status: SessionStatus,
pub profile: String,
pub profile_config: TmuxProfile,
pub created_at: DateTime<Utc>,
pub last_activity: Option<DateTime<Utc>>,
pub settings: SessionSettings,
}
#[allow(dead_code)]
impl Session {
pub fn new(name: impl Into<String>, profile: TmuxProfile) -> Self {
let name_str = name.into();
Self {
name: name_str.clone(),
status: SessionStatus::Creating,
profile: profile.name.clone(),
profile_config: profile,
created_at: Utc::now(),
last_activity: None,
settings: SessionSettings::default(),
}
}
pub fn update_activity(&mut self) {
self.last_activity = Some(Utc::now());
}
pub fn is_active(&self) -> bool {
matches!(self.status, SessionStatus::Active | SessionStatus::Detached)
}
pub fn has_error(&self) -> bool {
matches!(self.status, SessionStatus::Error(_))
}
pub fn error_message(&self) -> Option<&str> {
match &self.status {
SessionStatus::Error(msg) => Some(msg),
_ => None,
}
}
pub fn duration(&self) -> chrono::Duration {
Utc::now() - self.created_at
}
pub fn validate(&self) -> Result<(), String> {
if self.name.is_empty() {
return Err("Session name cannot be empty".to_string());
}
if !self
.name
.chars()
.all(|c| c.is_alphanumeric() || c == '-' || c == '_')
{
return Err(
"Session name can only contain alphanumeric characters, hyphens, and underscores"
.to_string(),
);
}
self.profile_config.validate()?;
Ok(())
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub enum SessionStatus {
#[default]
Creating,
Active,
Detached,
Terminating,
Error(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionSettings {
pub auto_sync: bool,
pub sync_interval_secs: Option<u64>,
pub conflict_resolution: ConflictResolution,
pub log_level: LogLevel,
pub enable_monitoring: bool,
pub max_duration_secs: Option<u64>,
pub auto_cleanup: bool,
}
impl Default for SessionSettings {
fn default() -> Self {
Self {
auto_sync: false,
sync_interval_secs: Some(300), conflict_resolution: ConflictResolution::default(),
log_level: LogLevel::default(),
enable_monitoring: true,
max_duration_secs: None, auto_cleanup: true,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TmuxProfile {
pub name: String,
pub description: String,
pub best_for_agent_count: Option<u32>,
pub layout: ProfileLayout,
pub script_path: PathBuf,
pub includes_supervisor: bool,
pub supervisor_config: Option<SupervisorConfig>,
}
#[allow(dead_code)]
impl TmuxProfile {
pub fn validate(&self) -> Result<(), String> {
if self.name.is_empty() {
return Err("Profile name cannot be empty".to_string());
}
if self.script_path.as_os_str().is_empty() {
return Err("Profile script path cannot be empty".to_string());
}
self.layout.validate()?;
if let Some(ref supervisor) = self.supervisor_config {
supervisor.validate()?;
}
Ok(())
}
pub fn is_suitable_for(&self, agent_count: u32) -> bool {
self.best_for_agent_count
.map(|best| agent_count <= best)
.unwrap_or(true)
}
pub fn total_panes(&self) -> u32 {
let mut count = self.layout.pane_sizes.len() as u32;
if self.includes_supervisor {
count += 1;
}
count
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileLayout {
pub layout_type: String,
pub pane_sizes: Vec<PaneSize>,
pub root_pane: Option<RootPaneConfig>,
}
#[allow(dead_code)]
impl ProfileLayout {
pub fn validate(&self) -> Result<(), String> {
if self.layout_type.is_empty() {
return Err("Layout type cannot be empty".to_string());
}
if self.pane_sizes.is_empty() {
return Err("Layout must have at least one pane size specification".to_string());
}
let valid_layouts = [
"main-horizontal",
"main-vertical",
"even-horizontal",
"tiled",
];
if !valid_layouts.contains(&self.layout_type.as_str()) {
return Err(format!(
"Invalid layout type '{}'. Valid options: {}",
self.layout_type,
valid_layouts.join(", ")
));
}
for (i, pane_size) in self.pane_sizes.iter().enumerate() {
if let Err(e) = pane_size.validate() {
return Err(format!("Pane size {} validation failed: {}", i + 1, e));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaneSize {
pub agent_id: String,
pub size_spec: String,
pub position: LayoutPosition,
}
#[allow(dead_code)]
impl PaneSize {
pub fn validate(&self) -> Result<(), String> {
if self.agent_id.is_empty() {
return Err("Agent ID cannot be empty".to_string());
}
if self.size_spec.is_empty() {
return Err("Size specification cannot be empty".to_string());
}
if !self.size_spec.ends_with('%') && !self.size_spec.ends_with("px") {
return Err("Size specification must end with '%' or 'px'".to_string());
}
Ok(())
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum LayoutPosition {
Top,
Bottom,
Left,
Right,
Center,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RootPaneConfig {
pub enabled: bool,
pub position: LayoutPosition,
pub size: String,
pub work_dir: PathBuf,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SupervisorConfig {
pub position: SupervisorPosition,
pub size: SupervisorSize,
pub work_dir: PathBuf,
pub startup_commands: Vec<String>,
pub focus_by_default: bool,
}
#[allow(dead_code)]
impl SupervisorConfig {
pub fn validate(&self) -> Result<(), String> {
if self.work_dir.as_os_str().is_empty() {
return Err("Supervisor work directory cannot be empty".to_string());
}
Ok(())
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum SupervisorPosition {
Top,
Bottom,
Left,
Right,
Hidden,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SupervisorSize {
Fixed(u32),
Percentage(u8),
Auto,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct SessionLayout {
pub layout_type: LayoutType,
pub pane_config: Vec<PaneConfig>,
pub dimensions: Option<SessionDimensions>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[allow(dead_code)]
pub enum LayoutType {
Tiled,
MainVertical,
MainHorizontal,
Custom(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct PaneConfig {
pub agent_name: String,
pub size: PaneSize,
pub index: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct SessionDimensions {
pub width: u32,
pub height: u32,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_session_creation() {
let profile = TmuxProfile {
name: "test-profile".to_string(),
description: "Test profile".to_string(),
best_for_agent_count: Some(3),
layout: ProfileLayout {
layout_type: "tiled".to_string(),
pane_sizes: vec![PaneSize {
agent_id: "agent-1".to_string(),
size_spec: "50%".to_string(),
position: LayoutPosition::Top,
}],
root_pane: None,
},
script_path: PathBuf::from("test.sh"),
includes_supervisor: false,
supervisor_config: None,
};
let session = Session::new("test-session", profile);
assert_eq!(session.name, "test-session");
assert_eq!(session.status, SessionStatus::Creating);
assert_eq!(session.profile, "test-profile");
}
#[test]
fn test_session_validation() {
let profile = TmuxProfile {
name: "test-profile".to_string(),
description: "Test profile".to_string(),
best_for_agent_count: Some(3),
layout: ProfileLayout {
layout_type: "tiled".to_string(),
pane_sizes: vec![PaneSize {
agent_id: "agent-1".to_string(),
size_spec: "50%".to_string(),
position: LayoutPosition::Top,
}],
root_pane: None,
},
script_path: PathBuf::from("test.sh"),
includes_supervisor: false,
supervisor_config: None,
};
let session = Session::new("valid-session", profile.clone());
assert!(session.validate().is_ok());
let mut invalid_session = Session::new("", profile.clone());
assert!(invalid_session.validate().is_err());
invalid_session.name = "invalid session!".to_string();
assert!(invalid_session.validate().is_err());
}
#[test]
fn test_profile_validation() {
let valid_profile = TmuxProfile {
name: "profile0".to_string(),
description: "Valid profile".to_string(),
best_for_agent_count: Some(3),
layout: ProfileLayout {
layout_type: "tiled".to_string(),
pane_sizes: vec![PaneSize {
agent_id: "agent-1".to_string(),
size_spec: "50%".to_string(),
position: LayoutPosition::Top,
}],
root_pane: None,
},
script_path: PathBuf::from("profile0.sh"),
includes_supervisor: false,
supervisor_config: None,
};
assert!(valid_profile.validate().is_ok());
let mut invalid_profile = valid_profile.clone();
invalid_profile.layout.layout_type = "".to_string();
assert!(invalid_profile.validate().is_err());
invalid_profile.layout.layout_type = "invalid".to_string();
assert!(invalid_profile.validate().is_err());
}
#[test]
fn test_pane_size_validation() {
let valid_pane = PaneSize {
agent_id: "agent-1".to_string(),
size_spec: "50%".to_string(),
position: LayoutPosition::Top,
};
assert!(valid_pane.validate().is_ok());
let mut invalid_pane = valid_pane.clone();
invalid_pane.agent_id = "".to_string();
assert!(invalid_pane.validate().is_err());
invalid_pane.agent_id = "agent-1".to_string();
invalid_pane.size_spec = "50".to_string(); assert!(invalid_pane.validate().is_err());
}
#[test]
fn test_session_settings() {
let settings = SessionSettings::default();
assert!(!settings.auto_sync);
assert_eq!(settings.sync_interval_secs, Some(300));
assert_eq!(settings.conflict_resolution, ConflictResolution::Manual);
assert!(settings.enable_monitoring);
assert!(settings.auto_cleanup);
}
}