Skip to main content

blyte_cli/
wait.rs

1use std::collections::HashSet;
2use std::io::Write;
3use std::path::Path;
4use std::time::{Duration, Instant};
5
6pub fn run(ids: &[String], any: bool, timeout_secs: u64) -> i32 {
7    let out = std::process::Command::new("git")
8        .args(["rev-parse", "--show-toplevel"])
9        .output();
10    let Ok(out) = out else {
11        eprintln!("error: git not found");
12        return 2;
13    };
14    if !out.status.success() {
15        eprintln!("error: not a git repository");
16        return 2;
17    }
18    let root = std::path::PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
19    wait_in(
20        &root.join(".wt"),
21        ids,
22        any,
23        Duration::from_secs(timeout_secs),
24        Duration::from_secs(2),
25        Duration::from_secs(15),
26        &mut std::io::stdout(),
27        &mut std::io::stderr(),
28    )
29}
30
31fn try_read_summary(wt: &Path, id: &str) -> Option<serde_json::Value> {
32    let path = wt.join(format!("{id}.json"));
33    let s = std::fs::read_to_string(path).ok()?;
34    serde_json::from_str(&s).ok()
35}
36
37fn read_start_pid(path: &Path) -> Option<libc::pid_t> {
38    let s = std::fs::read_to_string(path).ok()?;
39    let val: serde_json::Value = serde_json::from_str(&s).ok()?;
40    val.get("pid")
41        .and_then(|v| v.as_i64())
42        .map(|v| v as libc::pid_t)
43}
44
45fn is_pid_alive(pid: libc::pid_t) -> bool {
46    if pid <= 0 {
47        return false;
48    }
49    let ret = unsafe { libc::kill(pid, 0) };
50    if ret == 0 {
51        true
52    } else {
53        std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
54    }
55}
56
57fn format_summary_line(id: &str, summary: &serde_json::Value) -> String {
58    let outcome = summary
59        .get("outcome")
60        .and_then(|v| v.as_str())
61        .unwrap_or("?");
62    let turns = summary
63        .get("turns")
64        .and_then(|v| {
65            v.as_i64()
66                .map(|t| t.to_string())
67                .or_else(|| v.as_u64().map(|t| t.to_string()))
68        })
69        .unwrap_or_else(|| "?".to_string());
70    let cost = match summary.get("cost_usd").and_then(|v| v.as_f64()) {
71        Some(c) => format!("${:.2}", c),
72        None => "-".to_string(),
73    };
74    format!("{id} {outcome} {turns} {cost}")
75}
76
77enum IdStatus {
78    Finished(String),
79    Running,
80    LooksDead,
81    Unknown,
82}
83
84fn check_id_status(wt: &Path, id: &str) -> IdStatus {
85    // 1. finished: wt/<id>.json exists and parses as JSON
86    if let Some(summary) = try_read_summary(wt, id) {
87        return IdStatus::Finished(format_summary_line(id, &summary));
88    }
89
90    // 2. running: wt/<id>.start.json exists, its pid is > 0 and alive
91    let start_path = wt.join(format!("{id}.start.json"));
92    if start_path.exists() {
93        if let Some(pid) = read_start_pid(&start_path) {
94            if is_pid_alive(pid) {
95                return IdStatus::Running;
96            }
97        }
98
99        // 3. dead: otherwise, if wt/<id>.start.json exists. Before declaring a run dead, check
100        // wt/<id>.json once more (the run may have written its summary and exited between the two checks);
101        // if it now exists the run is finished.
102        if let Some(summary) = try_read_summary(wt, id) {
103            return IdStatus::Finished(format_summary_line(id, &summary));
104        }
105        return IdStatus::LooksDead;
106    }
107
108    IdStatus::Unknown
109}
110
111fn is_known(wt: &Path, id: &str) -> bool {
112    let has_summary = try_read_summary(wt, id).is_some();
113    let has_start = wt.join(format!("{id}.start.json")).exists();
114    has_summary || has_start
115}
116
117#[allow(clippy::too_many_arguments)]
118pub fn wait_in(
119    wt: &Path,
120    ids: &[String],
121    any: bool,
122    timeout: Duration,
123    poll: Duration,
124    grace: Duration,
125    out: &mut impl Write,
126    err: &mut impl Write,
127) -> i32 {
128    let mut unique_ids: Vec<&str> = Vec::new();
129    let mut seen = HashSet::new();
130    for id in ids {
131        if seen.insert(id.as_str()) {
132            unique_ids.push(id.as_str());
133        }
134    }
135
136    if unique_ids.is_empty() {
137        return 0;
138    }
139
140    let start_time = Instant::now();
141    let mut printed = vec![false; unique_ids.len()];
142    let mut first_dead = vec![None; unique_ids.len()];
143    let mut printed_count = 0;
144
145    loop {
146        let mut printed_this_poll = false;
147        for (i, id) in unique_ids.iter().enumerate() {
148            if printed[i] {
149                continue;
150            }
151            match check_id_status(wt, id) {
152                IdStatus::Finished(line) => {
153                    let _ = writeln!(out, "{line}");
154                    let _ = out.flush();
155                    printed[i] = true;
156                    first_dead[i] = None;
157                    printed_count += 1;
158                    printed_this_poll = true;
159                }
160                IdStatus::Running => {
161                    first_dead[i] = None;
162                }
163                IdStatus::LooksDead => {
164                    let first_seen = *first_dead[i].get_or_insert_with(Instant::now);
165                    if grace.is_zero() || first_seen.elapsed() >= grace {
166                        let _ = writeln!(out, "{id} dead - -");
167                        let _ = out.flush();
168                        printed[i] = true;
169                        first_dead[i] = None;
170                        printed_count += 1;
171                        printed_this_poll = true;
172                    }
173                }
174                IdStatus::Unknown => {
175                    first_dead[i] = None;
176                }
177            }
178        }
179
180        if printed_count == unique_ids.len() {
181            return 0;
182        }
183
184        if any && printed_this_poll {
185            return 0;
186        }
187
188        let elapsed = start_time.elapsed();
189
190        if elapsed >= timeout && timeout < grace {
191            let unprinted: Vec<&str> = unique_ids
192                .iter()
193                .enumerate()
194                .filter(|(i, _)| !printed[*i])
195                .map(|(_, id)| *id)
196                .collect();
197            let _ = writeln!(err, "still running: {}", unprinted.join(" "));
198            let _ = err.flush();
199            return 2;
200        }
201
202        if elapsed >= grace {
203            let unknown_ids: Vec<&str> = unique_ids
204                .iter()
205                .enumerate()
206                .filter(|(i, id)| !printed[*i] && !is_known(wt, id))
207                .map(|(_, id)| *id)
208                .collect();
209            if !unknown_ids.is_empty() {
210                for id in unknown_ids {
211                    let _ = writeln!(err, "no dispatch {id} here");
212                }
213                let _ = err.flush();
214                return 1;
215            }
216        }
217
218        if elapsed >= timeout {
219            let unprinted: Vec<&str> = unique_ids
220                .iter()
221                .enumerate()
222                .filter(|(i, _)| !printed[*i])
223                .map(|(_, id)| *id)
224                .collect();
225            let _ = writeln!(err, "still running: {}", unprinted.join(" "));
226            let _ = err.flush();
227            return 2;
228        }
229
230        let remaining = timeout.saturating_sub(start_time.elapsed());
231        let sleep_dur = poll.min(remaining);
232        std::thread::sleep(sleep_dur);
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    #[test]
241    fn finished_run_prints_summary_line() {
242        let dir = tempfile::tempdir().unwrap();
243        let wt = dir.path();
244        std::fs::write(
245            wt.join("T1.json"),
246            r#"{"outcome":"verified","turns":41,"cost_usd":0.374}"#,
247        )
248        .unwrap();
249        let mut out = Vec::new();
250        let mut err = Vec::new();
251        let code = wait_in(
252            wt,
253            &["T1".to_string()],
254            false,
255            Duration::from_secs(5),
256            Duration::from_millis(10),
257            Duration::ZERO,
258            &mut out,
259            &mut err,
260        );
261        assert_eq!(code, 0);
262        assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 41 $0.37\n");
263        assert!(err.is_empty());
264    }
265
266    #[test]
267    fn missing_cost_prints_dash() {
268        let dir = tempfile::tempdir().unwrap();
269        let wt = dir.path();
270        std::fs::write(
271            wt.join("T1.json"),
272            r#"{"outcome":"gate_failed","turns":7,"cost_usd":null}"#,
273        )
274        .unwrap();
275        let mut out = Vec::new();
276        let mut err = Vec::new();
277        let code = wait_in(
278            wt,
279            &["T1".to_string()],
280            false,
281            Duration::from_secs(5),
282            Duration::from_millis(10),
283            Duration::ZERO,
284            &mut out,
285            &mut err,
286        );
287        assert_eq!(code, 0);
288        assert_eq!(String::from_utf8(out).unwrap(), "T1 gate_failed 7 -\n");
289        assert!(err.is_empty());
290    }
291
292    #[test]
293    fn dead_run() {
294        let dir = tempfile::tempdir().unwrap();
295        let wt = dir.path();
296        let mut child = std::process::Command::new("true").spawn().unwrap();
297        let pid = child.id();
298        child.wait().unwrap();
299        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
300        let mut out = Vec::new();
301        let mut err = Vec::new();
302        let code = wait_in(
303            wt,
304            &["T1".to_string()],
305            false,
306            Duration::from_secs(5),
307            Duration::from_millis(10),
308            Duration::ZERO,
309            &mut out,
310            &mut err,
311        );
312        assert_eq!(code, 0);
313        assert_eq!(String::from_utf8(out).unwrap(), "T1 dead - -\n");
314        assert!(err.is_empty());
315    }
316
317    #[test]
318    fn zero_pid_is_dead() {
319        let dir = tempfile::tempdir().unwrap();
320        let wt = dir.path();
321        std::fs::write(wt.join("T1.start.json"), r#"{"pid": 0}"#).unwrap();
322        let mut out = Vec::new();
323        let mut err = Vec::new();
324        let code = wait_in(
325            wt,
326            &["T1".to_string()],
327            false,
328            Duration::from_secs(5),
329            Duration::from_millis(10),
330            Duration::ZERO,
331            &mut out,
332            &mut err,
333        );
334        assert_eq!(code, 0);
335        assert_eq!(String::from_utf8(out).unwrap(), "T1 dead - -\n");
336        assert!(err.is_empty());
337    }
338
339    #[test]
340    fn unknown_id_errors_without_waiting() {
341        let dir = tempfile::tempdir().unwrap();
342        let wt = dir.path();
343        let mut out = Vec::new();
344        let mut err = Vec::new();
345        let start = Instant::now();
346        let code = wait_in(
347            wt,
348            &["T9".to_string()],
349            false,
350            Duration::from_secs(5),
351            Duration::from_millis(10),
352            Duration::from_millis(50),
353            &mut out,
354            &mut err,
355        );
356        let elapsed = start.elapsed();
357        assert_eq!(code, 1);
358        let err_str = String::from_utf8(err).unwrap();
359        assert!(err_str.contains("no dispatch T9 here"));
360        assert!(out.is_empty());
361        assert!(elapsed < Duration::from_secs(1));
362    }
363
364    #[test]
365    fn timeout_with_running_run() {
366        let dir = tempfile::tempdir().unwrap();
367        let wt = dir.path();
368        let pid = std::process::id();
369        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
370        let mut out = Vec::new();
371        let mut err = Vec::new();
372        let code = wait_in(
373            wt,
374            &["T1".to_string()],
375            false,
376            Duration::from_millis(50),
377            Duration::from_millis(10),
378            Duration::ZERO,
379            &mut out,
380            &mut err,
381        );
382        assert_eq!(code, 2);
383        assert!(out.is_empty());
384        let err_str = String::from_utf8(err).unwrap();
385        assert!(err_str.contains("still running: T1"));
386    }
387
388    #[test]
389    fn all_mode_waits_for_every_run() {
390        let dir = tempfile::tempdir().unwrap();
391        let wt = dir.path();
392        std::fs::write(
393            wt.join("T1.json"),
394            r#"{"outcome":"verified","turns":41,"cost_usd":0.374}"#,
395        )
396        .unwrap();
397        let pid = std::process::id();
398        std::fs::write(wt.join("T2.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
399        let wt_clone = wt.to_path_buf();
400        std::thread::spawn(move || {
401            std::thread::sleep(Duration::from_millis(100));
402            std::fs::write(
403                wt_clone.join("T2.json"),
404                r#"{"outcome":"verified","turns":10,"cost_usd":0.10}"#,
405            )
406            .unwrap();
407        });
408        let mut out = Vec::new();
409        let mut err = Vec::new();
410        let code = wait_in(
411            wt,
412            &["T1".to_string(), "T2".to_string()],
413            false,
414            Duration::from_secs(5),
415            Duration::from_millis(10),
416            Duration::ZERO,
417            &mut out,
418            &mut err,
419        );
420        assert_eq!(code, 0);
421        let out_str = String::from_utf8(out).unwrap();
422        assert_eq!(out_str, "T1 verified 41 $0.37\nT2 verified 10 $0.10\n");
423        assert!(err.is_empty());
424    }
425
426    #[test]
427    fn any_mode_returns_after_first() {
428        let dir = tempfile::tempdir().unwrap();
429        let wt = dir.path();
430        let pid = std::process::id();
431        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
432        std::fs::write(
433            wt.join("T2.json"),
434            r#"{"outcome":"verified","turns":12,"cost_usd":0.20}"#,
435        )
436        .unwrap();
437        let mut out = Vec::new();
438        let mut err = Vec::new();
439        let code = wait_in(
440            wt,
441            &["T1".to_string(), "T2".to_string()],
442            true,
443            Duration::from_secs(5),
444            Duration::from_millis(10),
445            Duration::ZERO,
446            &mut out,
447            &mut err,
448        );
449        assert_eq!(code, 0);
450        assert_eq!(String::from_utf8(out).unwrap(), "T2 verified 12 $0.20\n");
451        assert!(err.is_empty());
452    }
453
454    #[test]
455    fn any_mode_prints_all_already_finished() {
456        let dir = tempfile::tempdir().unwrap();
457        let wt = dir.path();
458        std::fs::write(
459            wt.join("T1.json"),
460            r#"{"outcome":"verified","turns":1,"cost_usd":0.01}"#,
461        )
462        .unwrap();
463        std::fs::write(
464            wt.join("T2.json"),
465            r#"{"outcome":"gate_failed","turns":2,"cost_usd":0.02}"#,
466        )
467        .unwrap();
468        let mut out = Vec::new();
469        let mut err = Vec::new();
470        let code = wait_in(
471            wt,
472            &["T1".to_string(), "T2".to_string()],
473            true,
474            Duration::from_secs(5),
475            Duration::from_millis(10),
476            Duration::ZERO,
477            &mut out,
478            &mut err,
479        );
480        assert_eq!(code, 0);
481        let out_str = String::from_utf8(out).unwrap();
482        let lines: Vec<&str> = out_str.lines().collect();
483        assert_eq!(lines, vec!["T1 verified 1 $0.01", "T2 gate_failed 2 $0.02"]);
484        assert!(err.is_empty());
485    }
486
487    #[test]
488    fn any_mode_timeout() {
489        let dir = tempfile::tempdir().unwrap();
490        let wt = dir.path();
491        let pid = std::process::id();
492        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
493        let mut out = Vec::new();
494        let mut err = Vec::new();
495        let code = wait_in(
496            wt,
497            &["T1".to_string()],
498            true,
499            Duration::from_millis(50),
500            Duration::from_millis(10),
501            Duration::ZERO,
502            &mut out,
503            &mut err,
504        );
505        assert_eq!(code, 2);
506        assert!(out.is_empty());
507        let err_str = String::from_utf8(err).unwrap();
508        assert!(err_str.contains("still running: T1"));
509    }
510
511    #[test]
512    fn summary_written_after_start_counts_as_finished() {
513        let dir = tempfile::tempdir().unwrap();
514        let wt = dir.path();
515        let mut child = std::process::Command::new("true").spawn().unwrap();
516        let pid = child.id();
517        child.wait().unwrap();
518        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
519        std::fs::write(
520            wt.join("T1.json"),
521            r#"{"outcome":"verified","turns":5,"cost_usd":0.05}"#,
522        )
523        .unwrap();
524        let mut out = Vec::new();
525        let mut err = Vec::new();
526        let code = wait_in(
527            wt,
528            &["T1".to_string()],
529            false,
530            Duration::from_secs(5),
531            Duration::from_millis(10),
532            Duration::ZERO,
533            &mut out,
534            &mut err,
535        );
536        assert_eq!(code, 0);
537        assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 5 $0.05\n");
538        assert!(err.is_empty());
539    }
540
541    #[test]
542    fn unparseable_summary_is_not_finished() {
543        let dir = tempfile::tempdir().unwrap();
544        let wt = dir.path();
545        std::fs::write(wt.join("T1.json"), r#"{"outc"#).unwrap();
546        let pid = std::process::id();
547        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
548        let mut out = Vec::new();
549        let mut err = Vec::new();
550        let code = wait_in(
551            wt,
552            &["T1".to_string()],
553            false,
554            Duration::from_millis(50),
555            Duration::from_millis(10),
556            Duration::ZERO,
557            &mut out,
558            &mut err,
559        );
560        assert_eq!(code, 2);
561        assert!(out.is_empty());
562        let err_str = String::from_utf8(err).unwrap();
563        assert!(err_str.contains("still running: T1"));
564    }
565
566    #[test]
567    fn duplicate_ids_reported_once() {
568        let dir = tempfile::tempdir().unwrap();
569        let wt = dir.path();
570        std::fs::write(
571            wt.join("T1.json"),
572            r#"{"outcome":"verified","turns":41,"cost_usd":0.374}"#,
573        )
574        .unwrap();
575        let mut out = Vec::new();
576        let mut err = Vec::new();
577        let code = wait_in(
578            wt,
579            &["T1".to_string(), "T1".to_string()],
580            false,
581            Duration::from_secs(5),
582            Duration::from_millis(10),
583            Duration::ZERO,
584            &mut out,
585            &mut err,
586        );
587        assert_eq!(code, 0);
588        assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 41 $0.37\n");
589        assert!(err.is_empty());
590    }
591
592    #[test]
593    fn finishing_run_within_grace_reports_summary() {
594        let dir = tempfile::tempdir().unwrap();
595        let wt = dir.path();
596        let mut child = std::process::Command::new("true").spawn().unwrap();
597        let pid = child.id();
598        child.wait().unwrap();
599        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
600        let wt_clone = wt.to_path_buf();
601        std::thread::spawn(move || {
602            std::thread::sleep(Duration::from_millis(100));
603            std::fs::write(
604                wt_clone.join("T1.json"),
605                r#"{"outcome":"verified","turns":3,"cost_usd":0.1}"#,
606            )
607            .unwrap();
608        });
609        let mut out = Vec::new();
610        let mut err = Vec::new();
611        let code = wait_in(
612            wt,
613            &["T1".to_string()],
614            false,
615            Duration::from_secs(5),
616            Duration::from_millis(10),
617            Duration::from_secs(2),
618            &mut out,
619            &mut err,
620        );
621        assert_eq!(code, 0);
622        assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 3 $0.10\n");
623        assert!(err.is_empty());
624    }
625
626    #[test]
627    fn dead_run_reported_after_grace() {
628        let dir = tempfile::tempdir().unwrap();
629        let wt = dir.path();
630        let mut child = std::process::Command::new("true").spawn().unwrap();
631        let pid = child.id();
632        child.wait().unwrap();
633        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
634        let mut out = Vec::new();
635        let mut err = Vec::new();
636        let start = Instant::now();
637        let code = wait_in(
638            wt,
639            &["T1".to_string()],
640            false,
641            Duration::from_secs(5),
642            Duration::from_millis(10),
643            Duration::from_millis(150),
644            &mut out,
645            &mut err,
646        );
647        let elapsed = start.elapsed();
648        assert_eq!(code, 0);
649        assert_eq!(String::from_utf8(out).unwrap(), "T1 dead - -\n");
650        assert!(elapsed >= Duration::from_millis(150));
651        assert!(err.is_empty());
652    }
653
654    #[test]
655    fn timeout_inside_grace_is_still_running() {
656        let dir = tempfile::tempdir().unwrap();
657        let wt = dir.path();
658        let mut child = std::process::Command::new("true").spawn().unwrap();
659        let pid = child.id();
660        child.wait().unwrap();
661        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
662        let mut out = Vec::new();
663        let mut err = Vec::new();
664        let code = wait_in(
665            wt,
666            &["T1".to_string()],
667            false,
668            Duration::from_millis(100),
669            Duration::from_millis(10),
670            Duration::from_secs(5),
671            &mut out,
672            &mut err,
673        );
674        assert_eq!(code, 2);
675        assert!(out.is_empty());
676        let err_str = String::from_utf8(err).unwrap();
677        assert!(err_str.contains("still running: T1"));
678    }
679
680    #[test]
681    fn summary_without_start_file_written_after_start() {
682        let dir = tempfile::tempdir().unwrap();
683        let wt = dir.path();
684        let wt_clone = wt.to_path_buf();
685        std::thread::spawn(move || {
686            std::thread::sleep(Duration::from_millis(100));
687            std::fs::write(
688                wt_clone.join("T1.json"),
689                r#"{"outcome":"verified","turns":15,"cost_usd":0.25}"#,
690            )
691            .unwrap();
692        });
693        let mut out = Vec::new();
694        let mut err = Vec::new();
695        let code = wait_in(
696            wt,
697            &["T1".to_string()],
698            false,
699            Duration::from_secs(5),
700            Duration::from_millis(10),
701            Duration::from_secs(2),
702            &mut out,
703            &mut err,
704        );
705        assert_eq!(code, 0);
706        assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 15 $0.25\n");
707        assert!(err.is_empty());
708    }
709
710    #[test]
711    fn one_summary_one_never_appearing() {
712        let dir = tempfile::tempdir().unwrap();
713        let wt = dir.path();
714        std::fs::write(
715            wt.join("T1.json"),
716            r#"{"outcome":"verified","turns":10,"cost_usd":0.10}"#,
717        )
718        .unwrap();
719        let mut out = Vec::new();
720        let mut err = Vec::new();
721        let code = wait_in(
722            wt,
723            &["T1".to_string(), "T2".to_string()],
724            false,
725            Duration::from_secs(5),
726            Duration::from_millis(10),
727            Duration::from_millis(50),
728            &mut out,
729            &mut err,
730        );
731        assert_eq!(code, 1);
732        let err_str = String::from_utf8(err).unwrap();
733        assert!(err_str.contains("no dispatch T2 here"));
734        assert!(!err_str.contains("no dispatch T1 here"));
735        assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 10 $0.10\n");
736    }
737
738    #[test]
739    fn timeout_before_grace_with_unknown_id() {
740        let dir = tempfile::tempdir().unwrap();
741        let wt = dir.path();
742        let mut out = Vec::new();
743        let mut err = Vec::new();
744        let code = wait_in(
745            wt,
746            &["T9".to_string()],
747            false,
748            Duration::from_millis(50),
749            Duration::from_millis(10),
750            Duration::from_secs(5),
751            &mut out,
752            &mut err,
753        );
754        assert_eq!(code, 2);
755        assert!(out.is_empty());
756        let err_str = String::from_utf8(err).unwrap();
757        assert!(err_str.contains("still running: T9"));
758    }
759
760    #[test]
761    fn multiple_unknown_ids_reported_in_argument_order() {
762        let dir = tempfile::tempdir().unwrap();
763        let wt = dir.path();
764        let mut out = Vec::new();
765        let mut err = Vec::new();
766        let code = wait_in(
767            wt,
768            &["B".to_string(), "A".to_string()],
769            false,
770            Duration::from_secs(5),
771            Duration::from_millis(10),
772            Duration::from_millis(50),
773            &mut out,
774            &mut err,
775        );
776        assert_eq!(code, 1);
777        assert!(out.is_empty());
778        let err_str = String::from_utf8(err).unwrap();
779        assert_eq!(err_str, "no dispatch B here\nno dispatch A here\n");
780    }
781
782    #[test]
783    fn cli_parses_wait() {
784        use crate::cli::{Cli, Command};
785        use clap::Parser;
786
787        let cli =
788            Cli::try_parse_from(["blyte", "wait", "A", "B", "--any", "--timeout", "10"]).unwrap();
789        assert_eq!(
790            cli.command,
791            Some(Command::Wait {
792                ids: vec!["A".to_string(), "B".to_string()],
793                any: true,
794                timeout: 10,
795            })
796        );
797
798        let cli = Cli::try_parse_from(["blyte", "wait", "A"]).unwrap();
799        assert_eq!(
800            cli.command,
801            Some(Command::Wait {
802                ids: vec!["A".to_string()],
803                any: false,
804                timeout: 280,
805            })
806        );
807
808        assert!(Cli::try_parse_from(["blyte", "wait"]).is_err());
809    }
810}