Skip to main content

taimux_cli/
restart.rs

1//! Putting a claude session back on the version that is installed now.
2//!
3//! The part where a mistake costs a turn of work rather than a redraw.
4//! Everything here is built around one rule: **a pane it
5//! cannot be sure about is skipped, with a reason.** Guessing which conversation
6//! a pane is on and then interrupting it is worse than doing nothing.
7//!
8//! The guards, in the order they are applied, and what each is for:
9//!
10//! 1. **Not this pane.** Restarting the pane taimux is running in would kill
11//!    taimux mid-restart.
12//! 2. **Only a stale version.** A pane already on the installed version has
13//!    nothing to gain from being interrupted.
14//! 3. **Idle**, unless `--include-busy`. A turn in flight is work in progress.
15//! 4. **A conversation that could be identified**, from the ladder in `conv`.
16//! 5. **No dialog on screen**, ever, even with `--include-busy`: a half-answered
17//!    permission prompt is the one state where a Ctrl-C means something else.
18//! 6. **No unsent draft, and a settled transcript**, unless `--include-busy`.
19//! 7. **No transcript claimed twice.** Resuming one conversation into two panes
20//!    is the same mistake on a restart as on a restore.
21
22use std::collections::HashMap;
23
24use taimux_core::{conv, state, tmux};
25
26/// Is this transcript quiet enough to interrupt?
27///
28/// Two refusals: an unanswered `tool_use` as the very last record (a tool call is
29/// still in flight), and any activity in the last 45 seconds. The second is
30/// insurance for the first, because the screen reading is the most fragile thing
31/// in this tool and a recently-touched transcript is worth leaving alone whatever
32/// the screen said.
33///
34/// The `tool_use` test is a text match on the final line rather than a parse of
35/// `.message.content[]`, which is the one approximation: an assistant turn whose
36/// own prose quotes that key reads as busy. It fails toward "leave it alone", and
37/// the recency guard covers the same ground, so the cost is a pane skipped rather
38/// than a turn lost.
39pub fn transcript_is_settled(text: &str, now: i64) -> Result<(), String> {
40    let Some(last) = text.lines().rfind(|l| !l.trim().is_empty()) else {
41        return Ok(()); // unknown shape: do not block on a guess
42    };
43    if taimux_core::json::field(last, "type") == "assistant"
44        && (last.contains("\"type\":\"tool_use\"") || last.contains("\"type\": \"tool_use\""))
45    {
46        return Err("a tool call is still running".into());
47    }
48    let ts = taimux_core::json::field(last, "timestamp");
49    if ts.is_empty() {
50        return Ok(());
51    }
52    let Some(then) = parse_iso8601(&ts) else {
53        return Ok(()); // unparseable: not evidence of anything
54    };
55    if now - then < 45 {
56        return Err("active in the last 45s".into());
57    }
58    Ok(())
59}
60
61/// An ISO 8601 UTC timestamp to epoch seconds, which is all claude writes:
62/// `2026-09-02T01:23:45.678Z`. The parse is `turn::epoch_ms`, which the state
63/// reading needs to the millisecond; this only wants the second.
64fn parse_iso8601(s: &str) -> Option<i64> {
65    taimux_core::turn::epoch_ms(s).map(|ms| ms.div_euclid(1000))
66}
67
68/// Is the screen free of anything a Ctrl-C would mean something else to?
69///
70/// Applied even with `--include-busy`, because this is the one state where the
71/// keystroke that starts a restart is also an answer to a question.
72pub fn screen_has_no_dialog(screen: &str) -> Result<(), String> {
73    if state::awaits_input(screen) {
74        return Err("a dialog is waiting for an answer".into());
75    }
76    let tail: Vec<&str> = screen
77        .lines()
78        .filter(|l| !l.trim().is_empty())
79        .rev()
80        .take(4)
81        .collect();
82    if tail
83        .iter()
84        .any(|l| l.contains("Press Ctrl-C again to exit"))
85    {
86        return Err("a Ctrl-C is already half-pressed".into());
87    }
88    Ok(())
89}
90
91/// Is the prompt box empty?
92///
93/// Unsent text in it is work nobody has committed yet, and a restart would throw
94/// it away. The non-breaking space claude pads the box with is stripped before
95/// the check, or every box would look occupied.
96pub fn screen_has_no_draft(screen: &str) -> Result<(), String> {
97    let txt: Vec<&str> = screen.lines().filter(|l| !l.trim().is_empty()).collect();
98    if txt.is_empty() {
99        return Ok(());
100    }
101    let Some(box_line) = txt.iter().rev().find(|l| l.contains('❯')) else {
102        return Err("no prompt box on screen".into());
103    };
104    let after = box_line.split_once('❯').map(|(_, r)| r).unwrap_or("");
105    let rest: String = after
106        .chars()
107        .filter(|c| !c.is_whitespace() && *c != '\u{a0}')
108        .collect();
109    if rest.is_empty() {
110        Ok(())
111    } else {
112        Err("unsent text in the prompt box".into())
113    }
114}
115
116/// The rows claude needs before it draws its prompt box at all.
117///
118/// Measured against 2.1.278 in a tmux server of its own, a row at a time: at six
119/// the `❯` is on screen and whatever has been typed into it with it, at five the
120/// last row is the box's own top rule and neither the glyph nor the draft is
121/// anywhere on the pane, and by three nothing of the box survives. Width does not
122/// move it, 46, 54, 63, 80 and 213 columns all break in the same place.
123///
124/// A pane under it is not a pane in a strange state, it is a pane that cannot be
125/// READ: the box, an unsent draft inside it and a dialog over it go off the
126/// bottom together, so `screen_has_no_draft` refuses it and would go on refusing
127/// it for as long as the pane stays that size. Nine of the fourteen outdated
128/// panes on this machine were exactly that, which is how a sweep meant to clear
129/// the outdated list offered to clear four of them.
130const BOX_ROWS: usize = 6;
131
132/// One tmux command line, as the arguments it is made of.
133type Cmd = Vec<String>;
134
135/// Getting a pane to a readable size, and putting the window back after.
136type ZoomSteps = (Vec<Cmd>, Vec<Cmd>);
137
138/// What it takes to read a pane at a size claude will draw on, and what it takes
139/// to put the window back afterwards.
140///
141/// Split out from the running of it so the ORDER can be tested without a tmux to
142/// run it against, the order being the whole of the difficulty. `None` when there
143/// is nothing to gain: a pane already tall enough, or a window no taller than the
144/// pane it holds, where zooming would hand it the rows it already has.
145///
146/// **Zoom rather than `resize-pane -y`**, and only a crowded window shows why:
147/// seven panes in seventeen rows share eleven rows of content, six of which are
148/// already spoken for by the others, so the tallest any one of them can be made
149/// is five, one short of what the box needs. Zoom is the only growth that does
150/// not have to come out of a sibling. It also leaves the LAYOUT untouched, so
151/// putting the window back is a matter of the zoom flag and the active pane
152/// rather than of replaying a layout string and hoping it lands.
153fn zoom_steps(
154    pane: &str,
155    zoomed: bool,
156    pane_rows: usize,
157    window_rows: usize,
158    active: &str,
159    last: &str,
160) -> Option<ZoomSteps> {
161    if pane_rows >= BOX_ROWS || window_rows < BOX_ROWS || window_rows <= pane_rows {
162        return None;
163    }
164    let cmd = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Cmd>();
165
166    let mut go = Vec::new();
167    // `-Z` toggles the WINDOW's zoom whatever pane it is pointed at, so on a
168    // window that arrives zoomed the first one only ever switches the OTHER pane
169    // off, and a second is what zooms this one. Two identical command lines in a
170    // row is not a duplicated push.
171    if zoomed {
172        go.push(cmd(&["resize-pane", "-Z", "-t", pane]));
173    }
174    go.push(cmd(&["resize-pane", "-Z", "-t", pane]));
175
176    let mut back = vec![cmd(&["resize-pane", "-Z", "-t", pane])];
177    // Zooming made this pane the active one and pushed whatever was active into
178    // the window's "last pane", so both have to go back, and in that order:
179    // selecting the old last pane first leaves the old active one current with
180    // the right pane behind it. `prefix + ;` is the user's binding, not taimux's
181    // to spend. A pane that was active already has neither to restore.
182    if active != pane {
183        if !last.is_empty() && last != pane {
184            back.push(cmd(&["select-pane", "-t", last]));
185        }
186        if !active.is_empty() {
187            back.push(cmd(&["select-pane", "-t", active]));
188        }
189    }
190    // A window that arrives zoomed is zoomed on its active pane by definition,
191    // which is why that pane is never this one: it would have the window's full
192    // height and be refused above.
193    if zoomed && !active.is_empty() {
194        back.push(cmd(&["resize-pane", "-Z", "-t", active]));
195    }
196    Some((go, back))
197}
198
199/// The commands that put the window back, run when this goes out of scope.
200///
201/// A guard rather than a line at the end of the function because the read
202/// between the two can panic, and a window left zoomed on a pane nobody chose is
203/// a worse outcome than a pane left unread.
204struct Restoring(Vec<Cmd>);
205
206impl Drop for Restoring {
207    fn drop(&mut self) {
208        for c in &self.0 {
209            tmux::run(&c.iter().map(String::as_str).collect::<Vec<_>>());
210        }
211    }
212}
213
214/// One pane's screen, read at a size claude will draw its prompt box on.
215///
216/// `None` when the pane did not need it or the window cannot give it, in which
217/// case nothing was touched and the screen already in hand is the best there is.
218///
219/// The wait is not padding. claude redraws on the SIGWINCH and does it fast,
220/// measured at 13 to 16ms across six runs with the draft already in the first
221/// readable frame, but a capture taken with no wait at all comes back with no box
222/// at all: tmux does not reflow an old frame into the new rows, it hands over
223/// what is there and claude fills it a moment later. So the poll is what makes
224/// the read real, and its ceiling is thirty times the measurement rather than a
225/// guess at it.
226pub fn capture_zoomed(pane: &str) -> Option<String> {
227    if !taimux_core::env::on("TAIMUX_ZOOM_TO_READ") {
228        return None;
229    }
230    let geom = tmux::ask(&[
231        "display-message",
232        "-p",
233        "-t",
234        pane,
235        "-F",
236        "#{window_zoomed_flag}\t#{pane_height}\t#{window_height}\t#{window_id}",
237    ])?;
238    let g: Vec<&str> = geom.trim_end().split('\t').collect();
239    if g.len() < 4 {
240        return None;
241    }
242    let (zoomed, win) = (g[0] == "1", g[3]);
243    let pane_rows: usize = g[1].parse().ok()?;
244    let window_rows: usize = g[2].parse().ok()?;
245
246    let mut active = String::new();
247    let mut last = String::new();
248    for l in tmux::ask(&[
249        "list-panes",
250        "-t",
251        win,
252        "-F",
253        "#{pane_id}\t#{pane_active}\t#{pane_last}",
254    ])?
255    .lines()
256    {
257        let c: Vec<&str> = l.split('\t').collect();
258        if c.len() < 3 {
259            continue;
260        }
261        if c[1] == "1" {
262            active = c[0].to_string();
263        }
264        if c[2] == "1" {
265            last = c[0].to_string();
266        }
267    }
268
269    let (go, back) = zoom_steps(pane, zoomed, pane_rows, window_rows, &active, &last)?;
270    for c in &go {
271        tmux::run(&c.iter().map(String::as_str).collect::<Vec<_>>());
272    }
273    let _restore = Restoring(back);
274
275    let deadline = std::time::Instant::now() + std::time::Duration::from_millis(500);
276    loop {
277        let screen = tmux::capture(pane).unwrap_or_default();
278        if screen.contains('❯') || std::time::Instant::now() >= deadline {
279            return Some(screen);
280        }
281        std::thread::sleep(std::time::Duration::from_millis(10));
282    }
283}
284
285/// The version a running process is executing, read from its own `/proc/exe`
286/// rather than from the binary on `$PATH`: a long-lived session goes on running
287/// the release it started under.
288pub fn version_of_pid(pid: i32, versions_dir: &str) -> Option<String> {
289    let exe = std::fs::read_link(format!("/proc/{}/exe", pid)).ok()?;
290    let exe = exe.to_string_lossy();
291    let exe = exe.trim_end_matches(" (deleted)"); // replaced by an update
292    let prefix = format!("{}/", versions_dir);
293    exe.strip_prefix(&prefix)
294        .filter(|rest| !rest.is_empty())
295        .map(|rest| rest.split('/').next().unwrap_or(rest).to_string())
296}
297
298/// One pane the plan will act on.
299pub struct Planned {
300    pub pane: String,
301    pub target: String,
302    pub pid: i32,
303    pub cmd: String,
304    pub title: String,
305    pub via: String,
306}
307
308pub struct Plan {
309    pub newver: String,
310    pub launcher: String,
311    pub go: Vec<Planned>,
312    pub skipped: Vec<String>,
313    /// Set when at least one pane was skipped for being unresolvable, which gets
314    /// its own paragraph: it is the one skip the reader can act on.
315    pub unresolved: bool,
316}
317
318pub struct Opts {
319    pub include_busy: bool,
320    pub only_panes: Vec<String>,
321    pub force_transcript: Option<String>,
322    pub self_pane: String,
323}
324
325/// Everything the plan needs from the outside, so it can be built against
326/// fixtures as well as against a live machine.
327pub trait Env {
328    fn capture(&self, pane: &str) -> String;
329    /// The same pane read at a size claude will draw its prompt box on, for the
330    /// one that is too short to show one at the size it is.
331    ///
332    /// `None` by default, and for every fixture: a screen handed over by a test
333    /// is already the screen that test means, and only the live implementation
334    /// has a window to zoom.
335    fn capture_zoomed(&self, _pane: &str) -> Option<String> {
336        None
337    }
338    fn hook_state(&self, pane: &str, pid: i32) -> Option<String>;
339    fn version_of_pid(&self, pid: i32) -> Option<String>;
340    fn cwd_of(&self, pid: i32) -> Option<String>;
341    fn argv_of(&self, pid: i32) -> Vec<String>;
342    fn resolve(&self, pane: &str, cwd: &str, title: &str, pid: i32) -> Result<String, String>;
343    fn read_transcript(&self, path: &str) -> Option<String>;
344    fn now(&self) -> i64;
345}
346
347/// Decide what to restart, and say why for everything else.
348///
349/// `agents` is `claude agents --json`, fetched by the caller and only when a
350/// stale non-pane process actually needs naming: the CLI costs about three
351/// seconds to start.
352pub fn plan(
353    rows: &str,
354    newver: &str,
355    launcher: &str,
356    o: &Opts,
357    e: &dyn Env,
358    versions_dir: &str,
359    agents: &dyn Fn() -> String,
360) -> Plan {
361    let mut p = Plan {
362        newver: newver.to_string(),
363        launcher: launcher.to_string(),
364        go: Vec::new(),
365        skipped: Vec::new(),
366        unresolved: false,
367    };
368    let mut claimed: HashMap<String, String> = HashMap::new();
369    // Every pane's agent pid, so the non-pane sweep below can tell a session
370    // that has a pane from one that has not.
371    let mut matched: Vec<i32> = Vec::new();
372
373    for line in rows.lines() {
374        let f: Vec<&str> = line.split('\t').collect();
375        if f.len() < 7 || f[3] != "claude" {
376            continue;
377        }
378        let (id, tgt, cwd, title) = (f[0], f[1], f[2], f[6]);
379        let pid: i32 = f[4].parse().unwrap_or(0);
380
381        let Some(ver) = (pid != 0).then(|| e.version_of_pid(pid)).flatten() else {
382            p.skipped.push(format!(
383                "{} {}  looks like claude but no session process was found under the pane",
384                id, tgt
385            ));
386            continue;
387        };
388        matched.push(pid);
389        if !o.only_panes.is_empty() && !o.only_panes.iter().any(|w| w == id) {
390            continue;
391        }
392        if ver == newver {
393            continue; // nothing to gain from interrupting it
394        }
395        if id == o.self_pane {
396            p.skipped.push(format!(
397                "{} {}  {}, this pane: restart it by hand (killing it would kill taimux)",
398                id, tgt, ver
399            ));
400            continue;
401        }
402
403        let mut screen = e.capture(id);
404        // A screen with no prompt box on it is either a session doing something
405        // unusual or a pane too short to draw one, and those want opposite
406        // answers: the first is a refusal, the second is a measurement that has
407        // not been taken yet. Taking it costs the window a zoom for the
408        // milliseconds claude needs to redraw, and buys a reading of the box, of
409        // anything typed into it and of any dialog over it, none of which is on
410        // the pane at the size it sits at. It happens here rather than after the
411        // state check on purpose: `merge` is reading the same blank screen.
412        if !screen.contains('❯') {
413            if let Some(bigger) = e.capture_zoomed(id) {
414                screen = bigger;
415            }
416        }
417        let hook = e.hook_state(id, pid);
418        let st = state::merge(&screen, hook.as_deref());
419        if st.as_str() != "idle" && !o.include_busy {
420            p.skipped.push(format!(
421                "{} {}  {}, {}: rerun when idle, or --include-busy",
422                id,
423                tgt,
424                ver,
425                st.as_str()
426            ));
427            continue;
428        }
429        // Idle is not the same as nothing to lose. A turn that left a shell or a
430        // subagent running is over and its prompt is free, which is why the list
431        // shows it idle, but that work runs as the session's children and dies
432        // with it. This used to be one question, answered "working" for both, on
433        // a pane whose two watchers were due to report hours later.
434        if state::background(&screen, hook.as_deref()) && !o.include_busy {
435            p.skipped.push(format!(
436                "{} {}  {}, work still in flight: rerun once it reports back, or --include-busy",
437                id, tgt, ver
438            ));
439            continue;
440        }
441
442        let ccwd = e.cwd_of(pid).unwrap_or_else(|| cwd.to_string());
443        let (transcript, via) = match &o.force_transcript {
444            Some(t) => (t.clone(), "--transcript, given".to_string()),
445            None => match e.resolve(id, &ccwd, title, pid) {
446                Ok(t) => {
447                    // resolve() hands back "<path>\t<why>"
448                    let (path, why) = t.split_once('\t').unwrap_or((t.as_str(), ""));
449                    (path.to_string(), why.to_string())
450                }
451                Err(why) => {
452                    p.skipped
453                        .push(format!("{} {}  {}, unresolved: {}", id, tgt, ver, why));
454                    p.unresolved = true;
455                    continue;
456                }
457            },
458        };
459
460        if let Err(why) = screen_has_no_dialog(&screen) {
461            p.skipped
462                .push(format!("{} {}  {}, not settled: {}", id, tgt, ver, why));
463            continue;
464        }
465        if !o.include_busy {
466            let settled =
467                screen_has_no_draft(&screen).and_then(|()| match e.read_transcript(&transcript) {
468                    Some(text) => transcript_is_settled(&text, e.now()),
469                    None => Ok(()),
470                });
471            if let Err(why) = settled {
472                p.skipped
473                    .push(format!("{} {}  {}, not settled: {}", id, tgt, ver, why));
474                continue;
475            }
476        }
477
478        if let Some(first) = claimed.get(&transcript) {
479            p.skipped.push(format!(
480                "{} {}  {}, resolves to the same transcript as {}",
481                id, tgt, ver, first
482            ));
483            continue;
484        }
485        claimed.insert(transcript.clone(), id.to_string());
486
487        let Some(cmd) = conv::build_cmd(&e.argv_of(pid), &transcript, &ccwd, cwd) else {
488            p.skipped
489                .push(format!("{} {}  {}, could not read its argv", id, tgt, ver));
490            continue;
491        };
492        p.go.push(Planned {
493            pane: id.to_string(),
494            target: tgt.to_string(),
495            pid,
496            cmd,
497            title: title.to_string(),
498            via: format!("{} -> {}, {}, {}", ver, newver, via, st.as_str()),
499        });
500    }
501
502    // Stale claude processes that are not a pane's foreground job. Reported,
503    // never touched: a restart types into a PANE, and these have none, so the
504    // only useful thing to do about a stale one is name it. The naming costs a
505    // `claude agents --json`, so it is fetched lazily and once.
506    let mut agents_json: Option<String> = None;
507    for np in nonpane_pids(&matched, versions_dir) {
508        let Some(ver) = e.version_of_pid(np) else {
509            continue;
510        };
511        if ver == newver {
512            continue;
513        }
514        let j = agents_json.get_or_insert_with(agents);
515        p.skipped.push(format!(
516            "pid {}  {}, not a tmux pane: {}",
517            np,
518            ver,
519            describe_nonpane(&e.argv_of(np), j)
520        ));
521    }
522    p
523}
524
525/// The plan, as the reader sees it. Byte-for-byte what bash printed, because the
526/// only way to know a port of this is right is to compare it.
527pub fn render(p: &Plan) -> String {
528    let mut s = format!("claude: {} installed at {}\n\n", p.newver, p.launcher);
529    if p.go.is_empty() {
530        s.push_str("nothing to restart.\n");
531    } else {
532        s.push_str(&format!("to restart ({}):\n", p.go.len()));
533        for g in &p.go {
534            s.push_str(&format!("  {:<5} {:<14} {}\n", g.pane, g.target, g.title));
535            s.push_str(&format!("        {}\n", g.via));
536            s.push_str(&format!("        {}\n", g.cmd));
537        }
538    }
539    if !p.skipped.is_empty() {
540        s.push_str(&format!("\nskipped ({}):\n", p.skipped.len()));
541        for k in &p.skipped {
542            s.push_str(&format!("  {}\n", k));
543        }
544    }
545    if p.unresolved {
546        s.push_str(
547            "\nAn unresolved pane means guessing, so it was left alone: restart it by hand\n\
548             with `claude -c` in that pane, or from its /resume picker. Each session records\n\
549             its pane at the next SessionStart, so a pane resolves cleanly once restarted.\n",
550        );
551    }
552    s
553}
554
555/// Interrupt a session, wait for it to go, and type its replacement.
556///
557/// Two Ctrl-Cs, because the first one arms claude's "press again to exit" and the
558/// second takes it. `/exit` after six waits is for a session that ignores both,
559/// and thirty waits (twelve seconds) is where it gives up rather than typing a
560/// command into a pane that still has a session in it.
561pub fn restart_pane(pane: &str, pid: i32, cmd: &str) -> bool {
562    use std::thread::sleep;
563    use std::time::Duration;
564
565    tmux::run(&["send-keys", "-t", pane, "C-c"]);
566    sleep(Duration::from_millis(300));
567    tmux::run(&["send-keys", "-t", pane, "C-c"]);
568
569    let mut waited = 0;
570    let mut sent_exit = false;
571    while alive(pid) {
572        sleep(Duration::from_millis(400));
573        waited += 1;
574        if waited >= 6 && !sent_exit {
575            tmux::run(&["send-keys", "-t", pane, "/exit", "Enter"]);
576            sent_exit = true;
577        }
578        if waited >= 30 {
579            return false;
580        }
581    }
582    sleep(Duration::from_millis(500));
583    tmux::run(&["send-keys", "-t", pane, "C-c"]);
584    sleep(Duration::from_millis(200));
585    tmux::run(&["send-keys", "-t", pane, cmd, "Enter"])
586}
587
588/// Is a pid still there? `/proc` rather than `kill -0`, since nothing is being
589/// signalled and a directory read cannot be mistaken for one.
590fn alive(pid: i32) -> bool {
591    std::path::Path::new(&format!("/proc/{}", pid)).exists()
592}
593
594/// The default answer is yes, so a bare Enter restarts. The plan has already been
595/// printed by then, which is what makes that safe.
596pub fn confirm_yes(answer: &str) -> bool {
597    matches!(answer.trim(), "" | "y" | "Y" | "yes" | "YES" | "Yes")
598}
599
600/// The live implementation of everything `plan` needs.
601pub struct Live {
602    pub versions_dir: String,
603}
604
605impl Env for Live {
606    fn capture(&self, pane: &str) -> String {
607        tmux::ask_raw(&["capture-pane", "-p", "-t", pane]).unwrap_or_default()
608    }
609    fn capture_zoomed(&self, pane: &str) -> Option<String> {
610        capture_zoomed(pane)
611    }
612    fn hook_state(&self, pane: &str, pid: i32) -> Option<String> {
613        taimux_core::hook::hook_state_of(pane, pid)
614    }
615    fn version_of_pid(&self, pid: i32) -> Option<String> {
616        version_of_pid(pid, &self.versions_dir)
617    }
618    fn cwd_of(&self, pid: i32) -> Option<String> {
619        std::fs::read_link(format!("/proc/{}/cwd", pid))
620            .ok()
621            .map(|p| p.to_string_lossy().into_owned())
622            .filter(|s| !s.is_empty())
623    }
624    fn argv_of(&self, pid: i32) -> Vec<String> {
625        conv::argv_of(pid)
626    }
627    fn resolve(&self, pane: &str, cwd: &str, title: &str, pid: i32) -> Result<String, String> {
628        conv::resolve(pane, cwd, title, pid)
629            .map(|r| format!("{}\t{}", r.transcript.display(), r.why))
630    }
631    fn read_transcript(&self, path: &str) -> Option<String> {
632        std::fs::read_to_string(path).ok()
633    }
634    fn now(&self) -> i64 {
635        std::time::SystemTime::now()
636            .duration_since(std::time::UNIX_EPOCH)
637            .map(|d| d.as_secs() as i64)
638            .unwrap_or(0)
639    }
640}
641
642/// What a session started right now would run, refusing rather than guessing when
643/// the launcher points somewhere unexpected.
644pub fn installed(launcher: &str, versions_dir: &str) -> Result<String, String> {
645    let target = std::fs::canonicalize(launcher)
646        .map(|p| p.to_string_lossy().into_owned())
647        .unwrap_or_default();
648    let prefix = format!("{}/", versions_dir);
649    match target.strip_prefix(&prefix) {
650        Some(rest) if !rest.is_empty() => Ok(rest.split('/').next().unwrap_or(rest).to_string()),
651        _ => Err(format!(
652            "restart: {} does not point into {} (got '{}')",
653            launcher,
654            versions_dir,
655            if target.is_empty() {
656                "nothing"
657            } else {
658                &target
659            }
660        )),
661    }
662}
663
664pub fn versions_dir() -> String {
665    format!(
666        "{}/.local/share/claude/versions",
667        std::env::var("HOME").unwrap_or_default()
668    )
669}
670
671pub fn launcher() -> String {
672    format!(
673        "{}/.local/bin/claude",
674        std::env::var("HOME").unwrap_or_default()
675    )
676}
677
678#[cfg(test)]
679mod tests {
680    use super::*;
681
682    #[test]
683    fn a_timestamp_becomes_epoch_seconds() {
684        // 2026-09-02T01:23:45Z
685        assert_eq!(parse_iso8601("2026-09-02T01:23:45.678Z"), Some(1788312225));
686        assert_eq!(parse_iso8601("1970-01-01T00:00:00Z"), Some(0));
687        // a leap day, which a hand-rolled calendar is where it goes wrong
688        assert_eq!(parse_iso8601("2024-02-29T00:00:00Z"), Some(1709164800));
689    }
690
691    /// Anything not of that exact shape reads as "no answer", which the caller
692    /// treats as not-evidence rather than as busy: guessing busy would skip a
693    /// pane on a malformed line forever.
694    #[test]
695    fn an_unparseable_timestamp_is_no_answer() {
696        assert_eq!(parse_iso8601(""), None);
697        assert_eq!(parse_iso8601("yesterday"), None);
698        assert_eq!(parse_iso8601("2026-09-02 01:23:45"), None);
699        assert_eq!(parse_iso8601("2026-13-02T01:23:45Z"), None);
700    }
701
702    #[test]
703    fn a_tool_call_still_running_is_not_settled() {
704        let t = r#"{"type":"assistant","message":{"content":[{"type":"tool_use"}]},"timestamp":"2020-01-01T00:00:00Z"}"#;
705        assert_eq!(
706            transcript_is_settled(t, 1788312225),
707            Err("a tool call is still running".into())
708        );
709    }
710
711    /// Insurance for the screen reading, which is the most fragile thing here.
712    #[test]
713    fn recent_activity_is_not_settled_whatever_the_screen_said() {
714        let t = r#"{"type":"user","timestamp":"2026-09-02T01:23:45Z"}"#;
715        assert!(transcript_is_settled(t, 1788312225 + 10).is_err());
716        assert!(transcript_is_settled(t, 1788312225 + 100).is_ok());
717    }
718
719    #[test]
720    fn an_empty_or_odd_transcript_does_not_block() {
721        assert!(transcript_is_settled("", 0).is_ok());
722        assert!(transcript_is_settled("not json at all\n", 0).is_ok());
723        // no timestamp: nothing to judge recency by
724        assert!(transcript_is_settled(r#"{"type":"user"}"#, 0).is_ok());
725    }
726
727    /// A dialog is what `state::awaits_input` recognises, so the fixture has to
728    /// be one it would: either the footer in the last few lines, or a numbered
729    /// choice on the LOWEST prompt line. A made-up shape asserts nothing.
730    #[test]
731    fn a_dialog_on_screen_blocks_a_restart() {
732        let footer = "some output\n\nDo you want to proceed?\n";
733        assert_eq!(
734            screen_has_no_dialog(footer),
735            Err("a dialog is waiting for an answer".into())
736        );
737        let choice = "some output\n1. Yes\n2. No\n❯ 1. Yes\n";
738        assert_eq!(
739            screen_has_no_dialog(choice),
740            Err("a dialog is waiting for an answer".into())
741        );
742        // an ordinary idle screen is not a dialog
743        assert!(screen_has_no_dialog("some output\n❯ \n").is_ok());
744    }
745
746    /// A half-pressed Ctrl-C is the one state where the keystroke that starts a
747    /// restart is also an answer to something else.
748    #[test]
749    fn a_half_pressed_ctrl_c_blocks_a_restart() {
750        let screen = "work\n\nPress Ctrl-C again to exit\n";
751        assert_eq!(
752            screen_has_no_dialog(screen),
753            Err("a Ctrl-C is already half-pressed".into())
754        );
755    }
756
757    #[test]
758    fn an_empty_prompt_box_is_no_draft() {
759        assert!(screen_has_no_draft("stuff\n❯ \n").is_ok());
760        // the non-breaking space claude pads the box with is not a draft
761        assert!(screen_has_no_draft("stuff\n❯ \u{a0}\u{a0}\n").is_ok());
762        assert_eq!(
763            screen_has_no_draft("stuff\n❯ half a thought\n"),
764            Err("unsent text in the prompt box".into())
765        );
766    }
767
768    /// The four rows a pane has to be given before any of this can be asked of
769    /// it, and the two it can be left at.
770    #[test]
771    fn a_pane_tall_enough_to_read_is_left_alone() {
772        // already showing its box: nothing to gain, and nothing touched
773        assert!(zoom_steps("%1", false, 6, 40, "%2", "%3").is_none());
774        assert!(zoom_steps("%1", false, 40, 40, "%2", "%3").is_none());
775        // a window no taller than the pane has no rows to lend it
776        assert!(zoom_steps("%1", false, 3, 3, "%2", "%3").is_none());
777        assert!(zoom_steps("%1", false, 3, 5, "%2", "%3").is_none());
778    }
779
780    /// The common shape: a three-row pane in a window nobody has zoomed. One
781    /// zoom out and back, and the pane that was active is active again with the
782    /// pane that was behind it still behind it.
783    #[test]
784    fn a_short_pane_is_zoomed_and_the_selection_put_back() {
785        let (go, back) = zoom_steps("%1", false, 3, 17, "%2", "%3").unwrap();
786        assert_eq!(go, vec![vec!["resize-pane", "-Z", "-t", "%1"]]);
787        assert_eq!(
788            back,
789            vec![
790                vec!["resize-pane", "-Z", "-t", "%1"],
791                vec!["select-pane", "-t", "%3"],
792                vec!["select-pane", "-t", "%2"],
793            ]
794        );
795    }
796
797    /// A window that arrives zoomed on another pane takes TWO `-Z` to zoom this
798    /// one, because the first is spent switching the other one off, and it is
799    /// owed a re-zoom at the end.
800    #[test]
801    fn a_window_zoomed_elsewhere_is_handed_back_zoomed() {
802        let (go, back) = zoom_steps("%1", true, 3, 17, "%2", "%3").unwrap();
803        assert_eq!(
804            go,
805            vec![
806                vec!["resize-pane", "-Z", "-t", "%1"],
807                vec!["resize-pane", "-Z", "-t", "%1"],
808            ]
809        );
810        assert_eq!(
811            back,
812            vec![
813                vec!["resize-pane", "-Z", "-t", "%1"],
814                vec!["select-pane", "-t", "%3"],
815                vec!["select-pane", "-t", "%2"],
816                vec!["resize-pane", "-Z", "-t", "%2"],
817            ]
818        );
819    }
820
821    /// Zooming the pane that is already active changes no selection, so putting
822    /// one back would be the only thing that moved it.
823    #[test]
824    fn an_active_short_pane_has_no_selection_to_restore() {
825        let (go, back) = zoom_steps("%1", false, 3, 17, "%1", "%3").unwrap();
826        assert_eq!(go.len(), 1);
827        assert_eq!(back, vec![vec!["resize-pane", "-Z", "-t", "%1"]]);
828    }
829
830    /// No box at all means the screen is not what it is expected to be, and that
831    /// is a refusal rather than a shrug.
832    #[test]
833    fn no_prompt_box_is_a_refusal() {
834        assert_eq!(
835            screen_has_no_draft("just some text\n"),
836            Err("no prompt box on screen".into())
837        );
838        // …but a genuinely blank screen is not judged at all
839        assert!(screen_has_no_draft("").is_ok());
840        assert!(screen_has_no_draft("   \n\n").is_ok());
841    }
842
843    #[test]
844    fn a_bare_enter_confirms() {
845        assert!(confirm_yes(""));
846        assert!(confirm_yes("y"));
847        assert!(confirm_yes("YES"));
848        assert!(!confirm_yes("n"));
849        assert!(!confirm_yes("no"));
850        assert!(!confirm_yes("maybe"));
851    }
852
853    #[test]
854    fn the_launcher_must_point_into_the_versions_dir() {
855        let root = std::env::temp_dir().join(format!("jmrs{}", std::process::id()));
856        let vers = root.join("versions");
857        std::fs::create_dir_all(&vers).unwrap();
858        std::fs::write(vers.join("2.1.258"), "x").unwrap();
859        let link = root.join("claude");
860        std::os::unix::fs::symlink(vers.join("2.1.258"), &link).unwrap();
861        assert_eq!(
862            installed(&link.to_string_lossy(), &vers.to_string_lossy()),
863            Ok("2.1.258".into())
864        );
865        // pointing elsewhere is a refusal that names what it found
866        std::fs::write(root.join("elsewhere"), "x").unwrap();
867        std::fs::remove_file(&link).unwrap();
868        std::os::unix::fs::symlink(root.join("elsewhere"), &link).unwrap();
869        let e = installed(&link.to_string_lossy(), &vers.to_string_lossy()).expect_err("refused");
870        assert!(e.contains("elsewhere"));
871        let _ = std::fs::remove_dir_all(&root);
872    }
873}
874
875/// A claude process that is not any pane's foreground job: Zed's ACP bridge, a
876/// background agent, one of the daemon's spare pty hosts.
877///
878/// Reported, never touched. A restart types into a PANE, and these have none, so
879/// the only useful thing to do about a stale one is name it.
880pub fn nonpane_pids(matched: &[i32], versions_dir: &str) -> Vec<i32> {
881    let mut out = Vec::new();
882    for e in std::fs::read_dir("/proc").into_iter().flatten().flatten() {
883        let Some(pid) = e.file_name().to_str().and_then(|s| s.parse::<i32>().ok()) else {
884            continue;
885        };
886        if matched.contains(&pid) {
887            continue;
888        }
889        // Either its comm is "claude" (pgrep -x claude) or it is running out of
890        // the versions directory (pgrep -f "^<vdir>/").
891        let comm = std::fs::read_to_string(format!("/proc/{}/comm", pid)).unwrap_or_default();
892        let argv = conv::argv_of(pid);
893        let is_claude = comm.trim() == "claude"
894            || argv
895                .first()
896                .map(|a| a.starts_with(&format!("{}/", versions_dir)))
897                .unwrap_or(false);
898        if is_claude {
899            out.push(pid);
900        }
901    }
902    out.sort_unstable();
903    out
904}
905
906/// The object in a JSON array whose `key` starts with `prefix`, as raw text.
907///
908/// A brace matcher rather than a parser, and rather than the `jq` the bash
909/// version shelled out to. It only has to find one element of one array, and the
910/// depth count is what makes it safe against nested objects: taking everything
911/// between the first `{` and the first `}` would truncate any element with a
912/// nested field.
913fn json_object_with_prefix(text: &str, key: &str, prefix: &str) -> Option<String> {
914    let needle = format!("\"{}\":\"{}", key, prefix);
915    let at = text.find(&needle).or_else(|| {
916        let spaced = format!("\"{}\": \"{}", key, prefix);
917        text.find(&spaced)
918    })?;
919    // back to the opening brace of the object holding it
920    let mut depth = 0i32;
921    let bytes = text.as_bytes();
922    let mut start = None;
923    for i in (0..at).rev() {
924        match bytes[i] {
925            b'}' => depth += 1,
926            b'{' => {
927                if depth == 0 {
928                    start = Some(i);
929                    break;
930                }
931                depth -= 1;
932            }
933            _ => {}
934        }
935    }
936    let start = start?;
937    // forward to its matching close
938    let mut depth = 0i32;
939    for i in start..bytes.len() {
940        match bytes[i] {
941            b'{' => depth += 1,
942            b'}' => {
943                depth -= 1;
944                if depth == 0 {
945                    return Some(text[start..=i].to_string());
946                }
947            }
948            _ => {}
949        }
950    }
951    None
952}
953
954/// What to say about a claude that has no pane.
955///
956/// `agents_json` is `claude agents --json`, which costs about three seconds of
957/// CLI startup, so it is fetched once by the caller and only when something needs
958/// naming. Its own `pid` field points at the pty-host wrapper rather than at the
959/// session, so it is read for kind, state and name and nothing else.
960pub fn describe_nonpane(argv: &[String], agents_json: &str) -> String {
961    if argv.is_empty() {
962        return "gone".into();
963    }
964    let (mut sid, mut res, mut forked) = (String::new(), String::new(), false);
965    for i in 1..argv.len() {
966        match argv[i].as_str() {
967            "--fork-session" => forked = true,
968            "--session-id" => sid = argv.get(i + 1).cloned().unwrap_or_default(),
969            "-r" | "--resume" => res = argv.get(i + 1).cloned().unwrap_or_default(),
970            _ => {}
971        }
972    }
973    let own = base_id(if sid.is_empty() { &res } else { &sid });
974    let parent = if forked && !res.is_empty() {
975        base_id(&res)
976    } else {
977        String::new()
978    };
979
980    let (mut kind, mut st, mut name) = ("?".to_string(), "?".to_string(), String::new());
981    if !own.is_empty() {
982        if let Some(obj) = json_object_with_prefix(agents_json, "sessionId", &own) {
983            let f = |k: &str| taimux_core::json::field(&obj, k);
984            let k = f("kind");
985            if !k.is_empty() {
986                kind = k;
987            }
988            let s = {
989                let a = f("state");
990                if a.is_empty() {
991                    f("status")
992                } else {
993                    a
994                }
995            };
996            if !s.is_empty() {
997                st = s;
998            }
999            name = f("name");
1000        }
1001    }
1002    let mut out = format!("{} {}", kind, st);
1003    if forked {
1004        out.push_str(" fork");
1005    }
1006    if !name.is_empty() {
1007        out.push_str(&format!(" \"{}\"", name));
1008    }
1009    if !own.is_empty() {
1010        out.push_str(&format!(" [{}]", own.chars().take(8).collect::<String>()));
1011    }
1012    if !parent.is_empty() {
1013        out.push_str(&format!(
1014            " of [{}]",
1015            parent.chars().take(8).collect::<String>()
1016        ));
1017    }
1018    out
1019}
1020
1021/// `basename x .jsonl`: a session id, whether it arrived as one or as a path.
1022fn base_id(s: &str) -> String {
1023    if s.is_empty() {
1024        return String::new();
1025    }
1026    let b = s.rsplit('/').next().unwrap_or(s);
1027    b.strip_suffix(".jsonl").unwrap_or(b).to_string()
1028}
1029
1030#[cfg(test)]
1031mod nonpane_tests {
1032    use super::*;
1033
1034    fn v(a: &[&str]) -> Vec<String> {
1035        a.iter().map(|s| s.to_string()).collect()
1036    }
1037
1038    #[test]
1039    fn a_session_id_is_read_out_of_a_path_or_taken_as_it_stands() {
1040        assert_eq!(base_id("/a/b/263946b5-9bd7.jsonl"), "263946b5-9bd7");
1041        assert_eq!(base_id("263946b5"), "263946b5");
1042        assert_eq!(base_id(""), "");
1043    }
1044
1045    /// The depth count is the whole point: taking everything between the first
1046    /// brace and the first close would truncate any element with a nested field,
1047    /// and `claude agents --json` has them.
1048    #[test]
1049    fn the_right_object_comes_back_whole() {
1050        let j = r#"[{"sessionId":"aaa111","kind":"task","meta":{"a":1},"name":"first"},
1051                    {"sessionId":"bbb222","kind":"agent","name":"second"}]"#;
1052        let o = json_object_with_prefix(j, "sessionId", "bbb222").expect("found");
1053        assert!(o.contains("second"));
1054        assert!(!o.contains("first"));
1055        let o = json_object_with_prefix(j, "sessionId", "aaa").expect("found by prefix");
1056        assert!(o.contains("first"));
1057        assert!(
1058            o.contains("\"meta\":{\"a\":1}"),
1059            "nested field truncated: {}",
1060            o
1061        );
1062        assert!(json_object_with_prefix(j, "sessionId", "zzz").is_none());
1063    }
1064
1065    #[test]
1066    fn a_process_with_no_argv_is_simply_gone() {
1067        assert_eq!(describe_nonpane(&[], "[]"), "gone");
1068    }
1069
1070    #[test]
1071    fn an_unnamed_session_still_says_what_it_can() {
1072        let d = describe_nonpane(&v(&["claude", "--session-id", "263946b5-9bd7"]), "[]");
1073        assert_eq!(d, "? ? [263946b5]");
1074    }
1075
1076    #[test]
1077    fn a_named_one_says_kind_state_and_name() {
1078        let j =
1079            r#"[{"sessionId":"263946b5-9bd7","kind":"task","state":"running","name":"the thing"}]"#;
1080        let d = describe_nonpane(&v(&["claude", "--session-id", "263946b5-9bd7"]), j);
1081        assert_eq!(d, "task running \"the thing\" [263946b5]");
1082    }
1083
1084    /// `status` is the older field name, and one of the two is what a given
1085    /// version emits.
1086    #[test]
1087    fn status_stands_in_for_state() {
1088        let j = r#"[{"sessionId":"aaa11111","kind":"agent","status":"idle"}]"#;
1089        let d = describe_nonpane(&v(&["claude", "--session-id", "aaa11111"]), j);
1090        assert_eq!(d, "agent idle [aaa11111]");
1091    }
1092
1093    /// A fork names both itself and its parent, because that is the pair you need
1094    /// to work out which one is the stale one.
1095    #[test]
1096    fn a_fork_names_its_parent_too() {
1097        let d = describe_nonpane(
1098            &v(&[
1099                "claude",
1100                "--session-id",
1101                "child111",
1102                "--fork-session",
1103                "--resume",
1104                "/p/parent22.jsonl",
1105            ]),
1106            "[]",
1107        );
1108        assert_eq!(d, "? ? fork [child111] of [parent22]");
1109    }
1110}
1111
1112#[cfg(test)]
1113mod plan_tests {
1114    use super::*;
1115
1116    /// A machine with one stale pane, one current one, and whatever else the test
1117    /// asks for. The `Env` trait exists for this: the live differential can only
1118    /// reach "nothing to restart" while every session is on the installed
1119    /// version, so the branch that actually acts needs a fixture.
1120    struct Fake {
1121        /// pid -> version
1122        vers: HashMap<i32, String>,
1123        /// pane -> screen
1124        screens: HashMap<String, String>,
1125        /// pane -> resolved transcript, or the refusal
1126        resolved: HashMap<String, Result<String, String>>,
1127        /// pane -> what the same pane shows once it has been zoomed, for a pane
1128        /// too short to draw a prompt box at the size it sits at
1129        zoomed: HashMap<String, String>,
1130        /// how many panes were zoomed to be read, since a zoom is something the
1131        /// user watching that window sees happen
1132        zooms: std::cell::Cell<usize>,
1133        /// pane -> the hook line's state, for the panes that have one
1134        hooks: HashMap<String, String>,
1135        transcript: String,
1136        now: i64,
1137    }
1138
1139    impl Env for Fake {
1140        fn capture(&self, pane: &str) -> String {
1141            self.screens.get(pane).cloned().unwrap_or_default()
1142        }
1143        fn capture_zoomed(&self, pane: &str) -> Option<String> {
1144            let bigger = self.zoomed.get(pane).cloned();
1145            if bigger.is_some() {
1146                self.zooms.set(self.zooms.get() + 1);
1147            }
1148            bigger
1149        }
1150        fn hook_state(&self, pane: &str, _pid: i32) -> Option<String> {
1151            self.hooks.get(pane).cloned()
1152        }
1153        fn version_of_pid(&self, pid: i32) -> Option<String> {
1154            self.vers.get(&pid).cloned()
1155        }
1156        fn cwd_of(&self, _pid: i32) -> Option<String> {
1157            Some("/w".into())
1158        }
1159        fn argv_of(&self, _pid: i32) -> Vec<String> {
1160            vec!["claude".into()]
1161        }
1162        fn resolve(&self, pane: &str, _c: &str, _t: &str, _p: i32) -> Result<String, String> {
1163            self.resolved
1164                .get(pane)
1165                .cloned()
1166                .unwrap_or_else(|| Err("no candidate".into()))
1167        }
1168        fn read_transcript(&self, _path: &str) -> Option<String> {
1169            Some(self.transcript.clone())
1170        }
1171        fn now(&self) -> i64 {
1172            self.now
1173        }
1174    }
1175
1176    fn fake() -> Fake {
1177        let mut vers = HashMap::new();
1178        vers.insert(11, "2.1.100".to_string()); // stale
1179        vers.insert(22, "2.1.258".to_string()); // current
1180        let mut screens = HashMap::new();
1181        // an idle screen with an empty prompt box
1182        screens.insert("%1".to_string(), "some output\n❯ \n".to_string());
1183        screens.insert("%2".to_string(), "some output\n❯ \n".to_string());
1184        let mut resolved = HashMap::new();
1185        resolved.insert("%1".to_string(), Ok("/t/a.jsonl\tpane map".to_string()));
1186        Fake {
1187            vers,
1188            screens,
1189            resolved,
1190            zoomed: HashMap::new(),
1191            zooms: std::cell::Cell::new(0),
1192            hooks: HashMap::new(),
1193            transcript: r#"{"type":"user","timestamp":"2020-01-01T00:00:00Z"}"#.to_string(),
1194            now: 1788312225,
1195        }
1196    }
1197
1198    fn opts() -> Opts {
1199        Opts {
1200            include_busy: false,
1201            only_panes: Vec::new(),
1202            force_transcript: None,
1203            self_pane: String::new(),
1204        }
1205    }
1206
1207    const ROWS: &str = "%1\tw:1.1\t/w\tclaude\t11\tclaude\tproj: the stale one\n\
1208                        %2\tw:2.1\t/w\tclaude\t22\tclaude\tproj: the current one";
1209
1210    fn plan_of(e: &Fake, o: &Opts) -> Plan {
1211        plan(ROWS, "2.1.258", "/l/claude", o, e, "/nowhere", &|| {
1212            "[]".into()
1213        })
1214    }
1215
1216    #[test]
1217    fn a_stale_pane_is_planned_and_a_current_one_is_not() {
1218        let p = plan_of(&fake(), &opts());
1219        assert_eq!(p.go.len(), 1);
1220        assert_eq!(p.go[0].pane, "%1");
1221        assert_eq!(p.go[0].cmd, "command claude --resume /t/a.jsonl");
1222        assert_eq!(p.go[0].via, "2.1.100 -> 2.1.258, pane map, idle");
1223        assert!(p.skipped.is_empty());
1224    }
1225
1226    /// The rendered plan is the whole user interface of `restart -n`, so its
1227    /// exact shape is what the bash comparison was made on.
1228    #[test]
1229    fn the_rendered_plan_reads_the_way_it_always_did() {
1230        let out = render(&plan_of(&fake(), &opts()));
1231        assert_eq!(
1232            out,
1233            "claude: 2.1.258 installed at /l/claude\n\n\
1234             to restart (1):\n\
1235             \x20 %1    w:1.1          proj: the stale one\n\
1236             \x20       2.1.100 -> 2.1.258, pane map, idle\n\
1237             \x20       command claude --resume /t/a.jsonl\n"
1238        );
1239    }
1240
1241    /// Restarting the pane taimux is running in would kill taimux mid-restart.
1242    #[test]
1243    fn this_pane_is_never_restarted() {
1244        let mut o = opts();
1245        o.self_pane = "%1".into();
1246        let p = plan_of(&fake(), &o);
1247        assert!(p.go.is_empty());
1248        assert!(p.skipped[0].contains("this pane"));
1249        assert!(p.skipped[0].contains("killing it would kill taimux"));
1250    }
1251
1252    #[test]
1253    fn a_pane_that_is_not_idle_waits_for_include_busy() {
1254        let mut e = fake();
1255        // an activity line: mid-turn
1256        e.screens
1257            .insert("%1".into(), "Twisting… (35s · ↓ 1.6k tokens)\n❯ \n".into());
1258        let p = plan_of(&e, &opts());
1259        assert!(p.go.is_empty());
1260        assert!(p.skipped[0].contains("rerun when idle, or --include-busy"));
1261
1262        let mut o = opts();
1263        o.include_busy = true;
1264        assert_eq!(plan_of(&e, &o).go.len(), 1);
1265    }
1266
1267    /// Idle at its prompt, and still not restartable without asking: the shells
1268    /// a finished turn left running are the session's children and die with it.
1269    #[test]
1270    fn a_pane_with_work_in_flight_waits_for_include_busy() {
1271        let mut e = fake();
1272        e.screens.insert(
1273            "%1".into(),
1274            "✻ Cogitated for 1m 3s · done 4:55 PM · 2 shells still running\n❯ \n".into(),
1275        );
1276        let p = plan_of(&e, &opts());
1277        assert!(p.go.is_empty());
1278        assert!(
1279            p.skipped[0].contains("work still in flight"),
1280            "{:?}",
1281            p.skipped
1282        );
1283
1284        // The line alone says so as well, on a screen that shows nothing of it.
1285        let mut e = fake();
1286        e.hooks.insert("%1".into(), "bg".into());
1287        let p = plan_of(&e, &opts());
1288        assert!(p.go.is_empty());
1289        assert!(
1290            p.skipped[0].contains("work still in flight"),
1291            "{:?}",
1292            p.skipped
1293        );
1294
1295        let mut o = opts();
1296        o.include_busy = true;
1297        assert_eq!(plan_of(&e, &o).go.len(), 1);
1298    }
1299
1300    /// Even with --include-busy: a half-answered permission prompt is the one
1301    /// state where the Ctrl-C that starts a restart means something else.
1302    #[test]
1303    fn a_dialog_blocks_a_restart_even_with_include_busy() {
1304        let mut e = fake();
1305        e.screens
1306            .insert("%1".into(), "output\n\nDo you want to proceed?\n".into());
1307        let mut o = opts();
1308        o.include_busy = true;
1309        let p = plan_of(&e, &o);
1310        assert!(p.go.is_empty());
1311        assert!(p.skipped[0].contains("a dialog is waiting for an answer"));
1312    }
1313
1314    #[test]
1315    fn an_unsent_draft_is_left_alone() {
1316        let mut e = fake();
1317        e.screens
1318            .insert("%1".into(), "output\n❯ half a thought\n".into());
1319        let p = plan_of(&e, &opts());
1320        assert!(p.skipped[0].contains("unsent text in the prompt box"));
1321    }
1322
1323    /// The pane this whole thing is for: three rows, no box on it, and a session
1324    /// sitting idle behind that. Read at a size it can be read at, it is an
1325    /// ordinary restart.
1326    #[test]
1327    fn a_pane_too_short_for_its_box_is_read_zoomed() {
1328        let mut e = fake();
1329        e.screens.insert(
1330            "%1".into(),
1331            "  current: 2.1.100 · latest…\n────────\n".into(),
1332        );
1333        e.zoomed.insert("%1".into(), "some output\n❯ \n".into());
1334        let p = plan_of(&e, &opts());
1335        assert_eq!(e.zooms.get(), 1);
1336        assert_eq!(p.go.len(), 1);
1337        assert_eq!(p.go[0].pane, "%1");
1338        assert!(p.skipped.is_empty());
1339    }
1340
1341    /// And the point of reading it rather than assuming: a draft is invisible at
1342    /// three rows too, so the zoomed read is the only thing that can find one.
1343    /// Refused here for what is actually in the box, not for the box being
1344    /// missing.
1345    #[test]
1346    fn a_draft_hidden_by_a_short_pane_still_refuses() {
1347        let mut e = fake();
1348        e.screens
1349            .insert("%1".into(), "  current: 2.1.100…\n".into());
1350        e.zoomed
1351            .insert("%1".into(), "output\n❯ half a thought\n".into());
1352        let p = plan_of(&e, &opts());
1353        assert_eq!(e.zooms.get(), 1);
1354        assert!(p.go.is_empty());
1355        assert!(p.skipped[0].contains("unsent text in the prompt box"));
1356    }
1357
1358    /// A dialog is off the bottom of a short pane with the box, so the zoomed
1359    /// read is what finds that too, and a dialog is refused with or without
1360    /// `--include-busy`.
1361    #[test]
1362    fn a_dialog_hidden_by_a_short_pane_is_found_by_the_zoom() {
1363        let mut e = fake();
1364        e.screens.insert("%1".into(), "  Bash command\n".into());
1365        e.zoomed.insert(
1366            "%1".into(),
1367            "Do you want to proceed?\n❯ 1. Yes\n  2. No\n".into(),
1368        );
1369        let mut o = opts();
1370        o.include_busy = true;
1371        let p = plan_of(&e, &o);
1372        assert!(p.go.is_empty());
1373        assert!(p.skipped[0].contains("a dialog is waiting for an answer"));
1374    }
1375
1376    /// A pane already showing its box is never zoomed: the read is already good,
1377    /// and a zoom is something the person watching that window sees happen.
1378    #[test]
1379    fn a_pane_that_shows_its_box_is_not_zoomed() {
1380        let e = fake();
1381        let p = plan_of(&e, &opts());
1382        assert_eq!(e.zooms.get(), 0);
1383        assert_eq!(p.go.len(), 1);
1384    }
1385
1386    /// A transcript touched in the last 45 seconds is left alone whatever the
1387    /// screen said, because the screen reading is the fragile half.
1388    #[test]
1389    fn a_recently_active_transcript_is_left_alone() {
1390        let mut e = fake();
1391        e.transcript = r#"{"type":"user","timestamp":"2026-09-02T01:23:45Z"}"#.into();
1392        e.now = 1788312225 + 10;
1393        let p = plan_of(&e, &opts());
1394        assert!(p.skipped[0].contains("active in the last 45s"));
1395    }
1396
1397    #[test]
1398    fn an_unresolved_pane_says_so_and_earns_the_paragraph() {
1399        let mut e = fake();
1400        e.resolved
1401            .insert("%1".into(), Err("3 transcripts share this title".into()));
1402        let p = plan_of(&e, &opts());
1403        assert!(p.go.is_empty());
1404        assert!(p.unresolved);
1405        assert!(p.skipped[0].contains("unresolved: 3 transcripts share this title"));
1406        assert!(render(&p).contains("restart it by hand"));
1407    }
1408
1409    /// Two panes on one conversation is the same mistake on a restart as on a
1410    /// restore: the second one to claim it gets skipped rather than resumed.
1411    #[test]
1412    fn one_transcript_is_never_resumed_into_two_panes() {
1413        let mut e = fake();
1414        e.vers.insert(22, "2.1.100".into()); // make the second one stale too
1415        e.resolved
1416            .insert("%2".into(), Ok("/t/a.jsonl\tpane map".into()));
1417        let p = plan_of(&e, &opts());
1418        assert_eq!(p.go.len(), 1);
1419        assert_eq!(p.go[0].pane, "%1");
1420        assert!(p.skipped[0].contains("resolves to the same transcript as %1"));
1421    }
1422
1423    #[test]
1424    fn only_panes_narrows_the_plan_without_changing_the_verdicts() {
1425        let mut o = opts();
1426        o.only_panes = vec!["%2".into()];
1427        let p = plan_of(&fake(), &o);
1428        assert!(p.go.is_empty());
1429        assert!(p.skipped.is_empty()); // %1 was not considered at all
1430    }
1431
1432    #[test]
1433    fn a_pane_with_no_session_process_is_reported_not_dropped() {
1434        let rows = "%9\tw:9.9\t/w\tclaude\t0\tclaude\tno pid here";
1435        let p = plan(rows, "2.1.258", "/l", &opts(), &fake(), "/nowhere", &|| {
1436            "[]".into()
1437        });
1438        assert!(p.go.is_empty());
1439        assert_eq!(p.skipped.len(), 1);
1440        assert!(p.skipped[0].contains("no session process was found"));
1441    }
1442
1443    #[test]
1444    fn nothing_to_restart_says_so() {
1445        let mut e = fake();
1446        e.vers.insert(11, "2.1.258".into());
1447        let out = render(&plan_of(&e, &opts()));
1448        assert!(out.contains("nothing to restart."));
1449        assert!(!out.contains("to restart ("));
1450    }
1451
1452    /// --transcript names the conversation outright, which is the escape hatch
1453    /// for a pane the ladder refuses.
1454    #[test]
1455    fn a_given_transcript_overrides_the_ladder() {
1456        let mut e = fake();
1457        e.resolved.insert("%1".into(), Err("no candidate".into()));
1458        let mut o = opts();
1459        o.force_transcript = Some("/given.jsonl".into());
1460        let p = plan_of(&e, &o);
1461        assert_eq!(p.go.len(), 1);
1462        assert!(p.go[0].via.contains("--transcript, given"));
1463        assert!(p.go[0].cmd.contains("--resume /given.jsonl"));
1464    }
1465}