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, SessionFields),
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    /// A PR beyond the session's tracked one (`PrOpened`'s `pr`) was
25    /// detected — most often an agent accidentally opening a second PR.
26    /// Unlike `PrOpened`, this must never change which PR a session tracks;
27    /// it only makes the extra PR visible (e.g. on the Pull Requests
28    /// ledger) so a human notices and can clean it up. `PR::session_id`
29    /// carries the owning session — no separate field needed.
30    ExtraPrDetected(PR),
31    ReviewComment  { pr_id: PrId, comment: Comment },
32    Notification(Notification),
33}
34
35pub struct Engine {
36    pub store: Arc<Store>,
37    tx: broadcast::Sender<Event>,
38    pty_writers:  Mutex<HashMap<SessionId, tokio::sync::mpsc::UnboundedSender<Vec<u8>>>>,
39    /// Per-session cancellation senders for active FIFO reader tasks.
40    /// Sending () to the stored sender stops the running reader immediately.
41    stream_cancel: Mutex<HashMap<SessionId, tokio::sync::oneshot::Sender<()>>>,
42    /// Optional GitHub API client. None when no token is configured.
43    pub github: Option<Arc<dyn GithubApi>>,
44}
45
46impl Engine {
47    pub fn new(store: Arc<Store>) -> Arc<Self> {
48        let (tx, _) = broadcast::channel(256);
49        Arc::new(Self {
50            store,
51            tx,
52            pty_writers:   Mutex::new(HashMap::new()),
53            stream_cancel: Mutex::new(HashMap::new()),
54            github:        None,
55        })
56    }
57
58    pub fn new_with_github(store: Arc<Store>, token: String) -> Arc<Self> {
59        let (tx, _) = broadcast::channel(256);
60        let github = GitHubClient::new(token).ok()
61            .map(|c| Arc::new(c) as Arc<dyn GithubApi>);
62        Arc::new(Self {
63            store,
64            tx,
65            pty_writers:   Mutex::new(HashMap::new()),
66            stream_cancel: Mutex::new(HashMap::new()),
67            github,
68        })
69    }
70
71    /// Construct an `Engine` with a caller-supplied `GithubApi` — the
72    /// dependency-injection seam tests use to drive the GitHub-enrichment
73    /// poller against a fake instead of the real network.
74    pub fn new_with_github_api(store: Arc<Store>, github: Arc<dyn GithubApi>) -> Arc<Self> {
75        let (tx, _) = broadcast::channel(256);
76        Arc::new(Self {
77            store,
78            tx,
79            pty_writers:   Mutex::new(HashMap::new()),
80            stream_cancel: Mutex::new(HashMap::new()),
81            github:        Some(github),
82        })
83    }
84
85    /// Cancel any running FIFO reader for `session_id` and return a fresh
86    /// cancellation receiver for the new reader.  Call this at the top of
87    /// every `start_streaming` invocation.
88    pub async fn register_stream(
89        &self,
90        session_id: SessionId,
91    ) -> tokio::sync::oneshot::Receiver<()> {
92        let mut map = self.stream_cancel.lock().await;
93        if let Some(old_tx) = map.remove(&session_id) {
94            let _ = old_tx.send(());
95        }
96        let (tx, rx) = tokio::sync::oneshot::channel();
97        map.insert(session_id, tx);
98        rx
99    }
100
101    pub fn emit(&self, event: Event) {
102        let _ = self.tx.send(event);
103    }
104
105    pub fn subscribe(&self) -> broadcast::Receiver<Event> {
106        self.tx.subscribe()
107    }
108
109    pub async fn register_pty_writer(
110        &self,
111        session_id: SessionId,
112        writer: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
113    ) {
114        self.pty_writers.lock().await.insert(session_id, writer);
115    }
116
117    pub async fn get_pty_writer(
118        &self,
119        session_id: &str,
120    ) -> Option<tokio::sync::mpsc::UnboundedSender<Vec<u8>>> {
121        self.pty_writers.lock().await.get(session_id).cloned()
122    }
123
124    /// Kill all worker sessions belonging to an orchestrator, delete from DB, emit events.
125    pub async fn remove_orchestrator(&self, orchestrator_id: &str) -> anyhow::Result<()> {
126        let workers = self.store.sessions_by_orchestrator(orchestrator_id)?;
127        let sessions_dir = crate::config::AppConfig::sessions_dir();
128        for session in &workers {
129            let _ = crate::tmux::kill_session(&session.id).await;
130            remove_worktree_and_artifacts(&session.id, session.workspace_path.as_deref(), &sessions_dir).await;
131        }
132        // Also kill the orchestrator's own tmux session (same id as orchestrator).
133        let _ = crate::tmux::kill_session(orchestrator_id).await;
134        self.store.delete_orchestrator(orchestrator_id)?;
135        for session in workers {
136            self.emit(Event::SessionDone(session.id));
137        }
138        self.emit(Event::OrchestratorRemoved(orchestrator_id.to_string()));
139        Ok(())
140    }
141
142    /// Kill the tmux session and delete it from the DB entirely.
143    pub async fn remove_session(&self, session_id: &str) -> anyhow::Result<()> {
144        let _ = crate::tmux::kill_session(session_id).await;
145        let workspace_path = self.store.get_session(session_id).ok().flatten()
146            .and_then(|s| s.workspace_path);
147        remove_worktree_and_artifacts(
148            session_id, workspace_path.as_deref(), &crate::config::AppConfig::sessions_dir(),
149        ).await;
150        self.store.delete_session(session_id)?;
151        self.emit(Event::SessionDone(session_id.to_string()));
152        Ok(())
153    }
154
155    /// Send a text message to the agent running in a session's tmux window.
156    /// The message is injected as keyboard input — the agent sees it as typed text.
157    /// Returns Ok(()) once delivery is verified (or gives no signal either way);
158    /// errors if the session has no active tmux window, tmux is unavailable, or
159    /// the message is still sitting unsubmitted at the input prompt after the
160    /// Enter retries (see `tmux::send_keys`).
161    pub async fn send_to_session(&self, session_id: &str, message: &str) -> anyhow::Result<()> {
162        crate::tmux::send_keys(session_id, message).await
163    }
164
165    /// Kill the tmux session, mark it Terminated in the DB, and emit SessionUpdated.
166    pub async fn terminate_session(&self, session_id: &str) -> anyhow::Result<()> {
167        // Best-effort tmux kill (session may already be dead).
168        let _ = crate::tmux::kill_session(session_id).await;
169
170        if let Some(mut session) = self.store.get_session(session_id)? {
171            // Never clobber a terminal status — most importantly, never flip
172            // a `Done` session back to `Terminated`. `Done` is only ever
173            // reached via `handle_merge_detection`, which already notified
174            // the orchestrator; `sweep_retired_sessions`'s notification
175            // dedup relies on `Done` meaning "already told" (see
176            // `lifecycle::poller::sweep_retired_sessions`), so re-marking it
177            // `Terminated` here would make the sweep send a second,
178            // contradictory notice for a PR that was in fact merged.
179            if matches!(
180                session.status,
181                SessionStatus::Done | SessionStatus::Terminated | SessionStatus::Interrupted
182            ) {
183                return Ok(());
184            }
185            session.status = SessionStatus::Terminated;
186            self.store.upsert_session(&session)?;
187            self.emit(Event::SessionUpdated(session, SessionFields::STATUS));
188        }
189        Ok(())
190    }
191
192    /// Kill the tmux session (best-effort), remove its worktree/artifacts,
193    /// and mark it Done in the DB. Called automatically when a PR is
194    /// merged. Emits SessionUpdated. Mirrors `remove_session`'s worktree
195    /// and artifact cleanup so the record isn't deleted here but still
196    /// stops leaking a checked-out worktree and per-session hook files.
197    pub async fn cleanup_session(&self, session_id: &str) -> anyhow::Result<()> {
198        self.cleanup_session_in(session_id, &crate::config::AppConfig::sessions_dir()).await
199    }
200
201    /// `cleanup_session`'s implementation, with the sessions dir as a
202    /// parameter so tests can point artifact removal at a tempdir instead
203    /// of the real `AppConfig::sessions_dir()`.
204    async fn cleanup_session_in(
205        &self,
206        session_id:   &str,
207        sessions_dir: &std::path::Path,
208    ) -> anyhow::Result<()> {
209        // Best-effort tmux kill — session may already be dead.
210        let _ = crate::tmux::kill_session(session_id).await;
211
212        if let Some(mut session) = self.store.get_session(session_id)? {
213            remove_worktree_and_artifacts(session_id, session.workspace_path.as_deref(), sessions_dir).await;
214            session.status = crate::types::SessionStatus::Done;
215            session.terminal_at = Some(crate::lifecycle::poller::now_millis());
216            self.store.upsert_session(&session)?;
217            self.emit(Event::SessionUpdated(session, SessionFields::STATUS | SessionFields::TERMINAL_AT));
218        }
219        Ok(())
220    }
221}
222
223/// Remove a session's worktree (if any) and hook artifacts — the shared
224/// teardown tail of `remove_orchestrator`, `remove_session`, and
225/// `cleanup_session`, so none of them leak a checked-out worktree or
226/// per-session hook files.
227async fn remove_worktree_and_artifacts(
228    session_id:     &str,
229    workspace_path: Option<&str>,
230    sessions_dir:   &std::path::Path,
231) {
232    if let Some(wp) = workspace_path {
233        remove_worker_worktree(wp, session_id).await;
234    }
235    crate::hooks::remove_session_artifacts(sessions_dir, session_id);
236}
237
238/// Remove a Ninox-managed git worktree (best-effort, never propagates errors).
239///
240/// Only acts on paths that match the `.claude/worktrees/{session_id}` pattern
241/// so it never touches unrelated directories.
242async fn remove_worker_worktree(workspace_path: &str, session_id: &str) {
243    let suffix = format!("/.claude/worktrees/{session_id}");
244    if !workspace_path.ends_with(&suffix) {
245        return; // Not a Ninox worktree — leave it alone.
246    }
247    // Derive the repo root by stripping the worktree suffix.
248    let repo_root = &workspace_path[..workspace_path.len() - suffix.len()];
249    if repo_root.is_empty() {
250        return;
251    }
252    let _ = tokio::process::Command::new("git")
253        .args(["-C", repo_root, "worktree", "remove", "--force", workspace_path])
254        .output()
255        .await;
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261    use crate::store::Store;
262    use tempfile::tempdir;
263
264    #[tokio::test]
265    async fn emit_received_by_subscriber() {
266        let store = Arc::new(Store::open(tempdir().unwrap().keep().join("t.db")).unwrap());
267        let engine = Engine::new(store);
268        let mut rx = engine.subscribe();
269        engine.emit(Event::SessionDone("s1".into()));
270        let event = rx.recv().await.unwrap();
271        assert!(matches!(event, Event::SessionDone(id) if id == "s1"));
272    }
273
274    #[tokio::test]
275    async fn terminate_emits_session_updated() {
276        let store = Arc::new(Store::open(tempdir().unwrap().keep().join("t.db")).unwrap());
277        let session = crate::types::Session {
278            id: "s1".into(), orchestrator_id: None, name: "w".into(),
279            repo: "r".into(), status: crate::types::SessionStatus::Working,
280            agent_type: "c".into(), cost_usd: 0.0, started_at: 0,
281            pr_number: None, pr_id: None, workspace_path: None, pid: None,
282            model: None, context_tokens: None, catalogue_path: None,
283            context_used_pct: None, context_total_tokens: None, context_window_size: None,
284            claude_session_id: None,
285            summary: None,
286            terminal_at: None, gate_status: None,
287        };
288        store.upsert_session(&session).unwrap();
289        let engine = Engine::new(store);
290        let mut rx = engine.subscribe();
291
292        engine.terminate_session("s1").await.unwrap();
293
294        let evt = rx.recv().await.unwrap();
295        if let Event::SessionUpdated(s, _fields) = evt {
296            assert!(matches!(s.status, crate::types::SessionStatus::Terminated));
297            assert_eq!(
298                s.terminal_at, None,
299                "user-initiated terminate_session must not stamp terminal_at — \
300                 that's reserved for the automatic lifecycle path, so this \
301                 session is purged on sight rather than held for the \
302                 retention grace period",
303            );
304        } else {
305            panic!("expected SessionUpdated");
306        }
307    }
308
309    /// A `Done` session (reached via `cleanup_session`, which already
310    /// notified the orchestrator about the merge) must never be flipped back
311    /// to `Terminated` by a later `terminate_session` call (e.g. the `DELETE
312    /// /sessions/:id` route firing on a stale client, or a race with the
313    /// poller). `sweep_retired_sessions`'s notification dedup relies on
314    /// `Done` meaning "already told" — reopening it as `Terminated` would
315    /// make the sweep send a second, contradictory notification claiming the
316    /// PR was never detected merged.
317    #[tokio::test]
318    async fn terminate_session_does_not_reopen_a_done_session() {
319        let store = Arc::new(Store::open(tempdir().unwrap().keep().join("t.db")).unwrap());
320        let session = crate::types::Session {
321            id: "s1".into(), orchestrator_id: None, name: "w".into(),
322            repo: "r".into(), status: crate::types::SessionStatus::Done,
323            agent_type: "c".into(), cost_usd: 0.0, started_at: 0,
324            pr_number: Some(1), pr_id: Some(1), workspace_path: None, pid: None,
325            model: None, context_tokens: None, catalogue_path: None,
326            context_used_pct: None, context_total_tokens: None, context_window_size: None,
327            claude_session_id: None,
328            summary: None,
329            terminal_at: Some(1_000), gate_status: None,
330        };
331        store.upsert_session(&session).unwrap();
332        let engine = Engine::new(Arc::clone(&store));
333        let mut rx = engine.subscribe();
334
335        engine.terminate_session("s1").await.unwrap();
336
337        assert!(
338            rx.try_recv().is_err(),
339            "a no-op terminate_session on a Done session must not emit SessionUpdated"
340        );
341        let after = store.get_session("s1").unwrap().unwrap();
342        assert!(matches!(after.status, crate::types::SessionStatus::Done), "status must stay Done");
343        assert_eq!(after.terminal_at, Some(1_000), "terminal_at must be untouched");
344    }
345
346    #[tokio::test]
347    async fn cleanup_session_sets_done_status() {
348        let store = Arc::new(
349            Store::open(tempdir().unwrap().keep().join("t.db")).unwrap()
350        );
351        let session = crate::types::Session {
352            id: "s1".into(), orchestrator_id: None, name: "w".into(),
353            repo: "r".into(), status: crate::types::SessionStatus::PrOpen,
354            agent_type: "c".into(), cost_usd: 0.0, started_at: 0,
355            pr_number: Some(1), pr_id: Some(1),
356            workspace_path: None, pid: None,
357            model: None, context_tokens: None, catalogue_path: None,
358            context_used_pct: None, context_total_tokens: None, context_window_size: None,
359            claude_session_id: None,
360            summary: None,
361            terminal_at: None, gate_status: None,
362        };
363        store.upsert_session(&session).unwrap();
364        let engine = Engine::new(Arc::clone(&store));
365        let mut rx = engine.subscribe();
366
367        engine.cleanup_session("s1").await.unwrap();
368
369        let evt = rx.recv().await.unwrap();
370        if let Event::SessionUpdated(s, _fields) = evt {
371            assert!(matches!(s.status, crate::types::SessionStatus::Done));
372            assert!(
373                s.terminal_at.is_some(),
374                "cleanup_session must stamp terminal_at so the retention sweep can hold this \
375                 record for the fleet board's grace window instead of purging it on sight",
376            );
377        } else {
378            panic!("expected SessionUpdated");
379        }
380    }
381
382    #[tokio::test]
383    async fn cleanup_session_removes_worktree_and_artifacts() {
384        // Real git repo + real worktree so we exercise the same
385        // `remove_worker_worktree` path `remove_session` uses, not a mock.
386        let repo_dir = tempdir().unwrap();
387        let run_git = |args: &[&str]| {
388            let status = std::process::Command::new("git")
389                .args(args)
390                .current_dir(repo_dir.path())
391                .status()
392                .unwrap();
393            assert!(status.success(), "git {args:?} failed");
394        };
395        run_git(&["init", "-q"]);
396        run_git(&["-c", "user.email=t@t.com", "-c", "user.name=t", "commit", "--allow-empty", "-q", "-m", "init"]);
397
398        let session_id = "s1";
399        let worktree_path = repo_dir.path().join(".claude/worktrees").join(session_id);
400        run_git(&["worktree", "add", "-q", worktree_path.to_str().unwrap()]);
401        assert!(worktree_path.exists(), "test setup: worktree must exist before cleanup");
402
403        let sessions_dir = tempdir().unwrap();
404        let artifact_path = sessions_dir.path().join(format!("{session_id}.json"));
405        std::fs::write(&artifact_path, "{}").unwrap();
406
407        let store = Arc::new(Store::open(tempdir().unwrap().keep().join("t.db")).unwrap());
408        let session = crate::types::Session {
409            id: session_id.into(), orchestrator_id: None, name: "w".into(),
410            repo: "r".into(), status: crate::types::SessionStatus::PrOpen,
411            agent_type: "c".into(), cost_usd: 0.0, started_at: 0,
412            pr_number: Some(1), pr_id: Some(1),
413            workspace_path: Some(worktree_path.to_string_lossy().to_string()),
414            pid: None,
415            model: None, context_tokens: None, catalogue_path: None,
416            context_used_pct: None, context_total_tokens: None, context_window_size: None,
417            claude_session_id: None,
418            summary: None,
419            terminal_at: None, gate_status: None,
420        };
421        store.upsert_session(&session).unwrap();
422        let engine = Engine::new(Arc::clone(&store));
423
424        engine.cleanup_session_in(session_id, sessions_dir.path()).await.unwrap();
425
426        assert!(!worktree_path.exists(), "cleanup_session must remove the worktree, like remove_session does");
427        assert!(!artifact_path.exists(), "cleanup_session must remove session artifacts, like remove_session does");
428        let after = store.get_session(session_id).unwrap().unwrap();
429        assert!(matches!(after.status, crate::types::SessionStatus::Done));
430    }
431
432    #[tokio::test]
433    async fn remove_worker_worktree_ignores_non_ninox_paths() {
434        // Should be a no-op for paths that don't match .claude/worktrees/{id}.
435        // We just verify it doesn't panic or error.
436        remove_worker_worktree("/some/random/path", "s1").await;
437        remove_worker_worktree("/repo/.claude/worktrees/other-id", "s1").await;
438        remove_worker_worktree("", "s1").await;
439    }
440}