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