1use std::collections::HashMap;
30
31use taimux_core::{conv, state, tmux};
32
33pub 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(()); };
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(()); };
62 if now - then < 45 {
63 return Err("active in the last 45s".into());
64 }
65 Ok(())
66}
67
68fn parse_iso8601(s: &str) -> Option<i64> {
72 taimux_core::turn::epoch_ms(s).map(|ms| ms.div_euclid(1000))
73}
74
75pub 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
98pub 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
123const BOX_ROWS: usize = 6;
138
139type Cmd = Vec<String>;
141
142type ZoomSteps = (Vec<Cmd>, Vec<Cmd>);
144
145fn 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 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 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 if zoomed && !active.is_empty() {
201 back.push(cmd(&["resize-pane", "-Z", "-t", active]));
202 }
203 Some((go, back))
204}
205
206struct 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
221pub 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
292pub 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)"); 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
305pub struct Planned {
307 pub pane: String,
308 pub target: String,
309 pub pid: i32,
312 pub cmd: String,
314 pub title: String,
315 pub via: String,
316 pub respawn: Option<String>,
320}
321
322pub struct PlannedBg {
324 pub id: String,
326 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 pub go_bg: Vec<PlannedBg>,
338 pub skipped: Vec<String>,
339 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
351pub trait Env {
354 fn capture(&self, pane: &str) -> String;
355 fn capture_zoomed(&self, _pane: &str) -> Option<String> {
362 None
363 }
364 fn hook_state(&self, pane: &str, pid: i32) -> Option<String>;
365 fn hook_mode(&self, _pane: &str, _pid: i32) -> Option<String> {
368 None
369 }
370 fn own_state(&self, _pid: i32, _screen: &str) -> Option<state::State> {
374 None
375 }
376 fn elsewhere(&self, _pane: &str, _pid: i32) -> Option<Elsewhere> {
379 None
380 }
381 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
394pub struct Elsewhere {
397 pub id: String,
399 pub pid: i32,
401 pub version: Option<String>,
403 pub transcript: Option<String>,
406}
407
408#[derive(Clone)]
411pub struct BgSession {
412 pub id: String,
414 pub pid: i32,
416 pub version: Option<String>,
418 pub name: String,
419 pub state: Option<state::State>,
421 pub transcript: Option<String>,
422 pub in_flight: Option<taimux_core::status::InFlight>,
425}
426
427fn typable_id(id: &str) -> bool {
431 !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
432}
433
434fn 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
449pub 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 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 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; }
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 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 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 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 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 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 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 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
711fn 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
769pub 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
809pub 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
842pub 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
874pub 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 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
917fn alive(pid: i32) -> bool {
920 std::path::Path::new(&format!("/proc/{}", pid)).exists()
921}
922
923pub fn confirm_yes(answer: &str) -> bool {
926 matches!(answer.trim(), "" | "y" | "Y" | "yes" | "YES" | "Yes")
927}
928
929pub 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 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
1014pub 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 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 assert_eq!(parse_iso8601("2024-02-29T00:00:00Z"), Some(1709164800));
1061 }
1062
1063 #[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 #[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 assert!(transcript_is_settled(r#"{"type":"user"}"#, 0).is_ok());
1097 }
1098
1099 #[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 assert!(screen_has_no_dialog("some output\n❯ \n").is_ok());
1116 }
1117
1118 #[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 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 #[test]
1143 fn a_pane_tall_enough_to_read_is_left_alone() {
1144 assert!(zoom_steps("%1", false, 6, 40, "%2", "%3").is_none());
1146 assert!(zoom_steps("%1", false, 40, 40, "%2", "%3").is_none());
1147 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 #[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 #[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 #[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 #[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 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 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
1247pub 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 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
1278fn 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 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 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
1326pub 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
1393fn 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 #[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 #[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 #[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 struct Fake {
1493 vers: HashMap<i32, String>,
1495 screens: HashMap<String, String>,
1497 resolved: HashMap<String, Result<String, String>>,
1499 zoomed: HashMap<String, String>,
1502 zooms: std::cell::Cell<usize>,
1505 hooks: HashMap<String, String>,
1507 modes: HashMap<String, String>,
1509 own: HashMap<i32, state::State>,
1511 away: HashMap<i32, (String, String, Option<String>)>,
1514 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()); vers.insert(22, "2.1.258".to_string()); let mut screens = HashMap::new();
1579 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 #[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()); 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 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 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 #[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 #[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 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 #[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 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 #[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 #[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 #[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 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 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 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 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 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 e.away
1855 .insert(11, ("2447b564".into(), "2.1.100".into(), None));
1856 assert_eq!(plan_of(&e, &opts()).go.len(), 1);
1857
1858 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 #[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 #[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 #[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 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 #[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 #[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; 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 #[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 let e = with(&|b| b.state = Some(state::State::Input));
2009 refused(&e, &busy, "waiting for an answer: claude attach f3836aef");
2010 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 let e = with(&|b| b.state = None);
2016 refused(&e, &busy, "says nothing of what it is doing");
2017 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 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 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 let mut e = with(&|_| {});
2040 e.transcript = r#"{"type":"user","timestamp":"2026-09-02T01:23:40Z"}"#.into();
2041 refused(&e, &opts(), "not settled");
2042 let e = with(&|b| b.id = "f38; x".into());
2044 assert!(plan_of(&e, &busy).go_bg.is_empty());
2045 }
2046
2047 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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()); 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()); }
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 #[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}