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//!
22//! A pane showing a **background session** goes through the same guards, read
23//! off the session it shows, with its worker's version standing in for the
24//! pane's and its job id for the conversation, and is put back differently:
25//! see `respawn` and `reattach`. Retyping such a pane would resume the
26//! transcript it started on, branching a conversation that carries on in the
27//! worker.
28
29use std::collections::HashMap;
30
31use taimux_core::{conv, state, tmux};
32
33/// Is this transcript quiet enough to interrupt?
34///
35/// Two refusals: an unanswered `tool_use` as the very last record (a tool call is
36/// still in flight), and any activity in the last 45 seconds. The second is
37/// insurance for the first, because the screen reading is the most fragile thing
38/// in this tool and a recently-touched transcript is worth leaving alone whatever
39/// the screen said.
40///
41/// The `tool_use` test is a text match on the final line rather than a parse of
42/// `.message.content[]`, which is the one approximation: an assistant turn whose
43/// own prose quotes that key reads as busy. It fails toward "leave it alone", and
44/// the recency guard covers the same ground, so the cost is a pane skipped rather
45/// than a turn lost.
46pub fn transcript_is_settled(text: &str, now: i64) -> Result<(), String> {
47    let Some(last) = text.lines().rfind(|l| !l.trim().is_empty()) else {
48        return Ok(()); // unknown shape: do not block on a guess
49    };
50    if taimux_core::json::field(last, "type") == "assistant"
51        && (last.contains("\"type\":\"tool_use\"") || last.contains("\"type\": \"tool_use\""))
52    {
53        return Err("a tool call is still running".into());
54    }
55    let ts = taimux_core::json::field(last, "timestamp");
56    if ts.is_empty() {
57        return Ok(());
58    }
59    let Some(then) = parse_iso8601(&ts) else {
60        return Ok(()); // unparseable: not evidence of anything
61    };
62    if now - then < 45 {
63        return Err("active in the last 45s".into());
64    }
65    Ok(())
66}
67
68/// An ISO 8601 UTC timestamp to epoch seconds, which is all claude writes:
69/// `2026-09-02T01:23:45.678Z`. The parse is `turn::epoch_ms`, which the state
70/// reading needs to the millisecond; this only wants the second.
71fn parse_iso8601(s: &str) -> Option<i64> {
72    taimux_core::turn::epoch_ms(s).map(|ms| ms.div_euclid(1000))
73}
74
75/// Is the screen free of anything a Ctrl-C would mean something else to?
76///
77/// Applied even with `--include-busy`, because this is the one state where the
78/// keystroke that starts a restart is also an answer to a question.
79pub fn screen_has_no_dialog(screen: &str) -> Result<(), String> {
80    if state::awaits_input(screen) {
81        return Err("a dialog is waiting for an answer".into());
82    }
83    let tail: Vec<&str> = screen
84        .lines()
85        .filter(|l| !l.trim().is_empty())
86        .rev()
87        .take(4)
88        .collect();
89    if tail
90        .iter()
91        .any(|l| l.contains("Press Ctrl-C again to exit"))
92    {
93        return Err("a Ctrl-C is already half-pressed".into());
94    }
95    Ok(())
96}
97
98/// Is the prompt box empty?
99///
100/// Unsent text in it is work nobody has committed yet, and a restart would throw
101/// it away. The non-breaking space claude pads the box with is stripped before
102/// the check, or every box would look occupied.
103pub fn screen_has_no_draft(screen: &str) -> Result<(), String> {
104    let txt: Vec<&str> = screen.lines().filter(|l| !l.trim().is_empty()).collect();
105    if txt.is_empty() {
106        return Ok(());
107    }
108    let Some(box_line) = txt.iter().rev().find(|l| l.contains('❯')) else {
109        return Err("no prompt box on screen".into());
110    };
111    let after = box_line.split_once('❯').map(|(_, r)| r).unwrap_or("");
112    let rest: String = after
113        .chars()
114        .filter(|c| !c.is_whitespace() && *c != '\u{a0}')
115        .collect();
116    if rest.is_empty() {
117        Ok(())
118    } else {
119        Err("unsent text in the prompt box".into())
120    }
121}
122
123/// The rows claude needs before it draws its prompt box at all.
124///
125/// Measured against 2.1.278 in a tmux server of its own, a row at a time: at six
126/// the `❯` is on screen and whatever has been typed into it with it, at five the
127/// last row is the box's own top rule and neither the glyph nor the draft is
128/// anywhere on the pane, and by three nothing of the box survives. Width does not
129/// move it, 46, 54, 63, 80 and 213 columns all break in the same place.
130///
131/// A pane under it is not a pane in a strange state, it is a pane that cannot be
132/// READ: the box, an unsent draft inside it and a dialog over it go off the
133/// bottom together, so `screen_has_no_draft` refuses it and would go on refusing
134/// it for as long as the pane stays that size. Nine of the fourteen outdated
135/// panes on this machine were exactly that, which is how a sweep meant to clear
136/// the outdated list offered to clear four of them.
137const BOX_ROWS: usize = 6;
138
139/// One tmux command line, as the arguments it is made of.
140type Cmd = Vec<String>;
141
142/// Getting a pane to a readable size, and putting the window back after.
143type ZoomSteps = (Vec<Cmd>, Vec<Cmd>);
144
145/// What it takes to read a pane at a size claude will draw on, and what it takes
146/// to put the window back afterwards.
147///
148/// Split out from the running of it so the ORDER can be tested without a tmux to
149/// run it against, the order being the whole of the difficulty. `None` when there
150/// is nothing to gain: a pane already tall enough, or a window no taller than the
151/// pane it holds, where zooming would hand it the rows it already has.
152///
153/// **Zoom rather than `resize-pane -y`**, and only a crowded window shows why:
154/// seven panes in seventeen rows share eleven rows of content, six of which are
155/// already spoken for by the others, so the tallest any one of them can be made
156/// is five, one short of what the box needs. Zoom is the only growth that does
157/// not have to come out of a sibling. It also leaves the LAYOUT untouched, so
158/// putting the window back is a matter of the zoom flag and the active pane
159/// rather than of replaying a layout string and hoping it lands.
160fn zoom_steps(
161    pane: &str,
162    zoomed: bool,
163    pane_rows: usize,
164    window_rows: usize,
165    active: &str,
166    last: &str,
167) -> Option<ZoomSteps> {
168    if pane_rows >= BOX_ROWS || window_rows < BOX_ROWS || window_rows <= pane_rows {
169        return None;
170    }
171    let cmd = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Cmd>();
172
173    let mut go = Vec::new();
174    // `-Z` toggles the WINDOW's zoom whatever pane it is pointed at, so on a
175    // window that arrives zoomed the first one only ever switches the OTHER pane
176    // off, and a second is what zooms this one. Two identical command lines in a
177    // row is not a duplicated push.
178    if zoomed {
179        go.push(cmd(&["resize-pane", "-Z", "-t", pane]));
180    }
181    go.push(cmd(&["resize-pane", "-Z", "-t", pane]));
182
183    let mut back = vec![cmd(&["resize-pane", "-Z", "-t", pane])];
184    // Zooming made this pane the active one and pushed whatever was active into
185    // the window's "last pane", so both have to go back, and in that order:
186    // selecting the old last pane first leaves the old active one current with
187    // the right pane behind it. `prefix + ;` is the user's binding, not taimux's
188    // to spend. A pane that was active already has neither to restore.
189    if active != pane {
190        if !last.is_empty() && last != pane {
191            back.push(cmd(&["select-pane", "-t", last]));
192        }
193        if !active.is_empty() {
194            back.push(cmd(&["select-pane", "-t", active]));
195        }
196    }
197    // A window that arrives zoomed is zoomed on its active pane by definition,
198    // which is why that pane is never this one: it would have the window's full
199    // height and be refused above.
200    if zoomed && !active.is_empty() {
201        back.push(cmd(&["resize-pane", "-Z", "-t", active]));
202    }
203    Some((go, back))
204}
205
206/// The commands that put the window back, run when this goes out of scope.
207///
208/// A guard rather than a line at the end of the function because the read
209/// between the two can panic, and a window left zoomed on a pane nobody chose is
210/// a worse outcome than a pane left unread.
211struct Restoring(Vec<Cmd>);
212
213impl Drop for Restoring {
214    fn drop(&mut self) {
215        for c in &self.0 {
216            tmux::run(&c.iter().map(String::as_str).collect::<Vec<_>>());
217        }
218    }
219}
220
221/// One pane's screen, read at a size claude will draw its prompt box on.
222///
223/// `None` when the pane did not need it or the window cannot give it, in which
224/// case nothing was touched and the screen already in hand is the best there is.
225///
226/// The wait is not padding. claude redraws on the SIGWINCH and does it fast,
227/// measured at 13 to 16ms across six runs with the draft already in the first
228/// readable frame, but a capture taken with no wait at all comes back with no box
229/// at all: tmux does not reflow an old frame into the new rows, it hands over
230/// what is there and claude fills it a moment later. So the poll is what makes
231/// the read real, and its ceiling is thirty times the measurement rather than a
232/// guess at it.
233pub fn capture_zoomed(pane: &str) -> Option<String> {
234    if !taimux_core::env::on("TAIMUX_ZOOM_TO_READ") {
235        return None;
236    }
237    let geom = tmux::ask(&[
238        "display-message",
239        "-p",
240        "-t",
241        pane,
242        "-F",
243        "#{window_zoomed_flag}\t#{pane_height}\t#{window_height}\t#{window_id}",
244    ])?;
245    let g: Vec<&str> = geom.trim_end().split('\t').collect();
246    if g.len() < 4 {
247        return None;
248    }
249    let (zoomed, win) = (g[0] == "1", g[3]);
250    let pane_rows: usize = g[1].parse().ok()?;
251    let window_rows: usize = g[2].parse().ok()?;
252
253    let mut active = String::new();
254    let mut last = String::new();
255    for l in tmux::ask(&[
256        "list-panes",
257        "-t",
258        win,
259        "-F",
260        "#{pane_id}\t#{pane_active}\t#{pane_last}",
261    ])?
262    .lines()
263    {
264        let c: Vec<&str> = l.split('\t').collect();
265        if c.len() < 3 {
266            continue;
267        }
268        if c[1] == "1" {
269            active = c[0].to_string();
270        }
271        if c[2] == "1" {
272            last = c[0].to_string();
273        }
274    }
275
276    let (go, back) = zoom_steps(pane, zoomed, pane_rows, window_rows, &active, &last)?;
277    for c in &go {
278        tmux::run(&c.iter().map(String::as_str).collect::<Vec<_>>());
279    }
280    let _restore = Restoring(back);
281
282    let deadline = std::time::Instant::now() + std::time::Duration::from_millis(500);
283    loop {
284        let screen = tmux::capture(pane).unwrap_or_default();
285        if screen.contains('❯') || std::time::Instant::now() >= deadline {
286            return Some(screen);
287        }
288        std::thread::sleep(std::time::Duration::from_millis(10));
289    }
290}
291
292/// The version a running process is executing, read from its own `/proc/exe`
293/// rather than from the binary on `$PATH`: a long-lived session goes on running
294/// the release it started under.
295pub fn version_of_pid(pid: i32, versions_dir: &str) -> Option<String> {
296    let exe = std::fs::read_link(format!("/proc/{}/exe", pid)).ok()?;
297    let exe = exe.to_string_lossy();
298    let exe = exe.trim_end_matches(" (deleted)"); // replaced by an update
299    let prefix = format!("{}/", versions_dir);
300    exe.strip_prefix(&prefix)
301        .filter(|rest| !rest.is_empty())
302        .map(|rest| rest.split('/').next().unwrap_or(rest).to_string())
303}
304
305/// One pane the plan will act on.
306pub struct Planned {
307    pub pane: String,
308    pub target: String,
309    /// The pane's own process: the session itself, or for a background session
310    /// only agent view's client of it.
311    pub pid: i32,
312    /// What gets typed into the pane once that process has gone.
313    pub cmd: String,
314    pub title: String,
315    pub via: String,
316    /// The background session to respawn before `cmd` attaches the pane to it
317    /// again, for a pane that only shows one. Two panes showing the same one
318    /// both carry it, and it is respawned once.
319    pub respawn: Option<String>,
320}
321
322/// A background session no pane shows, which the plan will respawn.
323pub struct PlannedBg {
324    /// The id `claude respawn` takes.
325    pub id: String,
326    /// Its worker now.
327    pub pid: i32,
328    pub name: String,
329    pub via: String,
330}
331
332pub struct Plan {
333    pub newver: String,
334    pub launcher: String,
335    pub go: Vec<Planned>,
336    /// Background sessions no pane shows: see `plan`.
337    pub go_bg: Vec<PlannedBg>,
338    pub skipped: Vec<String>,
339    /// Set when at least one pane was skipped for being unresolvable, which gets
340    /// its own paragraph: it is the one skip the reader can act on.
341    pub unresolved: bool,
342}
343
344pub struct Opts {
345    pub include_busy: bool,
346    pub only_panes: Vec<String>,
347    pub force_transcript: Option<String>,
348    pub self_pane: String,
349}
350
351/// Everything the plan needs from the outside, so it can be built against
352/// fixtures as well as against a live machine.
353pub trait Env {
354    fn capture(&self, pane: &str) -> String;
355    /// The same pane read at a size claude will draw its prompt box on, for the
356    /// one that is too short to show one at the size it is.
357    ///
358    /// `None` by default, and for every fixture: a screen handed over by a test
359    /// is already the screen that test means, and only the live implementation
360    /// has a window to zoom.
361    fn capture_zoomed(&self, _pane: &str) -> Option<String> {
362        None
363    }
364    fn hook_state(&self, pane: &str, pid: i32) -> Option<String>;
365    /// The permission mode on the session's hook line, the one its last turn
366    /// ran in. `None` by default, and for every fixture that predates it.
367    fn hook_mode(&self, _pane: &str, _pid: i32) -> Option<String> {
368        None
369    }
370    /// What the session says it is doing, Claude Code's own status
371    /// (`status::of`), which outranks the hook line wherever there is one.
372    /// `None` by default, and for every fixture that predates it.
373    fn own_state(&self, _pid: i32, _screen: &str) -> Option<state::State> {
374        None
375    }
376    /// The background session this pane shows when another process runs it:
377    /// an attach, or a pane whose conversation was moved into the background.
378    fn elsewhere(&self, _pane: &str, _pid: i32) -> Option<Elsewhere> {
379        None
380    }
381    /// Every background session running now, whether a pane shows it or not.
382    /// None by default, and for every fixture that predates it.
383    fn background(&self) -> Vec<BgSession> {
384        Vec::new()
385    }
386    fn version_of_pid(&self, pid: i32) -> Option<String>;
387    fn cwd_of(&self, pid: i32) -> Option<String>;
388    fn argv_of(&self, pid: i32) -> Vec<String>;
389    fn resolve(&self, pane: &str, cwd: &str, title: &str, pid: i32) -> Result<String, String>;
390    fn read_transcript(&self, path: &str) -> Option<String>;
391    fn now(&self) -> i64;
392}
393
394/// A session a pane shows while agent view's supervisor runs it, under
395/// another pid: see `status::Via::elsewhere`.
396pub struct Elsewhere {
397    /// The id `claude attach` takes.
398    pub id: String,
399    /// The process running it.
400    pub pid: i32,
401    /// The version that process runs, which is the one the row shows.
402    pub version: Option<String>,
403    /// The transcript that session writes, for the settled check, or `None`
404    /// where it is not where Claude Code puts it.
405    pub transcript: Option<String>,
406}
407
408/// A background session as Claude Code's own files describe it, for the ones
409/// no pane shows: there is no screen to read, so this is all there is.
410#[derive(Clone)]
411pub struct BgSession {
412    /// The id `claude respawn` takes.
413    pub id: String,
414    /// The worker running it.
415    pub pid: i32,
416    /// The version that worker runs.
417    pub version: Option<String>,
418    pub name: String,
419    /// What the session says it is doing.
420    pub state: Option<state::State>,
421    pub transcript: Option<String>,
422    /// What the job's own record says it left going, or `None` where that
423    /// record says nothing.
424    pub in_flight: Option<taimux_core::status::InFlight>,
425}
426
427/// An id that can be typed into a shell as it stands. A job id is eight hex
428/// digits and a session id a UUID, both read out of Claude Code's own files, so
429/// anything else means those files say something this does not understand.
430fn typable_id(id: &str) -> bool {
431    !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
432}
433
434/// What a pane shows, and the transcript behind it, judged quiet enough to put
435/// back: a dialog refuses even with `--include-busy`, an unsent draft and a
436/// transcript still being written to only without it.
437fn settled(screen: &str, transcript: Option<&str>, o: &Opts, e: &dyn Env) -> Result<(), String> {
438    screen_has_no_dialog(screen)?;
439    if o.include_busy {
440        return Ok(());
441    }
442    screen_has_no_draft(screen)?;
443    match transcript.and_then(|t| e.read_transcript(t)) {
444        Some(text) => transcript_is_settled(&text, e.now()),
445        None => Ok(()),
446    }
447}
448
449/// Decide what to restart, and say why for everything else.
450///
451/// `agents` is `claude agents --json`, fetched by the caller and only when a
452/// stale non-pane process actually needs naming: the CLI costs about three
453/// seconds to start.
454pub fn plan(
455    rows: &str,
456    newver: &str,
457    launcher: &str,
458    o: &Opts,
459    e: &dyn Env,
460    versions_dir: &str,
461    agents: &dyn Fn() -> String,
462) -> Plan {
463    let mut p = Plan {
464        newver: newver.to_string(),
465        launcher: launcher.to_string(),
466        go: Vec::new(),
467        go_bg: Vec::new(),
468        skipped: Vec::new(),
469        unresolved: false,
470    };
471    let mut claimed: HashMap<String, String> = HashMap::new();
472    // Every pane's agent pid, so the non-pane sweep below can tell a session
473    // that has a pane from one that has not.
474    let mut matched: Vec<i32> = Vec::new();
475
476    for line in rows.lines() {
477        let f: Vec<&str> = line.split('\t').collect();
478        if f.len() < 7 || f[3] != "claude" {
479            continue;
480        }
481        let (id, tgt, cwd, title) = (f[0], f[1], f[2], f[6]);
482        let pid: i32 = f[4].parse().unwrap_or(0);
483
484        let Some(ver) = (pid != 0).then(|| e.version_of_pid(pid)).flatten() else {
485            p.skipped.push(format!(
486                "{} {}  looks like claude but no session process was found under the pane",
487                id, tgt
488            ));
489            continue;
490        };
491        matched.push(pid);
492        if !o.only_panes.is_empty() && !o.only_panes.iter().any(|w| w == id) {
493            continue;
494        }
495
496        // A pane showing a session that agent view's supervisor runs, where the
497        // version that counts is its worker's, as the row shows it. Retyping the
498        // pane cannot reach that worker: it would resume the transcript the pane
499        // started on, branching a conversation that carries on elsewhere. The
500        // supervisor restarts a worker that has fallen behind only when nothing
501        // is attached to it (`respawnIfIdleStale`, 2.1.299), so this asks it to,
502        // with `claude respawn`, and attaches the pane again afterwards. Every
503        // guard below applies as it does to any pane: the screen is the
504        // session's own, and so is the state `own_state` reads.
505        let away = e.elsewhere(id, pid);
506        if let Some(a) = &away {
507            matched.push(a.pid);
508        }
509        let ver = match &away {
510            Some(a) => a.version.clone().unwrap_or_else(|| "?".into()),
511            None => ver,
512        };
513
514        if ver == newver {
515            continue; // nothing to gain from interrupting it
516        }
517        if id == o.self_pane {
518            p.skipped.push(format!(
519                "{} {}  {}, this pane: restart it by hand (killing it would kill taimux)",
520                id, tgt, ver
521            ));
522            continue;
523        }
524
525        let mut screen = e.capture(id);
526        // A screen with no prompt box on it is either a session doing something
527        // unusual or a pane too short to draw one, and those want opposite
528        // answers: the first is a refusal, the second is a measurement that has
529        // not been taken yet. Taking it costs the window a zoom for the
530        // milliseconds claude needs to redraw, and buys a reading of the box, of
531        // anything typed into it and of any dialog over it, none of which is on
532        // the pane at the size it sits at. It happens here rather than after the
533        // state check on purpose: `merge` is reading the same blank screen.
534        if !screen.contains('❯') {
535            if let Some(bigger) = e.capture_zoomed(id) {
536                screen = bigger;
537            }
538        }
539        let hook = e.hook_state(id, pid);
540        let st = state::reading(&screen, e.own_state(pid, &screen), hook.as_deref());
541        if st.as_str() != "idle" && !o.include_busy {
542            p.skipped.push(format!(
543                "{} {}  {}, {}: rerun when idle, or --include-busy",
544                id,
545                tgt,
546                ver,
547                st.as_str()
548            ));
549            continue;
550        }
551        // Idle is not the same as nothing to lose. A turn that left a shell or a
552        // subagent running is over and its prompt is free, which is why the list
553        // shows it idle, but that work runs as the session's children and dies
554        // with it. This used to be one question, answered "working" for both, on
555        // a pane whose two watchers were due to report hours later.
556        if state::background(&screen, hook.as_deref()) && !o.include_busy {
557            p.skipped.push(format!(
558                "{} {}  {}, work still in flight: rerun once it reports back, or --include-busy",
559                id, tgt, ver
560            ));
561            continue;
562        }
563
564        // A background session needs no ladder: its job id is what `claude
565        // attach` and `claude respawn` both take, and the worker resumes its own
566        // conversation.
567        if let Some(a) = &away {
568            if o.force_transcript.is_some() {
569                p.skipped.push(format!(
570                    "{} {}  {}, shows background session {}: --transcript does not apply, its worker is respawned instead",
571                    id, tgt, ver, a.id
572                ));
573                continue;
574            }
575            if !typable_id(&a.id) {
576                p.skipped.push(format!(
577                    "{} {}  {}, shows background session {:?}, an id not safe to type",
578                    id, tgt, ver, a.id
579                ));
580                continue;
581            }
582            if let Err(why) = settled(&screen, a.transcript.as_deref(), o, e) {
583                p.skipped
584                    .push(format!("{} {}  {}, not settled: {}", id, tgt, ver, why));
585                continue;
586            }
587            p.go.push(Planned {
588                pane: id.to_string(),
589                target: tgt.to_string(),
590                pid,
591                cmd: format!("command claude attach {}", a.id),
592                title: title.to_string(),
593                via: format!(
594                    "{} -> {}, background session {}, {}",
595                    ver,
596                    newver,
597                    a.id,
598                    st.as_str()
599                ),
600                respawn: Some(a.id.clone()),
601            });
602            continue;
603        }
604
605        let ccwd = e.cwd_of(pid).unwrap_or_else(|| cwd.to_string());
606        let (transcript, via) = match &o.force_transcript {
607            Some(t) => (t.clone(), "--transcript, given".to_string()),
608            None => match e.resolve(id, &ccwd, title, pid) {
609                Ok(t) => {
610                    // resolve() hands back "<path>\t<why>"
611                    let (path, why) = t.split_once('\t').unwrap_or((t.as_str(), ""));
612                    (path.to_string(), why.to_string())
613                }
614                Err(why) => {
615                    p.skipped
616                        .push(format!("{} {}  {}, unresolved: {}", id, tgt, ver, why));
617                    p.unresolved = true;
618                    continue;
619                }
620            },
621        };
622
623        if let Err(why) = settled(&screen, Some(&transcript), o, e) {
624            p.skipped
625                .push(format!("{} {}  {}, not settled: {}", id, tgt, ver, why));
626            continue;
627        }
628
629        if let Some(first) = claimed.get(&transcript) {
630            p.skipped.push(format!(
631                "{} {}  {}, resolves to the same transcript as {}",
632                id, tgt, ver, first
633            ));
634            continue;
635        }
636        claimed.insert(transcript.clone(), id.to_string());
637
638        // The mode it is in now, which a plain resume would not bring back: the
639        // footer of the screen read above, else the mode of its last turn.
640        let mode = conv::current_mode(&screen, e.hook_mode(id, pid).as_deref());
641        let Some(cmd) = conv::build_cmd(&e.argv_of(pid), &transcript, &ccwd, cwd, mode.as_deref())
642        else {
643            p.skipped
644                .push(format!("{} {}  {}, could not read its argv", id, tgt, ver));
645            continue;
646        };
647        p.go.push(Planned {
648            pane: id.to_string(),
649            target: tgt.to_string(),
650            pid,
651            cmd,
652            title: title.to_string(),
653            via: format!("{} -> {}, {}, {}", ver, newver, via, st.as_str()),
654            respawn: None,
655        });
656    }
657
658    // Background sessions no pane shows, which only a whole plan looks for:
659    // `--pane` names panes. Nothing to type into and no screen to read, so
660    // `claude respawn` is the whole of the restart, and what stands in for the
661    // screen is what Claude Code keeps itself: the session's own status, its
662    // transcript, and the job's record of work it left running and of replies
663    // saved for its next start. A worker some pane shows was dealt with above.
664    if o.only_panes.is_empty() {
665        for b in e.background() {
666            if matched.contains(&b.pid) {
667                continue;
668            }
669            matched.push(b.pid);
670            let ver = b.version.clone().unwrap_or_else(|| "?".into());
671            if ver == newver {
672                continue;
673            }
674            match plan_bg(&b, o, e) {
675                Ok(st) => p.go_bg.push(PlannedBg {
676                    id: b.id.clone(),
677                    pid: b.pid,
678                    name: b.name.clone(),
679                    via: format!("{} -> {}, no pane, {}", ver, newver, st.as_str()),
680                }),
681                Err(why) => p
682                    .skipped
683                    .push(format!("{} background  {}, {}", b.id, ver, why)),
684            }
685        }
686    }
687
688    // Stale claude processes that are not a pane's foreground job. Reported,
689    // never touched: a restart types into a PANE, and these have none, so the
690    // only useful thing to do about a stale one is name it. The naming costs a
691    // `claude agents --json`, so it is fetched lazily and once.
692    let mut agents_json: Option<String> = None;
693    for np in nonpane_pids(&matched, versions_dir) {
694        let Some(ver) = e.version_of_pid(np) else {
695            continue;
696        };
697        if ver == newver {
698            continue;
699        }
700        let j = agents_json.get_or_insert_with(agents);
701        p.skipped.push(format!(
702            "pid {}  {}, not a tmux pane: {}",
703            np,
704            ver,
705            describe_nonpane(&e.argv_of(np), j)
706        ));
707    }
708    p
709}
710
711/// Whether a background session no pane shows can be respawned, with the
712/// state it is in when it can.
713///
714/// The guards a pane gets, from what there is to read in place of a screen. A
715/// session waiting on an answer is refused whatever `--include-busy` says, as a
716/// dialog on screen is, and so is one holding a reply saved for its next start:
717/// a respawn sends that reply, which starts a turn nobody asked for now. A
718/// record that says nothing of work in flight is not taken to mean none.
719fn plan_bg(b: &BgSession, o: &Opts, e: &dyn Env) -> Result<state::State, String> {
720    if !typable_id(&b.id) {
721        return Err(format!("an id not safe to pass on: {:?}", b.id));
722    }
723    let st = match b.state {
724        Some(st @ state::State::Idle) => st,
725        Some(state::State::Input) => {
726            return Err(format!(
727                "waiting for an answer: claude attach {} to give it",
728                b.id
729            ))
730        }
731        Some(st @ state::State::Run) if o.include_busy => st,
732        Some(st) => {
733            return Err(format!(
734                "{}: rerun when idle, or --include-busy",
735                st.as_str()
736            ))
737        }
738        None => return Err("says nothing of what it is doing".into()),
739    };
740    match b.in_flight {
741        Some(f) if f.queued > 0 => {
742            return Err(format!(
743                "a reply is saved for its next start, which a respawn would send: claude attach {} to see it",
744                b.id
745            ))
746        }
747        _ if o.include_busy => {}
748        Some(f) if f.tasks > 0 => {
749            return Err(
750                "work still in flight: rerun once it reports back, or --include-busy".into(),
751            )
752        }
753        Some(_) => {}
754        None => {
755            return Err(
756                "its job record says nothing of work in flight: --include-busy to respawn it anyway"
757                    .into(),
758            )
759        }
760    }
761    if !o.include_busy {
762        if let Some(text) = b.transcript.as_deref().and_then(|t| e.read_transcript(t)) {
763            transcript_is_settled(&text, e.now()).map_err(|why| format!("not settled: {}", why))?;
764        }
765    }
766    Ok(st)
767}
768
769/// The plan, as the reader sees it. Byte-for-byte what bash printed, because the
770/// only way to know a port of this is right is to compare it.
771pub fn render(p: &Plan) -> String {
772    let mut s = format!("claude: {} installed at {}\n\n", p.newver, p.launcher);
773    if p.go.is_empty() && p.go_bg.is_empty() {
774        s.push_str("nothing to restart.\n");
775    } else {
776        s.push_str(&format!("to restart ({}):\n", p.go.len() + p.go_bg.len()));
777        for g in &p.go {
778            s.push_str(&format!("  {:<5} {:<14} {}\n", g.pane, g.target, g.title));
779            s.push_str(&format!("        {}\n", g.via));
780            match &g.respawn {
781                Some(job) => {
782                    s.push_str(&format!("        claude respawn {}, then {}\n", job, g.cmd))
783                }
784                None => s.push_str(&format!("        {}\n", g.cmd)),
785            }
786        }
787        for b in &p.go_bg {
788            s.push_str(&format!("  {:<5} {:<14} {}\n", b.id, "background", b.name));
789            s.push_str(&format!("        {}\n", b.via));
790            s.push_str(&format!("        claude respawn {}\n", b.id));
791        }
792    }
793    if !p.skipped.is_empty() {
794        s.push_str(&format!("\nskipped ({}):\n", p.skipped.len()));
795        for k in &p.skipped {
796            s.push_str(&format!("  {}\n", k));
797        }
798    }
799    if p.unresolved {
800        s.push_str(
801            "\nAn unresolved pane means guessing, so it was left alone: restart it by hand\n\
802             with `claude -c` in that pane, or from its /resume picker. Each session records\n\
803             its pane at the next SessionStart, so a pane resolves cleanly once restarted.\n",
804        );
805    }
806    s
807}
808
809/// Interrupt a session, wait for it to go, and type its replacement.
810///
811/// Two Ctrl-Cs, because the first one arms claude's "press again to exit" and the
812/// second takes it. `/exit` after six waits is for a session that ignores both,
813/// and thirty waits (twelve seconds) is where it gives up rather than typing a
814/// command into a pane that still has a session in it.
815pub fn restart_pane(pane: &str, pid: i32, cmd: &str) -> bool {
816    use std::thread::sleep;
817    use std::time::Duration;
818
819    tmux::run(&["send-keys", "-t", pane, "C-c"]);
820    sleep(Duration::from_millis(300));
821    tmux::run(&["send-keys", "-t", pane, "C-c"]);
822
823    let mut waited = 0;
824    let mut sent_exit = false;
825    while alive(pid) {
826        sleep(Duration::from_millis(400));
827        waited += 1;
828        if waited >= 6 && !sent_exit {
829            tmux::run(&["send-keys", "-t", pane, "/exit", "Enter"]);
830            sent_exit = true;
831        }
832        if waited >= 30 {
833            return false;
834        }
835    }
836    sleep(Duration::from_millis(500));
837    tmux::run(&["send-keys", "-t", pane, "C-c"]);
838    sleep(Duration::from_millis(200));
839    tmux::run(&["send-keys", "-t", pane, cmd, "Enter"])
840}
841
842/// Ask agent view's supervisor to put a background session on the version it
843/// runs now, by the route Claude Code documents.
844///
845/// `claude respawn <id>` (2.1.333) stops the worker and resumes the same
846/// conversation, under the same id and in the same permission mode, in a new
847/// one, in about half a second. Measured with a client attached, which the
848/// supervisor's own sweep of stale workers refuses. The new worker runs the
849/// supervisor's version, which is the installed one once the supervisor has
850/// taken an update. Run by path rather than by name, so no alias or function in
851/// anybody's shell gets between `claude` and its subcommand.
852pub fn respawn(launcher: &str, job: &str) -> Result<(), String> {
853    let o = std::process::Command::new(launcher)
854        .args(["respawn", job])
855        .stdin(std::process::Stdio::null())
856        .output()
857        .map_err(|e| format!("could not run {}: {}", launcher, e))?;
858    if o.status.success() {
859        return Ok(());
860    }
861    let said = format!(
862        "{}\n{}",
863        String::from_utf8_lossy(&o.stderr),
864        String::from_utf8_lossy(&o.stdout)
865    );
866    Err(said
867        .lines()
868        .map(str::trim)
869        .find(|l| !l.is_empty())
870        .map(str::to_string)
871        .unwrap_or_else(|| format!("claude respawn {}: {}", job, o.status)))
872}
873
874/// Take a pane's client off the background session just respawned, and attach
875/// the pane to it again.
876///
877/// A `claude attach` client exits by itself when its session restarts
878/// ("Session <id> has exited"). Agent view's client, which is what a pane whose
879/// conversation was moved into the background runs, goes back to its list
880/// ("That session was stopped") and stays. That one is ended with SIGTERM
881/// rather than with keys: a key reaches whichever session the client shows, and
882/// a client showing some other session would hand two Ctrl-Cs to THAT one's
883/// worker. A signal reaches the client alone, which holds no conversation of
884/// its own. Measured on 2.1.333: gone in about 600ms.
885pub fn reattach(pane: &str, client: i32, cmd: &str) -> bool {
886    use std::thread::sleep;
887    use std::time::Duration;
888
889    let gone = |polls: u32| {
890        for _ in 0..polls {
891            if !alive(client) {
892                return true;
893            }
894            sleep(Duration::from_millis(200));
895        }
896        !alive(client)
897    };
898    // Only a process still running a claude binary is signalled: a pid that has
899    // gone and been handed out again is somebody else's.
900    if !gone(10) && version_of_pid(client, &versions_dir()).is_some() {
901        let _ = std::process::Command::new("kill")
902            .args(["-TERM", &client.to_string()])
903            .stdin(std::process::Stdio::null())
904            .stdout(std::process::Stdio::null())
905            .stderr(std::process::Stdio::null())
906            .status();
907    }
908    if !gone(25) {
909        return false;
910    }
911    sleep(Duration::from_millis(300));
912    tmux::run(&["send-keys", "-t", pane, "C-c"]);
913    sleep(Duration::from_millis(200));
914    tmux::run(&["send-keys", "-t", pane, cmd, "Enter"])
915}
916
917/// Is a pid still there? `/proc` rather than `kill -0`, since nothing is being
918/// signalled and a directory read cannot be mistaken for one.
919fn alive(pid: i32) -> bool {
920    std::path::Path::new(&format!("/proc/{}", pid)).exists()
921}
922
923/// The default answer is yes, so a bare Enter restarts. The plan has already been
924/// printed by then, which is what makes that safe.
925pub fn confirm_yes(answer: &str) -> bool {
926    matches!(answer.trim(), "" | "y" | "Y" | "yes" | "YES" | "Yes")
927}
928
929/// The live implementation of everything `plan` needs.
930pub struct Live {
931    pub versions_dir: String,
932}
933
934impl Env for Live {
935    fn capture(&self, pane: &str) -> String {
936        tmux::ask_raw(&["capture-pane", "-p", "-t", pane]).unwrap_or_default()
937    }
938    fn capture_zoomed(&self, pane: &str) -> Option<String> {
939        capture_zoomed(pane)
940    }
941    fn hook_state(&self, pane: &str, pid: i32) -> Option<String> {
942        taimux_core::hook::hook_state_of(pane, pid)
943    }
944    fn hook_mode(&self, pane: &str, pid: i32) -> Option<String> {
945        taimux_core::hook::hook_entry(pane, pid).map(|e| e.mode)
946    }
947    fn own_state(&self, pid: i32, screen: &str) -> Option<state::State> {
948        taimux_core::status::of(pid, &|| screen.to_string()).and_then(|o| o.state())
949    }
950    fn elsewhere(&self, pane: &str, pid: i32) -> Option<Elsewhere> {
951        // the screen is only read for a pane whose conversation has moved
952        let o =
953            taimux_core::status::of(pid, &|| self.capture(pane)).filter(|o| o.via.elsewhere())?;
954        let id = if o.job.is_empty() {
955            o.session_id.get(..8).unwrap_or(&o.session_id)
956        } else {
957            &o.job
958        };
959        Some(Elsewhere {
960            id: id.to_string(),
961            pid: o.pid,
962            version: version_of_pid(o.pid, &self.versions_dir),
963            transcript: o.transcript().map(|t| t.display().to_string()),
964        })
965    }
966    fn background(&self) -> Vec<BgSession> {
967        taimux_core::status::background()
968            .into_iter()
969            .map(|o| {
970                let id = if o.job.is_empty() {
971                    o.session_id.get(..8).unwrap_or(&o.session_id).to_string()
972                } else {
973                    o.job.clone()
974                };
975                BgSession {
976                    version: version_of_pid(o.pid, &self.versions_dir),
977                    state: o.state(),
978                    transcript: o.transcript().map(|t| t.display().to_string()),
979                    in_flight: taimux_core::status::in_flight(&id),
980                    pid: o.pid,
981                    name: o.name,
982                    id,
983                }
984            })
985            .collect()
986    }
987    fn version_of_pid(&self, pid: i32) -> Option<String> {
988        version_of_pid(pid, &self.versions_dir)
989    }
990    fn cwd_of(&self, pid: i32) -> Option<String> {
991        std::fs::read_link(format!("/proc/{}/cwd", pid))
992            .ok()
993            .map(|p| p.to_string_lossy().into_owned())
994            .filter(|s| !s.is_empty())
995    }
996    fn argv_of(&self, pid: i32) -> Vec<String> {
997        conv::argv_of(pid)
998    }
999    fn resolve(&self, pane: &str, cwd: &str, title: &str, pid: i32) -> Result<String, String> {
1000        conv::resolve(pane, cwd, title, pid)
1001            .map(|r| format!("{}\t{}", r.transcript.display(), r.why))
1002    }
1003    fn read_transcript(&self, path: &str) -> Option<String> {
1004        std::fs::read_to_string(path).ok()
1005    }
1006    fn now(&self) -> i64 {
1007        std::time::SystemTime::now()
1008            .duration_since(std::time::UNIX_EPOCH)
1009            .map(|d| d.as_secs() as i64)
1010            .unwrap_or(0)
1011    }
1012}
1013
1014/// What a session started right now would run, refusing rather than guessing when
1015/// the launcher points somewhere unexpected.
1016pub fn installed(launcher: &str, versions_dir: &str) -> Result<String, String> {
1017    let target = std::fs::canonicalize(launcher)
1018        .map(|p| p.to_string_lossy().into_owned())
1019        .unwrap_or_default();
1020    let prefix = format!("{}/", versions_dir);
1021    match target.strip_prefix(&prefix) {
1022        Some(rest) if !rest.is_empty() => Ok(rest.split('/').next().unwrap_or(rest).to_string()),
1023        _ => Err(format!(
1024            "restart: {} does not point into {} (got '{}')",
1025            launcher,
1026            versions_dir,
1027            if target.is_empty() {
1028                "nothing"
1029            } else {
1030                &target
1031            }
1032        )),
1033    }
1034}
1035
1036pub fn versions_dir() -> String {
1037    format!(
1038        "{}/.local/share/claude/versions",
1039        std::env::var("HOME").unwrap_or_default()
1040    )
1041}
1042
1043pub fn launcher() -> String {
1044    format!(
1045        "{}/.local/bin/claude",
1046        std::env::var("HOME").unwrap_or_default()
1047    )
1048}
1049
1050#[cfg(test)]
1051mod tests {
1052    use super::*;
1053
1054    #[test]
1055    fn a_timestamp_becomes_epoch_seconds() {
1056        // 2026-09-02T01:23:45Z
1057        assert_eq!(parse_iso8601("2026-09-02T01:23:45.678Z"), Some(1788312225));
1058        assert_eq!(parse_iso8601("1970-01-01T00:00:00Z"), Some(0));
1059        // a leap day, which a hand-rolled calendar is where it goes wrong
1060        assert_eq!(parse_iso8601("2024-02-29T00:00:00Z"), Some(1709164800));
1061    }
1062
1063    /// Anything not of that exact shape reads as "no answer", which the caller
1064    /// treats as not-evidence rather than as busy: guessing busy would skip a
1065    /// pane on a malformed line forever.
1066    #[test]
1067    fn an_unparseable_timestamp_is_no_answer() {
1068        assert_eq!(parse_iso8601(""), None);
1069        assert_eq!(parse_iso8601("yesterday"), None);
1070        assert_eq!(parse_iso8601("2026-09-02 01:23:45"), None);
1071        assert_eq!(parse_iso8601("2026-13-02T01:23:45Z"), None);
1072    }
1073
1074    #[test]
1075    fn a_tool_call_still_running_is_not_settled() {
1076        let t = r#"{"type":"assistant","message":{"content":[{"type":"tool_use"}]},"timestamp":"2020-01-01T00:00:00Z"}"#;
1077        assert_eq!(
1078            transcript_is_settled(t, 1788312225),
1079            Err("a tool call is still running".into())
1080        );
1081    }
1082
1083    /// Insurance for the screen reading, which is the most fragile thing here.
1084    #[test]
1085    fn recent_activity_is_not_settled_whatever_the_screen_said() {
1086        let t = r#"{"type":"user","timestamp":"2026-09-02T01:23:45Z"}"#;
1087        assert!(transcript_is_settled(t, 1788312225 + 10).is_err());
1088        assert!(transcript_is_settled(t, 1788312225 + 100).is_ok());
1089    }
1090
1091    #[test]
1092    fn an_empty_or_odd_transcript_does_not_block() {
1093        assert!(transcript_is_settled("", 0).is_ok());
1094        assert!(transcript_is_settled("not json at all\n", 0).is_ok());
1095        // no timestamp: nothing to judge recency by
1096        assert!(transcript_is_settled(r#"{"type":"user"}"#, 0).is_ok());
1097    }
1098
1099    /// A dialog is what `state::awaits_input` recognises, so the fixture has to
1100    /// be one it would: either the footer in the last few lines, or a numbered
1101    /// choice on the LOWEST prompt line. A made-up shape asserts nothing.
1102    #[test]
1103    fn a_dialog_on_screen_blocks_a_restart() {
1104        let footer = "some output\n\nDo you want to proceed?\n";
1105        assert_eq!(
1106            screen_has_no_dialog(footer),
1107            Err("a dialog is waiting for an answer".into())
1108        );
1109        let choice = "some output\n1. Yes\n2. No\n❯ 1. Yes\n";
1110        assert_eq!(
1111            screen_has_no_dialog(choice),
1112            Err("a dialog is waiting for an answer".into())
1113        );
1114        // an ordinary idle screen is not a dialog
1115        assert!(screen_has_no_dialog("some output\n❯ \n").is_ok());
1116    }
1117
1118    /// A half-pressed Ctrl-C is the one state where the keystroke that starts a
1119    /// restart is also an answer to something else.
1120    #[test]
1121    fn a_half_pressed_ctrl_c_blocks_a_restart() {
1122        let screen = "work\n\nPress Ctrl-C again to exit\n";
1123        assert_eq!(
1124            screen_has_no_dialog(screen),
1125            Err("a Ctrl-C is already half-pressed".into())
1126        );
1127    }
1128
1129    #[test]
1130    fn an_empty_prompt_box_is_no_draft() {
1131        assert!(screen_has_no_draft("stuff\n❯ \n").is_ok());
1132        // the non-breaking space claude pads the box with is not a draft
1133        assert!(screen_has_no_draft("stuff\n❯ \u{a0}\u{a0}\n").is_ok());
1134        assert_eq!(
1135            screen_has_no_draft("stuff\n❯ half a thought\n"),
1136            Err("unsent text in the prompt box".into())
1137        );
1138    }
1139
1140    /// The four rows a pane has to be given before any of this can be asked of
1141    /// it, and the two it can be left at.
1142    #[test]
1143    fn a_pane_tall_enough_to_read_is_left_alone() {
1144        // already showing its box: nothing to gain, and nothing touched
1145        assert!(zoom_steps("%1", false, 6, 40, "%2", "%3").is_none());
1146        assert!(zoom_steps("%1", false, 40, 40, "%2", "%3").is_none());
1147        // a window no taller than the pane has no rows to lend it
1148        assert!(zoom_steps("%1", false, 3, 3, "%2", "%3").is_none());
1149        assert!(zoom_steps("%1", false, 3, 5, "%2", "%3").is_none());
1150    }
1151
1152    /// The common shape: a three-row pane in a window nobody has zoomed. One
1153    /// zoom out and back, and the pane that was active is active again with the
1154    /// pane that was behind it still behind it.
1155    #[test]
1156    fn a_short_pane_is_zoomed_and_the_selection_put_back() {
1157        let (go, back) = zoom_steps("%1", false, 3, 17, "%2", "%3").unwrap();
1158        assert_eq!(go, vec![vec!["resize-pane", "-Z", "-t", "%1"]]);
1159        assert_eq!(
1160            back,
1161            vec![
1162                vec!["resize-pane", "-Z", "-t", "%1"],
1163                vec!["select-pane", "-t", "%3"],
1164                vec!["select-pane", "-t", "%2"],
1165            ]
1166        );
1167    }
1168
1169    /// A window that arrives zoomed on another pane takes TWO `-Z` to zoom this
1170    /// one, because the first is spent switching the other one off, and it is
1171    /// owed a re-zoom at the end.
1172    #[test]
1173    fn a_window_zoomed_elsewhere_is_handed_back_zoomed() {
1174        let (go, back) = zoom_steps("%1", true, 3, 17, "%2", "%3").unwrap();
1175        assert_eq!(
1176            go,
1177            vec![
1178                vec!["resize-pane", "-Z", "-t", "%1"],
1179                vec!["resize-pane", "-Z", "-t", "%1"],
1180            ]
1181        );
1182        assert_eq!(
1183            back,
1184            vec![
1185                vec!["resize-pane", "-Z", "-t", "%1"],
1186                vec!["select-pane", "-t", "%3"],
1187                vec!["select-pane", "-t", "%2"],
1188                vec!["resize-pane", "-Z", "-t", "%2"],
1189            ]
1190        );
1191    }
1192
1193    /// Zooming the pane that is already active changes no selection, so putting
1194    /// one back would be the only thing that moved it.
1195    #[test]
1196    fn an_active_short_pane_has_no_selection_to_restore() {
1197        let (go, back) = zoom_steps("%1", false, 3, 17, "%1", "%3").unwrap();
1198        assert_eq!(go.len(), 1);
1199        assert_eq!(back, vec![vec!["resize-pane", "-Z", "-t", "%1"]]);
1200    }
1201
1202    /// No box at all means the screen is not what it is expected to be, and that
1203    /// is a refusal rather than a shrug.
1204    #[test]
1205    fn no_prompt_box_is_a_refusal() {
1206        assert_eq!(
1207            screen_has_no_draft("just some text\n"),
1208            Err("no prompt box on screen".into())
1209        );
1210        // …but a genuinely blank screen is not judged at all
1211        assert!(screen_has_no_draft("").is_ok());
1212        assert!(screen_has_no_draft("   \n\n").is_ok());
1213    }
1214
1215    #[test]
1216    fn a_bare_enter_confirms() {
1217        assert!(confirm_yes(""));
1218        assert!(confirm_yes("y"));
1219        assert!(confirm_yes("YES"));
1220        assert!(!confirm_yes("n"));
1221        assert!(!confirm_yes("no"));
1222        assert!(!confirm_yes("maybe"));
1223    }
1224
1225    #[test]
1226    fn the_launcher_must_point_into_the_versions_dir() {
1227        let root = std::env::temp_dir().join(format!("jmrs{}", std::process::id()));
1228        let vers = root.join("versions");
1229        std::fs::create_dir_all(&vers).unwrap();
1230        std::fs::write(vers.join("2.1.258"), "x").unwrap();
1231        let link = root.join("claude");
1232        std::os::unix::fs::symlink(vers.join("2.1.258"), &link).unwrap();
1233        assert_eq!(
1234            installed(&link.to_string_lossy(), &vers.to_string_lossy()),
1235            Ok("2.1.258".into())
1236        );
1237        // pointing elsewhere is a refusal that names what it found
1238        std::fs::write(root.join("elsewhere"), "x").unwrap();
1239        std::fs::remove_file(&link).unwrap();
1240        std::os::unix::fs::symlink(root.join("elsewhere"), &link).unwrap();
1241        let e = installed(&link.to_string_lossy(), &vers.to_string_lossy()).expect_err("refused");
1242        assert!(e.contains("elsewhere"));
1243        let _ = std::fs::remove_dir_all(&root);
1244    }
1245}
1246
1247/// A claude process that is not any pane's foreground job: Zed's ACP bridge, a
1248/// background agent, one of the daemon's spare pty hosts.
1249///
1250/// Reported, never touched. A restart types into a PANE, and these have none, so
1251/// the only useful thing to do about a stale one is name it.
1252pub fn nonpane_pids(matched: &[i32], versions_dir: &str) -> Vec<i32> {
1253    let mut out = Vec::new();
1254    for e in std::fs::read_dir("/proc").into_iter().flatten().flatten() {
1255        let Some(pid) = e.file_name().to_str().and_then(|s| s.parse::<i32>().ok()) else {
1256            continue;
1257        };
1258        if matched.contains(&pid) {
1259            continue;
1260        }
1261        // Either its comm is "claude" (pgrep -x claude) or it is running out of
1262        // the versions directory (pgrep -f "^<vdir>/").
1263        let comm = std::fs::read_to_string(format!("/proc/{}/comm", pid)).unwrap_or_default();
1264        let argv = conv::argv_of(pid);
1265        let is_claude = comm.trim() == "claude"
1266            || argv
1267                .first()
1268                .map(|a| a.starts_with(&format!("{}/", versions_dir)))
1269                .unwrap_or(false);
1270        if is_claude {
1271            out.push(pid);
1272        }
1273    }
1274    out.sort_unstable();
1275    out
1276}
1277
1278/// The object in a JSON array whose `key` starts with `prefix`, as raw text.
1279///
1280/// A brace matcher rather than a parser, and rather than the `jq` the bash
1281/// version shelled out to. It only has to find one element of one array, and the
1282/// depth count is what makes it safe against nested objects: taking everything
1283/// between the first `{` and the first `}` would truncate any element with a
1284/// nested field.
1285fn json_object_with_prefix(text: &str, key: &str, prefix: &str) -> Option<String> {
1286    let needle = format!("\"{}\":\"{}", key, prefix);
1287    let at = text.find(&needle).or_else(|| {
1288        let spaced = format!("\"{}\": \"{}", key, prefix);
1289        text.find(&spaced)
1290    })?;
1291    // back to the opening brace of the object holding it
1292    let mut depth = 0i32;
1293    let bytes = text.as_bytes();
1294    let mut start = None;
1295    for i in (0..at).rev() {
1296        match bytes[i] {
1297            b'}' => depth += 1,
1298            b'{' => {
1299                if depth == 0 {
1300                    start = Some(i);
1301                    break;
1302                }
1303                depth -= 1;
1304            }
1305            _ => {}
1306        }
1307    }
1308    let start = start?;
1309    // forward to its matching close
1310    let mut depth = 0i32;
1311    for i in start..bytes.len() {
1312        match bytes[i] {
1313            b'{' => depth += 1,
1314            b'}' => {
1315                depth -= 1;
1316                if depth == 0 {
1317                    return Some(text[start..=i].to_string());
1318                }
1319            }
1320            _ => {}
1321        }
1322    }
1323    None
1324}
1325
1326/// What to say about a claude that has no pane.
1327///
1328/// `agents_json` is `claude agents --json`, which costs about three seconds of
1329/// CLI startup, so it is fetched once by the caller and only when something needs
1330/// naming. Its own `pid` field points at the pty-host wrapper rather than at the
1331/// session, so it is read for kind, state and name and nothing else.
1332pub fn describe_nonpane(argv: &[String], agents_json: &str) -> String {
1333    if argv.is_empty() {
1334        return "gone".into();
1335    }
1336    let (mut sid, mut res, mut forked) = (String::new(), String::new(), false);
1337    for i in 1..argv.len() {
1338        match argv[i].as_str() {
1339            "--fork-session" => forked = true,
1340            "--session-id" => sid = argv.get(i + 1).cloned().unwrap_or_default(),
1341            "-r" | "--resume" => res = argv.get(i + 1).cloned().unwrap_or_default(),
1342            _ => {}
1343        }
1344    }
1345    let own = base_id(if sid.is_empty() { &res } else { &sid });
1346    let parent = if forked && !res.is_empty() {
1347        base_id(&res)
1348    } else {
1349        String::new()
1350    };
1351
1352    let (mut kind, mut st, mut name) = ("?".to_string(), "?".to_string(), String::new());
1353    if !own.is_empty() {
1354        if let Some(obj) = json_object_with_prefix(agents_json, "sessionId", &own) {
1355            let f = |k: &str| taimux_core::json::field(&obj, k);
1356            let k = f("kind");
1357            if !k.is_empty() {
1358                kind = k;
1359            }
1360            let s = {
1361                let a = f("state");
1362                if a.is_empty() {
1363                    f("status")
1364                } else {
1365                    a
1366                }
1367            };
1368            if !s.is_empty() {
1369                st = s;
1370            }
1371            name = f("name");
1372        }
1373    }
1374    let mut out = format!("{} {}", kind, st);
1375    if forked {
1376        out.push_str(" fork");
1377    }
1378    if !name.is_empty() {
1379        out.push_str(&format!(" \"{}\"", name));
1380    }
1381    if !own.is_empty() {
1382        out.push_str(&format!(" [{}]", own.chars().take(8).collect::<String>()));
1383    }
1384    if !parent.is_empty() {
1385        out.push_str(&format!(
1386            " of [{}]",
1387            parent.chars().take(8).collect::<String>()
1388        ));
1389    }
1390    out
1391}
1392
1393/// `basename x .jsonl`: a session id, whether it arrived as one or as a path.
1394fn base_id(s: &str) -> String {
1395    if s.is_empty() {
1396        return String::new();
1397    }
1398    let b = s.rsplit('/').next().unwrap_or(s);
1399    b.strip_suffix(".jsonl").unwrap_or(b).to_string()
1400}
1401
1402#[cfg(test)]
1403mod nonpane_tests {
1404    use super::*;
1405
1406    fn v(a: &[&str]) -> Vec<String> {
1407        a.iter().map(|s| s.to_string()).collect()
1408    }
1409
1410    #[test]
1411    fn a_session_id_is_read_out_of_a_path_or_taken_as_it_stands() {
1412        assert_eq!(base_id("/a/b/263946b5-9bd7.jsonl"), "263946b5-9bd7");
1413        assert_eq!(base_id("263946b5"), "263946b5");
1414        assert_eq!(base_id(""), "");
1415    }
1416
1417    /// The depth count is the whole point: taking everything between the first
1418    /// brace and the first close would truncate any element with a nested field,
1419    /// and `claude agents --json` has them.
1420    #[test]
1421    fn the_right_object_comes_back_whole() {
1422        let j = r#"[{"sessionId":"aaa111","kind":"task","meta":{"a":1},"name":"first"},
1423                    {"sessionId":"bbb222","kind":"agent","name":"second"}]"#;
1424        let o = json_object_with_prefix(j, "sessionId", "bbb222").expect("found");
1425        assert!(o.contains("second"));
1426        assert!(!o.contains("first"));
1427        let o = json_object_with_prefix(j, "sessionId", "aaa").expect("found by prefix");
1428        assert!(o.contains("first"));
1429        assert!(
1430            o.contains("\"meta\":{\"a\":1}"),
1431            "nested field truncated: {}",
1432            o
1433        );
1434        assert!(json_object_with_prefix(j, "sessionId", "zzz").is_none());
1435    }
1436
1437    #[test]
1438    fn a_process_with_no_argv_is_simply_gone() {
1439        assert_eq!(describe_nonpane(&[], "[]"), "gone");
1440    }
1441
1442    #[test]
1443    fn an_unnamed_session_still_says_what_it_can() {
1444        let d = describe_nonpane(&v(&["claude", "--session-id", "263946b5-9bd7"]), "[]");
1445        assert_eq!(d, "? ? [263946b5]");
1446    }
1447
1448    #[test]
1449    fn a_named_one_says_kind_state_and_name() {
1450        let j =
1451            r#"[{"sessionId":"263946b5-9bd7","kind":"task","state":"running","name":"the thing"}]"#;
1452        let d = describe_nonpane(&v(&["claude", "--session-id", "263946b5-9bd7"]), j);
1453        assert_eq!(d, "task running \"the thing\" [263946b5]");
1454    }
1455
1456    /// `status` is the older field name, and one of the two is what a given
1457    /// version emits.
1458    #[test]
1459    fn status_stands_in_for_state() {
1460        let j = r#"[{"sessionId":"aaa11111","kind":"agent","status":"idle"}]"#;
1461        let d = describe_nonpane(&v(&["claude", "--session-id", "aaa11111"]), j);
1462        assert_eq!(d, "agent idle [aaa11111]");
1463    }
1464
1465    /// A fork names both itself and its parent, because that is the pair you need
1466    /// to work out which one is the stale one.
1467    #[test]
1468    fn a_fork_names_its_parent_too() {
1469        let d = describe_nonpane(
1470            &v(&[
1471                "claude",
1472                "--session-id",
1473                "child111",
1474                "--fork-session",
1475                "--resume",
1476                "/p/parent22.jsonl",
1477            ]),
1478            "[]",
1479        );
1480        assert_eq!(d, "? ? fork [child111] of [parent22]");
1481    }
1482}
1483
1484#[cfg(test)]
1485mod plan_tests {
1486    use super::*;
1487
1488    /// A machine with one stale pane, one current one, and whatever else the test
1489    /// asks for. The `Env` trait exists for this: the live differential can only
1490    /// reach "nothing to restart" while every session is on the installed
1491    /// version, so the branch that actually acts needs a fixture.
1492    struct Fake {
1493        /// pid -> version
1494        vers: HashMap<i32, String>,
1495        /// pane -> screen
1496        screens: HashMap<String, String>,
1497        /// pane -> resolved transcript, or the refusal
1498        resolved: HashMap<String, Result<String, String>>,
1499        /// pane -> what the same pane shows once it has been zoomed, for a pane
1500        /// too short to draw a prompt box at the size it sits at
1501        zoomed: HashMap<String, String>,
1502        /// how many panes were zoomed to be read, since a zoom is something the
1503        /// user watching that window sees happen
1504        zooms: std::cell::Cell<usize>,
1505        /// pane -> the hook line's state, for the panes that have one
1506        hooks: HashMap<String, String>,
1507        /// pane -> the hook line's permission mode
1508        modes: HashMap<String, String>,
1509        /// pid -> what the session says it is doing, for the ones that say
1510        own: HashMap<i32, state::State>,
1511        /// pid -> the background session it shows: its id, its worker's
1512        /// version, and the transcript it writes
1513        away: HashMap<i32, (String, String, Option<String>)>,
1514        /// every background session running, as the files list them
1515        bgs: Vec<BgSession>,
1516        transcript: String,
1517        now: i64,
1518    }
1519
1520    impl Env for Fake {
1521        fn capture(&self, pane: &str) -> String {
1522            self.screens.get(pane).cloned().unwrap_or_default()
1523        }
1524        fn capture_zoomed(&self, pane: &str) -> Option<String> {
1525            let bigger = self.zoomed.get(pane).cloned();
1526            if bigger.is_some() {
1527                self.zooms.set(self.zooms.get() + 1);
1528            }
1529            bigger
1530        }
1531        fn hook_state(&self, pane: &str, _pid: i32) -> Option<String> {
1532            self.hooks.get(pane).cloned()
1533        }
1534        fn hook_mode(&self, pane: &str, _pid: i32) -> Option<String> {
1535            self.modes.get(pane).cloned()
1536        }
1537        fn own_state(&self, pid: i32, _screen: &str) -> Option<state::State> {
1538            self.own.get(&pid).copied()
1539        }
1540        fn elsewhere(&self, _pane: &str, pid: i32) -> Option<Elsewhere> {
1541            self.away.get(&pid).map(|(id, ver, transcript)| Elsewhere {
1542                id: id.clone(),
1543                pid: 1000 + pid,
1544                version: Some(ver.clone()),
1545                transcript: transcript.clone(),
1546            })
1547        }
1548        fn background(&self) -> Vec<BgSession> {
1549            self.bgs.clone()
1550        }
1551        fn version_of_pid(&self, pid: i32) -> Option<String> {
1552            self.vers.get(&pid).cloned()
1553        }
1554        fn cwd_of(&self, _pid: i32) -> Option<String> {
1555            Some("/w".into())
1556        }
1557        fn argv_of(&self, _pid: i32) -> Vec<String> {
1558            vec!["claude".into()]
1559        }
1560        fn resolve(&self, pane: &str, _c: &str, _t: &str, _p: i32) -> Result<String, String> {
1561            self.resolved
1562                .get(pane)
1563                .cloned()
1564                .unwrap_or_else(|| Err("no candidate".into()))
1565        }
1566        fn read_transcript(&self, _path: &str) -> Option<String> {
1567            Some(self.transcript.clone())
1568        }
1569        fn now(&self) -> i64 {
1570            self.now
1571        }
1572    }
1573
1574    fn fake() -> Fake {
1575        let mut vers = HashMap::new();
1576        vers.insert(11, "2.1.100".to_string()); // stale
1577        vers.insert(22, "2.1.258".to_string()); // current
1578        let mut screens = HashMap::new();
1579        // an idle screen with an empty prompt box
1580        screens.insert("%1".to_string(), "some output\n❯ \n".to_string());
1581        screens.insert("%2".to_string(), "some output\n❯ \n".to_string());
1582        let mut resolved = HashMap::new();
1583        resolved.insert("%1".to_string(), Ok("/t/a.jsonl\tpane map".to_string()));
1584        Fake {
1585            vers,
1586            screens,
1587            resolved,
1588            zoomed: HashMap::new(),
1589            zooms: std::cell::Cell::new(0),
1590            hooks: HashMap::new(),
1591            modes: HashMap::new(),
1592            own: HashMap::new(),
1593            away: HashMap::new(),
1594            bgs: Vec::new(),
1595            transcript: r#"{"type":"user","timestamp":"2020-01-01T00:00:00Z"}"#.to_string(),
1596            now: 1788312225,
1597        }
1598    }
1599
1600    fn opts() -> Opts {
1601        Opts {
1602            include_busy: false,
1603            only_panes: Vec::new(),
1604            force_transcript: None,
1605            self_pane: String::new(),
1606        }
1607    }
1608
1609    const ROWS: &str = "%1\tw:1.1\t/w\tclaude\t11\tclaude\tproj: the stale one\n\
1610                        %2\tw:2.1\t/w\tclaude\t22\tclaude\tproj: the current one";
1611
1612    fn plan_of(e: &Fake, o: &Opts) -> Plan {
1613        plan(ROWS, "2.1.258", "/l/claude", o, e, "/nowhere", &|| {
1614            "[]".into()
1615        })
1616    }
1617
1618    #[test]
1619    fn a_stale_pane_is_planned_and_a_current_one_is_not() {
1620        let p = plan_of(&fake(), &opts());
1621        assert_eq!(p.go.len(), 1);
1622        assert_eq!(p.go[0].pane, "%1");
1623        assert_eq!(p.go[0].cmd, "command claude --resume /t/a.jsonl");
1624        assert_eq!(p.go[0].via, "2.1.100 -> 2.1.258, pane map, idle");
1625        assert!(p.skipped.is_empty());
1626    }
1627
1628    /// A session comes back in the mode it is in, not the one it was launched
1629    /// in: a plain resume starts in the startup default, which put every pane
1630    /// flipped to auto back in manual. The footer is read first, because a
1631    /// `shift+tab` at an idle prompt moves nothing else, the hook line included.
1632    #[test]
1633    fn a_session_comes_back_in_the_mode_it_is_in() {
1634        let rule = "────────────────────────────────";
1635        let mut e = fake();
1636        e.screens.insert(
1637            "%1".into(),
1638            format!("some output\n{rule}\n❯ \n{rule}\n  ⏵⏵ accept edits on (shift+tab to cycle)\n"),
1639        );
1640        e.modes.insert("%1".into(), "auto".into()); // its last turn's
1641        let p = plan_of(&e, &opts());
1642        assert_eq!(p.go.len(), 1, "{:?}", p.skipped);
1643        assert_eq!(
1644            p.go[0].cmd,
1645            "command claude --permission-mode acceptEdits --resume /t/a.jsonl"
1646        );
1647
1648        // a footer that names nothing leaves it to the hook line
1649        let mut e = fake();
1650        e.modes.insert("%1".into(), "plan".into());
1651        let p = plan_of(&e, &opts());
1652        assert_eq!(
1653            p.go[0].cmd,
1654            "command claude --permission-mode plan --resume /t/a.jsonl"
1655        );
1656
1657        // and a line that has heard no mode yet leaves the argv as it is
1658        let mut e = fake();
1659        e.modes.insert("%1".into(), "-".into());
1660        assert_eq!(
1661            plan_of(&e, &opts()).go[0].cmd,
1662            "command claude --resume /t/a.jsonl"
1663        );
1664    }
1665
1666    /// The rendered plan is the whole user interface of `restart -n`, so its
1667    /// exact shape is what the bash comparison was made on.
1668    #[test]
1669    fn the_rendered_plan_reads_the_way_it_always_did() {
1670        let out = render(&plan_of(&fake(), &opts()));
1671        assert_eq!(
1672            out,
1673            "claude: 2.1.258 installed at /l/claude\n\n\
1674             to restart (1):\n\
1675             \x20 %1    w:1.1          proj: the stale one\n\
1676             \x20       2.1.100 -> 2.1.258, pane map, idle\n\
1677             \x20       command claude --resume /t/a.jsonl\n"
1678        );
1679    }
1680
1681    /// Restarting the pane taimux is running in would kill taimux mid-restart.
1682    #[test]
1683    fn this_pane_is_never_restarted() {
1684        let mut o = opts();
1685        o.self_pane = "%1".into();
1686        let p = plan_of(&fake(), &o);
1687        assert!(p.go.is_empty());
1688        assert!(p.skipped[0].contains("this pane"));
1689        assert!(p.skipped[0].contains("killing it would kill taimux"));
1690    }
1691
1692    #[test]
1693    fn a_pane_that_is_not_idle_waits_for_include_busy() {
1694        let mut e = fake();
1695        // an activity line: mid-turn
1696        e.screens
1697            .insert("%1".into(), "Twisting… (35s · ↓ 1.6k tokens)\n❯ \n".into());
1698        let p = plan_of(&e, &opts());
1699        assert!(p.go.is_empty());
1700        assert!(p.skipped[0].contains("rerun when idle, or --include-busy"));
1701
1702        let mut o = opts();
1703        o.include_busy = true;
1704        assert_eq!(plan_of(&e, &o).go.len(), 1);
1705    }
1706
1707    /// What the session says outranks a screen and a hook line that both look
1708    /// idle: a permission granted to a tool that is still running shows neither
1709    /// a counter nor a fresh line, and restarting it would kill the tool.
1710    #[test]
1711    fn a_session_that_says_it_is_busy_is_busy() {
1712        let mut e = fake();
1713        e.hooks.insert("%1".into(), "input".into());
1714        e.own.insert(11, state::State::Run);
1715        let p = plan_of(&e, &opts());
1716        assert!(p.go.is_empty());
1717        assert!(
1718            p.skipped[0].contains("run: rerun when idle"),
1719            "{:?}",
1720            p.skipped
1721        );
1722        // and an Esc the hook line never heard of frees it again
1723        e.hooks.insert("%1".into(), "run".into());
1724        e.own.insert(11, state::State::Idle);
1725        assert_eq!(plan_of(&e, &opts()).go.len(), 1);
1726    }
1727
1728    /// A pane showing a background session is put back by respawning the
1729    /// session's worker and attaching the pane to it again. Retyping it would
1730    /// resume the conversation the pane started on as a second branch, beside
1731    /// the one agent view goes on running, so the ladder is never asked: the
1732    /// job id is all either command takes.
1733    #[test]
1734    fn a_pane_showing_a_background_session_is_respawned_and_attached_again() {
1735        let mut e = fake();
1736        e.own.insert(11, state::State::Idle);
1737        e.away
1738            .insert(11, ("2447b564".into(), "2.1.100".into(), None));
1739        e.resolved.insert("%1".into(), Err("never asked".into()));
1740        let p = plan_of(&e, &opts());
1741        assert_eq!(p.go.len(), 1, "{:?}", p.skipped);
1742        let g = &p.go[0];
1743        assert_eq!(g.pane, "%1");
1744        assert_eq!(g.pid, 11, "the pane's own process, the client");
1745        assert_eq!(g.respawn.as_deref(), Some("2447b564"));
1746        assert_eq!(g.cmd, "command claude attach 2447b564");
1747        assert_eq!(
1748            g.via,
1749            "2.1.100 -> 2.1.258, background session 2447b564, idle"
1750        );
1751        assert!(!p.unresolved);
1752    }
1753
1754    /// The version that counts on a pane attached to a background session is
1755    /// its worker's, either way round: a current client on a stale worker is
1756    /// behind, and a stale client on a current worker has nothing to gain.
1757    #[test]
1758    fn an_attached_pane_is_judged_by_its_workers_version() {
1759        let mut e = fake();
1760        e.away
1761            .insert(22, ("880ae832".into(), "2.1.250".into(), None));
1762        let p = plan_of(&e, &opts());
1763        assert_eq!(p.go.len(), 2, "{:?}", p.skipped);
1764        assert_eq!(
1765            (p.go[0].pane.as_str(), p.go[0].respawn.as_deref()),
1766            ("%1", None)
1767        );
1768        assert_eq!(
1769            (p.go[1].pane.as_str(), p.go[1].respawn.as_deref()),
1770            ("%2", Some("880ae832"))
1771        );
1772        assert!(p.go[1].via.starts_with("2.1.250 -> 2.1.258, "));
1773
1774        let mut e = fake();
1775        e.away
1776            .insert(11, ("880ae832".into(), "2.1.258".into(), None));
1777        let p = plan_of(&e, &opts());
1778        assert!(p.go.is_empty());
1779        assert!(
1780            p.skipped.iter().all(|s| !s.starts_with("%1")),
1781            "{:?}",
1782            p.skipped
1783        );
1784    }
1785
1786    /// A respawn ends the worker, so it waits on everything a retype waits on,
1787    /// read off the session the pane shows: what it says it is doing, the
1788    /// screen, and its own transcript.
1789    #[test]
1790    fn a_background_session_waits_like_any_pane() {
1791        let bg = |e: &mut Fake| {
1792            e.away.insert(
1793                11,
1794                (
1795                    "2447b564".into(),
1796                    "2.1.100".into(),
1797                    Some("/t/bg.jsonl".into()),
1798                ),
1799            );
1800        };
1801        let mut busy = opts();
1802        busy.include_busy = true;
1803
1804        // a turn in flight in the worker
1805        let mut e = fake();
1806        bg(&mut e);
1807        e.own.insert(11, state::State::Run);
1808        let p = plan_of(&e, &opts());
1809        assert!(p.go.is_empty());
1810        assert!(
1811            p.skipped[0].contains("2.1.100, run: rerun when idle, or --include-busy"),
1812            "{:?}",
1813            p.skipped
1814        );
1815        assert_eq!(plan_of(&e, &busy).go.len(), 1);
1816
1817        // a shell its last turn left running
1818        let mut e = fake();
1819        bg(&mut e);
1820        e.screens.insert(
1821            "%1".into(),
1822            "✻ Cogitated for 3s · done 4:55 PM · 1 shell still running\n❯ \n".into(),
1823        );
1824        assert!(plan_of(&e, &opts()).skipped[0].contains("work still in flight"));
1825
1826        // a permission prompt, whatever --include-busy says
1827        let mut e = fake();
1828        bg(&mut e);
1829        e.screens.insert(
1830            "%1".into(),
1831            "some output\n\nDo you want to proceed?\n".into(),
1832        );
1833        let p = plan_of(&e, &busy);
1834        assert!(p.go.is_empty());
1835        assert!(
1836            p.skipped[0].contains("a dialog is waiting"),
1837            "{:?}",
1838            p.skipped
1839        );
1840
1841        // a draft in its prompt box, which lives in the worker
1842        let mut e = fake();
1843        bg(&mut e);
1844        e.screens
1845            .insert("%1".into(), "stuff\n❯ half a thought\n".into());
1846        assert!(plan_of(&e, &opts()).skipped[0].contains("unsent text in the prompt box"));
1847
1848        // its transcript written to a moment ago
1849        let mut e = fake();
1850        bg(&mut e);
1851        e.transcript = r#"{"type":"user","timestamp":"2026-09-02T01:23:40Z"}"#.into();
1852        assert!(plan_of(&e, &opts()).skipped[0].contains("not settled"));
1853        // …and no transcript to read is no evidence either way
1854        e.away
1855            .insert(11, ("2447b564".into(), "2.1.100".into(), None));
1856        assert_eq!(plan_of(&e, &opts()).go.len(), 1);
1857
1858        // and never the pane taimux runs in
1859        let mut e = fake();
1860        bg(&mut e);
1861        let mut me = opts();
1862        me.self_pane = "%1".into();
1863        assert!(plan_of(&e, &me).skipped[0].contains("this pane"));
1864    }
1865
1866    /// Two panes on one background session both go in the plan, carrying the
1867    /// same session: the respawn takes both clients off it, so both are
1868    /// attached again, and `restart` respawns it once.
1869    #[test]
1870    fn two_panes_on_one_background_session_are_both_attached_again() {
1871        let mut e = fake();
1872        e.vers.insert(22, "2.1.100".into());
1873        e.away
1874            .insert(11, ("2447b564".into(), "2.1.100".into(), None));
1875        e.away
1876            .insert(22, ("2447b564".into(), "2.1.100".into(), None));
1877        let p = plan_of(&e, &opts());
1878        assert_eq!(p.go.len(), 2, "{:?}", p.skipped);
1879        assert!(p
1880            .go
1881            .iter()
1882            .all(|g| g.respawn.as_deref() == Some("2447b564")));
1883    }
1884
1885    /// `--transcript` names a conversation to resume in the pane, and the one
1886    /// thing a respawn never does is resume anything in the pane.
1887    #[test]
1888    fn a_given_transcript_does_not_apply_to_a_background_session() {
1889        let mut e = fake();
1890        e.away
1891            .insert(11, ("2447b564".into(), "2.1.100".into(), None));
1892        let mut o = opts();
1893        o.only_panes = vec!["%1".into()];
1894        o.force_transcript = Some("/t/other.jsonl".into());
1895        let p = plan_of(&e, &o);
1896        assert!(p.go.is_empty());
1897        assert!(
1898            p.skipped[0].contains("--transcript does not apply"),
1899            "{:?}",
1900            p.skipped
1901        );
1902    }
1903
1904    /// The id is typed into the pane's shell, so it has to be one that a shell
1905    /// reads as a single plain word.
1906    #[test]
1907    fn an_id_unsafe_to_type_is_refused() {
1908        let mut e = fake();
1909        e.away
1910            .insert(11, ("2447b564; rm -rf ~".into(), "2.1.100".into(), None));
1911        let p = plan_of(&e, &opts());
1912        assert!(p.go.is_empty());
1913        assert!(p.skipped[0].contains("not safe to type"), "{:?}", p.skipped);
1914        assert!(typable_id("2447b564"));
1915        assert!(typable_id("58b11e6b-39fd-484a-aa0f-44e86a8eb6d1"));
1916        assert!(!typable_id(""));
1917        assert!(!typable_id("a b"));
1918        assert!(!typable_id("$(x)"));
1919    }
1920
1921    /// An idle background session behind the installed version, no pane
1922    /// showing it, its record clean.
1923    fn bg_session() -> BgSession {
1924        BgSession {
1925            id: "f3836aef".into(),
1926            pid: 500,
1927            version: Some("2.1.100".into()),
1928            name: "jumpmux: stage".into(),
1929            state: Some(state::State::Idle),
1930            transcript: Some("/t/bg.jsonl".into()),
1931            in_flight: Some(taimux_core::status::InFlight {
1932                tasks: 0,
1933                queued: 0,
1934            }),
1935        }
1936    }
1937
1938    /// One no pane shows has nothing to type into, so a respawn is all of it,
1939    /// and only a whole plan looks for one: `--pane` names panes.
1940    #[test]
1941    fn a_background_session_no_pane_shows_is_respawned() {
1942        let mut e = fake();
1943        let mut current = bg_session();
1944        current.id = "aaaaaaaa".into();
1945        current.pid = 501;
1946        current.version = Some("2.1.258".into());
1947        e.bgs = vec![bg_session(), current];
1948        let p = plan_of(&e, &opts());
1949        assert_eq!(p.go.len(), 1, "the stale pane, as before");
1950        assert_eq!(p.go_bg.len(), 1, "{:?}", p.skipped);
1951        assert_eq!((p.go_bg[0].id.as_str(), p.go_bg[0].pid), ("f3836aef", 500));
1952        assert_eq!(p.go_bg[0].via, "2.1.100 -> 2.1.258, no pane, idle");
1953        let out = render(&p);
1954        assert!(out.contains("to restart (2):\n"), "{out}");
1955        assert!(
1956            out.ends_with(
1957                "\x20 f3836aef background     jumpmux: stage\n\
1958                 \x20       2.1.100 -> 2.1.258, no pane, idle\n\
1959                 \x20       claude respawn f3836aef\n"
1960            ),
1961            "{out}"
1962        );
1963
1964        let mut o = opts();
1965        o.only_panes = vec!["%1".into()];
1966        assert!(plan_of(&e, &o).go_bg.is_empty());
1967    }
1968
1969    /// A worker some pane shows is that pane's to put back, attach and all.
1970    #[test]
1971    fn a_background_session_a_pane_shows_is_left_to_the_pane() {
1972        let mut e = fake();
1973        e.away
1974            .insert(11, ("f3836aef".into(), "2.1.100".into(), None));
1975        let mut b = bg_session();
1976        b.pid = 1011; // the Fake's worker for pid 11
1977        e.bgs = vec![b];
1978        let p = plan_of(&e, &opts());
1979        assert!(p.go_bg.is_empty(), "planned twice");
1980        assert_eq!(p.go[0].respawn.as_deref(), Some("f3836aef"));
1981    }
1982
1983    /// The guards a pane gets, read off what there is in place of a screen.
1984    #[test]
1985    fn a_background_session_no_pane_shows_waits_like_any_pane() {
1986        let mut busy = opts();
1987        busy.include_busy = true;
1988        let with = |f: &dyn Fn(&mut BgSession)| {
1989            let mut e = fake();
1990            let mut b = bg_session();
1991            f(&mut b);
1992            e.bgs = vec![b];
1993            e
1994        };
1995        let refused = |e: &Fake, o: &Opts, why: &str| {
1996            let p = plan_of(e, o);
1997            assert!(p.go_bg.is_empty(), "planned despite {why}");
1998            assert!(
1999                p.skipped
2000                    .iter()
2001                    .any(|s| s.starts_with("f3836aef background  2.1.100, ") && s.contains(why)),
2002                "{why}: {:?}",
2003                p.skipped
2004            );
2005        };
2006
2007        // waiting on an answer, whatever --include-busy says
2008        let e = with(&|b| b.state = Some(state::State::Input));
2009        refused(&e, &busy, "waiting for an answer: claude attach f3836aef");
2010        // a turn in flight
2011        let e = with(&|b| b.state = Some(state::State::Run));
2012        refused(&e, &opts(), "run: rerun when idle, or --include-busy");
2013        assert_eq!(plan_of(&e, &busy).go_bg.len(), 1);
2014        // saying nothing at all
2015        let e = with(&|b| b.state = None);
2016        refused(&e, &busy, "says nothing of what it is doing");
2017        // a reply saved for its next start, which the respawn would send
2018        let e = with(&|b| {
2019            b.in_flight = Some(taimux_core::status::InFlight {
2020                tasks: 0,
2021                queued: 1,
2022            })
2023        });
2024        refused(&e, &busy, "a reply is saved for its next start");
2025        // a shell its last turn left running
2026        let e = with(&|b| {
2027            b.in_flight = Some(taimux_core::status::InFlight {
2028                tasks: 1,
2029                queued: 0,
2030            })
2031        });
2032        refused(&e, &opts(), "work still in flight");
2033        assert_eq!(plan_of(&e, &busy).go_bg.len(), 1);
2034        // a record that says nothing of it is not taken to mean none
2035        let e = with(&|b| b.in_flight = None);
2036        refused(&e, &opts(), "says nothing of work in flight");
2037        assert_eq!(plan_of(&e, &busy).go_bg.len(), 1);
2038        // its transcript written to a moment ago
2039        let mut e = with(&|_| {});
2040        e.transcript = r#"{"type":"user","timestamp":"2026-09-02T01:23:40Z"}"#.into();
2041        refused(&e, &opts(), "not settled");
2042        // an id that is not one
2043        let e = with(&|b| b.id = "f38; x".into());
2044        assert!(plan_of(&e, &busy).go_bg.is_empty());
2045    }
2046
2047    /// The plan says both halves, since the respawn is the half that never
2048    /// touches the pane and would otherwise go unmentioned.
2049    #[test]
2050    fn the_rendered_plan_names_the_respawn() {
2051        let mut e = fake();
2052        e.away
2053            .insert(11, ("2447b564".into(), "2.1.100".into(), None));
2054        assert_eq!(
2055            render(&plan_of(&e, &opts())),
2056            "claude: 2.1.258 installed at /l/claude\n\n\
2057             to restart (1):\n\
2058             \x20 %1    w:1.1          proj: the stale one\n\
2059             \x20       2.1.100 -> 2.1.258, background session 2447b564, idle\n\
2060             \x20       claude respawn 2447b564, then command claude attach 2447b564\n"
2061        );
2062    }
2063
2064    /// Idle at its prompt, and still not restartable without asking: the shells
2065    /// a finished turn left running are the session's children and die with it.
2066    #[test]
2067    fn a_pane_with_work_in_flight_waits_for_include_busy() {
2068        let mut e = fake();
2069        e.screens.insert(
2070            "%1".into(),
2071            "✻ Cogitated for 1m 3s · done 4:55 PM · 2 shells still running\n❯ \n".into(),
2072        );
2073        let p = plan_of(&e, &opts());
2074        assert!(p.go.is_empty());
2075        assert!(
2076            p.skipped[0].contains("work still in flight"),
2077            "{:?}",
2078            p.skipped
2079        );
2080
2081        // The line alone says so as well, on a screen that shows nothing of it.
2082        let mut e = fake();
2083        e.hooks.insert("%1".into(), "bg".into());
2084        let p = plan_of(&e, &opts());
2085        assert!(p.go.is_empty());
2086        assert!(
2087            p.skipped[0].contains("work still in flight"),
2088            "{:?}",
2089            p.skipped
2090        );
2091
2092        let mut o = opts();
2093        o.include_busy = true;
2094        assert_eq!(plan_of(&e, &o).go.len(), 1);
2095    }
2096
2097    /// Even with --include-busy: a half-answered permission prompt is the one
2098    /// state where the Ctrl-C that starts a restart means something else.
2099    #[test]
2100    fn a_dialog_blocks_a_restart_even_with_include_busy() {
2101        let mut e = fake();
2102        e.screens
2103            .insert("%1".into(), "output\n\nDo you want to proceed?\n".into());
2104        let mut o = opts();
2105        o.include_busy = true;
2106        let p = plan_of(&e, &o);
2107        assert!(p.go.is_empty());
2108        assert!(p.skipped[0].contains("a dialog is waiting for an answer"));
2109    }
2110
2111    #[test]
2112    fn an_unsent_draft_is_left_alone() {
2113        let mut e = fake();
2114        e.screens
2115            .insert("%1".into(), "output\n❯ half a thought\n".into());
2116        let p = plan_of(&e, &opts());
2117        assert!(p.skipped[0].contains("unsent text in the prompt box"));
2118    }
2119
2120    /// The pane this whole thing is for: three rows, no box on it, and a session
2121    /// sitting idle behind that. Read at a size it can be read at, it is an
2122    /// ordinary restart.
2123    #[test]
2124    fn a_pane_too_short_for_its_box_is_read_zoomed() {
2125        let mut e = fake();
2126        e.screens.insert(
2127            "%1".into(),
2128            "  current: 2.1.100 · latest…\n────────\n".into(),
2129        );
2130        e.zoomed.insert("%1".into(), "some output\n❯ \n".into());
2131        let p = plan_of(&e, &opts());
2132        assert_eq!(e.zooms.get(), 1);
2133        assert_eq!(p.go.len(), 1);
2134        assert_eq!(p.go[0].pane, "%1");
2135        assert!(p.skipped.is_empty());
2136    }
2137
2138    /// And the point of reading it rather than assuming: a draft is invisible at
2139    /// three rows too, so the zoomed read is the only thing that can find one.
2140    /// Refused here for what is actually in the box, not for the box being
2141    /// missing.
2142    #[test]
2143    fn a_draft_hidden_by_a_short_pane_still_refuses() {
2144        let mut e = fake();
2145        e.screens
2146            .insert("%1".into(), "  current: 2.1.100…\n".into());
2147        e.zoomed
2148            .insert("%1".into(), "output\n❯ half a thought\n".into());
2149        let p = plan_of(&e, &opts());
2150        assert_eq!(e.zooms.get(), 1);
2151        assert!(p.go.is_empty());
2152        assert!(p.skipped[0].contains("unsent text in the prompt box"));
2153    }
2154
2155    /// A dialog is off the bottom of a short pane with the box, so the zoomed
2156    /// read is what finds that too, and a dialog is refused with or without
2157    /// `--include-busy`.
2158    #[test]
2159    fn a_dialog_hidden_by_a_short_pane_is_found_by_the_zoom() {
2160        let mut e = fake();
2161        e.screens.insert("%1".into(), "  Bash command\n".into());
2162        e.zoomed.insert(
2163            "%1".into(),
2164            "Do you want to proceed?\n❯ 1. Yes\n  2. No\n".into(),
2165        );
2166        let mut o = opts();
2167        o.include_busy = true;
2168        let p = plan_of(&e, &o);
2169        assert!(p.go.is_empty());
2170        assert!(p.skipped[0].contains("a dialog is waiting for an answer"));
2171    }
2172
2173    /// A pane already showing its box is never zoomed: the read is already good,
2174    /// and a zoom is something the person watching that window sees happen.
2175    #[test]
2176    fn a_pane_that_shows_its_box_is_not_zoomed() {
2177        let e = fake();
2178        let p = plan_of(&e, &opts());
2179        assert_eq!(e.zooms.get(), 0);
2180        assert_eq!(p.go.len(), 1);
2181    }
2182
2183    /// A transcript touched in the last 45 seconds is left alone whatever the
2184    /// screen said, because the screen reading is the fragile half.
2185    #[test]
2186    fn a_recently_active_transcript_is_left_alone() {
2187        let mut e = fake();
2188        e.transcript = r#"{"type":"user","timestamp":"2026-09-02T01:23:45Z"}"#.into();
2189        e.now = 1788312225 + 10;
2190        let p = plan_of(&e, &opts());
2191        assert!(p.skipped[0].contains("active in the last 45s"));
2192    }
2193
2194    #[test]
2195    fn an_unresolved_pane_says_so_and_earns_the_paragraph() {
2196        let mut e = fake();
2197        e.resolved
2198            .insert("%1".into(), Err("3 transcripts share this title".into()));
2199        let p = plan_of(&e, &opts());
2200        assert!(p.go.is_empty());
2201        assert!(p.unresolved);
2202        assert!(p.skipped[0].contains("unresolved: 3 transcripts share this title"));
2203        assert!(render(&p).contains("restart it by hand"));
2204    }
2205
2206    /// Two panes on one conversation is the same mistake on a restart as on a
2207    /// restore: the second one to claim it gets skipped rather than resumed.
2208    #[test]
2209    fn one_transcript_is_never_resumed_into_two_panes() {
2210        let mut e = fake();
2211        e.vers.insert(22, "2.1.100".into()); // make the second one stale too
2212        e.resolved
2213            .insert("%2".into(), Ok("/t/a.jsonl\tpane map".into()));
2214        let p = plan_of(&e, &opts());
2215        assert_eq!(p.go.len(), 1);
2216        assert_eq!(p.go[0].pane, "%1");
2217        assert!(p.skipped[0].contains("resolves to the same transcript as %1"));
2218    }
2219
2220    #[test]
2221    fn only_panes_narrows_the_plan_without_changing_the_verdicts() {
2222        let mut o = opts();
2223        o.only_panes = vec!["%2".into()];
2224        let p = plan_of(&fake(), &o);
2225        assert!(p.go.is_empty());
2226        assert!(p.skipped.is_empty()); // %1 was not considered at all
2227    }
2228
2229    #[test]
2230    fn a_pane_with_no_session_process_is_reported_not_dropped() {
2231        let rows = "%9\tw:9.9\t/w\tclaude\t0\tclaude\tno pid here";
2232        let p = plan(rows, "2.1.258", "/l", &opts(), &fake(), "/nowhere", &|| {
2233            "[]".into()
2234        });
2235        assert!(p.go.is_empty());
2236        assert_eq!(p.skipped.len(), 1);
2237        assert!(p.skipped[0].contains("no session process was found"));
2238    }
2239
2240    #[test]
2241    fn nothing_to_restart_says_so() {
2242        let mut e = fake();
2243        e.vers.insert(11, "2.1.258".into());
2244        let out = render(&plan_of(&e, &opts()));
2245        assert!(out.contains("nothing to restart."));
2246        assert!(!out.contains("to restart ("));
2247    }
2248
2249    /// --transcript names the conversation outright, which is the escape hatch
2250    /// for a pane the ladder refuses.
2251    #[test]
2252    fn a_given_transcript_overrides_the_ladder() {
2253        let mut e = fake();
2254        e.resolved.insert("%1".into(), Err("no candidate".into()));
2255        let mut o = opts();
2256        o.force_transcript = Some("/given.jsonl".into());
2257        let p = plan_of(&e, &o);
2258        assert_eq!(p.go.len(), 1);
2259        assert!(p.go[0].via.contains("--transcript, given"));
2260        assert!(p.go[0].cmd.contains("--resume /given.jsonl"));
2261    }
2262}