1use std::collections::HashMap;
23
24use taimux_core::{conv, state, tmux};
25
26pub fn transcript_is_settled(text: &str, now: i64) -> Result<(), String> {
40 let Some(last) = text.lines().rfind(|l| !l.trim().is_empty()) else {
41 return Ok(()); };
43 if taimux_core::json::field(last, "type") == "assistant"
44 && (last.contains("\"type\":\"tool_use\"") || last.contains("\"type\": \"tool_use\""))
45 {
46 return Err("a tool call is still running".into());
47 }
48 let ts = taimux_core::json::field(last, "timestamp");
49 if ts.is_empty() {
50 return Ok(());
51 }
52 let Some(then) = parse_iso8601(&ts) else {
53 return Ok(()); };
55 if now - then < 45 {
56 return Err("active in the last 45s".into());
57 }
58 Ok(())
59}
60
61fn parse_iso8601(s: &str) -> Option<i64> {
65 taimux_core::turn::epoch_ms(s).map(|ms| ms.div_euclid(1000))
66}
67
68pub fn screen_has_no_dialog(screen: &str) -> Result<(), String> {
73 if state::awaits_input(screen) {
74 return Err("a dialog is waiting for an answer".into());
75 }
76 let tail: Vec<&str> = screen
77 .lines()
78 .filter(|l| !l.trim().is_empty())
79 .rev()
80 .take(4)
81 .collect();
82 if tail
83 .iter()
84 .any(|l| l.contains("Press Ctrl-C again to exit"))
85 {
86 return Err("a Ctrl-C is already half-pressed".into());
87 }
88 Ok(())
89}
90
91pub fn screen_has_no_draft(screen: &str) -> Result<(), String> {
97 let txt: Vec<&str> = screen.lines().filter(|l| !l.trim().is_empty()).collect();
98 if txt.is_empty() {
99 return Ok(());
100 }
101 let Some(box_line) = txt.iter().rev().find(|l| l.contains('❯')) else {
102 return Err("no prompt box on screen".into());
103 };
104 let after = box_line.split_once('❯').map(|(_, r)| r).unwrap_or("");
105 let rest: String = after
106 .chars()
107 .filter(|c| !c.is_whitespace() && *c != '\u{a0}')
108 .collect();
109 if rest.is_empty() {
110 Ok(())
111 } else {
112 Err("unsent text in the prompt box".into())
113 }
114}
115
116const BOX_ROWS: usize = 6;
131
132type Cmd = Vec<String>;
134
135type ZoomSteps = (Vec<Cmd>, Vec<Cmd>);
137
138fn zoom_steps(
154 pane: &str,
155 zoomed: bool,
156 pane_rows: usize,
157 window_rows: usize,
158 active: &str,
159 last: &str,
160) -> Option<ZoomSteps> {
161 if pane_rows >= BOX_ROWS || window_rows < BOX_ROWS || window_rows <= pane_rows {
162 return None;
163 }
164 let cmd = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Cmd>();
165
166 let mut go = Vec::new();
167 if zoomed {
172 go.push(cmd(&["resize-pane", "-Z", "-t", pane]));
173 }
174 go.push(cmd(&["resize-pane", "-Z", "-t", pane]));
175
176 let mut back = vec![cmd(&["resize-pane", "-Z", "-t", pane])];
177 if active != pane {
183 if !last.is_empty() && last != pane {
184 back.push(cmd(&["select-pane", "-t", last]));
185 }
186 if !active.is_empty() {
187 back.push(cmd(&["select-pane", "-t", active]));
188 }
189 }
190 if zoomed && !active.is_empty() {
194 back.push(cmd(&["resize-pane", "-Z", "-t", active]));
195 }
196 Some((go, back))
197}
198
199struct Restoring(Vec<Cmd>);
205
206impl Drop for Restoring {
207 fn drop(&mut self) {
208 for c in &self.0 {
209 tmux::run(&c.iter().map(String::as_str).collect::<Vec<_>>());
210 }
211 }
212}
213
214pub fn capture_zoomed(pane: &str) -> Option<String> {
227 if !taimux_core::env::on("TAIMUX_ZOOM_TO_READ") {
228 return None;
229 }
230 let geom = tmux::ask(&[
231 "display-message",
232 "-p",
233 "-t",
234 pane,
235 "-F",
236 "#{window_zoomed_flag}\t#{pane_height}\t#{window_height}\t#{window_id}",
237 ])?;
238 let g: Vec<&str> = geom.trim_end().split('\t').collect();
239 if g.len() < 4 {
240 return None;
241 }
242 let (zoomed, win) = (g[0] == "1", g[3]);
243 let pane_rows: usize = g[1].parse().ok()?;
244 let window_rows: usize = g[2].parse().ok()?;
245
246 let mut active = String::new();
247 let mut last = String::new();
248 for l in tmux::ask(&[
249 "list-panes",
250 "-t",
251 win,
252 "-F",
253 "#{pane_id}\t#{pane_active}\t#{pane_last}",
254 ])?
255 .lines()
256 {
257 let c: Vec<&str> = l.split('\t').collect();
258 if c.len() < 3 {
259 continue;
260 }
261 if c[1] == "1" {
262 active = c[0].to_string();
263 }
264 if c[2] == "1" {
265 last = c[0].to_string();
266 }
267 }
268
269 let (go, back) = zoom_steps(pane, zoomed, pane_rows, window_rows, &active, &last)?;
270 for c in &go {
271 tmux::run(&c.iter().map(String::as_str).collect::<Vec<_>>());
272 }
273 let _restore = Restoring(back);
274
275 let deadline = std::time::Instant::now() + std::time::Duration::from_millis(500);
276 loop {
277 let screen = tmux::capture(pane).unwrap_or_default();
278 if screen.contains('❯') || std::time::Instant::now() >= deadline {
279 return Some(screen);
280 }
281 std::thread::sleep(std::time::Duration::from_millis(10));
282 }
283}
284
285pub fn version_of_pid(pid: i32, versions_dir: &str) -> Option<String> {
289 let exe = std::fs::read_link(format!("/proc/{}/exe", pid)).ok()?;
290 let exe = exe.to_string_lossy();
291 let exe = exe.trim_end_matches(" (deleted)"); let prefix = format!("{}/", versions_dir);
293 exe.strip_prefix(&prefix)
294 .filter(|rest| !rest.is_empty())
295 .map(|rest| rest.split('/').next().unwrap_or(rest).to_string())
296}
297
298pub struct Planned {
300 pub pane: String,
301 pub target: String,
302 pub pid: i32,
303 pub cmd: String,
304 pub title: String,
305 pub via: String,
306}
307
308pub struct Plan {
309 pub newver: String,
310 pub launcher: String,
311 pub go: Vec<Planned>,
312 pub skipped: Vec<String>,
313 pub unresolved: bool,
316}
317
318pub struct Opts {
319 pub include_busy: bool,
320 pub only_panes: Vec<String>,
321 pub force_transcript: Option<String>,
322 pub self_pane: String,
323}
324
325pub trait Env {
328 fn capture(&self, pane: &str) -> String;
329 fn capture_zoomed(&self, _pane: &str) -> Option<String> {
336 None
337 }
338 fn hook_state(&self, pane: &str, pid: i32) -> Option<String>;
339 fn own_state(&self, _pid: i32) -> Option<state::State> {
343 None
344 }
345 fn moved_to(&self, _pid: i32) -> Option<String> {
348 None
349 }
350 fn version_of_pid(&self, pid: i32) -> Option<String>;
351 fn cwd_of(&self, pid: i32) -> Option<String>;
352 fn argv_of(&self, pid: i32) -> Vec<String>;
353 fn resolve(&self, pane: &str, cwd: &str, title: &str, pid: i32) -> Result<String, String>;
354 fn read_transcript(&self, path: &str) -> Option<String>;
355 fn now(&self) -> i64;
356}
357
358pub fn plan(
364 rows: &str,
365 newver: &str,
366 launcher: &str,
367 o: &Opts,
368 e: &dyn Env,
369 versions_dir: &str,
370 agents: &dyn Fn() -> String,
371) -> Plan {
372 let mut p = Plan {
373 newver: newver.to_string(),
374 launcher: launcher.to_string(),
375 go: Vec::new(),
376 skipped: Vec::new(),
377 unresolved: false,
378 };
379 let mut claimed: HashMap<String, String> = HashMap::new();
380 let mut matched: Vec<i32> = Vec::new();
383
384 for line in rows.lines() {
385 let f: Vec<&str> = line.split('\t').collect();
386 if f.len() < 7 || f[3] != "claude" {
387 continue;
388 }
389 let (id, tgt, cwd, title) = (f[0], f[1], f[2], f[6]);
390 let pid: i32 = f[4].parse().unwrap_or(0);
391
392 let Some(ver) = (pid != 0).then(|| e.version_of_pid(pid)).flatten() else {
393 p.skipped.push(format!(
394 "{} {} looks like claude but no session process was found under the pane",
395 id, tgt
396 ));
397 continue;
398 };
399 matched.push(pid);
400 if !o.only_panes.is_empty() && !o.only_panes.iter().any(|w| w == id) {
401 continue;
402 }
403 if ver == newver {
404 continue; }
406 if id == o.self_pane {
407 p.skipped.push(format!(
408 "{} {} {}, this pane: restart it by hand (killing it would kill taimux)",
409 id, tgt, ver
410 ));
411 continue;
412 }
413
414 let mut screen = e.capture(id);
415 if !screen.contains('❯') {
424 if let Some(bigger) = e.capture_zoomed(id) {
425 screen = bigger;
426 }
427 }
428 let hook = e.hook_state(id, pid);
429 let st = state::reading(&screen, e.own_state(pid), hook.as_deref());
430 if st.as_str() != "idle" && !o.include_busy {
431 p.skipped.push(format!(
432 "{} {} {}, {}: rerun when idle, or --include-busy",
433 id,
434 tgt,
435 ver,
436 st.as_str()
437 ));
438 continue;
439 }
440 if state::background(&screen, hook.as_deref()) && !o.include_busy {
446 p.skipped.push(format!(
447 "{} {} {}, work still in flight: rerun once it reports back, or --include-busy",
448 id, tgt, ver
449 ));
450 continue;
451 }
452
453 if let Some(sid) = e.moved_to(pid) {
457 let short = sid.get(..8).unwrap_or(&sid);
458 p.skipped.push(format!(
459 "{} {} {}, its conversation moved to background session {}: claude attach {}",
460 id, tgt, ver, short, short
461 ));
462 continue;
463 }
464
465 let ccwd = e.cwd_of(pid).unwrap_or_else(|| cwd.to_string());
466 let (transcript, via) = match &o.force_transcript {
467 Some(t) => (t.clone(), "--transcript, given".to_string()),
468 None => match e.resolve(id, &ccwd, title, pid) {
469 Ok(t) => {
470 let (path, why) = t.split_once('\t').unwrap_or((t.as_str(), ""));
472 (path.to_string(), why.to_string())
473 }
474 Err(why) => {
475 p.skipped
476 .push(format!("{} {} {}, unresolved: {}", id, tgt, ver, why));
477 p.unresolved = true;
478 continue;
479 }
480 },
481 };
482
483 if let Err(why) = screen_has_no_dialog(&screen) {
484 p.skipped
485 .push(format!("{} {} {}, not settled: {}", id, tgt, ver, why));
486 continue;
487 }
488 if !o.include_busy {
489 let settled =
490 screen_has_no_draft(&screen).and_then(|()| match e.read_transcript(&transcript) {
491 Some(text) => transcript_is_settled(&text, e.now()),
492 None => Ok(()),
493 });
494 if let Err(why) = settled {
495 p.skipped
496 .push(format!("{} {} {}, not settled: {}", id, tgt, ver, why));
497 continue;
498 }
499 }
500
501 if let Some(first) = claimed.get(&transcript) {
502 p.skipped.push(format!(
503 "{} {} {}, resolves to the same transcript as {}",
504 id, tgt, ver, first
505 ));
506 continue;
507 }
508 claimed.insert(transcript.clone(), id.to_string());
509
510 let Some(cmd) = conv::build_cmd(&e.argv_of(pid), &transcript, &ccwd, cwd) else {
511 p.skipped
512 .push(format!("{} {} {}, could not read its argv", id, tgt, ver));
513 continue;
514 };
515 p.go.push(Planned {
516 pane: id.to_string(),
517 target: tgt.to_string(),
518 pid,
519 cmd,
520 title: title.to_string(),
521 via: format!("{} -> {}, {}, {}", ver, newver, via, st.as_str()),
522 });
523 }
524
525 let mut agents_json: Option<String> = None;
530 for np in nonpane_pids(&matched, versions_dir) {
531 let Some(ver) = e.version_of_pid(np) else {
532 continue;
533 };
534 if ver == newver {
535 continue;
536 }
537 let j = agents_json.get_or_insert_with(agents);
538 p.skipped.push(format!(
539 "pid {} {}, not a tmux pane: {}",
540 np,
541 ver,
542 describe_nonpane(&e.argv_of(np), j)
543 ));
544 }
545 p
546}
547
548pub fn render(p: &Plan) -> String {
551 let mut s = format!("claude: {} installed at {}\n\n", p.newver, p.launcher);
552 if p.go.is_empty() {
553 s.push_str("nothing to restart.\n");
554 } else {
555 s.push_str(&format!("to restart ({}):\n", p.go.len()));
556 for g in &p.go {
557 s.push_str(&format!(" {:<5} {:<14} {}\n", g.pane, g.target, g.title));
558 s.push_str(&format!(" {}\n", g.via));
559 s.push_str(&format!(" {}\n", g.cmd));
560 }
561 }
562 if !p.skipped.is_empty() {
563 s.push_str(&format!("\nskipped ({}):\n", p.skipped.len()));
564 for k in &p.skipped {
565 s.push_str(&format!(" {}\n", k));
566 }
567 }
568 if p.unresolved {
569 s.push_str(
570 "\nAn unresolved pane means guessing, so it was left alone: restart it by hand\n\
571 with `claude -c` in that pane, or from its /resume picker. Each session records\n\
572 its pane at the next SessionStart, so a pane resolves cleanly once restarted.\n",
573 );
574 }
575 s
576}
577
578pub fn restart_pane(pane: &str, pid: i32, cmd: &str) -> bool {
585 use std::thread::sleep;
586 use std::time::Duration;
587
588 tmux::run(&["send-keys", "-t", pane, "C-c"]);
589 sleep(Duration::from_millis(300));
590 tmux::run(&["send-keys", "-t", pane, "C-c"]);
591
592 let mut waited = 0;
593 let mut sent_exit = false;
594 while alive(pid) {
595 sleep(Duration::from_millis(400));
596 waited += 1;
597 if waited >= 6 && !sent_exit {
598 tmux::run(&["send-keys", "-t", pane, "/exit", "Enter"]);
599 sent_exit = true;
600 }
601 if waited >= 30 {
602 return false;
603 }
604 }
605 sleep(Duration::from_millis(500));
606 tmux::run(&["send-keys", "-t", pane, "C-c"]);
607 sleep(Duration::from_millis(200));
608 tmux::run(&["send-keys", "-t", pane, cmd, "Enter"])
609}
610
611fn alive(pid: i32) -> bool {
614 std::path::Path::new(&format!("/proc/{}", pid)).exists()
615}
616
617pub fn confirm_yes(answer: &str) -> bool {
620 matches!(answer.trim(), "" | "y" | "Y" | "yes" | "YES" | "Yes")
621}
622
623pub struct Live {
625 pub versions_dir: String,
626}
627
628impl Env for Live {
629 fn capture(&self, pane: &str) -> String {
630 tmux::ask_raw(&["capture-pane", "-p", "-t", pane]).unwrap_or_default()
631 }
632 fn capture_zoomed(&self, pane: &str) -> Option<String> {
633 capture_zoomed(pane)
634 }
635 fn hook_state(&self, pane: &str, pid: i32) -> Option<String> {
636 taimux_core::hook::hook_state_of(pane, pid)
637 }
638 fn own_state(&self, pid: i32) -> Option<state::State> {
639 taimux_core::status::of(pid).and_then(|o| o.state())
640 }
641 fn moved_to(&self, pid: i32) -> Option<String> {
642 taimux_core::status::of(pid)
643 .filter(|o| o.via == taimux_core::status::Via::MovedTo)
644 .map(|o| o.session_id)
645 }
646 fn version_of_pid(&self, pid: i32) -> Option<String> {
647 version_of_pid(pid, &self.versions_dir)
648 }
649 fn cwd_of(&self, pid: i32) -> Option<String> {
650 std::fs::read_link(format!("/proc/{}/cwd", pid))
651 .ok()
652 .map(|p| p.to_string_lossy().into_owned())
653 .filter(|s| !s.is_empty())
654 }
655 fn argv_of(&self, pid: i32) -> Vec<String> {
656 conv::argv_of(pid)
657 }
658 fn resolve(&self, pane: &str, cwd: &str, title: &str, pid: i32) -> Result<String, String> {
659 conv::resolve(pane, cwd, title, pid)
660 .map(|r| format!("{}\t{}", r.transcript.display(), r.why))
661 }
662 fn read_transcript(&self, path: &str) -> Option<String> {
663 std::fs::read_to_string(path).ok()
664 }
665 fn now(&self) -> i64 {
666 std::time::SystemTime::now()
667 .duration_since(std::time::UNIX_EPOCH)
668 .map(|d| d.as_secs() as i64)
669 .unwrap_or(0)
670 }
671}
672
673pub fn installed(launcher: &str, versions_dir: &str) -> Result<String, String> {
676 let target = std::fs::canonicalize(launcher)
677 .map(|p| p.to_string_lossy().into_owned())
678 .unwrap_or_default();
679 let prefix = format!("{}/", versions_dir);
680 match target.strip_prefix(&prefix) {
681 Some(rest) if !rest.is_empty() => Ok(rest.split('/').next().unwrap_or(rest).to_string()),
682 _ => Err(format!(
683 "restart: {} does not point into {} (got '{}')",
684 launcher,
685 versions_dir,
686 if target.is_empty() {
687 "nothing"
688 } else {
689 &target
690 }
691 )),
692 }
693}
694
695pub fn versions_dir() -> String {
696 format!(
697 "{}/.local/share/claude/versions",
698 std::env::var("HOME").unwrap_or_default()
699 )
700}
701
702pub fn launcher() -> String {
703 format!(
704 "{}/.local/bin/claude",
705 std::env::var("HOME").unwrap_or_default()
706 )
707}
708
709#[cfg(test)]
710mod tests {
711 use super::*;
712
713 #[test]
714 fn a_timestamp_becomes_epoch_seconds() {
715 assert_eq!(parse_iso8601("2026-09-02T01:23:45.678Z"), Some(1788312225));
717 assert_eq!(parse_iso8601("1970-01-01T00:00:00Z"), Some(0));
718 assert_eq!(parse_iso8601("2024-02-29T00:00:00Z"), Some(1709164800));
720 }
721
722 #[test]
726 fn an_unparseable_timestamp_is_no_answer() {
727 assert_eq!(parse_iso8601(""), None);
728 assert_eq!(parse_iso8601("yesterday"), None);
729 assert_eq!(parse_iso8601("2026-09-02 01:23:45"), None);
730 assert_eq!(parse_iso8601("2026-13-02T01:23:45Z"), None);
731 }
732
733 #[test]
734 fn a_tool_call_still_running_is_not_settled() {
735 let t = r#"{"type":"assistant","message":{"content":[{"type":"tool_use"}]},"timestamp":"2020-01-01T00:00:00Z"}"#;
736 assert_eq!(
737 transcript_is_settled(t, 1788312225),
738 Err("a tool call is still running".into())
739 );
740 }
741
742 #[test]
744 fn recent_activity_is_not_settled_whatever_the_screen_said() {
745 let t = r#"{"type":"user","timestamp":"2026-09-02T01:23:45Z"}"#;
746 assert!(transcript_is_settled(t, 1788312225 + 10).is_err());
747 assert!(transcript_is_settled(t, 1788312225 + 100).is_ok());
748 }
749
750 #[test]
751 fn an_empty_or_odd_transcript_does_not_block() {
752 assert!(transcript_is_settled("", 0).is_ok());
753 assert!(transcript_is_settled("not json at all\n", 0).is_ok());
754 assert!(transcript_is_settled(r#"{"type":"user"}"#, 0).is_ok());
756 }
757
758 #[test]
762 fn a_dialog_on_screen_blocks_a_restart() {
763 let footer = "some output\n\nDo you want to proceed?\n";
764 assert_eq!(
765 screen_has_no_dialog(footer),
766 Err("a dialog is waiting for an answer".into())
767 );
768 let choice = "some output\n1. Yes\n2. No\n❯ 1. Yes\n";
769 assert_eq!(
770 screen_has_no_dialog(choice),
771 Err("a dialog is waiting for an answer".into())
772 );
773 assert!(screen_has_no_dialog("some output\n❯ \n").is_ok());
775 }
776
777 #[test]
780 fn a_half_pressed_ctrl_c_blocks_a_restart() {
781 let screen = "work\n\nPress Ctrl-C again to exit\n";
782 assert_eq!(
783 screen_has_no_dialog(screen),
784 Err("a Ctrl-C is already half-pressed".into())
785 );
786 }
787
788 #[test]
789 fn an_empty_prompt_box_is_no_draft() {
790 assert!(screen_has_no_draft("stuff\n❯ \n").is_ok());
791 assert!(screen_has_no_draft("stuff\n❯ \u{a0}\u{a0}\n").is_ok());
793 assert_eq!(
794 screen_has_no_draft("stuff\n❯ half a thought\n"),
795 Err("unsent text in the prompt box".into())
796 );
797 }
798
799 #[test]
802 fn a_pane_tall_enough_to_read_is_left_alone() {
803 assert!(zoom_steps("%1", false, 6, 40, "%2", "%3").is_none());
805 assert!(zoom_steps("%1", false, 40, 40, "%2", "%3").is_none());
806 assert!(zoom_steps("%1", false, 3, 3, "%2", "%3").is_none());
808 assert!(zoom_steps("%1", false, 3, 5, "%2", "%3").is_none());
809 }
810
811 #[test]
815 fn a_short_pane_is_zoomed_and_the_selection_put_back() {
816 let (go, back) = zoom_steps("%1", false, 3, 17, "%2", "%3").unwrap();
817 assert_eq!(go, vec![vec!["resize-pane", "-Z", "-t", "%1"]]);
818 assert_eq!(
819 back,
820 vec![
821 vec!["resize-pane", "-Z", "-t", "%1"],
822 vec!["select-pane", "-t", "%3"],
823 vec!["select-pane", "-t", "%2"],
824 ]
825 );
826 }
827
828 #[test]
832 fn a_window_zoomed_elsewhere_is_handed_back_zoomed() {
833 let (go, back) = zoom_steps("%1", true, 3, 17, "%2", "%3").unwrap();
834 assert_eq!(
835 go,
836 vec![
837 vec!["resize-pane", "-Z", "-t", "%1"],
838 vec!["resize-pane", "-Z", "-t", "%1"],
839 ]
840 );
841 assert_eq!(
842 back,
843 vec![
844 vec!["resize-pane", "-Z", "-t", "%1"],
845 vec!["select-pane", "-t", "%3"],
846 vec!["select-pane", "-t", "%2"],
847 vec!["resize-pane", "-Z", "-t", "%2"],
848 ]
849 );
850 }
851
852 #[test]
855 fn an_active_short_pane_has_no_selection_to_restore() {
856 let (go, back) = zoom_steps("%1", false, 3, 17, "%1", "%3").unwrap();
857 assert_eq!(go.len(), 1);
858 assert_eq!(back, vec![vec!["resize-pane", "-Z", "-t", "%1"]]);
859 }
860
861 #[test]
864 fn no_prompt_box_is_a_refusal() {
865 assert_eq!(
866 screen_has_no_draft("just some text\n"),
867 Err("no prompt box on screen".into())
868 );
869 assert!(screen_has_no_draft("").is_ok());
871 assert!(screen_has_no_draft(" \n\n").is_ok());
872 }
873
874 #[test]
875 fn a_bare_enter_confirms() {
876 assert!(confirm_yes(""));
877 assert!(confirm_yes("y"));
878 assert!(confirm_yes("YES"));
879 assert!(!confirm_yes("n"));
880 assert!(!confirm_yes("no"));
881 assert!(!confirm_yes("maybe"));
882 }
883
884 #[test]
885 fn the_launcher_must_point_into_the_versions_dir() {
886 let root = std::env::temp_dir().join(format!("jmrs{}", std::process::id()));
887 let vers = root.join("versions");
888 std::fs::create_dir_all(&vers).unwrap();
889 std::fs::write(vers.join("2.1.258"), "x").unwrap();
890 let link = root.join("claude");
891 std::os::unix::fs::symlink(vers.join("2.1.258"), &link).unwrap();
892 assert_eq!(
893 installed(&link.to_string_lossy(), &vers.to_string_lossy()),
894 Ok("2.1.258".into())
895 );
896 std::fs::write(root.join("elsewhere"), "x").unwrap();
898 std::fs::remove_file(&link).unwrap();
899 std::os::unix::fs::symlink(root.join("elsewhere"), &link).unwrap();
900 let e = installed(&link.to_string_lossy(), &vers.to_string_lossy()).expect_err("refused");
901 assert!(e.contains("elsewhere"));
902 let _ = std::fs::remove_dir_all(&root);
903 }
904}
905
906pub fn nonpane_pids(matched: &[i32], versions_dir: &str) -> Vec<i32> {
912 let mut out = Vec::new();
913 for e in std::fs::read_dir("/proc").into_iter().flatten().flatten() {
914 let Some(pid) = e.file_name().to_str().and_then(|s| s.parse::<i32>().ok()) else {
915 continue;
916 };
917 if matched.contains(&pid) {
918 continue;
919 }
920 let comm = std::fs::read_to_string(format!("/proc/{}/comm", pid)).unwrap_or_default();
923 let argv = conv::argv_of(pid);
924 let is_claude = comm.trim() == "claude"
925 || argv
926 .first()
927 .map(|a| a.starts_with(&format!("{}/", versions_dir)))
928 .unwrap_or(false);
929 if is_claude {
930 out.push(pid);
931 }
932 }
933 out.sort_unstable();
934 out
935}
936
937fn json_object_with_prefix(text: &str, key: &str, prefix: &str) -> Option<String> {
945 let needle = format!("\"{}\":\"{}", key, prefix);
946 let at = text.find(&needle).or_else(|| {
947 let spaced = format!("\"{}\": \"{}", key, prefix);
948 text.find(&spaced)
949 })?;
950 let mut depth = 0i32;
952 let bytes = text.as_bytes();
953 let mut start = None;
954 for i in (0..at).rev() {
955 match bytes[i] {
956 b'}' => depth += 1,
957 b'{' => {
958 if depth == 0 {
959 start = Some(i);
960 break;
961 }
962 depth -= 1;
963 }
964 _ => {}
965 }
966 }
967 let start = start?;
968 let mut depth = 0i32;
970 for i in start..bytes.len() {
971 match bytes[i] {
972 b'{' => depth += 1,
973 b'}' => {
974 depth -= 1;
975 if depth == 0 {
976 return Some(text[start..=i].to_string());
977 }
978 }
979 _ => {}
980 }
981 }
982 None
983}
984
985pub fn describe_nonpane(argv: &[String], agents_json: &str) -> String {
992 if argv.is_empty() {
993 return "gone".into();
994 }
995 let (mut sid, mut res, mut forked) = (String::new(), String::new(), false);
996 for i in 1..argv.len() {
997 match argv[i].as_str() {
998 "--fork-session" => forked = true,
999 "--session-id" => sid = argv.get(i + 1).cloned().unwrap_or_default(),
1000 "-r" | "--resume" => res = argv.get(i + 1).cloned().unwrap_or_default(),
1001 _ => {}
1002 }
1003 }
1004 let own = base_id(if sid.is_empty() { &res } else { &sid });
1005 let parent = if forked && !res.is_empty() {
1006 base_id(&res)
1007 } else {
1008 String::new()
1009 };
1010
1011 let (mut kind, mut st, mut name) = ("?".to_string(), "?".to_string(), String::new());
1012 if !own.is_empty() {
1013 if let Some(obj) = json_object_with_prefix(agents_json, "sessionId", &own) {
1014 let f = |k: &str| taimux_core::json::field(&obj, k);
1015 let k = f("kind");
1016 if !k.is_empty() {
1017 kind = k;
1018 }
1019 let s = {
1020 let a = f("state");
1021 if a.is_empty() {
1022 f("status")
1023 } else {
1024 a
1025 }
1026 };
1027 if !s.is_empty() {
1028 st = s;
1029 }
1030 name = f("name");
1031 }
1032 }
1033 let mut out = format!("{} {}", kind, st);
1034 if forked {
1035 out.push_str(" fork");
1036 }
1037 if !name.is_empty() {
1038 out.push_str(&format!(" \"{}\"", name));
1039 }
1040 if !own.is_empty() {
1041 out.push_str(&format!(" [{}]", own.chars().take(8).collect::<String>()));
1042 }
1043 if !parent.is_empty() {
1044 out.push_str(&format!(
1045 " of [{}]",
1046 parent.chars().take(8).collect::<String>()
1047 ));
1048 }
1049 out
1050}
1051
1052fn base_id(s: &str) -> String {
1054 if s.is_empty() {
1055 return String::new();
1056 }
1057 let b = s.rsplit('/').next().unwrap_or(s);
1058 b.strip_suffix(".jsonl").unwrap_or(b).to_string()
1059}
1060
1061#[cfg(test)]
1062mod nonpane_tests {
1063 use super::*;
1064
1065 fn v(a: &[&str]) -> Vec<String> {
1066 a.iter().map(|s| s.to_string()).collect()
1067 }
1068
1069 #[test]
1070 fn a_session_id_is_read_out_of_a_path_or_taken_as_it_stands() {
1071 assert_eq!(base_id("/a/b/263946b5-9bd7.jsonl"), "263946b5-9bd7");
1072 assert_eq!(base_id("263946b5"), "263946b5");
1073 assert_eq!(base_id(""), "");
1074 }
1075
1076 #[test]
1080 fn the_right_object_comes_back_whole() {
1081 let j = r#"[{"sessionId":"aaa111","kind":"task","meta":{"a":1},"name":"first"},
1082 {"sessionId":"bbb222","kind":"agent","name":"second"}]"#;
1083 let o = json_object_with_prefix(j, "sessionId", "bbb222").expect("found");
1084 assert!(o.contains("second"));
1085 assert!(!o.contains("first"));
1086 let o = json_object_with_prefix(j, "sessionId", "aaa").expect("found by prefix");
1087 assert!(o.contains("first"));
1088 assert!(
1089 o.contains("\"meta\":{\"a\":1}"),
1090 "nested field truncated: {}",
1091 o
1092 );
1093 assert!(json_object_with_prefix(j, "sessionId", "zzz").is_none());
1094 }
1095
1096 #[test]
1097 fn a_process_with_no_argv_is_simply_gone() {
1098 assert_eq!(describe_nonpane(&[], "[]"), "gone");
1099 }
1100
1101 #[test]
1102 fn an_unnamed_session_still_says_what_it_can() {
1103 let d = describe_nonpane(&v(&["claude", "--session-id", "263946b5-9bd7"]), "[]");
1104 assert_eq!(d, "? ? [263946b5]");
1105 }
1106
1107 #[test]
1108 fn a_named_one_says_kind_state_and_name() {
1109 let j =
1110 r#"[{"sessionId":"263946b5-9bd7","kind":"task","state":"running","name":"the thing"}]"#;
1111 let d = describe_nonpane(&v(&["claude", "--session-id", "263946b5-9bd7"]), j);
1112 assert_eq!(d, "task running \"the thing\" [263946b5]");
1113 }
1114
1115 #[test]
1118 fn status_stands_in_for_state() {
1119 let j = r#"[{"sessionId":"aaa11111","kind":"agent","status":"idle"}]"#;
1120 let d = describe_nonpane(&v(&["claude", "--session-id", "aaa11111"]), j);
1121 assert_eq!(d, "agent idle [aaa11111]");
1122 }
1123
1124 #[test]
1127 fn a_fork_names_its_parent_too() {
1128 let d = describe_nonpane(
1129 &v(&[
1130 "claude",
1131 "--session-id",
1132 "child111",
1133 "--fork-session",
1134 "--resume",
1135 "/p/parent22.jsonl",
1136 ]),
1137 "[]",
1138 );
1139 assert_eq!(d, "? ? fork [child111] of [parent22]");
1140 }
1141}
1142
1143#[cfg(test)]
1144mod plan_tests {
1145 use super::*;
1146
1147 struct Fake {
1152 vers: HashMap<i32, String>,
1154 screens: HashMap<String, String>,
1156 resolved: HashMap<String, Result<String, String>>,
1158 zoomed: HashMap<String, String>,
1161 zooms: std::cell::Cell<usize>,
1164 hooks: HashMap<String, String>,
1166 own: HashMap<i32, state::State>,
1168 moved: HashMap<i32, String>,
1170 transcript: String,
1171 now: i64,
1172 }
1173
1174 impl Env for Fake {
1175 fn capture(&self, pane: &str) -> String {
1176 self.screens.get(pane).cloned().unwrap_or_default()
1177 }
1178 fn capture_zoomed(&self, pane: &str) -> Option<String> {
1179 let bigger = self.zoomed.get(pane).cloned();
1180 if bigger.is_some() {
1181 self.zooms.set(self.zooms.get() + 1);
1182 }
1183 bigger
1184 }
1185 fn hook_state(&self, pane: &str, _pid: i32) -> Option<String> {
1186 self.hooks.get(pane).cloned()
1187 }
1188 fn own_state(&self, pid: i32) -> Option<state::State> {
1189 self.own.get(&pid).copied()
1190 }
1191 fn moved_to(&self, pid: i32) -> Option<String> {
1192 self.moved.get(&pid).cloned()
1193 }
1194 fn version_of_pid(&self, pid: i32) -> Option<String> {
1195 self.vers.get(&pid).cloned()
1196 }
1197 fn cwd_of(&self, _pid: i32) -> Option<String> {
1198 Some("/w".into())
1199 }
1200 fn argv_of(&self, _pid: i32) -> Vec<String> {
1201 vec!["claude".into()]
1202 }
1203 fn resolve(&self, pane: &str, _c: &str, _t: &str, _p: i32) -> Result<String, String> {
1204 self.resolved
1205 .get(pane)
1206 .cloned()
1207 .unwrap_or_else(|| Err("no candidate".into()))
1208 }
1209 fn read_transcript(&self, _path: &str) -> Option<String> {
1210 Some(self.transcript.clone())
1211 }
1212 fn now(&self) -> i64 {
1213 self.now
1214 }
1215 }
1216
1217 fn fake() -> Fake {
1218 let mut vers = HashMap::new();
1219 vers.insert(11, "2.1.100".to_string()); vers.insert(22, "2.1.258".to_string()); let mut screens = HashMap::new();
1222 screens.insert("%1".to_string(), "some output\n❯ \n".to_string());
1224 screens.insert("%2".to_string(), "some output\n❯ \n".to_string());
1225 let mut resolved = HashMap::new();
1226 resolved.insert("%1".to_string(), Ok("/t/a.jsonl\tpane map".to_string()));
1227 Fake {
1228 vers,
1229 screens,
1230 resolved,
1231 zoomed: HashMap::new(),
1232 zooms: std::cell::Cell::new(0),
1233 hooks: HashMap::new(),
1234 own: HashMap::new(),
1235 moved: HashMap::new(),
1236 transcript: r#"{"type":"user","timestamp":"2020-01-01T00:00:00Z"}"#.to_string(),
1237 now: 1788312225,
1238 }
1239 }
1240
1241 fn opts() -> Opts {
1242 Opts {
1243 include_busy: false,
1244 only_panes: Vec::new(),
1245 force_transcript: None,
1246 self_pane: String::new(),
1247 }
1248 }
1249
1250 const ROWS: &str = "%1\tw:1.1\t/w\tclaude\t11\tclaude\tproj: the stale one\n\
1251 %2\tw:2.1\t/w\tclaude\t22\tclaude\tproj: the current one";
1252
1253 fn plan_of(e: &Fake, o: &Opts) -> Plan {
1254 plan(ROWS, "2.1.258", "/l/claude", o, e, "/nowhere", &|| {
1255 "[]".into()
1256 })
1257 }
1258
1259 #[test]
1260 fn a_stale_pane_is_planned_and_a_current_one_is_not() {
1261 let p = plan_of(&fake(), &opts());
1262 assert_eq!(p.go.len(), 1);
1263 assert_eq!(p.go[0].pane, "%1");
1264 assert_eq!(p.go[0].cmd, "command claude --resume /t/a.jsonl");
1265 assert_eq!(p.go[0].via, "2.1.100 -> 2.1.258, pane map, idle");
1266 assert!(p.skipped.is_empty());
1267 }
1268
1269 #[test]
1272 fn the_rendered_plan_reads_the_way_it_always_did() {
1273 let out = render(&plan_of(&fake(), &opts()));
1274 assert_eq!(
1275 out,
1276 "claude: 2.1.258 installed at /l/claude\n\n\
1277 to restart (1):\n\
1278 \x20 %1 w:1.1 proj: the stale one\n\
1279 \x20 2.1.100 -> 2.1.258, pane map, idle\n\
1280 \x20 command claude --resume /t/a.jsonl\n"
1281 );
1282 }
1283
1284 #[test]
1286 fn this_pane_is_never_restarted() {
1287 let mut o = opts();
1288 o.self_pane = "%1".into();
1289 let p = plan_of(&fake(), &o);
1290 assert!(p.go.is_empty());
1291 assert!(p.skipped[0].contains("this pane"));
1292 assert!(p.skipped[0].contains("killing it would kill taimux"));
1293 }
1294
1295 #[test]
1296 fn a_pane_that_is_not_idle_waits_for_include_busy() {
1297 let mut e = fake();
1298 e.screens
1300 .insert("%1".into(), "Twisting… (35s · ↓ 1.6k tokens)\n❯ \n".into());
1301 let p = plan_of(&e, &opts());
1302 assert!(p.go.is_empty());
1303 assert!(p.skipped[0].contains("rerun when idle, or --include-busy"));
1304
1305 let mut o = opts();
1306 o.include_busy = true;
1307 assert_eq!(plan_of(&e, &o).go.len(), 1);
1308 }
1309
1310 #[test]
1314 fn a_session_that_says_it_is_busy_is_busy() {
1315 let mut e = fake();
1316 e.hooks.insert("%1".into(), "input".into());
1317 e.own.insert(11, state::State::Run);
1318 let p = plan_of(&e, &opts());
1319 assert!(p.go.is_empty());
1320 assert!(
1321 p.skipped[0].contains("run: rerun when idle"),
1322 "{:?}",
1323 p.skipped
1324 );
1325 e.hooks.insert("%1".into(), "run".into());
1327 e.own.insert(11, state::State::Idle);
1328 assert_eq!(plan_of(&e, &opts()).go.len(), 1);
1329 }
1330
1331 #[test]
1335 fn a_pane_whose_conversation_moved_to_the_background_is_left_alone() {
1336 let mut e = fake();
1337 e.own.insert(11, state::State::Idle);
1338 e.moved
1339 .insert(11, "2447b564-7a96-4774-b70a-ef4b730bdd4d".into());
1340 let mut o = opts();
1341 o.include_busy = true; let p = plan_of(&e, &o);
1343 assert!(p.go.is_empty());
1344 assert!(
1345 p.skipped[0].contains("moved to background session 2447b564: claude attach 2447b564"),
1346 "{:?}",
1347 p.skipped
1348 );
1349 }
1350
1351 #[test]
1354 fn a_pane_with_work_in_flight_waits_for_include_busy() {
1355 let mut e = fake();
1356 e.screens.insert(
1357 "%1".into(),
1358 "✻ Cogitated for 1m 3s · done 4:55 PM · 2 shells still running\n❯ \n".into(),
1359 );
1360 let p = plan_of(&e, &opts());
1361 assert!(p.go.is_empty());
1362 assert!(
1363 p.skipped[0].contains("work still in flight"),
1364 "{:?}",
1365 p.skipped
1366 );
1367
1368 let mut e = fake();
1370 e.hooks.insert("%1".into(), "bg".into());
1371 let p = plan_of(&e, &opts());
1372 assert!(p.go.is_empty());
1373 assert!(
1374 p.skipped[0].contains("work still in flight"),
1375 "{:?}",
1376 p.skipped
1377 );
1378
1379 let mut o = opts();
1380 o.include_busy = true;
1381 assert_eq!(plan_of(&e, &o).go.len(), 1);
1382 }
1383
1384 #[test]
1387 fn a_dialog_blocks_a_restart_even_with_include_busy() {
1388 let mut e = fake();
1389 e.screens
1390 .insert("%1".into(), "output\n\nDo you want to proceed?\n".into());
1391 let mut o = opts();
1392 o.include_busy = true;
1393 let p = plan_of(&e, &o);
1394 assert!(p.go.is_empty());
1395 assert!(p.skipped[0].contains("a dialog is waiting for an answer"));
1396 }
1397
1398 #[test]
1399 fn an_unsent_draft_is_left_alone() {
1400 let mut e = fake();
1401 e.screens
1402 .insert("%1".into(), "output\n❯ half a thought\n".into());
1403 let p = plan_of(&e, &opts());
1404 assert!(p.skipped[0].contains("unsent text in the prompt box"));
1405 }
1406
1407 #[test]
1411 fn a_pane_too_short_for_its_box_is_read_zoomed() {
1412 let mut e = fake();
1413 e.screens.insert(
1414 "%1".into(),
1415 " current: 2.1.100 · latest…\n────────\n".into(),
1416 );
1417 e.zoomed.insert("%1".into(), "some output\n❯ \n".into());
1418 let p = plan_of(&e, &opts());
1419 assert_eq!(e.zooms.get(), 1);
1420 assert_eq!(p.go.len(), 1);
1421 assert_eq!(p.go[0].pane, "%1");
1422 assert!(p.skipped.is_empty());
1423 }
1424
1425 #[test]
1430 fn a_draft_hidden_by_a_short_pane_still_refuses() {
1431 let mut e = fake();
1432 e.screens
1433 .insert("%1".into(), " current: 2.1.100…\n".into());
1434 e.zoomed
1435 .insert("%1".into(), "output\n❯ half a thought\n".into());
1436 let p = plan_of(&e, &opts());
1437 assert_eq!(e.zooms.get(), 1);
1438 assert!(p.go.is_empty());
1439 assert!(p.skipped[0].contains("unsent text in the prompt box"));
1440 }
1441
1442 #[test]
1446 fn a_dialog_hidden_by_a_short_pane_is_found_by_the_zoom() {
1447 let mut e = fake();
1448 e.screens.insert("%1".into(), " Bash command\n".into());
1449 e.zoomed.insert(
1450 "%1".into(),
1451 "Do you want to proceed?\n❯ 1. Yes\n 2. No\n".into(),
1452 );
1453 let mut o = opts();
1454 o.include_busy = true;
1455 let p = plan_of(&e, &o);
1456 assert!(p.go.is_empty());
1457 assert!(p.skipped[0].contains("a dialog is waiting for an answer"));
1458 }
1459
1460 #[test]
1463 fn a_pane_that_shows_its_box_is_not_zoomed() {
1464 let e = fake();
1465 let p = plan_of(&e, &opts());
1466 assert_eq!(e.zooms.get(), 0);
1467 assert_eq!(p.go.len(), 1);
1468 }
1469
1470 #[test]
1473 fn a_recently_active_transcript_is_left_alone() {
1474 let mut e = fake();
1475 e.transcript = r#"{"type":"user","timestamp":"2026-09-02T01:23:45Z"}"#.into();
1476 e.now = 1788312225 + 10;
1477 let p = plan_of(&e, &opts());
1478 assert!(p.skipped[0].contains("active in the last 45s"));
1479 }
1480
1481 #[test]
1482 fn an_unresolved_pane_says_so_and_earns_the_paragraph() {
1483 let mut e = fake();
1484 e.resolved
1485 .insert("%1".into(), Err("3 transcripts share this title".into()));
1486 let p = plan_of(&e, &opts());
1487 assert!(p.go.is_empty());
1488 assert!(p.unresolved);
1489 assert!(p.skipped[0].contains("unresolved: 3 transcripts share this title"));
1490 assert!(render(&p).contains("restart it by hand"));
1491 }
1492
1493 #[test]
1496 fn one_transcript_is_never_resumed_into_two_panes() {
1497 let mut e = fake();
1498 e.vers.insert(22, "2.1.100".into()); e.resolved
1500 .insert("%2".into(), Ok("/t/a.jsonl\tpane map".into()));
1501 let p = plan_of(&e, &opts());
1502 assert_eq!(p.go.len(), 1);
1503 assert_eq!(p.go[0].pane, "%1");
1504 assert!(p.skipped[0].contains("resolves to the same transcript as %1"));
1505 }
1506
1507 #[test]
1508 fn only_panes_narrows_the_plan_without_changing_the_verdicts() {
1509 let mut o = opts();
1510 o.only_panes = vec!["%2".into()];
1511 let p = plan_of(&fake(), &o);
1512 assert!(p.go.is_empty());
1513 assert!(p.skipped.is_empty()); }
1515
1516 #[test]
1517 fn a_pane_with_no_session_process_is_reported_not_dropped() {
1518 let rows = "%9\tw:9.9\t/w\tclaude\t0\tclaude\tno pid here";
1519 let p = plan(rows, "2.1.258", "/l", &opts(), &fake(), "/nowhere", &|| {
1520 "[]".into()
1521 });
1522 assert!(p.go.is_empty());
1523 assert_eq!(p.skipped.len(), 1);
1524 assert!(p.skipped[0].contains("no session process was found"));
1525 }
1526
1527 #[test]
1528 fn nothing_to_restart_says_so() {
1529 let mut e = fake();
1530 e.vers.insert(11, "2.1.258".into());
1531 let out = render(&plan_of(&e, &opts()));
1532 assert!(out.contains("nothing to restart."));
1533 assert!(!out.contains("to restart ("));
1534 }
1535
1536 #[test]
1539 fn a_given_transcript_overrides_the_ladder() {
1540 let mut e = fake();
1541 e.resolved.insert("%1".into(), Err("no candidate".into()));
1542 let mut o = opts();
1543 o.force_transcript = Some("/given.jsonl".into());
1544 let p = plan_of(&e, &o);
1545 assert_eq!(p.go.len(), 1);
1546 assert!(p.go[0].via.contains("--transcript, given"));
1547 assert!(p.go[0].cmd.contains("--resume /given.jsonl"));
1548 }
1549}