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(()) if the tmux send succeeded; returns an error if the session
158    /// has no active tmux window or tmux is unavailable.
159    pub async fn send_to_session(&self, session_id: &str, message: &str) -> anyhow::Result<()> {
160        crate::tmux::send_keys(session_id, message).await
161    }
162
163    /// Kill the tmux session, mark it Terminated in the DB, and emit SessionUpdated.
164    pub async fn terminate_session(&self, session_id: &str) -> anyhow::Result<()> {
165        // Best-effort tmux kill (session may already be dead).
166        let _ = crate::tmux::kill_session(session_id).await;
167
168        if let Some(mut session) = self.store.get_session(session_id)? {
169            // Never clobber a terminal status — most importantly, never flip
170            // a `Done` session back to `Terminated`. `Done` is only ever
171            // reached via `handle_merge_detection`, which already notified
172            // the orchestrator; `sweep_retired_sessions`'s notification
173            // dedup relies on `Done` meaning "already told" (see
174            // `lifecycle::poller::sweep_retired_sessions`), so re-marking it
175            // `Terminated` here would make the sweep send a second,
176            // contradictory notice for a PR that was in fact merged.
177            if matches!(
178                session.status,
179                SessionStatus::Done | SessionStatus::Terminated | SessionStatus::Interrupted
180            ) {
181                return Ok(());
182            }
183            session.status = SessionStatus::Terminated;
184            self.store.upsert_session(&session)?;
185            self.emit(Event::SessionUpdated(session, SessionFields::STATUS));
186        }
187        Ok(())
188    }
189
190    /// Kill the tmux session (best-effort), remove its worktree/artifacts,
191    /// and mark it Done in the DB. Called automatically when a PR is
192    /// merged. Emits SessionUpdated. Mirrors `remove_session`'s worktree
193    /// and artifact cleanup so the record isn't deleted here but still
194    /// stops leaking a checked-out worktree and per-session hook files.
195    pub async fn cleanup_session(&self, session_id: &str) -> anyhow::Result<()> {
196        self.cleanup_session_in(session_id, &crate::config::AppConfig::sessions_dir()).await
197    }
198
199    /// `cleanup_session`'s implementation, with the sessions dir as a
200    /// parameter so tests can point artifact removal at a tempdir instead
201    /// of the real `AppConfig::sessions_dir()`.
202    async fn cleanup_session_in(
203        &self,
204        session_id:   &str,
205        sessions_dir: &std::path::Path,
206    ) -> anyhow::Result<()> {
207        // Best-effort tmux kill — session may already be dead.
208        let _ = crate::tmux::kill_session(session_id).await;
209
210        if let Some(mut session) = self.store.get_session(session_id)? {
211            remove_worktree_and_artifacts(session_id, session.workspace_path.as_deref(), sessions_dir).await;
212            session.status = crate::types::SessionStatus::Done;
213            session.terminal_at = Some(crate::lifecycle::poller::now_millis());
214            self.store.upsert_session(&session)?;
215            self.emit(Event::SessionUpdated(session, SessionFields::STATUS | SessionFields::TERMINAL_AT));
216        }
217        Ok(())
218    }
219}
220
221/// Remove a session's worktree (if any) and hook artifacts — the shared
222/// teardown tail of `remove_orchestrator`, `remove_session`, and
223/// `cleanup_session`, so none of them leak a checked-out worktree or
224/// per-session hook files.
225async fn remove_worktree_and_artifacts(
226    session_id:     &str,
227    workspace_path: Option<&str>,
228    sessions_dir:   &std::path::Path,
229) {
230    if let Some(wp) = workspace_path {
231        remove_worker_worktree(wp, session_id).await;
232    }
233    crate::hooks::remove_session_artifacts(sessions_dir, session_id);
234}
235
236/// Remove a Ninox-managed git worktree (best-effort, never propagates errors).
237///
238/// Only acts on paths that match the `.claude/worktrees/{session_id}` pattern
239/// so it never touches unrelated directories.
240async fn remove_worker_worktree(workspace_path: &str, session_id: &str) {
241    let suffix = format!("/.claude/worktrees/{session_id}");
242    if !workspace_path.ends_with(&suffix) {
243        return; // Not a Ninox worktree — leave it alone.
244    }
245    // Derive the repo root by stripping the worktree suffix.
246    let repo_root = &workspace_path[..workspace_path.len() - suffix.len()];
247    if repo_root.is_empty() {
248        return;
249    }
250    let _ = tokio::process::Command::new("git")
251        .args(["-C", repo_root, "worktree", "remove", "--force", workspace_path])
252        .output()
253        .await;
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259    use crate::store::Store;
260    use tempfile::tempdir;
261
262    #[tokio::test]
263    async fn emit_received_by_subscriber() {
264        let store = Arc::new(Store::open(tempdir().unwrap().keep().join("t.db")).unwrap());
265        let engine = Engine::new(store);
266        let mut rx = engine.subscribe();
267        engine.emit(Event::SessionDone("s1".into()));
268        let event = rx.recv().await.unwrap();
269        assert!(matches!(event, Event::SessionDone(id) if id == "s1"));
270    }
271
272    #[tokio::test]
273    async fn terminate_emits_session_updated() {
274        let store = Arc::new(Store::open(tempdir().unwrap().keep().join("t.db")).unwrap());
275        let session = crate::types::Session {
276            id: "s1".into(), orchestrator_id: None, name: "w".into(),
277            repo: "r".into(), status: crate::types::SessionStatus::Working,
278            agent_type: "c".into(), cost_usd: 0.0, started_at: 0,
279            pr_number: None, pr_id: None, workspace_path: None, pid: None,
280            model: None, context_tokens: None, catalogue_path: None,
281            context_used_pct: None, context_total_tokens: None, context_window_size: None,
282            claude_session_id: None,
283            summary: None,
284            terminal_at: None, gate_status: None,
285        };
286        store.upsert_session(&session).unwrap();
287        let engine = Engine::new(store);
288        let mut rx = engine.subscribe();
289
290        engine.terminate_session("s1").await.unwrap();
291
292        let evt = rx.recv().await.unwrap();
293        if let Event::SessionUpdated(s, _fields) = evt {
294            assert!(matches!(s.status, crate::types::SessionStatus::Terminated));
295            assert_eq!(
296                s.terminal_at, None,
297                "user-initiated terminate_session must not stamp terminal_at — \
298                 that's reserved for the automatic lifecycle path, so this \
299                 session is purged on sight rather than held for the \
300                 retention grace period",
301            );
302        } else {
303            panic!("expected SessionUpdated");
304        }
305    }
306
307    /// A `Done` session (reached via `cleanup_session`, which already
308    /// notified the orchestrator about the merge) must never be flipped back
309    /// to `Terminated` by a later `terminate_session` call (e.g. the `DELETE
310    /// /sessions/:id` route firing on a stale client, or a race with the
311    /// poller). `sweep_retired_sessions`'s notification dedup relies on
312    /// `Done` meaning "already told" — reopening it as `Terminated` would
313    /// make the sweep send a second, contradictory notification claiming the
314    /// PR was never detected merged.
315    #[tokio::test]
316    async fn terminate_session_does_not_reopen_a_done_session() {
317        let store = Arc::new(Store::open(tempdir().unwrap().keep().join("t.db")).unwrap());
318        let session = crate::types::Session {
319            id: "s1".into(), orchestrator_id: None, name: "w".into(),
320            repo: "r".into(), status: crate::types::SessionStatus::Done,
321            agent_type: "c".into(), cost_usd: 0.0, started_at: 0,
322            pr_number: Some(1), pr_id: Some(1), workspace_path: None, pid: None,
323            model: None, context_tokens: None, catalogue_path: None,
324            context_used_pct: None, context_total_tokens: None, context_window_size: None,
325            claude_session_id: None,
326            summary: None,
327            terminal_at: Some(1_000), gate_status: None,
328        };
329        store.upsert_session(&session).unwrap();
330        let engine = Engine::new(Arc::clone(&store));
331        let mut rx = engine.subscribe();
332
333        engine.terminate_session("s1").await.unwrap();
334
335        assert!(
336            rx.try_recv().is_err(),
337            "a no-op terminate_session on a Done session must not emit SessionUpdated"
338        );
339        let after = store.get_session("s1").unwrap().unwrap();
340        assert!(matches!(after.status, crate::types::SessionStatus::Done), "status must stay Done");
341        assert_eq!(after.terminal_at, Some(1_000), "terminal_at must be untouched");
342    }
343
344    #[tokio::test]
345    async fn cleanup_session_sets_done_status() {
346        let store = Arc::new(
347            Store::open(tempdir().unwrap().keep().join("t.db")).unwrap()
348        );
349        let session = crate::types::Session {
350            id: "s1".into(), orchestrator_id: None, name: "w".into(),
351            repo: "r".into(), status: crate::types::SessionStatus::PrOpen,
352            agent_type: "c".into(), cost_usd: 0.0, started_at: 0,
353            pr_number: Some(1), pr_id: Some(1),
354            workspace_path: None, pid: None,
355            model: None, context_tokens: None, catalogue_path: None,
356            context_used_pct: None, context_total_tokens: None, context_window_size: None,
357            claude_session_id: None,
358            summary: None,
359            terminal_at: None, gate_status: None,
360        };
361        store.upsert_session(&session).unwrap();
362        let engine = Engine::new(Arc::clone(&store));
363        let mut rx = engine.subscribe();
364
365        engine.cleanup_session("s1").await.unwrap();
366
367        let evt = rx.recv().await.unwrap();
368        if let Event::SessionUpdated(s, _fields) = evt {
369            assert!(matches!(s.status, crate::types::SessionStatus::Done));
370            assert!(
371                s.terminal_at.is_some(),
372                "cleanup_session must stamp terminal_at so the retention sweep can hold this \
373                 record for the fleet board's grace window instead of purging it on sight",
374            );
375        } else {
376            panic!("expected SessionUpdated");
377        }
378    }
379
380    #[tokio::test]
381    async fn cleanup_session_removes_worktree_and_artifacts() {
382        // Real git repo + real worktree so we exercise the same
383        // `remove_worker_worktree` path `remove_session` uses, not a mock.
384        let repo_dir = tempdir().unwrap();
385        let run_git = |args: &[&str]| {
386            let status = std::process::Command::new("git")
387                .args(args)
388                .current_dir(repo_dir.path())
389                .status()
390                .unwrap();
391            assert!(status.success(), "git {args:?} failed");
392        };
393        run_git(&["init", "-q"]);
394        run_git(&["-c", "user.email=t@t.com", "-c", "user.name=t", "commit", "--allow-empty", "-q", "-m", "init"]);
395
396        let session_id = "s1";
397        let worktree_path = repo_dir.path().join(".claude/worktrees").join(session_id);
398        run_git(&["worktree", "add", "-q", worktree_path.to_str().unwrap()]);
399        assert!(worktree_path.exists(), "test setup: worktree must exist before cleanup");
400
401        let sessions_dir = tempdir().unwrap();
402        let artifact_path = sessions_dir.path().join(format!("{session_id}.json"));
403        std::fs::write(&artifact_path, "{}").unwrap();
404
405        let store = Arc::new(Store::open(tempdir().unwrap().keep().join("t.db")).unwrap());
406        let session = crate::types::Session {
407            id: session_id.into(), orchestrator_id: None, name: "w".into(),
408            repo: "r".into(), status: crate::types::SessionStatus::PrOpen,
409            agent_type: "c".into(), cost_usd: 0.0, started_at: 0,
410            pr_number: Some(1), pr_id: Some(1),
411            workspace_path: Some(worktree_path.to_string_lossy().to_string()),
412            pid: None,
413            model: None, context_tokens: None, catalogue_path: None,
414            context_used_pct: None, context_total_tokens: None, context_window_size: None,
415            claude_session_id: None,
416            summary: None,
417            terminal_at: None, gate_status: None,
418        };
419        store.upsert_session(&session).unwrap();
420        let engine = Engine::new(Arc::clone(&store));
421
422        engine.cleanup_session_in(session_id, sessions_dir.path()).await.unwrap();
423
424        assert!(!worktree_path.exists(), "cleanup_session must remove the worktree, like remove_session does");
425        assert!(!artifact_path.exists(), "cleanup_session must remove session artifacts, like remove_session does");
426        let after = store.get_session(session_id).unwrap().unwrap();
427        assert!(matches!(after.status, crate::types::SessionStatus::Done));
428    }
429
430    #[tokio::test]
431    async fn remove_worker_worktree_ignores_non_ninox_paths() {
432        // Should be a no-op for paths that don't match .claude/worktrees/{id}.
433        // We just verify it doesn't panic or error.
434        remove_worker_worktree("/some/random/path", "s1").await;
435        remove_worker_worktree("/repo/.claude/worktrees/other-id", "s1").await;
436        remove_worker_worktree("", "s1").await;
437    }
438}