Skip to main content

ninox_core/
events.rs

1use crate::{github::{GitHubClient, GithubApi}, store::Store, types::*};
2use std::{collections::HashMap, sync::Arc};
3use tokio::sync::{broadcast, Mutex};
4
5#[derive(Debug, Clone)]
6pub enum Event {
7    OrchestratorSpawned(Orchestrator),
8    OrchestratorRemoved(OrchestratorId),
9    SessionUpdated(Session),
10    SessionSpawned(Session),
11    SessionDone(SessionId),
12    TerminalOutput { session_id: SessionId, bytes: Vec<u8> },
13    /// Rendering stream from an attached tmux client (AttachedClient).
14    /// `generation` identifies which `AttachedClient::spawn` call produced
15    /// this event — consumers must ignore events whose generation doesn't
16    /// match the currently-live client for `session_id` so a stale client
17    /// (superseded by a fresh attach) cannot clobber the new one.
18    ClientOutput   { session_id: SessionId, generation: u64, bytes: Vec<u8> },
19    /// The attached tmux client process exited (detach, kill, server gone).
20    /// See `ClientOutput` for why `generation` matters.
21    ClientClosed   { session_id: SessionId, generation: u64 },
22    CiUpdated      { pr_id: PrId, status: CIStatus },
23    PrOpened       { session_id: SessionId, pr: PR },
24    ReviewComment  { pr_id: PrId, comment: Comment },
25    Notification(Notification),
26}
27
28pub struct Engine {
29    pub store: Arc<Store>,
30    tx: broadcast::Sender<Event>,
31    pty_writers:  Mutex<HashMap<SessionId, tokio::sync::mpsc::UnboundedSender<Vec<u8>>>>,
32    /// Per-session cancellation senders for active FIFO reader tasks.
33    /// Sending () to the stored sender stops the running reader immediately.
34    stream_cancel: Mutex<HashMap<SessionId, tokio::sync::oneshot::Sender<()>>>,
35    /// Optional GitHub API client. None when no token is configured.
36    pub github: Option<Arc<dyn GithubApi>>,
37}
38
39impl Engine {
40    pub fn new(store: Arc<Store>) -> Arc<Self> {
41        let (tx, _) = broadcast::channel(256);
42        Arc::new(Self {
43            store,
44            tx,
45            pty_writers:   Mutex::new(HashMap::new()),
46            stream_cancel: Mutex::new(HashMap::new()),
47            github:        None,
48        })
49    }
50
51    pub fn new_with_github(store: Arc<Store>, token: String) -> Arc<Self> {
52        let (tx, _) = broadcast::channel(256);
53        let github = GitHubClient::new(token).ok()
54            .map(|c| Arc::new(c) as Arc<dyn GithubApi>);
55        Arc::new(Self {
56            store,
57            tx,
58            pty_writers:   Mutex::new(HashMap::new()),
59            stream_cancel: Mutex::new(HashMap::new()),
60            github,
61        })
62    }
63
64    /// Construct an `Engine` with a caller-supplied `GithubApi` — the
65    /// dependency-injection seam tests use to drive the GitHub-enrichment
66    /// poller against a fake instead of the real network.
67    pub fn new_with_github_api(store: Arc<Store>, github: Arc<dyn GithubApi>) -> Arc<Self> {
68        let (tx, _) = broadcast::channel(256);
69        Arc::new(Self {
70            store,
71            tx,
72            pty_writers:   Mutex::new(HashMap::new()),
73            stream_cancel: Mutex::new(HashMap::new()),
74            github:        Some(github),
75        })
76    }
77
78    /// Cancel any running FIFO reader for `session_id` and return a fresh
79    /// cancellation receiver for the new reader.  Call this at the top of
80    /// every `start_streaming` invocation.
81    pub async fn register_stream(
82        &self,
83        session_id: SessionId,
84    ) -> tokio::sync::oneshot::Receiver<()> {
85        let mut map = self.stream_cancel.lock().await;
86        if let Some(old_tx) = map.remove(&session_id) {
87            let _ = old_tx.send(());
88        }
89        let (tx, rx) = tokio::sync::oneshot::channel();
90        map.insert(session_id, tx);
91        rx
92    }
93
94    pub fn emit(&self, event: Event) {
95        let _ = self.tx.send(event);
96    }
97
98    pub fn subscribe(&self) -> broadcast::Receiver<Event> {
99        self.tx.subscribe()
100    }
101
102    pub async fn register_pty_writer(
103        &self,
104        session_id: SessionId,
105        writer: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
106    ) {
107        self.pty_writers.lock().await.insert(session_id, writer);
108    }
109
110    pub async fn get_pty_writer(
111        &self,
112        session_id: &str,
113    ) -> Option<tokio::sync::mpsc::UnboundedSender<Vec<u8>>> {
114        self.pty_writers.lock().await.get(session_id).cloned()
115    }
116
117    /// Kill all worker sessions belonging to an orchestrator, delete from DB, emit events.
118    pub async fn remove_orchestrator(&self, orchestrator_id: &str) -> anyhow::Result<()> {
119        let workers = self.store.sessions_by_orchestrator(orchestrator_id)?;
120        let sessions_dir = crate::config::AppConfig::sessions_dir();
121        for session in &workers {
122            let _ = crate::tmux::kill_session(&session.id).await;
123            if let Some(ref wp) = session.workspace_path {
124                remove_worker_worktree(wp, &session.id).await;
125            }
126            crate::hooks::remove_session_artifacts(&sessions_dir, &session.id);
127        }
128        // Also kill the orchestrator's own tmux session (same id as orchestrator).
129        let _ = crate::tmux::kill_session(orchestrator_id).await;
130        self.store.delete_orchestrator(orchestrator_id)?;
131        for session in workers {
132            self.emit(Event::SessionDone(session.id));
133        }
134        self.emit(Event::OrchestratorRemoved(orchestrator_id.to_string()));
135        Ok(())
136    }
137
138    /// Kill the tmux session and delete it from the DB entirely.
139    pub async fn remove_session(&self, session_id: &str) -> anyhow::Result<()> {
140        let _ = crate::tmux::kill_session(session_id).await;
141        if let Ok(Some(session)) = self.store.get_session(session_id) {
142            if let Some(ref wp) = session.workspace_path {
143                remove_worker_worktree(wp, session_id).await;
144            }
145        }
146        crate::hooks::remove_session_artifacts(
147            &crate::config::AppConfig::sessions_dir(), session_id,
148        );
149        self.store.delete_session(session_id)?;
150        self.emit(Event::SessionDone(session_id.to_string()));
151        Ok(())
152    }
153
154    /// Send a text message to the agent running in a session's tmux window.
155    /// The message is injected as keyboard input — the agent sees it as typed text.
156    /// Returns Ok(()) if the tmux send succeeded; returns an error if the session
157    /// has no active tmux window or tmux is unavailable.
158    pub async fn send_to_session(&self, session_id: &str, message: &str) -> anyhow::Result<()> {
159        crate::tmux::send_keys(session_id, message).await
160    }
161
162    /// Kill the tmux session, mark it Terminated in the DB, and emit SessionUpdated.
163    pub async fn terminate_session(&self, session_id: &str) -> anyhow::Result<()> {
164        // Best-effort tmux kill (session may already be dead).
165        let _ = crate::tmux::kill_session(session_id).await;
166
167        if let Some(mut session) = self.store.get_session(session_id)? {
168            session.status = crate::types::SessionStatus::Terminated;
169            self.store.upsert_session(&session)?;
170            self.emit(Event::SessionUpdated(session));
171        }
172        Ok(())
173    }
174
175    /// Kill the tmux session (best-effort) and mark it Done in the DB.
176    /// Called automatically when a PR is merged. Emits SessionUpdated.
177    pub async fn cleanup_session(&self, session_id: &str) -> anyhow::Result<()> {
178        // Best-effort tmux kill — session may already be dead.
179        let _ = crate::tmux::kill_session(session_id).await;
180
181        if let Some(mut session) = self.store.get_session(session_id)? {
182            session.status = crate::types::SessionStatus::Done;
183            session.terminal_at = Some(crate::lifecycle::poller::now_millis());
184            self.store.upsert_session(&session)?;
185            self.emit(Event::SessionUpdated(session));
186        }
187        Ok(())
188    }
189}
190
191/// Remove a Ninox-managed git worktree (best-effort, never propagates errors).
192///
193/// Only acts on paths that match the `.claude/worktrees/{session_id}` pattern
194/// so it never touches unrelated directories.
195async fn remove_worker_worktree(workspace_path: &str, session_id: &str) {
196    let suffix = format!("/.claude/worktrees/{session_id}");
197    if !workspace_path.ends_with(&suffix) {
198        return; // Not a Ninox worktree — leave it alone.
199    }
200    // Derive the repo root by stripping the worktree suffix.
201    let repo_root = &workspace_path[..workspace_path.len() - suffix.len()];
202    if repo_root.is_empty() {
203        return;
204    }
205    let _ = tokio::process::Command::new("git")
206        .args(["-C", repo_root, "worktree", "remove", "--force", workspace_path])
207        .output()
208        .await;
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214    use crate::store::Store;
215    use tempfile::tempdir;
216
217    #[tokio::test]
218    async fn emit_received_by_subscriber() {
219        let store = Arc::new(Store::open(tempdir().unwrap().keep().join("t.db")).unwrap());
220        let engine = Engine::new(store);
221        let mut rx = engine.subscribe();
222        engine.emit(Event::SessionDone("s1".into()));
223        let event = rx.recv().await.unwrap();
224        assert!(matches!(event, Event::SessionDone(id) if id == "s1"));
225    }
226
227    #[tokio::test]
228    async fn terminate_emits_session_updated() {
229        let store = Arc::new(Store::open(tempdir().unwrap().keep().join("t.db")).unwrap());
230        let session = crate::types::Session {
231            id: "s1".into(), orchestrator_id: None, name: "w".into(),
232            repo: "r".into(), status: crate::types::SessionStatus::Working,
233            agent_type: "c".into(), cost_usd: 0.0, started_at: 0,
234            pr_number: None, pr_id: None, workspace_path: None, pid: None,
235            model: None, context_tokens: None, catalogue_path: None,
236            context_used_pct: None, context_total_tokens: None, context_window_size: None,
237            claude_session_id: None,
238            terminal_at: None,
239        };
240        store.upsert_session(&session).unwrap();
241        let engine = Engine::new(store);
242        let mut rx = engine.subscribe();
243
244        engine.terminate_session("s1").await.unwrap();
245
246        let evt = rx.recv().await.unwrap();
247        if let Event::SessionUpdated(s) = evt {
248            assert!(matches!(s.status, crate::types::SessionStatus::Terminated));
249            assert_eq!(
250                s.terminal_at, None,
251                "user-initiated terminate_session must not stamp terminal_at — \
252                 that's reserved for the automatic lifecycle path, so this \
253                 session is purged on sight rather than held for the \
254                 retention grace period",
255            );
256        } else {
257            panic!("expected SessionUpdated");
258        }
259    }
260
261    #[tokio::test]
262    async fn cleanup_session_sets_done_status() {
263        let store = Arc::new(
264            Store::open(tempdir().unwrap().keep().join("t.db")).unwrap()
265        );
266        let session = crate::types::Session {
267            id: "s1".into(), orchestrator_id: None, name: "w".into(),
268            repo: "r".into(), status: crate::types::SessionStatus::PrOpen,
269            agent_type: "c".into(), cost_usd: 0.0, started_at: 0,
270            pr_number: Some(1), pr_id: Some(1),
271            workspace_path: None, pid: None,
272            model: None, context_tokens: None, catalogue_path: None,
273            context_used_pct: None, context_total_tokens: None, context_window_size: None,
274            claude_session_id: None,
275            terminal_at: None,
276        };
277        store.upsert_session(&session).unwrap();
278        let engine = Engine::new(Arc::clone(&store));
279        let mut rx = engine.subscribe();
280
281        engine.cleanup_session("s1").await.unwrap();
282
283        let evt = rx.recv().await.unwrap();
284        if let Event::SessionUpdated(s) = evt {
285            assert!(matches!(s.status, crate::types::SessionStatus::Done));
286            assert!(
287                s.terminal_at.is_some(),
288                "cleanup_session must stamp terminal_at so the retention sweep can hold this \
289                 record for the fleet board's grace window instead of purging it on sight",
290            );
291        } else {
292            panic!("expected SessionUpdated");
293        }
294    }
295
296    #[tokio::test]
297    async fn remove_worker_worktree_ignores_non_ninox_paths() {
298        // Should be a no-op for paths that don't match .claude/worktrees/{id}.
299        // We just verify it doesn't panic or error.
300        remove_worker_worktree("/some/random/path", "s1").await;
301        remove_worker_worktree("/repo/.claude/worktrees/other-id", "s1").await;
302        remove_worker_worktree("", "s1").await;
303    }
304}