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