1#![allow(dead_code)]
7
8use crate::utils::project;
9use crate::utils::tmux::{kill_session, list_sessions, SessionInfo};
10use anyhow::{Context, Result};
11use std::fs;
12use std::path::Path;
13use std::process::Command;
14use std::time::{Duration, SystemTime};
15
16#[derive(Debug, Clone)]
18pub struct SessionHealth {
19 pub name: String,
21 pub status: SessionStatus,
23 pub windows: usize,
25 pub active_panes: usize,
27 pub age_seconds: u64,
29 pub last_activity: Option<SystemTime>,
31 pub issues: Vec<SessionIssue>,
33}
34
35#[derive(Debug, Clone, PartialEq)]
37pub enum SessionStatus {
38 Healthy,
40 Degraded,
42 Dead,
44 Orphaned,
46}
47
48#[derive(Debug, Clone)]
50pub enum SessionIssue {
51 NoActivePanes,
53 IdleTooLong(Duration),
55 ZombieProcesses(usize),
57 WorkspaceMissing(String),
59 GitIssues(String),
61 TmuxSocketIssues(String),
63 HighMemoryUsage(u64),
65}
66
67#[derive(Debug, Clone)]
69pub enum RecoveryAction {
70 None,
72 Restart,
74 Cleanup,
76 Repair,
78 Prompt,
80}
81
82#[derive(Debug, Clone)]
84pub struct RecoveryConfig {
85 pub max_idle_time: Duration,
87 pub max_session_age: Duration,
89 pub auto_cleanup: bool,
91 pub cleanup_dirs: Vec<String>,
93 pub monitored_processes: Vec<String>,
95}
96
97impl Default for RecoveryConfig {
98 fn default() -> Self {
99 Self {
100 max_idle_time: Duration::from_secs(3600), max_session_age: Duration::from_secs(86400), auto_cleanup: false,
103 cleanup_dirs: vec!["/tmp".to_string(), "/var/tmp".to_string()],
104 monitored_processes: vec!["tmux".to_string(), "git".to_string(), "sprite".to_string()],
105 }
106 }
107}
108
109pub fn analyze_session_health(config: &RecoveryConfig) -> Result<Vec<SessionHealth>> {
111 let sessions = match list_sessions() {
112 Ok(sessions) => sessions,
113 Err(_) => {
114 return Ok(Vec::new());
116 }
117 };
118
119 let mut health_reports = Vec::new();
120
121 for session in sessions {
122 let health = check_session_health(&session, config)?;
123 health_reports.push(health);
124 }
125
126 Ok(health_reports)
127}
128
129pub fn check_session_health(
131 session: &SessionInfo,
132 config: &RecoveryConfig,
133) -> Result<SessionHealth> {
134 let mut issues = Vec::new();
135 let mut active_panes = 0;
136
137 let is_responsive = check_session_responsiveness(&session.name)?;
139
140 match crate::utils::tmux::get_session_panes(&session.name) {
142 Ok(panes) => {
143 active_panes = panes.len();
144 if active_panes == 0 {
145 issues.push(SessionIssue::NoActivePanes);
146 }
147 }
148 Err(_) => {
149 issues.push(SessionIssue::TmuxSocketIssues(
150 "Failed to list session panes".to_string(),
151 ));
152 }
153 }
154
155 let age_seconds = parse_session_age(&session.created)?;
157 if age_seconds > config.max_session_age.as_secs() {
158 issues.push(SessionIssue::IdleTooLong(Duration::from_secs(age_seconds)));
159 }
160
161 if let Some(workspace_issue) = check_workspace_integrity(&session.name)? {
163 issues.push(workspace_issue);
164 }
165
166 if let Ok(zombie_count) = count_zombie_processes(&session.name) {
168 if zombie_count > 0 {
169 issues.push(SessionIssue::ZombieProcesses(zombie_count));
170 }
171 }
172
173 let status = if !is_responsive
175 || issues
176 .iter()
177 .any(|i| matches!(i, SessionIssue::TmuxSocketIssues(_)))
178 {
179 SessionStatus::Dead
180 } else if issues
181 .iter()
182 .any(|i| matches!(i, SessionIssue::WorkspaceMissing(_)))
183 {
184 SessionStatus::Orphaned
185 } else if !issues.is_empty() {
186 SessionStatus::Degraded
187 } else {
188 SessionStatus::Healthy
189 };
190
191 Ok(SessionHealth {
192 name: session.name.clone(),
193 status,
194 windows: session.windows,
195 active_panes,
196 age_seconds,
197 last_activity: None, issues,
199 })
200}
201
202fn check_session_responsiveness(session_name: &str) -> Result<bool> {
204 let output = Command::new("tmux")
205 .args(["display-message", "-p", "-t", session_name, "#S"])
206 .output()
207 .context("Failed to check session responsiveness")?;
208
209 Ok(output.status.success() && !output.stdout.is_empty())
210}
211
212fn parse_session_age(_created_str: &str) -> Result<u64> {
214 Ok(3600) }
218
219fn check_workspace_integrity(session_name: &str) -> Result<Option<SessionIssue>> {
221 match project::find_project_root() {
223 Ok(project_root) => {
224 let config_path = project_root.join("agents").join("agents.yaml");
225
226 if !config_path.exists() {
227 return Ok(Some(SessionIssue::WorkspaceMissing(format!(
228 "Sprite configuration not found at {}",
229 config_path.display()
230 ))));
231 }
232
233 let git_metadata = project_root.join(".git");
234 if !git_metadata.exists() {
235 return Ok(Some(SessionIssue::GitIssues(format!(
236 "Project root {} is not a git repository",
237 project_root.display()
238 ))));
239 }
240
241 Ok(None)
242 }
243 Err(_) => Ok(Some(SessionIssue::WorkspaceMissing(format!(
244 "No Sprite project detected for session {}",
245 session_name
246 )))),
247 }
248}
249
250fn count_zombie_processes(_session_name: &str) -> Result<usize> {
252 Ok(0)
255}
256
257pub fn get_recovery_action(health: &SessionHealth, config: &RecoveryConfig) -> RecoveryAction {
259 match health.status {
260 SessionStatus::Healthy => RecoveryAction::None,
261 SessionStatus::Dead => {
262 if config.auto_cleanup {
263 RecoveryAction::Cleanup
264 } else {
265 RecoveryAction::Prompt
266 }
267 }
268 SessionStatus::Orphaned => {
269 if config.auto_cleanup {
270 RecoveryAction::Cleanup
271 } else {
272 RecoveryAction::Prompt
273 }
274 }
275 SessionStatus::Degraded => {
276 if health
277 .issues
278 .iter()
279 .any(|i| matches!(i, SessionIssue::NoActivePanes))
280 {
281 RecoveryAction::Repair
282 } else if health.age_seconds > config.max_session_age.as_secs() {
283 if config.auto_cleanup {
284 RecoveryAction::Cleanup
285 } else {
286 RecoveryAction::Prompt
287 }
288 } else {
289 RecoveryAction::Repair
290 }
291 }
292 }
293}
294
295pub fn perform_recovery_action(session_name: &str, action: RecoveryAction) -> Result<()> {
297 match action {
298 RecoveryAction::None => Ok(()),
299 RecoveryAction::Restart => {
300 println!("๐ Restarting session: {}", session_name);
301 kill_session(session_name)?;
303 Ok(())
305 }
306 RecoveryAction::Cleanup => {
307 println!("๐งน Cleaning up session: {}", session_name);
308 cleanup_session_resources(session_name)?;
309 kill_session(session_name)?;
310 Ok(())
311 }
312 RecoveryAction::Repair => {
313 println!("๐ง Repairing session: {}", session_name);
314 repair_session(session_name)?;
315 Ok(())
316 }
317 RecoveryAction::Prompt => {
318 println!("โ Action required for session: {}", session_name);
319 Ok(())
321 }
322 }
323}
324
325pub fn cleanup_session_resources(session_name: &str) -> Result<()> {
327 let temp_patterns = vec![
329 format!("/tmp/sprite-{}-*", session_name),
330 format!("/var/tmp/sprite-{}-*", session_name),
331 format!("/tmp/tmux-{}*", session_name),
332 ];
333
334 for pattern in temp_patterns {
335 if let Ok(output) = Command::new("find")
336 .args(["/tmp", "-name", &pattern, "-delete"])
337 .output()
338 {
339 if !output.status.success() {
340 eprintln!(
341 "Warning: Failed to cleanup pattern {}: {}",
342 pattern,
343 String::from_utf8_lossy(&output.stderr)
344 );
345 }
346 }
347 }
348
349 let state_dir = Path::new(".sprites");
351 if state_dir.exists() {
352 let session_state = state_dir.join(format!("{}.json", session_name));
353 if session_state.exists() {
354 fs::remove_file(&session_state).with_context(|| {
355 format!("Failed to remove session state file: {:?}", session_state)
356 })?;
357 }
358 }
359
360 Ok(())
361}
362
363fn repair_session(session_name: &str) -> Result<()> {
365 match crate::utils::tmux::get_session_panes(session_name) {
367 Ok(panes) if panes.is_empty() => {
368 crate::utils::tmux::create_window(session_name, "recovery")?;
370 println!("โ
Created recovery window for session: {}", session_name);
371 }
372 Ok(_) => {
373 println!("โ
Session {} appears to be functioning", session_name);
374 }
375 Err(e) => {
376 eprintln!("โ Failed to repair session {}: {}", session_name, e);
377 return Err(e);
378 }
379 }
380
381 Ok(())
382}
383
384pub fn cleanup_old_sessions(config: &RecoveryConfig) -> Result<Vec<String>> {
386 let health_reports = analyze_session_health(config)?;
387 let mut cleaned_sessions = Vec::new();
388
389 for health in health_reports {
390 let action = get_recovery_action(&health, config);
391
392 if matches!(action, RecoveryAction::Cleanup) {
393 if let Err(e) = perform_recovery_action(&health.name, action) {
394 eprintln!("Failed to cleanup session {}: {}", health.name, e);
395 } else {
396 cleaned_sessions.push(health.name);
397 }
398 }
399 }
400
401 Ok(cleaned_sessions)
402}
403
404pub fn cleanup_temp_files(config: &RecoveryConfig) -> Result<()> {
406 for temp_dir in &config.cleanup_dirs {
407 if Path::new(temp_dir).exists() {
408 cleanup_directory(temp_dir, "sprite-*")?;
409 cleanup_directory(temp_dir, "tmux-*")?;
410 }
411 }
412 Ok(())
413}
414
415fn cleanup_directory(dir: &str, pattern: &str) -> Result<()> {
417 let output = Command::new("find")
418 .args([dir, "-name", pattern, "-mtime", "+1", "-delete"])
419 .output()
420 .context("Failed to cleanup temporary files")?;
421
422 if !output.status.success() {
423 eprintln!(
424 "Warning: Failed to cleanup {} in {}: {}",
425 pattern,
426 dir,
427 String::from_utf8_lossy(&output.stderr)
428 );
429 }
430
431 Ok(())
432}
433
434pub fn generate_health_report(health_reports: &[SessionHealth]) -> String {
436 let mut report = String::new();
437 report.push_str("๐ฅ Session Health Report\n");
438 report.push_str("========================\n\n");
439
440 let mut healthy_count = 0;
441 let mut degraded_count = 0;
442 let mut dead_count = 0;
443 let mut orphaned_count = 0;
444
445 for health in health_reports {
446 match health.status {
447 SessionStatus::Healthy => healthy_count += 1,
448 SessionStatus::Degraded => degraded_count += 1,
449 SessionStatus::Dead => dead_count += 1,
450 SessionStatus::Orphaned => orphaned_count += 1,
451 }
452
453 let status_icon = match health.status {
454 SessionStatus::Healthy => "๐ข",
455 SessionStatus::Degraded => "๐ก",
456 SessionStatus::Dead => "๐ด",
457 SessionStatus::Orphaned => "โช",
458 };
459
460 report.push_str(&format!(
461 "{} {} ({} windows, {} panes, {}s old)\n",
462 status_icon, health.name, health.windows, health.active_panes, health.age_seconds
463 ));
464
465 if !health.issues.is_empty() {
466 for issue in &health.issues {
467 let issue_desc = match issue {
468 SessionIssue::NoActivePanes => "No active panes".to_string(),
469 SessionIssue::IdleTooLong(duration) => format!("Idle for {:?}", duration),
470 SessionIssue::ZombieProcesses(count) => format!("{} zombie processes", count),
471 SessionIssue::WorkspaceMissing(path) => format!("Workspace missing: {}", path),
472 SessionIssue::GitIssues(msg) => format!("Git issues: {}", msg),
473 SessionIssue::TmuxSocketIssues(msg) => format!("Tmux socket issues: {}", msg),
474 SessionIssue::HighMemoryUsage(bytes) => {
475 format!("High memory usage: {} MB", bytes / 1024 / 1024)
476 }
477 };
478 report.push_str(&format!(" โ ๏ธ {}\n", issue_desc));
479 }
480 }
481 report.push('\n');
482 }
483
484 report.push_str("--- Summary ---\n");
485 report.push_str(&format!("๐ข Healthy: {}\n", healthy_count));
486 report.push_str(&format!("๐ก Degraded: {}\n", degraded_count));
487 report.push_str(&format!("๐ด Dead: {}\n", dead_count));
488 report.push_str(&format!("โช Orphaned: {}\n", orphaned_count));
489
490 report
491}
492
493#[cfg(test)]
494mod tests {
495 use super::*;
496
497 #[test]
498 fn test_recovery_config_default() {
499 let config = RecoveryConfig::default();
500 assert_eq!(config.max_idle_time, Duration::from_secs(3600));
501 assert_eq!(config.max_session_age, Duration::from_secs(86400));
502 assert!(!config.auto_cleanup);
503 }
504
505 #[test]
506 fn test_session_age_parsing() {
507 let age = parse_session_age("created Wed Oct 18 10:30:00 2023").unwrap();
508 assert_eq!(age, 3600); }
510
511 #[test]
512 fn test_health_report_generation() {
513 let health = SessionHealth {
514 name: "test-session".to_string(),
515 status: SessionStatus::Healthy,
516 windows: 3,
517 active_panes: 3,
518 age_seconds: 1800,
519 last_activity: None,
520 issues: vec![],
521 };
522
523 let report = generate_health_report(&[health]);
524 assert!(report.contains("Session Health Report"));
525 assert!(report.contains("test-session"));
526 assert!(report.contains("๐ข"));
527 }
528
529 #[test]
530 fn test_recovery_action_selection() {
531 let config = RecoveryConfig::default();
532
533 let healthy_session = SessionHealth {
534 name: "healthy".to_string(),
535 status: SessionStatus::Healthy,
536 windows: 1,
537 active_panes: 1,
538 age_seconds: 100,
539 last_activity: None,
540 issues: vec![],
541 };
542
543 let action = get_recovery_action(&healthy_session, &config);
544 assert!(matches!(action, RecoveryAction::None));
545 }
546}