1use crate::{github::GitHubClient, 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 ClientOutput { session_id: SessionId, generation: u64, bytes: Vec<u8> },
19 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 stream_cancel: Mutex<HashMap<SessionId, tokio::sync::oneshot::Sender<()>>>,
35 pub github: Option<GitHubClient>,
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 Arc::new(Self {
55 store,
56 tx,
57 pty_writers: Mutex::new(HashMap::new()),
58 stream_cancel: Mutex::new(HashMap::new()),
59 github,
60 })
61 }
62
63 pub async fn register_stream(
67 &self,
68 session_id: SessionId,
69 ) -> tokio::sync::oneshot::Receiver<()> {
70 let mut map = self.stream_cancel.lock().await;
71 if let Some(old_tx) = map.remove(&session_id) {
72 let _ = old_tx.send(());
73 }
74 let (tx, rx) = tokio::sync::oneshot::channel();
75 map.insert(session_id, tx);
76 rx
77 }
78
79 pub fn emit(&self, event: Event) {
80 let _ = self.tx.send(event);
81 }
82
83 pub fn subscribe(&self) -> broadcast::Receiver<Event> {
84 self.tx.subscribe()
85 }
86
87 pub async fn register_pty_writer(
88 &self,
89 session_id: SessionId,
90 writer: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
91 ) {
92 self.pty_writers.lock().await.insert(session_id, writer);
93 }
94
95 pub async fn get_pty_writer(
96 &self,
97 session_id: &str,
98 ) -> Option<tokio::sync::mpsc::UnboundedSender<Vec<u8>>> {
99 self.pty_writers.lock().await.get(session_id).cloned()
100 }
101
102 pub async fn remove_orchestrator(&self, orchestrator_id: &str) -> anyhow::Result<()> {
104 let workers = self.store.sessions_by_orchestrator(orchestrator_id)?;
105 for session in &workers {
106 let _ = crate::tmux::kill_session(&session.id).await;
107 if let Some(ref wp) = session.workspace_path {
108 remove_worker_worktree(wp, &session.id).await;
109 }
110 }
111 let _ = crate::tmux::kill_session(orchestrator_id).await;
113 self.store.delete_orchestrator(orchestrator_id)?;
114 for session in workers {
115 self.emit(Event::SessionDone(session.id));
116 }
117 self.emit(Event::OrchestratorRemoved(orchestrator_id.to_string()));
118 Ok(())
119 }
120
121 pub async fn remove_session(&self, session_id: &str) -> anyhow::Result<()> {
123 let _ = crate::tmux::kill_session(session_id).await;
124 if let Ok(Some(session)) = self.store.get_session(session_id) {
125 if let Some(ref wp) = session.workspace_path {
126 remove_worker_worktree(wp, session_id).await;
127 }
128 }
129 self.store.delete_session(session_id)?;
130 self.emit(Event::SessionDone(session_id.to_string()));
131 Ok(())
132 }
133
134 pub async fn send_to_session(&self, session_id: &str, message: &str) -> anyhow::Result<()> {
139 crate::tmux::send_keys(session_id, message).await
140 }
141
142 pub async fn terminate_session(&self, session_id: &str) -> anyhow::Result<()> {
144 let _ = crate::tmux::kill_session(session_id).await;
146
147 if let Some(mut session) = self.store.get_session(session_id)? {
148 session.status = crate::types::SessionStatus::Terminated;
149 self.store.upsert_session(&session)?;
150 self.emit(Event::SessionUpdated(session));
151 }
152 Ok(())
153 }
154
155 pub async fn cleanup_session(&self, session_id: &str) -> anyhow::Result<()> {
158 let _ = crate::tmux::kill_session(session_id).await;
160
161 if let Some(mut session) = self.store.get_session(session_id)? {
162 session.status = crate::types::SessionStatus::Done;
163 self.store.upsert_session(&session)?;
164 self.emit(Event::SessionUpdated(session));
165 }
166 Ok(())
167 }
168}
169
170async fn remove_worker_worktree(workspace_path: &str, session_id: &str) {
175 let suffix = format!("/.claude/worktrees/{session_id}");
176 if !workspace_path.ends_with(&suffix) {
177 return; }
179 let repo_root = &workspace_path[..workspace_path.len() - suffix.len()];
181 if repo_root.is_empty() {
182 return;
183 }
184 let _ = tokio::process::Command::new("git")
185 .args(["-C", repo_root, "worktree", "remove", "--force", workspace_path])
186 .output()
187 .await;
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193 use crate::store::Store;
194 use tempfile::tempdir;
195
196 #[tokio::test]
197 async fn emit_received_by_subscriber() {
198 let store = Arc::new(Store::open(tempdir().unwrap().keep().join("t.db")).unwrap());
199 let engine = Engine::new(store);
200 let mut rx = engine.subscribe();
201 engine.emit(Event::SessionDone("s1".into()));
202 let event = rx.recv().await.unwrap();
203 assert!(matches!(event, Event::SessionDone(id) if id == "s1"));
204 }
205
206 #[tokio::test]
207 async fn terminate_emits_session_updated() {
208 let store = Arc::new(Store::open(tempdir().unwrap().keep().join("t.db")).unwrap());
209 let session = crate::types::Session {
210 id: "s1".into(), orchestrator_id: None, name: "w".into(),
211 repo: "r".into(), status: crate::types::SessionStatus::Working,
212 agent_type: "c".into(), cost_usd: 0.0, started_at: 0,
213 pr_number: None, pr_id: None, workspace_path: None, pid: None,
214 model: None, context_tokens: None, catalogue_path: None,
215 };
216 store.upsert_session(&session).unwrap();
217 let engine = Engine::new(store);
218 let mut rx = engine.subscribe();
219
220 engine.terminate_session("s1").await.unwrap();
221
222 let evt = rx.recv().await.unwrap();
223 if let Event::SessionUpdated(s) = evt {
224 assert!(matches!(s.status, crate::types::SessionStatus::Terminated));
225 } else {
226 panic!("expected SessionUpdated");
227 }
228 }
229
230 #[tokio::test]
231 async fn cleanup_session_sets_done_status() {
232 let store = Arc::new(
233 Store::open(tempdir().unwrap().keep().join("t.db")).unwrap()
234 );
235 let session = crate::types::Session {
236 id: "s1".into(), orchestrator_id: None, name: "w".into(),
237 repo: "r".into(), status: crate::types::SessionStatus::PrOpen,
238 agent_type: "c".into(), cost_usd: 0.0, started_at: 0,
239 pr_number: Some(1), pr_id: Some(1),
240 workspace_path: None, pid: None,
241 model: None, context_tokens: None, catalogue_path: None,
242 };
243 store.upsert_session(&session).unwrap();
244 let engine = Engine::new(Arc::clone(&store));
245 let mut rx = engine.subscribe();
246
247 engine.cleanup_session("s1").await.unwrap();
248
249 let evt = rx.recv().await.unwrap();
250 if let Event::SessionUpdated(s) = evt {
251 assert!(matches!(s.status, crate::types::SessionStatus::Done));
252 } else {
253 panic!("expected SessionUpdated");
254 }
255 }
256
257 #[tokio::test]
258 async fn remove_worker_worktree_ignores_non_ninox_paths() {
259 remove_worker_worktree("/some/random/path", "s1").await;
262 remove_worker_worktree("/repo/.claude/worktrees/other-id", "s1").await;
263 remove_worker_worktree("", "s1").await;
264 }
265}