Skip to main content

taimux_cli/
act.rs

1//! The two keys that act rather than navigate: ctrl-x on a row, f8 on the list.
2//!
3//! Both own the whole screen for as long as they are up, because the picker has
4//! just handed it over, and both END in a detached restart: a restart waits up to
5//! twelve seconds for a session to exit and then polls for it to come back, so
6//! run inline it would freeze the popup for half a minute.
7//!
8//! The shape of each is the same and it is deliberate: **say what will happen,
9//! ask, and never offer something that would be refused anyway.** A restart that
10//! declines is not a failure to explain away, it is the guard working.
11
12use std::io::{Read, Write};
13
14use crate::{remote, restart};
15
16/// Own the screen the picker just handed over.
17fn clear(out: &mut impl Write) {
18    let _ = write!(out, "\x1b[H\x1b[2J");
19}
20
21/// What the terminal answered when a key was asked for.
22///
23/// The two cases used to be one `None`, and conflating them is why a screen
24/// could vanish before it was read. A key that cannot be waited for is not a
25/// key that was pressed: with no readable `/dev/tty` the read returns at once,
26/// `any_key` returns at once, and the caller's `resume()` wipes the screen in
27/// the same breath. Nothing anywhere said the pause had not happened.
28enum Pressed {
29    Key(char),
30    /// No `/dev/tty` to open, or it answered EOF or an error. **Nothing waited.**
31    Unreadable,
32}
33
34/// Wait for any single key, on the terminal rather than on stdin: the picker's
35/// stdout is where the answer goes, and a popup has no stdin worth reading.
36fn any_key() {
37    print!("  Press any key…");
38    let _ = std::io::stdout().flush();
39    if let Pressed::Unreadable = read_one_key() {
40        // Say so rather than racing past. This screen is about to be wiped by
41        // whoever handed the terminal over, so an unread message is the same as
42        // no message, and "it flashed and went" is exactly how this was
43        // reported.
44        println!("\r\n  (no readable terminal to wait on, so this was not held)");
45        let _ = std::io::stdout().flush();
46    }
47}
48
49fn read_one_key() -> Pressed {
50    let Ok(mut tty) = std::fs::File::open("/dev/tty") else {
51        return Pressed::Unreadable;
52    };
53    // Raw mode, or the read waits for a newline and "any key" becomes "Enter".
54    let raw = crossterm::terminal::enable_raw_mode().is_ok();
55    let mut b = [0u8; 1];
56    let got = match tty.read(&mut b) {
57        Ok(1) => Pressed::Key(b[0] as char),
58        // 0 is EOF and an Err is a terminal we cannot read; neither is a press.
59        _ => Pressed::Unreadable,
60    };
61    if raw {
62        let _ = crossterm::terminal::disable_raw_mode();
63    }
64    got
65}
66
67/// Report a child that could not be started, and hold the screen while it is
68/// read.
69///
70/// The caller has already left the alternate screen, so this lands where the
71/// child would have drawn, and the pause is what stops `resume()` wiping it.
72/// Without this the whole failure was invisible: the picker suspended, the
73/// child never ran, the picker resumed, and the only evidence was a flicker.
74///
75/// **Written to `/dev/tty`, never to stdout.** Everything else in this file is
76/// printed by a CHILD, whose stdout `act_child` has already pointed at the
77/// terminal. This one runs in the PICKER, whose stdout carries exactly one
78/// thing, the chosen pane id. Printing it cost the first attempt at this fix:
79/// the report went down the pipe to whoever called the picker, the screen
80/// stayed blank, and the test caught it.
81pub fn report_failed_child(what: &str, e: &std::io::Error) {
82    let Ok(mut tty) = std::fs::OpenOptions::new().write(true).open("/dev/tty") else {
83        return;
84    };
85    // \r\n throughout: the picker may still have the terminal in raw mode when
86    // this runs, where a bare \n moves down without returning to column 0 and
87    // the message walks off to the right.
88    let _ = write!(
89        tty,
90        "\x1b[H\x1b[2J\x1b[1mtaimux: could not run {}\x1b[0m\r\n\r\n  {}\r\n\r\n\
91         \x20 The picker re-runs its OWN binary for this, so the usual cause is\r\n\
92         \x20 that binary moving or being rebuilt underneath a running picker.\r\n\
93         \x20 Closing and reopening the picker picks up the new one.\r\n\r\n\
94         \x20 Press any key…",
95        what, e
96    );
97    let _ = tty.flush();
98    let _ = read_one_key();
99}
100
101/// The pane lines of a plan, and the line of each background session no pane
102/// shows, without their detail lines or the skip list.
103///
104/// The detail lines are indented further and the skip list sits past the
105/// `skipped (` heading, so this is a state machine over two headings rather than
106/// a guess at indentation.
107fn plan_panes(plan: &str) -> Vec<&str> {
108    let mut on = false;
109    let mut out = Vec::new();
110    for l in plan.lines() {
111        if l.starts_with("to restart (") {
112            on = true;
113            continue;
114        }
115        if l.starts_with("skipped (") {
116            on = false;
117        }
118        // a pane's line, or a background session's that no pane shows
119        if on && l.starts_with("  ") && !l.starts_with("   ") {
120            out.push(l);
121        }
122    }
123    out
124}
125
126fn count_in(plan: &str, heading: &str) -> Option<usize> {
127    plan.lines()
128        .find(|l| l.starts_with(heading))
129        .and_then(|l| l.split(['(', ')']).nth(1))
130        .and_then(|n| n.parse().ok())
131}
132
133/// The one line of a plan that is about this pane.
134fn why_for(plan: &str, pane: &str) -> Option<String> {
135    let needle = format!("  {} ", pane);
136    plan.lines()
137        .find(|l| l.contains(&needle))
138        .map(|l| l.trim_start().to_string())
139}
140
141/// Fire a restart and return AT ONCE, appending to the log beside everything
142/// else this keeps in the runtime directory.
143///
144/// Detached, so closing the popup (or picking a pane and leaving) cannot SIGHUP a
145/// restart mid-flight and leave a pane with a dead session and nothing typed
146/// into it. Nothing is printed: the picker owns the screen, and a detached job
147/// has nowhere to print anyway.
148pub fn note(line: &str) {
149    let log = taimux_core::paths::runtime_dir().join("restart.log");
150    if let Some(d) = log.parent() {
151        let _ = std::fs::create_dir_all(d);
152    }
153    if let Ok(mut f) = std::fs::OpenOptions::new()
154        .create(true)
155        .append(true)
156        .open(&log)
157    {
158        let _ = writeln!(f, "--- {} {}", taimux_core::log::stamp(), line);
159    }
160}
161
162/// The stdio a DETACHED job must have, and the reason it is a function.
163///
164/// stdout and stderr go to the log, which was always so. stdin is the one that
165/// was missing, and Rust inherits it: `Command::spawn` defaults every stream to
166/// the parent's, so a restart fired from the picker kept the POPUP'S pty open
167/// on fd 0 long after the picker had exited. tmux then had a popup whose
168/// command was gone but whose terminal still had a holder, which is a popup
169/// that sits there blank, echoing whatever is typed at it, until the restart
170/// finally ends and lets go. Reported exactly that way: blank after F8,
171/// confirm, then Enter, and gone the moment every agent had come back.
172///
173/// It is also the definition of detaching. A job that outlives the thing that
174/// started it must not hold that thing's terminal.
175fn detached(
176    cmd: &mut std::process::Command,
177    out: std::fs::File,
178    err: std::fs::File,
179) -> &mut std::process::Command {
180    cmd.stdin(std::process::Stdio::null())
181        .stdout(out)
182        .stderr(err)
183}
184
185pub fn restart_detached(exe: &str, pane: &str, force: bool) {
186    let log = taimux_core::paths::runtime_dir().join("restart.log");
187    note(if pane.is_empty() {
188        "all outdated panes"
189    } else {
190        pane
191    });
192    let mut args: Vec<String> = vec!["restart".into(), "-y".into()];
193    if pane.starts_with('%') {
194        args.push("--pane".into());
195        args.push(pane.into());
196    }
197    if force {
198        args.push("--include-busy".into());
199    }
200    let Ok(out) = std::fs::OpenOptions::new()
201        .create(true)
202        .append(true)
203        .open(&log)
204    else {
205        return;
206    };
207    let Ok(err) = out.try_clone() else { return };
208    let Ok(out2) = out.try_clone() else { return };
209    // setsid so it survives the popup closing. `Command` cannot setsid without
210    // libc, so this goes through the program, and falls back to a plain spawn
211    // where there is none: a restart that dies with the popup is still better
212    // than no restart, and the log says which happened.
213    let spawned = detached(
214        std::process::Command::new("setsid").arg(exe).args(&args),
215        out2,
216        err,
217    )
218    .spawn();
219    if spawned.is_err() {
220        let Ok(out3) = std::fs::OpenOptions::new()
221            .create(true)
222            .append(true)
223            .open(&log)
224        else {
225            return;
226        };
227        let Ok(err2) = out3.try_clone() else { return };
228        let _ = detached(std::process::Command::new(exe).args(&args), out3, err2).spawn();
229    }
230}
231
232/// ctrl-x: restart the highlighted session.
233pub fn restart_one(exe: &str, pane: &str) {
234    let mut out = std::io::stdout();
235
236    // An ended conversation has nothing to restart: there is no process behind
237    // it and no pane to type into. Enter is the key that acts on those rows, and
238    // saying so beats a keypress that looks like it did nothing.
239    if pane.starts_with("dead:") {
240        clear(&mut out);
241        println!("\x1b[1mtaimux: that session has already ended\x1b[0m\n");
242        println!("  There is nothing running to restart. Press Enter on it instead:");
243        println!("  it opens again in a new window, in its own directory.\n");
244        any_key();
245        return;
246    }
247
248    // Another host's session. A restart reads /proc, resolves a transcript under
249    // ~/.claude and sends keys to a tmux pane, all of which have to happen where
250    // the session is, and that host's own taimux does all three. Rather than
251    // half a feature, the key says so and hands over the line that would do it.
252    if let Some(host) = remote::pane_host(pane) {
253        clear(&mut out);
254        println!(
255            "\x1b[1mtaimux: {} is on {}\x1b[0m\n",
256            remote::pane_local(pane),
257            host
258        );
259        println!("  Restarting is local-only. From that host, or from here:\n");
260        println!(
261            "    ssh {} taimux restart --pane {}\n",
262            host,
263            remote::pane_local(pane)
264        );
265        any_key();
266        return;
267    }
268    if !pane.starts_with('%') {
269        return; // not a pane id: nothing to act on
270    }
271
272    // A pane with no session in it, which the every-pane list puts one Tab
273    // away from every session. Said at once rather than after the plan, which
274    // takes its time to arrive at "nothing to do" and then cannot say why. A
275    // pane with a restart in flight runs a shell for a moment too, and is still
276    // the restart's to report on.
277    let agent = taimux_core::panes::agent_rows()
278        .lines()
279        .any(|l| l.split('\t').next() == Some(pane));
280    if !agent && !taimux_core::restarting::held().contains_key(pane) {
281        clear(&mut out);
282        println!("\x1b[1mtaimux: {} is not running an agent\x1b[0m\n", pane);
283        println!("  There is no session in it to restart.\n");
284        any_key();
285        return;
286    }
287
288    let plan = plan_of(exe, &["-n", "--pane", pane]);
289    if plan.contains("\nto restart (") || plan.starts_with("to restart (") {
290        restart_detached(exe, pane, false);
291        return;
292    }
293
294    clear(&mut out);
295    println!("\x1b[1mtaimux: {} will not restart cleanly\x1b[0m\n", pane);
296    let Some(why) = why_for(&plan, pane) else {
297        println!("  Nothing to do: it is already on the installed version, or it is");
298        println!("  not a claude pane.\n");
299        any_key();
300        return;
301    };
302    println!("  {}", why);
303
304    // Never offer a force that would be refused anyway: an unresolved
305    // conversation, this very pane, and a transcript already claimed by another
306    // pane are all untouched by --include-busy.
307    let forced = plan_of(exe, &["-n", "--pane", pane, "--include-busy"]);
308    if !(forced.contains("\nto restart (") || forced.starts_with("to restart (")) {
309        println!(
310            "\n  Forcing would not help:\n  {}",
311            why_for(&forced, pane).unwrap_or_else(|| "same refusal".into())
312        );
313        println!();
314        any_key();
315        return;
316    }
317
318    println!("\n  Forcing accepts losing an in-flight turn. A pane holding a");
319    println!("  permission dialog is still refused, so nothing gets answered for you.");
320    print!("\n\x1b[1mForce the restart?\x1b[0m [Y/n] ");
321    let _ = out.flush();
322    // An unreadable terminal declines, which is the safe default, but it SAYS
323    // so: a silent "no" here is indistinguishable from the user answering n,
324    // and the two want very different things done about them.
325    let go = match read_one_key() {
326        Pressed::Key(c) => restart::confirm_yes(&c.to_string()),
327        Pressed::Unreadable => {
328            print!("\r\n  (no readable terminal to answer on, so nothing was restarted)");
329            false
330        }
331    };
332    println!();
333    if go {
334        restart_detached(exe, pane, true);
335        println!(
336            "\n  Forced, detached. Watch the version, or read\n  {}",
337            taimux_core::paths::runtime_dir()
338                .join("restart.log")
339                .display()
340        );
341        std::thread::sleep(std::time::Duration::from_millis(1200));
342    } else {
343        println!("\n  Left alone.");
344        std::thread::sleep(std::time::Duration::from_millis(600));
345    }
346}
347
348/// f8: restart every outdated session, after showing the plan and asking.
349///
350/// "outdated" throughout, which is the word the picker's own list of those rows
351/// uses: the border label, the header hint and this screen are all reached in
352/// one keypress of each other, and two words for one thing there read as two
353/// different things.
354pub fn sweep(exe: &str) {
355    let mut out = std::io::stdout();
356    // Timed, and written down when it fires. A sweep is the one press that can
357    // leave the picker with real work to do afterwards, and when it was reported
358    // as a freeze there was no record of how long any phase took, so every
359    // theory about it stayed a theory. The picker writes its own slow refreshes
360    // to this same log, which is what lets the two halves be read as one
361    // timeline.
362    let at = std::time::Instant::now();
363    let plan = plan_of(exe, &["-n"]);
364    let planned = at.elapsed();
365    let n = count_in(&plan, "to restart (");
366    let skipped = count_in(&plan, "skipped (");
367
368    clear(&mut out);
369    println!("\x1b[1mtaimux: restart every outdated session\x1b[0m\n");
370
371    let Some(n) = n.filter(|n| *n >= 1) else {
372        println!("Nothing to restart. Either every session is already on the");
373        println!("installed version, or the ones behind it are busy.");
374        if let Some(s) = skipped {
375            println!("\n  {} left alone.", s);
376        }
377        println!();
378        any_key();
379        return;
380    };
381
382    for l in plan_panes(&plan) {
383        println!("{}", l);
384    }
385    if let Some(s) = skipped {
386        println!("\n  {} left alone (working, waiting, or unidentified).", s);
387    }
388    print!("\n\x1b[1mRestart {} session(s)?\x1b[0m [Y/n] ", n);
389    let _ = out.flush();
390    // An unreadable terminal declines, which is the safe default, but it SAYS
391    // so: a silent "no" here is indistinguishable from the user answering n,
392    // and the two want very different things done about them.
393    let go = match read_one_key() {
394        Pressed::Key(c) => restart::confirm_yes(&c.to_string()),
395        Pressed::Unreadable => {
396            print!("\r\n  (no readable terminal to answer on, so nothing was restarted)");
397            false
398        }
399    };
400    println!();
401    if go {
402        note(&format!(
403            "sweep: {} to restart, plan took {:.1}s, {:.1}s from keypress to firing",
404            n,
405            planned.as_secs_f32(),
406            at.elapsed().as_secs_f32()
407        ));
408        restart_detached(exe, "", false);
409        println!(
410            "\nStarted, detached. Watch the version column, or read\n{}",
411            taimux_core::paths::runtime_dir()
412                .join("restart.log")
413                .display()
414        );
415        std::thread::sleep(std::time::Duration::from_millis(1200));
416    } else {
417        println!("\nNothing restarted.");
418        std::thread::sleep(std::time::Duration::from_millis(700));
419    }
420}
421
422/// A plan, as text, by asking ourselves for one.
423///
424/// A subprocess rather than a direct call, and that is not laziness: the plan has
425/// to be the SAME text the reader would get from `taimux restart -n`, and the
426/// only way to be sure of that is to run it.
427fn plan_of(exe: &str, args: &[&str]) -> String {
428    std::process::Command::new(exe)
429        .arg("restart")
430        .args(args)
431        .output()
432        .map(|o| {
433            let mut s = String::from_utf8_lossy(&o.stdout).into_owned();
434            s.push_str(&String::from_utf8_lossy(&o.stderr));
435            s
436        })
437        .unwrap_or_default()
438}
439
440// ── ctrl-o: carry a conversation into a different agent ─────────────────────
441
442/// Which conversation a row is about, and which tool wrote it.
443///
444/// Two shapes answer: a **past** row says so in its own id, and a **live claude
445/// pane** can be resolved to the transcript it is writing (the pane map, then
446/// the argv, which is the same ladder `restart` walks). A live pane running any
447/// other agent cannot be, and that is not a gap this key can close: which
448/// conversation a pane is on is something the agent has to publish, and claude
449/// is the only one that does.
450pub fn conversation_of(pane: &str) -> Result<(String, String), String> {
451    if let Some((agent, key)) = taimux_core::index::split_past_id(pane) {
452        return Ok((agent.to_string(), key.to_string()));
453    }
454    if pane == "dead:!" {
455        return Err("that row is a note, not a conversation".into());
456    }
457    if remote::pane_host(pane).is_some() {
458        return Err(format!(
459            "{} is on another host, and a handoff reads its transcript and starts \
460             an agent in its directory, both of which have to happen over there",
461            remote::pane_local(pane)
462        ));
463    }
464    let rows = taimux_core::panes::agent_rows();
465    let row = rows
466        .lines()
467        .map(|l| l.split('\t').collect::<Vec<_>>())
468        .find(|f| f.len() >= 5 && f[0] == pane)
469        // Every row in that scan is an agent pane, so a miss is either a pane
470        // that has closed or one running an ordinary shell. Neither has a
471        // conversation, and saying "gone" about the second would send you
472        // looking for a pane that is right there.
473        .ok_or_else(|| format!("{} is not running an agent, or is not there any more", pane))?;
474    if row[3] != "claude" {
475        return Err(format!(
476            "taimux cannot tell which conversation a {} pane is on, so there is \
477             nothing to hand over. Only claude publishes that",
478            row[3]
479        ));
480    }
481    let pid: i32 = row[4].parse().unwrap_or(0);
482    let cwd = std::fs::read_link(format!("/proc/{}/cwd", pid))
483        .map(|p| p.to_string_lossy().into_owned())
484        .unwrap_or_else(|_| row[2].to_string());
485    match taimux_core::conv::resolve_from_pane(pane, &cwd, pid) {
486        Some(r) => Ok(("claude".into(), r.transcript.to_string_lossy().into_owned())),
487        None => Err("that pane's conversation could not be identified".into()),
488    }
489}
490
491/// ctrl-o: pick a target agent, then open the conversation in it.
492pub fn handoff_one(pane: &str) {
493    let mut out = std::io::stdout();
494    clear(&mut out);
495
496    let (agent, key) = match conversation_of(pane) {
497        Ok(v) => v,
498        Err(why) => {
499            println!("\x1b[1mtaimux: nothing to hand off here\x1b[0m\n");
500            println!("  {}.\n", why);
501            any_key();
502            return;
503        }
504    };
505
506    // The source is not offered as a target: continuing a conversation in the
507    // tool that already has it is Enter, which resumes it rather than starting a
508    // fresh one carrying a summary of itself.
509    let targets: Vec<&str> = taimux_core::handoff::installed()
510        .into_iter()
511        .filter(|t| *t != agent)
512        .collect();
513    if targets.is_empty() {
514        println!("\x1b[1mtaimux: no other agent is installed\x1b[0m\n");
515        println!("  A handoff starts a DIFFERENT tool on this conversation, and");
516        println!("  {} is the only one on your PATH.\n", agent);
517        any_key();
518        return;
519    }
520
521    let meta = taimux_core::agents::meta(&agent, &key);
522    let title = if meta.title.is_empty() {
523        "(no title)"
524    } else {
525        &meta.title
526    };
527    println!(
528        "\x1b[1mtaimux: continue this {} conversation elsewhere\x1b[0m\n",
529        taimux_core::handoff::display_name(&agent)
530    );
531    println!("  \x1b[1;36m{}\x1b[0m", title);
532    println!(
533        "  \x1b[90m{}\x1b[0m\n",
534        if meta.cwd.is_empty() { "?" } else { &meta.cwd }
535    );
536    println!("  The prompt carries the task, the repository's state and the last");
537    println!("  few turns, and points at the transcript for the rest.\n");
538    for (i, t) in targets.iter().enumerate() {
539        println!(
540            "    \x1b[1m{}\x1b[0m  {}",
541            i + 1,
542            taimux_core::handoff::display_name(t)
543        );
544    }
545    println!("\n  Anything else cancels.");
546    let _ = out.flush();
547
548    let Pressed::Key(c) = read_one_key() else {
549        println!("\r\n  (no readable terminal to ask on)");
550        return;
551    };
552    let Some(target) = c
553        .to_digit(10)
554        .and_then(|n| targets.get(n as usize - 1).copied())
555    else {
556        return; // anything that is not one of the offered numbers cancels
557    };
558
559    // Built AFTER the choice, not before: it forks git twice and reads the tail
560    // of a transcript, which is work nobody asked for while a menu is on screen.
561    let turns = taimux_core::env::var("TAIMUX_HANDOFF_TURNS")
562        .and_then(|v| v.parse().ok())
563        .unwrap_or(taimux_core::handoff::DEFAULT_TURNS);
564    let prompt = taimux_core::handoff::build(&agent, &key, turns);
565    let cmd = match taimux_core::handoff::launch(target, &prompt) {
566        Ok(c) => c,
567        Err(why) => {
568            println!("\r\n\r\n  {}.\r\n", why);
569            any_key();
570            return;
571        }
572    };
573    // The same refusal Enter makes, and for the same reason: an agent started in
574    // the wrong directory works on a different project, silently.
575    let cwd = if std::path::Path::new(&meta.cwd).is_dir() {
576        meta.cwd.clone()
577    } else {
578        clear(&mut out);
579        println!(
580            "\x1b[1mtaimux: {} is gone\x1b[0m\n",
581            if meta.cwd.is_empty() {
582                "its directory"
583            } else {
584                &meta.cwd
585            }
586        );
587        println!("  A handoff starts an agent in the directory the conversation ran");
588        println!("  in, and that one is no longer there.\n");
589        any_key();
590        return;
591    };
592
593    if taimux_core::tmux::run(&["new-window", "-c", &cwd, &cmd]) {
594        return; // the new window is the feedback
595    }
596    clear(&mut out);
597    println!("\x1b[1mtaimux: tmux would not open a window\x1b[0m\n");
598    any_key();
599}
600
601#[cfg(test)]
602mod tests {
603
604    /// A detached job must not hold the terminal it was detached from.
605    ///
606    /// This is the F8 blank-popup bug, and it is invisible by inspection:
607    /// `Command::spawn` inherits every stream it is not told about, so the
608    /// omission looks like nothing at all. Asserted through /proc rather than
609    /// by reading the source, because the whole defect was that the source
610    /// looked fine.
611    #[test]
612    fn a_detached_job_does_not_hold_the_terminal() {
613        let dir = std::env::temp_dir().join(format!("taimux-detached-{}", std::process::id()));
614        std::fs::create_dir_all(&dir).unwrap();
615        let logp = dir.join("log");
616        let out = std::fs::File::create(&logp).unwrap();
617        let err = out.try_clone().unwrap();
618
619        let mut cmd = std::process::Command::new("sleep");
620        cmd.arg("30");
621        // Hand it a terminal FIRST, so `detached` has something hostile to
622        // override. Without this the test is vacuous wherever the harness's own
623        // stdin is already /dev/null, which is most of CI: inheriting would give
624        // /dev/null too and the assertion would pass on the broken code.
625        let had_tty = match std::fs::File::open("/dev/tty") {
626            Ok(tty) => {
627                cmd.stdin(std::process::Stdio::from(tty));
628                true
629            }
630            Err(_) => false,
631        };
632        let mut child = detached(&mut cmd, out, err).spawn().expect("spawn sleep");
633
634        let fd0 = std::fs::read_link(format!("/proc/{}/fd/0", child.id()));
635        let _ = child.kill();
636        let _ = child.wait();
637        let _ = std::fs::remove_dir_all(&dir);
638
639        // /proc is Linux-only, and so is everything else here that reads it.
640        let Ok(fd0) = fd0 else { return };
641        if !had_tty {
642            // No controlling terminal to be wrongly kept, so there is nothing
643            // here to prove. Said out loud rather than passing quietly.
644            eprintln!("no /dev/tty in this environment, so this proves nothing");
645            return;
646        }
647        let fd0 = fd0.to_string_lossy().into_owned();
648        assert!(
649            !fd0.contains("/pts/") && !fd0.contains("/dev/tty"),
650            "a detached job kept a terminal on stdin: {fd0}"
651        );
652        assert!(
653            fd0.contains("null"),
654            "expected /dev/null on stdin, got {fd0}"
655        );
656    }
657
658    use super::*;
659
660    const PLAN: &str = "claude: 2.1.258 installed at /l/claude\n\
661                        \n\
662                        to restart (3):\n\
663                        \x20 %19   platform:4.1   a title\n\
664                        \x20       2.1.100 -> 2.1.258, pane map, idle\n\
665                        \x20       command claude --resume /t.jsonl\n\
666                        \x20 %23   platform:4.5   another\n\
667                        \x20       2.1.100 -> 2.1.258, pane map, idle\n\
668                        \x20       command claude\n\
669                        \x20 f3836aef background     a job\n\
670                        \x20       2.1.100 -> 2.1.258, no pane, idle\n\
671                        \x20       claude respawn f3836aef\n\
672                        \n\
673                        skipped (3):\n\
674                        \x20 %77 main:1.1  2.1.100, run: rerun when idle\n";
675
676    /// The pane lines only, and the line of each background session no pane
677    /// shows: the detail lines are indented further and the skip list sits
678    /// past its own heading, so a guess at indentation would take either of
679    /// them.
680    #[test]
681    fn only_the_pane_lines_of_the_plan_are_shown() {
682        assert_eq!(
683            plan_panes(PLAN),
684            vec![
685                "  %19   platform:4.1   a title",
686                "  %23   platform:4.5   another",
687                "  f3836aef background     a job"
688            ]
689        );
690    }
691
692    #[test]
693    fn the_counts_come_off_the_headings() {
694        assert_eq!(count_in(PLAN, "to restart ("), Some(3));
695        assert_eq!(count_in(PLAN, "skipped ("), Some(3));
696        assert_eq!(count_in("nothing to restart.\n", "to restart ("), None);
697    }
698
699    #[test]
700    fn a_panes_own_reason_is_picked_out_of_the_skip_list() {
701        assert_eq!(
702            why_for(PLAN, "%77").as_deref(),
703            Some("%77 main:1.1  2.1.100, run: rerun when idle")
704        );
705        assert_eq!(why_for(PLAN, "%99"), None);
706    }
707
708    /// A plan with nothing in it must not be read as having something: that is
709    /// the difference between firing a restart and explaining a refusal.
710    #[test]
711    fn an_empty_plan_is_not_mistaken_for_a_full_one() {
712        let empty = "claude: 2.1.258 installed at /l\n\nnothing to restart.\n";
713        assert!(plan_panes(empty).is_empty());
714        assert_eq!(count_in(empty, "to restart ("), None);
715    }
716}