task_mcp/
state.rs

1//! Task state management.
2
3use std::collections::HashMap;
4use std::path::PathBuf;
5use std::sync::Arc;
6use std::time::Instant;
7
8use tokio::sync::Mutex;
9
10/// Information about a managed task.
11#[derive(Debug, Clone)]
12pub struct TaskInfo {
13    /// Unique name for this task.
14    pub name: String,
15    /// Process ID of the running task.
16    pub pid: u32,
17    /// The command that was executed.
18    pub command: String,
19    /// Working directory the command runs in.
20    pub cwd: Option<PathBuf>,
21    /// Path to the stdout log file.
22    pub stdout_path: PathBuf,
23    /// Path to the stderr log file.
24    pub stderr_path: PathBuf,
25    /// When the task was started.
26    pub started_at: Instant,
27}
28
29/// Manages the collection of tracked tasks.
30#[derive(Clone)]
31pub struct TaskManager {
32    tasks: Arc<Mutex<HashMap<String, TaskInfo>>>,
33}
34
35impl TaskManager {
36    /// Create a new empty task manager.
37    #[must_use]
38    pub fn new() -> Self {
39        Self {
40            tasks: Arc::new(Mutex::new(HashMap::new())),
41        }
42    }
43
44    /// Get a task by name.
45    pub async fn get(&self, name: &str) -> Option<TaskInfo> {
46        let tasks = self.tasks.lock().await;
47        tasks.get(name).cloned()
48    }
49
50    /// Insert or update a task.
51    pub async fn insert(&self, info: TaskInfo) {
52        let mut tasks = self.tasks.lock().await;
53        tasks.insert(info.name.clone(), info);
54    }
55
56    /// Remove a task by name, returning it if it existed.
57    pub async fn remove(&self, name: &str) -> Option<TaskInfo> {
58        let mut tasks = self.tasks.lock().await;
59        tasks.remove(name)
60    }
61
62    /// List all tracked tasks.
63    pub async fn list(&self) -> Vec<TaskInfo> {
64        let tasks = self.tasks.lock().await;
65        tasks.values().cloned().collect()
66    }
67}
68
69impl Default for TaskManager {
70    fn default() -> Self {
71        Self::new()
72    }
73}