Skip to main content

orch/cli/
events.rs

1//! CLI handler for `orch task events`. Connects to the event bus websocket
2//! and prints task status transitions in real time
3//!
4//! If the websocket is unreachable (stale port file after service restart/crash),
5//! falls back to polling the SQLite store for status changes.
6
7use anyhow::Context;
8use futures::StreamExt;
9use std::collections::HashMap;
10use std::collections::HashSet;
11use std::net::SocketAddr;
12use std::net::TcpStream;
13use std::net::{Ipv4Addr, SocketAddrV4};
14use std::time::Duration;
15use tokio::time;
16use tokio_tungstenite::connect_async;
17use tokio_tungstenite::tungstenite::Message;
18
19use crate::cli;
20use crate::engine::events::ControlMessage;
21use crate::engine::events::TaskEvent;
22use crate::engine::events::read_ws_credentials;
23use crate::store::Task;
24use crate::store::TaskStore;
25
26/// Probe whether a TCP socket is reachable on the given port.
27///
28/// Uses a short timeout (500ms) so the CLI doesn't hang on stale ports.
29fn probe_ws_port(port: u16) -> bool {
30    let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, port);
31    TcpStream::connect_timeout(&SocketAddr::V4(addr), Duration::from_millis(500)).is_ok()
32}
33
34/// Stream events from the event bus websocket. Falls back to store polling
35/// when the websocket port is stale or unreachable.
36///
37/// Output format: `HH:MM:SS task_id old_status → new_status agent PR: #N`
38pub async fn stream(repo: Option<&str>, task: Option<&str>) -> anyhow::Result<()> {
39    match read_ws_credentials() {
40        Ok((port, token)) if probe_ws_port(port) => stream_from_ws(port, &token, repo, task).await,
41        Ok((port, _)) => {
42            eprintln!("Event bus port {port} is not reachable — falling back to store polling.");
43            stream_from_store(repo, task).await
44        }
45        Err(_) => {
46            eprintln!("Event bus not available — falling back to store polling.");
47            stream_from_store(repo, task).await
48        }
49    }
50}
51
52/// Connect to the event bus websocket and stream events.
53async fn stream_from_ws(
54    port: u16,
55    token: &str,
56    repo: Option<&str>,
57    task: Option<&str>,
58) -> anyhow::Result<()> {
59    let mut url = format!(
60        "ws://127.0.0.1:{port}/events?token={}",
61        urlencoding::encode(token)
62    );
63    if let Some(r) = repo {
64        url.push_str("&repo=");
65        url.push_str(&urlencoding::encode(r));
66    }
67    if let Some(t) = task {
68        url.push_str("&task_id=");
69        url.push_str(&urlencoding::encode(t));
70    }
71
72    let (ws, _) = connect_async(&url)
73        .await
74        .context("failed to connect to event bus — is the service running?")?;
75
76    let (_write, mut read) = ws.split();
77
78    println!("Connected to event bus (port {port}). Streaming events...\n");
79
80    // Open the store for lag resyncs (best-effort — None if unavailable).
81    let store = cli::init_store().await.ok();
82
83    while let Some(msg) = read.next().await {
84        let msg = msg?;
85        if let Message::Text(text) = msg {
86            // First try to parse as a control message (lag notification).
87            if let Ok(ctrl) = serde_json::from_str::<ControlMessage>(&text) {
88                if ctrl.kind == "lagged" {
89                    eprintln!(
90                        "WARNING: event bus lagged — {} task transition(s) were dropped. \
91                         Resyncing current task state from store...",
92                        ctrl.missed
93                    );
94                    if let Some(ref s) = store {
95                        resync_from_store(s, repo, task).await;
96                    }
97                }
98                continue;
99            }
100
101            // Normal task event.
102            let Ok(event) = serde_json::from_str::<TaskEvent>(&text) else {
103                continue;
104            };
105
106            print_event(&event);
107        }
108    }
109
110    Ok(())
111}
112
113/// Format and print a single task event.
114fn print_event(event: &TaskEvent) {
115    let time = if event.timestamp.len() >= 19 {
116        &event.timestamp[11..19]
117    } else {
118        &event.timestamp
119    };
120    let agent_str = event.agent.as_deref().unwrap_or("");
121    let pr_str = event
122        .pr_number
123        .as_ref()
124        .map(|p| format!(" PR: #{p}"))
125        .unwrap_or_default();
126
127    println!(
128        "{time} {} {} \u{2192} {} {agent_str}{pr_str}",
129        event.task_id, event.old_status, event.new_status,
130    );
131}
132
133/// Resync: print current status of all active tasks from the store after a lag event.
134///
135/// This gives the operator a point-in-time snapshot so they know where things
136/// stand after missed transitions.
137async fn resync_from_store(
138    store: &TaskStore,
139    repo_filter: Option<&str>,
140    task_filter: Option<&str>,
141) {
142    let tasks = match store.list_all_active_global().await {
143        Ok(t) => t,
144        Err(e) => {
145            eprintln!("  resync failed: {e:#}");
146            return;
147        }
148    };
149
150    let now = chrono::Utc::now().format("%H:%M:%S");
151    let mut printed = 0usize;
152    for t in &tasks {
153        if let Some(rf) = repo_filter
154            && !t.repo.contains(rf)
155        {
156            continue;
157        }
158        let key = task_key(t);
159        if let Some(tf) = task_filter
160            && key != tf
161            && t.external_id.as_deref() != Some(tf)
162        {
163            continue;
164        }
165        let agent_str = t.agent.as_deref().unwrap_or("");
166        let pr_str = t
167            .pr_number
168            .map(|p| format!(" PR: #{p}"))
169            .unwrap_or_default();
170        println!(
171            "{now} [resync] {} {} {agent_str}{pr_str}",
172            key,
173            t.status.as_str(),
174        );
175        printed += 1;
176    }
177    if printed == 0 {
178        println!("{now} [resync] no active tasks");
179    }
180}
181
182/// Fallback: poll the SQLite store for task status changes.
183///
184/// When watching a specific task (`task` is Some), polls that task's status
185/// every 3 seconds and prints transitions. When watching all tasks, polls
186/// all active tasks and prints any status changes.
187async fn stream_from_store(
188    repo_filter: Option<&str>,
189    task_filter: Option<&str>,
190) -> anyhow::Result<()> {
191    let store = match cli::init_store().await {
192        Ok(s) => s,
193        Err(e) => {
194            anyhow::bail!(
195                "Cannot stream events: store unavailable ({e:#}). Is the service running?"
196            );
197        }
198    };
199
200    println!("Watching store for status changes (polling every 3s)...\n");
201
202    // Snapshot of last known statuses: task_key -> (status, agent, pr_number)
203    let mut last_status: HashMap<String, (String, Option<String>, Option<i32>)> = HashMap::new();
204
205    // Seed initial state
206    let tasks = store.list_all_active_global().await.unwrap_or_default();
207    for t in &tasks {
208        let key = task_key(t);
209        last_status.insert(
210            key,
211            (t.status.as_str().to_string(), t.agent.clone(), t.pr_number),
212        );
213    }
214
215    let mut interval = time::interval(Duration::from_secs(3));
216    loop {
217        interval.tick().await;
218
219        let Ok(tasks) = store.list_all_active_global().await else {
220            continue;
221        };
222
223        for t in &tasks {
224            let key = task_key(t);
225
226            // Apply filters
227            if let Some(ref rf) = repo_filter
228                && !t.repo.contains(rf)
229            {
230                continue;
231            }
232            if let Some(tf) = task_filter
233                && key != tf
234                && t.external_id.as_deref() != Some(tf)
235            {
236                continue;
237            }
238
239            let new_status = t.status.as_str().to_string();
240
241            match last_status.get(&key) {
242                Some((old_status, _, _)) if *old_status == new_status => {
243                    // No change
244                }
245                Some((old_status, _, _)) => {
246                    // Status changed — print transition
247                    let now = chrono::Utc::now().format("%H:%M:%S");
248                    let agent_str = t.agent.as_deref().unwrap_or("");
249                    let pr_str = t
250                        .pr_number
251                        .map(|p| format!(" PR: #{p}"))
252                        .unwrap_or_default();
253
254                    println!("{now} {key} {old_status} \u{2192} {new_status} {agent_str}{pr_str}");
255                    last_status.insert(key, (new_status, t.agent.clone(), t.pr_number));
256                }
257                None => {
258                    // New task appeared
259                    let now = chrono::Utc::now().format("%H:%M:%S");
260                    let agent_str = t.agent.as_deref().unwrap_or("");
261                    println!("{now} {key} - \u{2192} {new_status} {agent_str}");
262                    last_status.insert(key, (new_status, t.agent.clone(), t.pr_number));
263                }
264            }
265        }
266
267        // Check for tasks that were removed (completed + cleaned up)
268        let active_keys: HashSet<String> = tasks.iter().map(task_key).collect();
269        let disappeared: Vec<String> = last_status
270            .keys()
271            .filter(|k| !active_keys.contains(*k))
272            .cloned()
273            .collect();
274        for key in disappeared {
275            if let Some((old_status, _, _)) = last_status.remove(&key)
276                && old_status != "done"
277            {
278                let now = chrono::Utc::now().format("%H:%M:%S");
279                println!("{now} {key} {old_status} \u{2192} done");
280            }
281        }
282    }
283}
284
285/// Derive a display key for a task: prefer external_id, fall back to internal id.
286fn task_key(t: &Task) -> String {
287    t.external_id
288        .clone()
289        .unwrap_or_else(|| format!("internal:{}", t.id))
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295    use crate::store::TaskStatus;
296
297    #[test]
298    fn probe_ws_port_unreachable() {
299        // Port 1 should be unreachable (reserved).
300        assert!(!probe_ws_port(1));
301    }
302
303    #[test]
304    fn task_key_prefers_external_id() {
305        let t = Task {
306            id: 42,
307            external_id: Some("123".to_string()),
308            repo: "o/r".into(),
309            origin: "external".into(),
310            title: "t".into(),
311            body: String::new(),
312            status: TaskStatus::New,
313            source: String::new(),
314            source_id: String::new(),
315            author: String::new(),
316            url: String::new(),
317            labels: Vec::new(),
318            agent: None,
319            model: None,
320            complexity: String::new(),
321            estimate: 0,
322            route_reason: String::new(),
323            agent_profile: String::new(),
324            route_attempts: 0,
325            attempts: 0,
326            branch: String::new(),
327            worktree: String::new(),
328            worktree_cleaned: false,
329            owner_node: None,
330            summary: String::new(),
331            last_error: String::new(),
332            parent_id: None,
333            block_reason: None,
334            pr_number: None,
335            pr_review_context: String::new(),
336            last_review_ts: String::new(),
337            review_ts_map: "{}".to_string(),
338            last_comment_review_ts: String::new(),
339            merge_conflict_retries: 0,
340            ci_merge_failures: 0,
341            pr_create_failures: 0,
342            push_failures: 0,
343            network_retries: 0,
344            timeout_retries: 0,
345            review_agent_failures: 0,
346            review_resets: 0,
347            review_cycles: 0,
348            review_invocations: 0,
349            needs_review_refires: 0,
350            input_tokens: 0,
351            output_tokens: 0,
352            total_cost_usd: 0.0,
353            model_reroute_chain: String::new(),
354            limit_reroute_chain: String::new(),
355            memory: Vec::new(),
356            delegations: Vec::new(),
357            auto_unblock_count: 0,
358            auto_unblock_last_at: String::new(),
359            auto_unblock_last_reason: String::new(),
360            ci_recovery_count: 0,
361            no_code_reroutes: 0,
362            no_code_last_agent: String::new(),
363            created_at: String::new(),
364            updated_at: String::new(),
365        };
366        assert_eq!(task_key(&t), "123");
367    }
368
369    #[test]
370    fn task_key_falls_back_to_internal() {
371        let t = Task {
372            id: 7,
373            external_id: None,
374            repo: "o/r".into(),
375            origin: "internal".into(),
376            title: "t".into(),
377            body: String::new(),
378            status: TaskStatus::InProgress,
379            source: String::new(),
380            source_id: String::new(),
381            author: String::new(),
382            url: String::new(),
383            labels: Vec::new(),
384            agent: Some("claude".to_string()),
385            model: None,
386            complexity: String::new(),
387            estimate: 0,
388            route_reason: String::new(),
389            agent_profile: String::new(),
390            route_attempts: 0,
391            attempts: 1,
392            branch: String::new(),
393            worktree: String::new(),
394            worktree_cleaned: false,
395            owner_node: None,
396            summary: String::new(),
397            last_error: String::new(),
398            parent_id: None,
399            block_reason: None,
400            pr_number: None,
401            pr_review_context: String::new(),
402            last_review_ts: String::new(),
403            review_ts_map: "{}".to_string(),
404            last_comment_review_ts: String::new(),
405            merge_conflict_retries: 0,
406            ci_merge_failures: 0,
407            pr_create_failures: 0,
408            push_failures: 0,
409            network_retries: 0,
410            timeout_retries: 0,
411            review_agent_failures: 0,
412            review_resets: 0,
413            review_cycles: 0,
414            review_invocations: 0,
415            needs_review_refires: 0,
416            input_tokens: 0,
417            output_tokens: 0,
418            total_cost_usd: 0.0,
419            model_reroute_chain: String::new(),
420            limit_reroute_chain: String::new(),
421            memory: Vec::new(),
422            delegations: Vec::new(),
423            auto_unblock_count: 0,
424            auto_unblock_last_at: String::new(),
425            auto_unblock_last_reason: String::new(),
426            ci_recovery_count: 0,
427            no_code_reroutes: 0,
428            no_code_last_agent: String::new(),
429            created_at: String::new(),
430            updated_at: String::new(),
431        };
432        assert_eq!(task_key(&t), "internal:7");
433    }
434}