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    /// What the session says it is doing, Claude Code's own status
340    /// (`status::of`), which outranks the hook line wherever there is one.
341    /// `None` by default, and for every fixture that predates it.
342    fn own_state(&self, _pid: i32) -> Option<state::State> {
343        None
344    }
345    /// The background session this pane's conversation was moved into, when a
346    /// backgrounding left the pane's process behind as its client.
347    fn moved_to(&self, _pid: i32) -> Option<String> {
348        None
349    }
350    fn version_of_pid(&self, pid: i32) -> Option<String>;
351    fn cwd_of(&self, pid: i32) -> Option<String>;
352    fn argv_of(&self, pid: i32) -> Vec<String>;
353    fn resolve(&self, pane: &str, cwd: &str, title: &str, pid: i32) -> Result<String, String>;
354    fn read_transcript(&self, path: &str) -> Option<String>;
355    fn now(&self) -> i64;
356}
357
358/// Decide what to restart, and say why for everything else.
359///
360/// `agents` is `claude agents --json`, fetched by the caller and only when a
361/// stale non-pane process actually needs naming: the CLI costs about three
362/// seconds to start.
363pub fn plan(
364    rows: &str,
365    newver: &str,
366    launcher: &str,
367    o: &Opts,
368    e: &dyn Env,
369    versions_dir: &str,
370    agents: &dyn Fn() -> String,
371) -> Plan {
372    let mut p = Plan {
373        newver: newver.to_string(),
374        launcher: launcher.to_string(),
375        go: Vec::new(),
376        skipped: Vec::new(),
377        unresolved: false,
378    };
379    let mut claimed: HashMap<String, String> = HashMap::new();
380    // Every pane's agent pid, so the non-pane sweep below can tell a session
381    // that has a pane from one that has not.
382    let mut matched: Vec<i32> = Vec::new();
383
384    for line in rows.lines() {
385        let f: Vec<&str> = line.split('\t').collect();
386        if f.len() < 7 || f[3] != "claude" {
387            continue;
388        }
389        let (id, tgt, cwd, title) = (f[0], f[1], f[2], f[6]);
390        let pid: i32 = f[4].parse().unwrap_or(0);
391
392        let Some(ver) = (pid != 0).then(|| e.version_of_pid(pid)).flatten() else {
393            p.skipped.push(format!(
394                "{} {}  looks like claude but no session process was found under the pane",
395                id, tgt
396            ));
397            continue;
398        };
399        matched.push(pid);
400        if !o.only_panes.is_empty() && !o.only_panes.iter().any(|w| w == id) {
401            continue;
402        }
403        if ver == newver {
404            continue; // nothing to gain from interrupting it
405        }
406        if id == o.self_pane {
407            p.skipped.push(format!(
408                "{} {}  {}, this pane: restart it by hand (killing it would kill taimux)",
409                id, tgt, ver
410            ));
411            continue;
412        }
413
414        let mut screen = e.capture(id);
415        // A screen with no prompt box on it is either a session doing something
416        // unusual or a pane too short to draw one, and those want opposite
417        // answers: the first is a refusal, the second is a measurement that has
418        // not been taken yet. Taking it costs the window a zoom for the
419        // milliseconds claude needs to redraw, and buys a reading of the box, of
420        // anything typed into it and of any dialog over it, none of which is on
421        // the pane at the size it sits at. It happens here rather than after the
422        // state check on purpose: `merge` is reading the same blank screen.
423        if !screen.contains('❯') {
424            if let Some(bigger) = e.capture_zoomed(id) {
425                screen = bigger;
426            }
427        }
428        let hook = e.hook_state(id, pid);
429        let st = state::reading(&screen, e.own_state(pid), hook.as_deref());
430        if st.as_str() != "idle" && !o.include_busy {
431            p.skipped.push(format!(
432                "{} {}  {}, {}: rerun when idle, or --include-busy",
433                id,
434                tgt,
435                ver,
436                st.as_str()
437            ));
438            continue;
439        }
440        // Idle is not the same as nothing to lose. A turn that left a shell or a
441        // subagent running is over and its prompt is free, which is why the list
442        // shows it idle, but that work runs as the session's children and dies
443        // with it. This used to be one question, answered "working" for both, on
444        // a pane whose two watchers were due to report hours later.
445        if state::background(&screen, hook.as_deref()) && !o.include_busy {
446            p.skipped.push(format!(
447                "{} {}  {}, work still in flight: rerun once it reports back, or --include-busy",
448                id, tgt, ver
449            ));
450            continue;
451        }
452
453        // Its conversation runs on in agent view's supervisor. Resuming the
454        // transcript this pane started on would branch it from the point it was
455        // backgrounded, while the real one carries on elsewhere.
456        if let Some(sid) = e.moved_to(pid) {
457            let short = sid.get(..8).unwrap_or(&sid);
458            p.skipped.push(format!(
459                "{} {}  {}, its conversation moved to background session {}: claude attach {}",
460                id, tgt, ver, short, short
461            ));
462            continue;
463        }
464
465        let ccwd = e.cwd_of(pid).unwrap_or_else(|| cwd.to_string());
466        let (transcript, via) = match &o.force_transcript {
467            Some(t) => (t.clone(), "--transcript, given".to_string()),
468            None => match e.resolve(id, &ccwd, title, pid) {
469                Ok(t) => {
470                    // resolve() hands back "<path>\t<why>"
471                    let (path, why) = t.split_once('\t').unwrap_or((t.as_str(), ""));
472                    (path.to_string(), why.to_string())
473                }
474                Err(why) => {
475                    p.skipped
476                        .push(format!("{} {}  {}, unresolved: {}", id, tgt, ver, why));
477                    p.unresolved = true;
478                    continue;
479                }
480            },
481        };
482
483        if let Err(why) = screen_has_no_dialog(&screen) {
484            p.skipped
485                .push(format!("{} {}  {}, not settled: {}", id, tgt, ver, why));
486            continue;
487        }
488        if !o.include_busy {
489            let settled =
490                screen_has_no_draft(&screen).and_then(|()| match e.read_transcript(&transcript) {
491                    Some(text) => transcript_is_settled(&text, e.now()),
492                    None => Ok(()),
493                });
494            if let Err(why) = settled {
495                p.skipped
496                    .push(format!("{} {}  {}, not settled: {}", id, tgt, ver, why));
497                continue;
498            }
499        }
500
501        if let Some(first) = claimed.get(&transcript) {
502            p.skipped.push(format!(
503                "{} {}  {}, resolves to the same transcript as {}",
504                id, tgt, ver, first
505            ));
506            continue;
507        }
508        claimed.insert(transcript.clone(), id.to_string());
509
510        let Some(cmd) = conv::build_cmd(&e.argv_of(pid), &transcript, &ccwd, cwd) else {
511            p.skipped
512                .push(format!("{} {}  {}, could not read its argv", id, tgt, ver));
513            continue;
514        };
515        p.go.push(Planned {
516            pane: id.to_string(),
517            target: tgt.to_string(),
518            pid,
519            cmd,
520            title: title.to_string(),
521            via: format!("{} -> {}, {}, {}", ver, newver, via, st.as_str()),
522        });
523    }
524
525    // Stale claude processes that are not a pane's foreground job. Reported,
526    // never touched: a restart types into a PANE, and these have none, so the
527    // only useful thing to do about a stale one is name it. The naming costs a
528    // `claude agents --json`, so it is fetched lazily and once.
529    let mut agents_json: Option<String> = None;
530    for np in nonpane_pids(&matched, versions_dir) {
531        let Some(ver) = e.version_of_pid(np) else {
532            continue;
533        };
534        if ver == newver {
535            continue;
536        }
537        let j = agents_json.get_or_insert_with(agents);
538        p.skipped.push(format!(
539            "pid {}  {}, not a tmux pane: {}",
540            np,
541            ver,
542            describe_nonpane(&e.argv_of(np), j)
543        ));
544    }
545    p
546}
547
548/// The plan, as the reader sees it. Byte-for-byte what bash printed, because the
549/// only way to know a port of this is right is to compare it.
550pub fn render(p: &Plan) -> String {
551    let mut s = format!("claude: {} installed at {}\n\n", p.newver, p.launcher);
552    if p.go.is_empty() {
553        s.push_str("nothing to restart.\n");
554    } else {
555        s.push_str(&format!("to restart ({}):\n", p.go.len()));
556        for g in &p.go {
557            s.push_str(&format!("  {:<5} {:<14} {}\n", g.pane, g.target, g.title));
558            s.push_str(&format!("        {}\n", g.via));
559            s.push_str(&format!("        {}\n", g.cmd));
560        }
561    }
562    if !p.skipped.is_empty() {
563        s.push_str(&format!("\nskipped ({}):\n", p.skipped.len()));
564        for k in &p.skipped {
565            s.push_str(&format!("  {}\n", k));
566        }
567    }
568    if p.unresolved {
569        s.push_str(
570            "\nAn unresolved pane means guessing, so it was left alone: restart it by hand\n\
571             with `claude -c` in that pane, or from its /resume picker. Each session records\n\
572             its pane at the next SessionStart, so a pane resolves cleanly once restarted.\n",
573        );
574    }
575    s
576}
577
578/// Interrupt a session, wait for it to go, and type its replacement.
579///
580/// Two Ctrl-Cs, because the first one arms claude's "press again to exit" and the
581/// second takes it. `/exit` after six waits is for a session that ignores both,
582/// and thirty waits (twelve seconds) is where it gives up rather than typing a
583/// command into a pane that still has a session in it.
584pub fn restart_pane(pane: &str, pid: i32, cmd: &str) -> bool {
585    use std::thread::sleep;
586    use std::time::Duration;
587
588    tmux::run(&["send-keys", "-t", pane, "C-c"]);
589    sleep(Duration::from_millis(300));
590    tmux::run(&["send-keys", "-t", pane, "C-c"]);
591
592    let mut waited = 0;
593    let mut sent_exit = false;
594    while alive(pid) {
595        sleep(Duration::from_millis(400));
596        waited += 1;
597        if waited >= 6 && !sent_exit {
598            tmux::run(&["send-keys", "-t", pane, "/exit", "Enter"]);
599            sent_exit = true;
600        }
601        if waited >= 30 {
602            return false;
603        }
604    }
605    sleep(Duration::from_millis(500));
606    tmux::run(&["send-keys", "-t", pane, "C-c"]);
607    sleep(Duration::from_millis(200));
608    tmux::run(&["send-keys", "-t", pane, cmd, "Enter"])
609}
610
611/// Is a pid still there? `/proc` rather than `kill -0`, since nothing is being
612/// signalled and a directory read cannot be mistaken for one.
613fn alive(pid: i32) -> bool {
614    std::path::Path::new(&format!("/proc/{}", pid)).exists()
615}
616
617/// The default answer is yes, so a bare Enter restarts. The plan has already been
618/// printed by then, which is what makes that safe.
619pub fn confirm_yes(answer: &str) -> bool {
620    matches!(answer.trim(), "" | "y" | "Y" | "yes" | "YES" | "Yes")
621}
622
623/// The live implementation of everything `plan` needs.
624pub struct Live {
625    pub versions_dir: String,
626}
627
628impl Env for Live {
629    fn capture(&self, pane: &str) -> String {
630        tmux::ask_raw(&["capture-pane", "-p", "-t", pane]).unwrap_or_default()
631    }
632    fn capture_zoomed(&self, pane: &str) -> Option<String> {
633        capture_zoomed(pane)
634    }
635    fn hook_state(&self, pane: &str, pid: i32) -> Option<String> {
636        taimux_core::hook::hook_state_of(pane, pid)
637    }
638    fn own_state(&self, pid: i32) -> Option<state::State> {
639        taimux_core::status::of(pid).and_then(|o| o.state())
640    }
641    fn moved_to(&self, pid: i32) -> Option<String> {
642        taimux_core::status::of(pid)
643            .filter(|o| o.via == taimux_core::status::Via::MovedTo)
644            .map(|o| o.session_id)
645    }
646    fn version_of_pid(&self, pid: i32) -> Option<String> {
647        version_of_pid(pid, &self.versions_dir)
648    }
649    fn cwd_of(&self, pid: i32) -> Option<String> {
650        std::fs::read_link(format!("/proc/{}/cwd", pid))
651            .ok()
652            .map(|p| p.to_string_lossy().into_owned())
653            .filter(|s| !s.is_empty())
654    }
655    fn argv_of(&self, pid: i32) -> Vec<String> {
656        conv::argv_of(pid)
657    }
658    fn resolve(&self, pane: &str, cwd: &str, title: &str, pid: i32) -> Result<String, String> {
659        conv::resolve(pane, cwd, title, pid)
660            .map(|r| format!("{}\t{}", r.transcript.display(), r.why))
661    }
662    fn read_transcript(&self, path: &str) -> Option<String> {
663        std::fs::read_to_string(path).ok()
664    }
665    fn now(&self) -> i64 {
666        std::time::SystemTime::now()
667            .duration_since(std::time::UNIX_EPOCH)
668            .map(|d| d.as_secs() as i64)
669            .unwrap_or(0)
670    }
671}
672
673/// What a session started right now would run, refusing rather than guessing when
674/// the launcher points somewhere unexpected.
675pub fn installed(launcher: &str, versions_dir: &str) -> Result<String, String> {
676    let target = std::fs::canonicalize(launcher)
677        .map(|p| p.to_string_lossy().into_owned())
678        .unwrap_or_default();
679    let prefix = format!("{}/", versions_dir);
680    match target.strip_prefix(&prefix) {
681        Some(rest) if !rest.is_empty() => Ok(rest.split('/').next().unwrap_or(rest).to_string()),
682        _ => Err(format!(
683            "restart: {} does not point into {} (got '{}')",
684            launcher,
685            versions_dir,
686            if target.is_empty() {
687                "nothing"
688            } else {
689                &target
690            }
691        )),
692    }
693}
694
695pub fn versions_dir() -> String {
696    format!(
697        "{}/.local/share/claude/versions",
698        std::env::var("HOME").unwrap_or_default()
699    )
700}
701
702pub fn launcher() -> String {
703    format!(
704        "{}/.local/bin/claude",
705        std::env::var("HOME").unwrap_or_default()
706    )
707}
708
709#[cfg(test)]
710mod tests {
711    use super::*;
712
713    #[test]
714    fn a_timestamp_becomes_epoch_seconds() {
715        // 2026-09-02T01:23:45Z
716        assert_eq!(parse_iso8601("2026-09-02T01:23:45.678Z"), Some(1788312225));
717        assert_eq!(parse_iso8601("1970-01-01T00:00:00Z"), Some(0));
718        // a leap day, which a hand-rolled calendar is where it goes wrong
719        assert_eq!(parse_iso8601("2024-02-29T00:00:00Z"), Some(1709164800));
720    }
721
722    /// Anything not of that exact shape reads as "no answer", which the caller
723    /// treats as not-evidence rather than as busy: guessing busy would skip a
724    /// pane on a malformed line forever.
725    #[test]
726    fn an_unparseable_timestamp_is_no_answer() {
727        assert_eq!(parse_iso8601(""), None);
728        assert_eq!(parse_iso8601("yesterday"), None);
729        assert_eq!(parse_iso8601("2026-09-02 01:23:45"), None);
730        assert_eq!(parse_iso8601("2026-13-02T01:23:45Z"), None);
731    }
732
733    #[test]
734    fn a_tool_call_still_running_is_not_settled() {
735        let t = r#"{"type":"assistant","message":{"content":[{"type":"tool_use"}]},"timestamp":"2020-01-01T00:00:00Z"}"#;
736        assert_eq!(
737            transcript_is_settled(t, 1788312225),
738            Err("a tool call is still running".into())
739        );
740    }
741
742    /// Insurance for the screen reading, which is the most fragile thing here.
743    #[test]
744    fn recent_activity_is_not_settled_whatever_the_screen_said() {
745        let t = r#"{"type":"user","timestamp":"2026-09-02T01:23:45Z"}"#;
746        assert!(transcript_is_settled(t, 1788312225 + 10).is_err());
747        assert!(transcript_is_settled(t, 1788312225 + 100).is_ok());
748    }
749
750    #[test]
751    fn an_empty_or_odd_transcript_does_not_block() {
752        assert!(transcript_is_settled("", 0).is_ok());
753        assert!(transcript_is_settled("not json at all\n", 0).is_ok());
754        // no timestamp: nothing to judge recency by
755        assert!(transcript_is_settled(r#"{"type":"user"}"#, 0).is_ok());
756    }
757
758    /// A dialog is what `state::awaits_input` recognises, so the fixture has to
759    /// be one it would: either the footer in the last few lines, or a numbered
760    /// choice on the LOWEST prompt line. A made-up shape asserts nothing.
761    #[test]
762    fn a_dialog_on_screen_blocks_a_restart() {
763        let footer = "some output\n\nDo you want to proceed?\n";
764        assert_eq!(
765            screen_has_no_dialog(footer),
766            Err("a dialog is waiting for an answer".into())
767        );
768        let choice = "some output\n1. Yes\n2. No\n❯ 1. Yes\n";
769        assert_eq!(
770            screen_has_no_dialog(choice),
771            Err("a dialog is waiting for an answer".into())
772        );
773        // an ordinary idle screen is not a dialog
774        assert!(screen_has_no_dialog("some output\n❯ \n").is_ok());
775    }
776
777    /// A half-pressed Ctrl-C is the one state where the keystroke that starts a
778    /// restart is also an answer to something else.
779    #[test]
780    fn a_half_pressed_ctrl_c_blocks_a_restart() {
781        let screen = "work\n\nPress Ctrl-C again to exit\n";
782        assert_eq!(
783            screen_has_no_dialog(screen),
784            Err("a Ctrl-C is already half-pressed".into())
785        );
786    }
787
788    #[test]
789    fn an_empty_prompt_box_is_no_draft() {
790        assert!(screen_has_no_draft("stuff\n❯ \n").is_ok());
791        // the non-breaking space claude pads the box with is not a draft
792        assert!(screen_has_no_draft("stuff\n❯ \u{a0}\u{a0}\n").is_ok());
793        assert_eq!(
794            screen_has_no_draft("stuff\n❯ half a thought\n"),
795            Err("unsent text in the prompt box".into())
796        );
797    }
798
799    /// The four rows a pane has to be given before any of this can be asked of
800    /// it, and the two it can be left at.
801    #[test]
802    fn a_pane_tall_enough_to_read_is_left_alone() {
803        // already showing its box: nothing to gain, and nothing touched
804        assert!(zoom_steps("%1", false, 6, 40, "%2", "%3").is_none());
805        assert!(zoom_steps("%1", false, 40, 40, "%2", "%3").is_none());
806        // a window no taller than the pane has no rows to lend it
807        assert!(zoom_steps("%1", false, 3, 3, "%2", "%3").is_none());
808        assert!(zoom_steps("%1", false, 3, 5, "%2", "%3").is_none());
809    }
810
811    /// The common shape: a three-row pane in a window nobody has zoomed. One
812    /// zoom out and back, and the pane that was active is active again with the
813    /// pane that was behind it still behind it.
814    #[test]
815    fn a_short_pane_is_zoomed_and_the_selection_put_back() {
816        let (go, back) = zoom_steps("%1", false, 3, 17, "%2", "%3").unwrap();
817        assert_eq!(go, vec![vec!["resize-pane", "-Z", "-t", "%1"]]);
818        assert_eq!(
819            back,
820            vec![
821                vec!["resize-pane", "-Z", "-t", "%1"],
822                vec!["select-pane", "-t", "%3"],
823                vec!["select-pane", "-t", "%2"],
824            ]
825        );
826    }
827
828    /// A window that arrives zoomed on another pane takes TWO `-Z` to zoom this
829    /// one, because the first is spent switching the other one off, and it is
830    /// owed a re-zoom at the end.
831    #[test]
832    fn a_window_zoomed_elsewhere_is_handed_back_zoomed() {
833        let (go, back) = zoom_steps("%1", true, 3, 17, "%2", "%3").unwrap();
834        assert_eq!(
835            go,
836            vec![
837                vec!["resize-pane", "-Z", "-t", "%1"],
838                vec!["resize-pane", "-Z", "-t", "%1"],
839            ]
840        );
841        assert_eq!(
842            back,
843            vec![
844                vec!["resize-pane", "-Z", "-t", "%1"],
845                vec!["select-pane", "-t", "%3"],
846                vec!["select-pane", "-t", "%2"],
847                vec!["resize-pane", "-Z", "-t", "%2"],
848            ]
849        );
850    }
851
852    /// Zooming the pane that is already active changes no selection, so putting
853    /// one back would be the only thing that moved it.
854    #[test]
855    fn an_active_short_pane_has_no_selection_to_restore() {
856        let (go, back) = zoom_steps("%1", false, 3, 17, "%1", "%3").unwrap();
857        assert_eq!(go.len(), 1);
858        assert_eq!(back, vec![vec!["resize-pane", "-Z", "-t", "%1"]]);
859    }
860
861    /// No box at all means the screen is not what it is expected to be, and that
862    /// is a refusal rather than a shrug.
863    #[test]
864    fn no_prompt_box_is_a_refusal() {
865        assert_eq!(
866            screen_has_no_draft("just some text\n"),
867            Err("no prompt box on screen".into())
868        );
869        // …but a genuinely blank screen is not judged at all
870        assert!(screen_has_no_draft("").is_ok());
871        assert!(screen_has_no_draft("   \n\n").is_ok());
872    }
873
874    #[test]
875    fn a_bare_enter_confirms() {
876        assert!(confirm_yes(""));
877        assert!(confirm_yes("y"));
878        assert!(confirm_yes("YES"));
879        assert!(!confirm_yes("n"));
880        assert!(!confirm_yes("no"));
881        assert!(!confirm_yes("maybe"));
882    }
883
884    #[test]
885    fn the_launcher_must_point_into_the_versions_dir() {
886        let root = std::env::temp_dir().join(format!("jmrs{}", std::process::id()));
887        let vers = root.join("versions");
888        std::fs::create_dir_all(&vers).unwrap();
889        std::fs::write(vers.join("2.1.258"), "x").unwrap();
890        let link = root.join("claude");
891        std::os::unix::fs::symlink(vers.join("2.1.258"), &link).unwrap();
892        assert_eq!(
893            installed(&link.to_string_lossy(), &vers.to_string_lossy()),
894            Ok("2.1.258".into())
895        );
896        // pointing elsewhere is a refusal that names what it found
897        std::fs::write(root.join("elsewhere"), "x").unwrap();
898        std::fs::remove_file(&link).unwrap();
899        std::os::unix::fs::symlink(root.join("elsewhere"), &link).unwrap();
900        let e = installed(&link.to_string_lossy(), &vers.to_string_lossy()).expect_err("refused");
901        assert!(e.contains("elsewhere"));
902        let _ = std::fs::remove_dir_all(&root);
903    }
904}
905
906/// A claude process that is not any pane's foreground job: Zed's ACP bridge, a
907/// background agent, one of the daemon's spare pty hosts.
908///
909/// Reported, never touched. A restart types into a PANE, and these have none, so
910/// the only useful thing to do about a stale one is name it.
911pub fn nonpane_pids(matched: &[i32], versions_dir: &str) -> Vec<i32> {
912    let mut out = Vec::new();
913    for e in std::fs::read_dir("/proc").into_iter().flatten().flatten() {
914        let Some(pid) = e.file_name().to_str().and_then(|s| s.parse::<i32>().ok()) else {
915            continue;
916        };
917        if matched.contains(&pid) {
918            continue;
919        }
920        // Either its comm is "claude" (pgrep -x claude) or it is running out of
921        // the versions directory (pgrep -f "^<vdir>/").
922        let comm = std::fs::read_to_string(format!("/proc/{}/comm", pid)).unwrap_or_default();
923        let argv = conv::argv_of(pid);
924        let is_claude = comm.trim() == "claude"
925            || argv
926                .first()
927                .map(|a| a.starts_with(&format!("{}/", versions_dir)))
928                .unwrap_or(false);
929        if is_claude {
930            out.push(pid);
931        }
932    }
933    out.sort_unstable();
934    out
935}
936
937/// The object in a JSON array whose `key` starts with `prefix`, as raw text.
938///
939/// A brace matcher rather than a parser, and rather than the `jq` the bash
940/// version shelled out to. It only has to find one element of one array, and the
941/// depth count is what makes it safe against nested objects: taking everything
942/// between the first `{` and the first `}` would truncate any element with a
943/// nested field.
944fn json_object_with_prefix(text: &str, key: &str, prefix: &str) -> Option<String> {
945    let needle = format!("\"{}\":\"{}", key, prefix);
946    let at = text.find(&needle).or_else(|| {
947        let spaced = format!("\"{}\": \"{}", key, prefix);
948        text.find(&spaced)
949    })?;
950    // back to the opening brace of the object holding it
951    let mut depth = 0i32;
952    let bytes = text.as_bytes();
953    let mut start = None;
954    for i in (0..at).rev() {
955        match bytes[i] {
956            b'}' => depth += 1,
957            b'{' => {
958                if depth == 0 {
959                    start = Some(i);
960                    break;
961                }
962                depth -= 1;
963            }
964            _ => {}
965        }
966    }
967    let start = start?;
968    // forward to its matching close
969    let mut depth = 0i32;
970    for i in start..bytes.len() {
971        match bytes[i] {
972            b'{' => depth += 1,
973            b'}' => {
974                depth -= 1;
975                if depth == 0 {
976                    return Some(text[start..=i].to_string());
977                }
978            }
979            _ => {}
980        }
981    }
982    None
983}
984
985/// What to say about a claude that has no pane.
986///
987/// `agents_json` is `claude agents --json`, which costs about three seconds of
988/// CLI startup, so it is fetched once by the caller and only when something needs
989/// naming. Its own `pid` field points at the pty-host wrapper rather than at the
990/// session, so it is read for kind, state and name and nothing else.
991pub fn describe_nonpane(argv: &[String], agents_json: &str) -> String {
992    if argv.is_empty() {
993        return "gone".into();
994    }
995    let (mut sid, mut res, mut forked) = (String::new(), String::new(), false);
996    for i in 1..argv.len() {
997        match argv[i].as_str() {
998            "--fork-session" => forked = true,
999            "--session-id" => sid = argv.get(i + 1).cloned().unwrap_or_default(),
1000            "-r" | "--resume" => res = argv.get(i + 1).cloned().unwrap_or_default(),
1001            _ => {}
1002        }
1003    }
1004    let own = base_id(if sid.is_empty() { &res } else { &sid });
1005    let parent = if forked && !res.is_empty() {
1006        base_id(&res)
1007    } else {
1008        String::new()
1009    };
1010
1011    let (mut kind, mut st, mut name) = ("?".to_string(), "?".to_string(), String::new());
1012    if !own.is_empty() {
1013        if let Some(obj) = json_object_with_prefix(agents_json, "sessionId", &own) {
1014            let f = |k: &str| taimux_core::json::field(&obj, k);
1015            let k = f("kind");
1016            if !k.is_empty() {
1017                kind = k;
1018            }
1019            let s = {
1020                let a = f("state");
1021                if a.is_empty() {
1022                    f("status")
1023                } else {
1024                    a
1025                }
1026            };
1027            if !s.is_empty() {
1028                st = s;
1029            }
1030            name = f("name");
1031        }
1032    }
1033    let mut out = format!("{} {}", kind, st);
1034    if forked {
1035        out.push_str(" fork");
1036    }
1037    if !name.is_empty() {
1038        out.push_str(&format!(" \"{}\"", name));
1039    }
1040    if !own.is_empty() {
1041        out.push_str(&format!(" [{}]", own.chars().take(8).collect::<String>()));
1042    }
1043    if !parent.is_empty() {
1044        out.push_str(&format!(
1045            " of [{}]",
1046            parent.chars().take(8).collect::<String>()
1047        ));
1048    }
1049    out
1050}
1051
1052/// `basename x .jsonl`: a session id, whether it arrived as one or as a path.
1053fn base_id(s: &str) -> String {
1054    if s.is_empty() {
1055        return String::new();
1056    }
1057    let b = s.rsplit('/').next().unwrap_or(s);
1058    b.strip_suffix(".jsonl").unwrap_or(b).to_string()
1059}
1060
1061#[cfg(test)]
1062mod nonpane_tests {
1063    use super::*;
1064
1065    fn v(a: &[&str]) -> Vec<String> {
1066        a.iter().map(|s| s.to_string()).collect()
1067    }
1068
1069    #[test]
1070    fn a_session_id_is_read_out_of_a_path_or_taken_as_it_stands() {
1071        assert_eq!(base_id("/a/b/263946b5-9bd7.jsonl"), "263946b5-9bd7");
1072        assert_eq!(base_id("263946b5"), "263946b5");
1073        assert_eq!(base_id(""), "");
1074    }
1075
1076    /// The depth count is the whole point: taking everything between the first
1077    /// brace and the first close would truncate any element with a nested field,
1078    /// and `claude agents --json` has them.
1079    #[test]
1080    fn the_right_object_comes_back_whole() {
1081        let j = r#"[{"sessionId":"aaa111","kind":"task","meta":{"a":1},"name":"first"},
1082                    {"sessionId":"bbb222","kind":"agent","name":"second"}]"#;
1083        let o = json_object_with_prefix(j, "sessionId", "bbb222").expect("found");
1084        assert!(o.contains("second"));
1085        assert!(!o.contains("first"));
1086        let o = json_object_with_prefix(j, "sessionId", "aaa").expect("found by prefix");
1087        assert!(o.contains("first"));
1088        assert!(
1089            o.contains("\"meta\":{\"a\":1}"),
1090            "nested field truncated: {}",
1091            o
1092        );
1093        assert!(json_object_with_prefix(j, "sessionId", "zzz").is_none());
1094    }
1095
1096    #[test]
1097    fn a_process_with_no_argv_is_simply_gone() {
1098        assert_eq!(describe_nonpane(&[], "[]"), "gone");
1099    }
1100
1101    #[test]
1102    fn an_unnamed_session_still_says_what_it_can() {
1103        let d = describe_nonpane(&v(&["claude", "--session-id", "263946b5-9bd7"]), "[]");
1104        assert_eq!(d, "? ? [263946b5]");
1105    }
1106
1107    #[test]
1108    fn a_named_one_says_kind_state_and_name() {
1109        let j =
1110            r#"[{"sessionId":"263946b5-9bd7","kind":"task","state":"running","name":"the thing"}]"#;
1111        let d = describe_nonpane(&v(&["claude", "--session-id", "263946b5-9bd7"]), j);
1112        assert_eq!(d, "task running \"the thing\" [263946b5]");
1113    }
1114
1115    /// `status` is the older field name, and one of the two is what a given
1116    /// version emits.
1117    #[test]
1118    fn status_stands_in_for_state() {
1119        let j = r#"[{"sessionId":"aaa11111","kind":"agent","status":"idle"}]"#;
1120        let d = describe_nonpane(&v(&["claude", "--session-id", "aaa11111"]), j);
1121        assert_eq!(d, "agent idle [aaa11111]");
1122    }
1123
1124    /// A fork names both itself and its parent, because that is the pair you need
1125    /// to work out which one is the stale one.
1126    #[test]
1127    fn a_fork_names_its_parent_too() {
1128        let d = describe_nonpane(
1129            &v(&[
1130                "claude",
1131                "--session-id",
1132                "child111",
1133                "--fork-session",
1134                "--resume",
1135                "/p/parent22.jsonl",
1136            ]),
1137            "[]",
1138        );
1139        assert_eq!(d, "? ? fork [child111] of [parent22]");
1140    }
1141}
1142
1143#[cfg(test)]
1144mod plan_tests {
1145    use super::*;
1146
1147    /// A machine with one stale pane, one current one, and whatever else the test
1148    /// asks for. The `Env` trait exists for this: the live differential can only
1149    /// reach "nothing to restart" while every session is on the installed
1150    /// version, so the branch that actually acts needs a fixture.
1151    struct Fake {
1152        /// pid -> version
1153        vers: HashMap<i32, String>,
1154        /// pane -> screen
1155        screens: HashMap<String, String>,
1156        /// pane -> resolved transcript, or the refusal
1157        resolved: HashMap<String, Result<String, String>>,
1158        /// pane -> what the same pane shows once it has been zoomed, for a pane
1159        /// too short to draw a prompt box at the size it sits at
1160        zoomed: HashMap<String, String>,
1161        /// how many panes were zoomed to be read, since a zoom is something the
1162        /// user watching that window sees happen
1163        zooms: std::cell::Cell<usize>,
1164        /// pane -> the hook line's state, for the panes that have one
1165        hooks: HashMap<String, String>,
1166        /// pid -> what the session says it is doing, for the ones that say
1167        own: HashMap<i32, state::State>,
1168        /// pid -> the background session its conversation was moved into
1169        moved: HashMap<i32, String>,
1170        transcript: String,
1171        now: i64,
1172    }
1173
1174    impl Env for Fake {
1175        fn capture(&self, pane: &str) -> String {
1176            self.screens.get(pane).cloned().unwrap_or_default()
1177        }
1178        fn capture_zoomed(&self, pane: &str) -> Option<String> {
1179            let bigger = self.zoomed.get(pane).cloned();
1180            if bigger.is_some() {
1181                self.zooms.set(self.zooms.get() + 1);
1182            }
1183            bigger
1184        }
1185        fn hook_state(&self, pane: &str, _pid: i32) -> Option<String> {
1186            self.hooks.get(pane).cloned()
1187        }
1188        fn own_state(&self, pid: i32) -> Option<state::State> {
1189            self.own.get(&pid).copied()
1190        }
1191        fn moved_to(&self, pid: i32) -> Option<String> {
1192            self.moved.get(&pid).cloned()
1193        }
1194        fn version_of_pid(&self, pid: i32) -> Option<String> {
1195            self.vers.get(&pid).cloned()
1196        }
1197        fn cwd_of(&self, _pid: i32) -> Option<String> {
1198            Some("/w".into())
1199        }
1200        fn argv_of(&self, _pid: i32) -> Vec<String> {
1201            vec!["claude".into()]
1202        }
1203        fn resolve(&self, pane: &str, _c: &str, _t: &str, _p: i32) -> Result<String, String> {
1204            self.resolved
1205                .get(pane)
1206                .cloned()
1207                .unwrap_or_else(|| Err("no candidate".into()))
1208        }
1209        fn read_transcript(&self, _path: &str) -> Option<String> {
1210            Some(self.transcript.clone())
1211        }
1212        fn now(&self) -> i64 {
1213            self.now
1214        }
1215    }
1216
1217    fn fake() -> Fake {
1218        let mut vers = HashMap::new();
1219        vers.insert(11, "2.1.100".to_string()); // stale
1220        vers.insert(22, "2.1.258".to_string()); // current
1221        let mut screens = HashMap::new();
1222        // an idle screen with an empty prompt box
1223        screens.insert("%1".to_string(), "some output\n❯ \n".to_string());
1224        screens.insert("%2".to_string(), "some output\n❯ \n".to_string());
1225        let mut resolved = HashMap::new();
1226        resolved.insert("%1".to_string(), Ok("/t/a.jsonl\tpane map".to_string()));
1227        Fake {
1228            vers,
1229            screens,
1230            resolved,
1231            zoomed: HashMap::new(),
1232            zooms: std::cell::Cell::new(0),
1233            hooks: HashMap::new(),
1234            own: HashMap::new(),
1235            moved: HashMap::new(),
1236            transcript: r#"{"type":"user","timestamp":"2020-01-01T00:00:00Z"}"#.to_string(),
1237            now: 1788312225,
1238        }
1239    }
1240
1241    fn opts() -> Opts {
1242        Opts {
1243            include_busy: false,
1244            only_panes: Vec::new(),
1245            force_transcript: None,
1246            self_pane: String::new(),
1247        }
1248    }
1249
1250    const ROWS: &str = "%1\tw:1.1\t/w\tclaude\t11\tclaude\tproj: the stale one\n\
1251                        %2\tw:2.1\t/w\tclaude\t22\tclaude\tproj: the current one";
1252
1253    fn plan_of(e: &Fake, o: &Opts) -> Plan {
1254        plan(ROWS, "2.1.258", "/l/claude", o, e, "/nowhere", &|| {
1255            "[]".into()
1256        })
1257    }
1258
1259    #[test]
1260    fn a_stale_pane_is_planned_and_a_current_one_is_not() {
1261        let p = plan_of(&fake(), &opts());
1262        assert_eq!(p.go.len(), 1);
1263        assert_eq!(p.go[0].pane, "%1");
1264        assert_eq!(p.go[0].cmd, "command claude --resume /t/a.jsonl");
1265        assert_eq!(p.go[0].via, "2.1.100 -> 2.1.258, pane map, idle");
1266        assert!(p.skipped.is_empty());
1267    }
1268
1269    /// The rendered plan is the whole user interface of `restart -n`, so its
1270    /// exact shape is what the bash comparison was made on.
1271    #[test]
1272    fn the_rendered_plan_reads_the_way_it_always_did() {
1273        let out = render(&plan_of(&fake(), &opts()));
1274        assert_eq!(
1275            out,
1276            "claude: 2.1.258 installed at /l/claude\n\n\
1277             to restart (1):\n\
1278             \x20 %1    w:1.1          proj: the stale one\n\
1279             \x20       2.1.100 -> 2.1.258, pane map, idle\n\
1280             \x20       command claude --resume /t/a.jsonl\n"
1281        );
1282    }
1283
1284    /// Restarting the pane taimux is running in would kill taimux mid-restart.
1285    #[test]
1286    fn this_pane_is_never_restarted() {
1287        let mut o = opts();
1288        o.self_pane = "%1".into();
1289        let p = plan_of(&fake(), &o);
1290        assert!(p.go.is_empty());
1291        assert!(p.skipped[0].contains("this pane"));
1292        assert!(p.skipped[0].contains("killing it would kill taimux"));
1293    }
1294
1295    #[test]
1296    fn a_pane_that_is_not_idle_waits_for_include_busy() {
1297        let mut e = fake();
1298        // an activity line: mid-turn
1299        e.screens
1300            .insert("%1".into(), "Twisting… (35s · ↓ 1.6k tokens)\n❯ \n".into());
1301        let p = plan_of(&e, &opts());
1302        assert!(p.go.is_empty());
1303        assert!(p.skipped[0].contains("rerun when idle, or --include-busy"));
1304
1305        let mut o = opts();
1306        o.include_busy = true;
1307        assert_eq!(plan_of(&e, &o).go.len(), 1);
1308    }
1309
1310    /// What the session says outranks a screen and a hook line that both look
1311    /// idle: a permission granted to a tool that is still running shows neither
1312    /// a counter nor a fresh line, and restarting it would kill the tool.
1313    #[test]
1314    fn a_session_that_says_it_is_busy_is_busy() {
1315        let mut e = fake();
1316        e.hooks.insert("%1".into(), "input".into());
1317        e.own.insert(11, state::State::Run);
1318        let p = plan_of(&e, &opts());
1319        assert!(p.go.is_empty());
1320        assert!(
1321            p.skipped[0].contains("run: rerun when idle"),
1322            "{:?}",
1323            p.skipped
1324        );
1325        // and an Esc the hook line never heard of frees it again
1326        e.hooks.insert("%1".into(), "run".into());
1327        e.own.insert(11, state::State::Idle);
1328        assert_eq!(plan_of(&e, &opts()).go.len(), 1);
1329    }
1330
1331    /// A pane left behind by a backgrounding is idle, and restarting it would
1332    /// resume the conversation it started on as a second branch, beside the
1333    /// one agent view goes on running.
1334    #[test]
1335    fn a_pane_whose_conversation_moved_to_the_background_is_left_alone() {
1336        let mut e = fake();
1337        e.own.insert(11, state::State::Idle);
1338        e.moved
1339            .insert(11, "2447b564-7a96-4774-b70a-ef4b730bdd4d".into());
1340        let mut o = opts();
1341        o.include_busy = true; // not a busy-ness question at all
1342        let p = plan_of(&e, &o);
1343        assert!(p.go.is_empty());
1344        assert!(
1345            p.skipped[0].contains("moved to background session 2447b564: claude attach 2447b564"),
1346            "{:?}",
1347            p.skipped
1348        );
1349    }
1350
1351    /// Idle at its prompt, and still not restartable without asking: the shells
1352    /// a finished turn left running are the session's children and die with it.
1353    #[test]
1354    fn a_pane_with_work_in_flight_waits_for_include_busy() {
1355        let mut e = fake();
1356        e.screens.insert(
1357            "%1".into(),
1358            "✻ Cogitated for 1m 3s · done 4:55 PM · 2 shells still running\n❯ \n".into(),
1359        );
1360        let p = plan_of(&e, &opts());
1361        assert!(p.go.is_empty());
1362        assert!(
1363            p.skipped[0].contains("work still in flight"),
1364            "{:?}",
1365            p.skipped
1366        );
1367
1368        // The line alone says so as well, on a screen that shows nothing of it.
1369        let mut e = fake();
1370        e.hooks.insert("%1".into(), "bg".into());
1371        let p = plan_of(&e, &opts());
1372        assert!(p.go.is_empty());
1373        assert!(
1374            p.skipped[0].contains("work still in flight"),
1375            "{:?}",
1376            p.skipped
1377        );
1378
1379        let mut o = opts();
1380        o.include_busy = true;
1381        assert_eq!(plan_of(&e, &o).go.len(), 1);
1382    }
1383
1384    /// Even with --include-busy: a half-answered permission prompt is the one
1385    /// state where the Ctrl-C that starts a restart means something else.
1386    #[test]
1387    fn a_dialog_blocks_a_restart_even_with_include_busy() {
1388        let mut e = fake();
1389        e.screens
1390            .insert("%1".into(), "output\n\nDo you want to proceed?\n".into());
1391        let mut o = opts();
1392        o.include_busy = true;
1393        let p = plan_of(&e, &o);
1394        assert!(p.go.is_empty());
1395        assert!(p.skipped[0].contains("a dialog is waiting for an answer"));
1396    }
1397
1398    #[test]
1399    fn an_unsent_draft_is_left_alone() {
1400        let mut e = fake();
1401        e.screens
1402            .insert("%1".into(), "output\n❯ half a thought\n".into());
1403        let p = plan_of(&e, &opts());
1404        assert!(p.skipped[0].contains("unsent text in the prompt box"));
1405    }
1406
1407    /// The pane this whole thing is for: three rows, no box on it, and a session
1408    /// sitting idle behind that. Read at a size it can be read at, it is an
1409    /// ordinary restart.
1410    #[test]
1411    fn a_pane_too_short_for_its_box_is_read_zoomed() {
1412        let mut e = fake();
1413        e.screens.insert(
1414            "%1".into(),
1415            "  current: 2.1.100 · latest…\n────────\n".into(),
1416        );
1417        e.zoomed.insert("%1".into(), "some output\n❯ \n".into());
1418        let p = plan_of(&e, &opts());
1419        assert_eq!(e.zooms.get(), 1);
1420        assert_eq!(p.go.len(), 1);
1421        assert_eq!(p.go[0].pane, "%1");
1422        assert!(p.skipped.is_empty());
1423    }
1424
1425    /// And the point of reading it rather than assuming: a draft is invisible at
1426    /// three rows too, so the zoomed read is the only thing that can find one.
1427    /// Refused here for what is actually in the box, not for the box being
1428    /// missing.
1429    #[test]
1430    fn a_draft_hidden_by_a_short_pane_still_refuses() {
1431        let mut e = fake();
1432        e.screens
1433            .insert("%1".into(), "  current: 2.1.100…\n".into());
1434        e.zoomed
1435            .insert("%1".into(), "output\n❯ half a thought\n".into());
1436        let p = plan_of(&e, &opts());
1437        assert_eq!(e.zooms.get(), 1);
1438        assert!(p.go.is_empty());
1439        assert!(p.skipped[0].contains("unsent text in the prompt box"));
1440    }
1441
1442    /// A dialog is off the bottom of a short pane with the box, so the zoomed
1443    /// read is what finds that too, and a dialog is refused with or without
1444    /// `--include-busy`.
1445    #[test]
1446    fn a_dialog_hidden_by_a_short_pane_is_found_by_the_zoom() {
1447        let mut e = fake();
1448        e.screens.insert("%1".into(), "  Bash command\n".into());
1449        e.zoomed.insert(
1450            "%1".into(),
1451            "Do you want to proceed?\n❯ 1. Yes\n  2. No\n".into(),
1452        );
1453        let mut o = opts();
1454        o.include_busy = true;
1455        let p = plan_of(&e, &o);
1456        assert!(p.go.is_empty());
1457        assert!(p.skipped[0].contains("a dialog is waiting for an answer"));
1458    }
1459
1460    /// A pane already showing its box is never zoomed: the read is already good,
1461    /// and a zoom is something the person watching that window sees happen.
1462    #[test]
1463    fn a_pane_that_shows_its_box_is_not_zoomed() {
1464        let e = fake();
1465        let p = plan_of(&e, &opts());
1466        assert_eq!(e.zooms.get(), 0);
1467        assert_eq!(p.go.len(), 1);
1468    }
1469
1470    /// A transcript touched in the last 45 seconds is left alone whatever the
1471    /// screen said, because the screen reading is the fragile half.
1472    #[test]
1473    fn a_recently_active_transcript_is_left_alone() {
1474        let mut e = fake();
1475        e.transcript = r#"{"type":"user","timestamp":"2026-09-02T01:23:45Z"}"#.into();
1476        e.now = 1788312225 + 10;
1477        let p = plan_of(&e, &opts());
1478        assert!(p.skipped[0].contains("active in the last 45s"));
1479    }
1480
1481    #[test]
1482    fn an_unresolved_pane_says_so_and_earns_the_paragraph() {
1483        let mut e = fake();
1484        e.resolved
1485            .insert("%1".into(), Err("3 transcripts share this title".into()));
1486        let p = plan_of(&e, &opts());
1487        assert!(p.go.is_empty());
1488        assert!(p.unresolved);
1489        assert!(p.skipped[0].contains("unresolved: 3 transcripts share this title"));
1490        assert!(render(&p).contains("restart it by hand"));
1491    }
1492
1493    /// Two panes on one conversation is the same mistake on a restart as on a
1494    /// restore: the second one to claim it gets skipped rather than resumed.
1495    #[test]
1496    fn one_transcript_is_never_resumed_into_two_panes() {
1497        let mut e = fake();
1498        e.vers.insert(22, "2.1.100".into()); // make the second one stale too
1499        e.resolved
1500            .insert("%2".into(), Ok("/t/a.jsonl\tpane map".into()));
1501        let p = plan_of(&e, &opts());
1502        assert_eq!(p.go.len(), 1);
1503        assert_eq!(p.go[0].pane, "%1");
1504        assert!(p.skipped[0].contains("resolves to the same transcript as %1"));
1505    }
1506
1507    #[test]
1508    fn only_panes_narrows_the_plan_without_changing_the_verdicts() {
1509        let mut o = opts();
1510        o.only_panes = vec!["%2".into()];
1511        let p = plan_of(&fake(), &o);
1512        assert!(p.go.is_empty());
1513        assert!(p.skipped.is_empty()); // %1 was not considered at all
1514    }
1515
1516    #[test]
1517    fn a_pane_with_no_session_process_is_reported_not_dropped() {
1518        let rows = "%9\tw:9.9\t/w\tclaude\t0\tclaude\tno pid here";
1519        let p = plan(rows, "2.1.258", "/l", &opts(), &fake(), "/nowhere", &|| {
1520            "[]".into()
1521        });
1522        assert!(p.go.is_empty());
1523        assert_eq!(p.skipped.len(), 1);
1524        assert!(p.skipped[0].contains("no session process was found"));
1525    }
1526
1527    #[test]
1528    fn nothing_to_restart_says_so() {
1529        let mut e = fake();
1530        e.vers.insert(11, "2.1.258".into());
1531        let out = render(&plan_of(&e, &opts()));
1532        assert!(out.contains("nothing to restart."));
1533        assert!(!out.contains("to restart ("));
1534    }
1535
1536    /// --transcript names the conversation outright, which is the escape hatch
1537    /// for a pane the ladder refuses.
1538    #[test]
1539    fn a_given_transcript_overrides_the_ladder() {
1540        let mut e = fake();
1541        e.resolved.insert("%1".into(), Err("no candidate".into()));
1542        let mut o = opts();
1543        o.force_transcript = Some("/given.jsonl".into());
1544        let p = plan_of(&e, &o);
1545        assert_eq!(p.go.len(), 1);
1546        assert!(p.go[0].via.contains("--transcript, given"));
1547        assert!(p.go[0].cmd.contains("--resume /given.jsonl"));
1548    }
1549}