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 version_of_pid(&self, pid: i32) -> Option<String>;
340 fn cwd_of(&self, pid: i32) -> Option<String>;
341 fn argv_of(&self, pid: i32) -> Vec<String>;
342 fn resolve(&self, pane: &str, cwd: &str, title: &str, pid: i32) -> Result<String, String>;
343 fn read_transcript(&self, path: &str) -> Option<String>;
344 fn now(&self) -> i64;
345}
346
347pub fn plan(
353 rows: &str,
354 newver: &str,
355 launcher: &str,
356 o: &Opts,
357 e: &dyn Env,
358 versions_dir: &str,
359 agents: &dyn Fn() -> String,
360) -> Plan {
361 let mut p = Plan {
362 newver: newver.to_string(),
363 launcher: launcher.to_string(),
364 go: Vec::new(),
365 skipped: Vec::new(),
366 unresolved: false,
367 };
368 let mut claimed: HashMap<String, String> = HashMap::new();
369 let mut matched: Vec<i32> = Vec::new();
372
373 for line in rows.lines() {
374 let f: Vec<&str> = line.split('\t').collect();
375 if f.len() < 7 || f[3] != "claude" {
376 continue;
377 }
378 let (id, tgt, cwd, title) = (f[0], f[1], f[2], f[6]);
379 let pid: i32 = f[4].parse().unwrap_or(0);
380
381 let Some(ver) = (pid != 0).then(|| e.version_of_pid(pid)).flatten() else {
382 p.skipped.push(format!(
383 "{} {} looks like claude but no session process was found under the pane",
384 id, tgt
385 ));
386 continue;
387 };
388 matched.push(pid);
389 if !o.only_panes.is_empty() && !o.only_panes.iter().any(|w| w == id) {
390 continue;
391 }
392 if ver == newver {
393 continue; }
395 if id == o.self_pane {
396 p.skipped.push(format!(
397 "{} {} {}, this pane: restart it by hand (killing it would kill taimux)",
398 id, tgt, ver
399 ));
400 continue;
401 }
402
403 let mut screen = e.capture(id);
404 if !screen.contains('❯') {
413 if let Some(bigger) = e.capture_zoomed(id) {
414 screen = bigger;
415 }
416 }
417 let hook = e.hook_state(id, pid);
418 let st = state::merge(&screen, hook.as_deref());
419 if st.as_str() != "idle" && !o.include_busy {
420 p.skipped.push(format!(
421 "{} {} {}, {}: rerun when idle, or --include-busy",
422 id,
423 tgt,
424 ver,
425 st.as_str()
426 ));
427 continue;
428 }
429 if state::background(&screen, hook.as_deref()) && !o.include_busy {
435 p.skipped.push(format!(
436 "{} {} {}, work still in flight: rerun once it reports back, or --include-busy",
437 id, tgt, ver
438 ));
439 continue;
440 }
441
442 let ccwd = e.cwd_of(pid).unwrap_or_else(|| cwd.to_string());
443 let (transcript, via) = match &o.force_transcript {
444 Some(t) => (t.clone(), "--transcript, given".to_string()),
445 None => match e.resolve(id, &ccwd, title, pid) {
446 Ok(t) => {
447 let (path, why) = t.split_once('\t').unwrap_or((t.as_str(), ""));
449 (path.to_string(), why.to_string())
450 }
451 Err(why) => {
452 p.skipped
453 .push(format!("{} {} {}, unresolved: {}", id, tgt, ver, why));
454 p.unresolved = true;
455 continue;
456 }
457 },
458 };
459
460 if let Err(why) = screen_has_no_dialog(&screen) {
461 p.skipped
462 .push(format!("{} {} {}, not settled: {}", id, tgt, ver, why));
463 continue;
464 }
465 if !o.include_busy {
466 let settled =
467 screen_has_no_draft(&screen).and_then(|()| match e.read_transcript(&transcript) {
468 Some(text) => transcript_is_settled(&text, e.now()),
469 None => Ok(()),
470 });
471 if let Err(why) = settled {
472 p.skipped
473 .push(format!("{} {} {}, not settled: {}", id, tgt, ver, why));
474 continue;
475 }
476 }
477
478 if let Some(first) = claimed.get(&transcript) {
479 p.skipped.push(format!(
480 "{} {} {}, resolves to the same transcript as {}",
481 id, tgt, ver, first
482 ));
483 continue;
484 }
485 claimed.insert(transcript.clone(), id.to_string());
486
487 let Some(cmd) = conv::build_cmd(&e.argv_of(pid), &transcript, &ccwd, cwd) else {
488 p.skipped
489 .push(format!("{} {} {}, could not read its argv", id, tgt, ver));
490 continue;
491 };
492 p.go.push(Planned {
493 pane: id.to_string(),
494 target: tgt.to_string(),
495 pid,
496 cmd,
497 title: title.to_string(),
498 via: format!("{} -> {}, {}, {}", ver, newver, via, st.as_str()),
499 });
500 }
501
502 let mut agents_json: Option<String> = None;
507 for np in nonpane_pids(&matched, versions_dir) {
508 let Some(ver) = e.version_of_pid(np) else {
509 continue;
510 };
511 if ver == newver {
512 continue;
513 }
514 let j = agents_json.get_or_insert_with(agents);
515 p.skipped.push(format!(
516 "pid {} {}, not a tmux pane: {}",
517 np,
518 ver,
519 describe_nonpane(&e.argv_of(np), j)
520 ));
521 }
522 p
523}
524
525pub fn render(p: &Plan) -> String {
528 let mut s = format!("claude: {} installed at {}\n\n", p.newver, p.launcher);
529 if p.go.is_empty() {
530 s.push_str("nothing to restart.\n");
531 } else {
532 s.push_str(&format!("to restart ({}):\n", p.go.len()));
533 for g in &p.go {
534 s.push_str(&format!(" {:<5} {:<14} {}\n", g.pane, g.target, g.title));
535 s.push_str(&format!(" {}\n", g.via));
536 s.push_str(&format!(" {}\n", g.cmd));
537 }
538 }
539 if !p.skipped.is_empty() {
540 s.push_str(&format!("\nskipped ({}):\n", p.skipped.len()));
541 for k in &p.skipped {
542 s.push_str(&format!(" {}\n", k));
543 }
544 }
545 if p.unresolved {
546 s.push_str(
547 "\nAn unresolved pane means guessing, so it was left alone: restart it by hand\n\
548 with `claude -c` in that pane, or from its /resume picker. Each session records\n\
549 its pane at the next SessionStart, so a pane resolves cleanly once restarted.\n",
550 );
551 }
552 s
553}
554
555pub fn restart_pane(pane: &str, pid: i32, cmd: &str) -> bool {
562 use std::thread::sleep;
563 use std::time::Duration;
564
565 tmux::run(&["send-keys", "-t", pane, "C-c"]);
566 sleep(Duration::from_millis(300));
567 tmux::run(&["send-keys", "-t", pane, "C-c"]);
568
569 let mut waited = 0;
570 let mut sent_exit = false;
571 while alive(pid) {
572 sleep(Duration::from_millis(400));
573 waited += 1;
574 if waited >= 6 && !sent_exit {
575 tmux::run(&["send-keys", "-t", pane, "/exit", "Enter"]);
576 sent_exit = true;
577 }
578 if waited >= 30 {
579 return false;
580 }
581 }
582 sleep(Duration::from_millis(500));
583 tmux::run(&["send-keys", "-t", pane, "C-c"]);
584 sleep(Duration::from_millis(200));
585 tmux::run(&["send-keys", "-t", pane, cmd, "Enter"])
586}
587
588fn alive(pid: i32) -> bool {
591 std::path::Path::new(&format!("/proc/{}", pid)).exists()
592}
593
594pub fn confirm_yes(answer: &str) -> bool {
597 matches!(answer.trim(), "" | "y" | "Y" | "yes" | "YES" | "Yes")
598}
599
600pub struct Live {
602 pub versions_dir: String,
603}
604
605impl Env for Live {
606 fn capture(&self, pane: &str) -> String {
607 tmux::ask_raw(&["capture-pane", "-p", "-t", pane]).unwrap_or_default()
608 }
609 fn capture_zoomed(&self, pane: &str) -> Option<String> {
610 capture_zoomed(pane)
611 }
612 fn hook_state(&self, pane: &str, pid: i32) -> Option<String> {
613 taimux_core::hook::hook_state_of(pane, pid)
614 }
615 fn version_of_pid(&self, pid: i32) -> Option<String> {
616 version_of_pid(pid, &self.versions_dir)
617 }
618 fn cwd_of(&self, pid: i32) -> Option<String> {
619 std::fs::read_link(format!("/proc/{}/cwd", pid))
620 .ok()
621 .map(|p| p.to_string_lossy().into_owned())
622 .filter(|s| !s.is_empty())
623 }
624 fn argv_of(&self, pid: i32) -> Vec<String> {
625 conv::argv_of(pid)
626 }
627 fn resolve(&self, pane: &str, cwd: &str, title: &str, pid: i32) -> Result<String, String> {
628 conv::resolve(pane, cwd, title, pid)
629 .map(|r| format!("{}\t{}", r.transcript.display(), r.why))
630 }
631 fn read_transcript(&self, path: &str) -> Option<String> {
632 std::fs::read_to_string(path).ok()
633 }
634 fn now(&self) -> i64 {
635 std::time::SystemTime::now()
636 .duration_since(std::time::UNIX_EPOCH)
637 .map(|d| d.as_secs() as i64)
638 .unwrap_or(0)
639 }
640}
641
642pub fn installed(launcher: &str, versions_dir: &str) -> Result<String, String> {
645 let target = std::fs::canonicalize(launcher)
646 .map(|p| p.to_string_lossy().into_owned())
647 .unwrap_or_default();
648 let prefix = format!("{}/", versions_dir);
649 match target.strip_prefix(&prefix) {
650 Some(rest) if !rest.is_empty() => Ok(rest.split('/').next().unwrap_or(rest).to_string()),
651 _ => Err(format!(
652 "restart: {} does not point into {} (got '{}')",
653 launcher,
654 versions_dir,
655 if target.is_empty() {
656 "nothing"
657 } else {
658 &target
659 }
660 )),
661 }
662}
663
664pub fn versions_dir() -> String {
665 format!(
666 "{}/.local/share/claude/versions",
667 std::env::var("HOME").unwrap_or_default()
668 )
669}
670
671pub fn launcher() -> String {
672 format!(
673 "{}/.local/bin/claude",
674 std::env::var("HOME").unwrap_or_default()
675 )
676}
677
678#[cfg(test)]
679mod tests {
680 use super::*;
681
682 #[test]
683 fn a_timestamp_becomes_epoch_seconds() {
684 assert_eq!(parse_iso8601("2026-09-02T01:23:45.678Z"), Some(1788312225));
686 assert_eq!(parse_iso8601("1970-01-01T00:00:00Z"), Some(0));
687 assert_eq!(parse_iso8601("2024-02-29T00:00:00Z"), Some(1709164800));
689 }
690
691 #[test]
695 fn an_unparseable_timestamp_is_no_answer() {
696 assert_eq!(parse_iso8601(""), None);
697 assert_eq!(parse_iso8601("yesterday"), None);
698 assert_eq!(parse_iso8601("2026-09-02 01:23:45"), None);
699 assert_eq!(parse_iso8601("2026-13-02T01:23:45Z"), None);
700 }
701
702 #[test]
703 fn a_tool_call_still_running_is_not_settled() {
704 let t = r#"{"type":"assistant","message":{"content":[{"type":"tool_use"}]},"timestamp":"2020-01-01T00:00:00Z"}"#;
705 assert_eq!(
706 transcript_is_settled(t, 1788312225),
707 Err("a tool call is still running".into())
708 );
709 }
710
711 #[test]
713 fn recent_activity_is_not_settled_whatever_the_screen_said() {
714 let t = r#"{"type":"user","timestamp":"2026-09-02T01:23:45Z"}"#;
715 assert!(transcript_is_settled(t, 1788312225 + 10).is_err());
716 assert!(transcript_is_settled(t, 1788312225 + 100).is_ok());
717 }
718
719 #[test]
720 fn an_empty_or_odd_transcript_does_not_block() {
721 assert!(transcript_is_settled("", 0).is_ok());
722 assert!(transcript_is_settled("not json at all\n", 0).is_ok());
723 assert!(transcript_is_settled(r#"{"type":"user"}"#, 0).is_ok());
725 }
726
727 #[test]
731 fn a_dialog_on_screen_blocks_a_restart() {
732 let footer = "some output\n\nDo you want to proceed?\n";
733 assert_eq!(
734 screen_has_no_dialog(footer),
735 Err("a dialog is waiting for an answer".into())
736 );
737 let choice = "some output\n1. Yes\n2. No\n❯ 1. Yes\n";
738 assert_eq!(
739 screen_has_no_dialog(choice),
740 Err("a dialog is waiting for an answer".into())
741 );
742 assert!(screen_has_no_dialog("some output\n❯ \n").is_ok());
744 }
745
746 #[test]
749 fn a_half_pressed_ctrl_c_blocks_a_restart() {
750 let screen = "work\n\nPress Ctrl-C again to exit\n";
751 assert_eq!(
752 screen_has_no_dialog(screen),
753 Err("a Ctrl-C is already half-pressed".into())
754 );
755 }
756
757 #[test]
758 fn an_empty_prompt_box_is_no_draft() {
759 assert!(screen_has_no_draft("stuff\n❯ \n").is_ok());
760 assert!(screen_has_no_draft("stuff\n❯ \u{a0}\u{a0}\n").is_ok());
762 assert_eq!(
763 screen_has_no_draft("stuff\n❯ half a thought\n"),
764 Err("unsent text in the prompt box".into())
765 );
766 }
767
768 #[test]
771 fn a_pane_tall_enough_to_read_is_left_alone() {
772 assert!(zoom_steps("%1", false, 6, 40, "%2", "%3").is_none());
774 assert!(zoom_steps("%1", false, 40, 40, "%2", "%3").is_none());
775 assert!(zoom_steps("%1", false, 3, 3, "%2", "%3").is_none());
777 assert!(zoom_steps("%1", false, 3, 5, "%2", "%3").is_none());
778 }
779
780 #[test]
784 fn a_short_pane_is_zoomed_and_the_selection_put_back() {
785 let (go, back) = zoom_steps("%1", false, 3, 17, "%2", "%3").unwrap();
786 assert_eq!(go, vec![vec!["resize-pane", "-Z", "-t", "%1"]]);
787 assert_eq!(
788 back,
789 vec![
790 vec!["resize-pane", "-Z", "-t", "%1"],
791 vec!["select-pane", "-t", "%3"],
792 vec!["select-pane", "-t", "%2"],
793 ]
794 );
795 }
796
797 #[test]
801 fn a_window_zoomed_elsewhere_is_handed_back_zoomed() {
802 let (go, back) = zoom_steps("%1", true, 3, 17, "%2", "%3").unwrap();
803 assert_eq!(
804 go,
805 vec![
806 vec!["resize-pane", "-Z", "-t", "%1"],
807 vec!["resize-pane", "-Z", "-t", "%1"],
808 ]
809 );
810 assert_eq!(
811 back,
812 vec![
813 vec!["resize-pane", "-Z", "-t", "%1"],
814 vec!["select-pane", "-t", "%3"],
815 vec!["select-pane", "-t", "%2"],
816 vec!["resize-pane", "-Z", "-t", "%2"],
817 ]
818 );
819 }
820
821 #[test]
824 fn an_active_short_pane_has_no_selection_to_restore() {
825 let (go, back) = zoom_steps("%1", false, 3, 17, "%1", "%3").unwrap();
826 assert_eq!(go.len(), 1);
827 assert_eq!(back, vec![vec!["resize-pane", "-Z", "-t", "%1"]]);
828 }
829
830 #[test]
833 fn no_prompt_box_is_a_refusal() {
834 assert_eq!(
835 screen_has_no_draft("just some text\n"),
836 Err("no prompt box on screen".into())
837 );
838 assert!(screen_has_no_draft("").is_ok());
840 assert!(screen_has_no_draft(" \n\n").is_ok());
841 }
842
843 #[test]
844 fn a_bare_enter_confirms() {
845 assert!(confirm_yes(""));
846 assert!(confirm_yes("y"));
847 assert!(confirm_yes("YES"));
848 assert!(!confirm_yes("n"));
849 assert!(!confirm_yes("no"));
850 assert!(!confirm_yes("maybe"));
851 }
852
853 #[test]
854 fn the_launcher_must_point_into_the_versions_dir() {
855 let root = std::env::temp_dir().join(format!("jmrs{}", std::process::id()));
856 let vers = root.join("versions");
857 std::fs::create_dir_all(&vers).unwrap();
858 std::fs::write(vers.join("2.1.258"), "x").unwrap();
859 let link = root.join("claude");
860 std::os::unix::fs::symlink(vers.join("2.1.258"), &link).unwrap();
861 assert_eq!(
862 installed(&link.to_string_lossy(), &vers.to_string_lossy()),
863 Ok("2.1.258".into())
864 );
865 std::fs::write(root.join("elsewhere"), "x").unwrap();
867 std::fs::remove_file(&link).unwrap();
868 std::os::unix::fs::symlink(root.join("elsewhere"), &link).unwrap();
869 let e = installed(&link.to_string_lossy(), &vers.to_string_lossy()).expect_err("refused");
870 assert!(e.contains("elsewhere"));
871 let _ = std::fs::remove_dir_all(&root);
872 }
873}
874
875pub fn nonpane_pids(matched: &[i32], versions_dir: &str) -> Vec<i32> {
881 let mut out = Vec::new();
882 for e in std::fs::read_dir("/proc").into_iter().flatten().flatten() {
883 let Some(pid) = e.file_name().to_str().and_then(|s| s.parse::<i32>().ok()) else {
884 continue;
885 };
886 if matched.contains(&pid) {
887 continue;
888 }
889 let comm = std::fs::read_to_string(format!("/proc/{}/comm", pid)).unwrap_or_default();
892 let argv = conv::argv_of(pid);
893 let is_claude = comm.trim() == "claude"
894 || argv
895 .first()
896 .map(|a| a.starts_with(&format!("{}/", versions_dir)))
897 .unwrap_or(false);
898 if is_claude {
899 out.push(pid);
900 }
901 }
902 out.sort_unstable();
903 out
904}
905
906fn json_object_with_prefix(text: &str, key: &str, prefix: &str) -> Option<String> {
914 let needle = format!("\"{}\":\"{}", key, prefix);
915 let at = text.find(&needle).or_else(|| {
916 let spaced = format!("\"{}\": \"{}", key, prefix);
917 text.find(&spaced)
918 })?;
919 let mut depth = 0i32;
921 let bytes = text.as_bytes();
922 let mut start = None;
923 for i in (0..at).rev() {
924 match bytes[i] {
925 b'}' => depth += 1,
926 b'{' => {
927 if depth == 0 {
928 start = Some(i);
929 break;
930 }
931 depth -= 1;
932 }
933 _ => {}
934 }
935 }
936 let start = start?;
937 let mut depth = 0i32;
939 for i in start..bytes.len() {
940 match bytes[i] {
941 b'{' => depth += 1,
942 b'}' => {
943 depth -= 1;
944 if depth == 0 {
945 return Some(text[start..=i].to_string());
946 }
947 }
948 _ => {}
949 }
950 }
951 None
952}
953
954pub fn describe_nonpane(argv: &[String], agents_json: &str) -> String {
961 if argv.is_empty() {
962 return "gone".into();
963 }
964 let (mut sid, mut res, mut forked) = (String::new(), String::new(), false);
965 for i in 1..argv.len() {
966 match argv[i].as_str() {
967 "--fork-session" => forked = true,
968 "--session-id" => sid = argv.get(i + 1).cloned().unwrap_or_default(),
969 "-r" | "--resume" => res = argv.get(i + 1).cloned().unwrap_or_default(),
970 _ => {}
971 }
972 }
973 let own = base_id(if sid.is_empty() { &res } else { &sid });
974 let parent = if forked && !res.is_empty() {
975 base_id(&res)
976 } else {
977 String::new()
978 };
979
980 let (mut kind, mut st, mut name) = ("?".to_string(), "?".to_string(), String::new());
981 if !own.is_empty() {
982 if let Some(obj) = json_object_with_prefix(agents_json, "sessionId", &own) {
983 let f = |k: &str| taimux_core::json::field(&obj, k);
984 let k = f("kind");
985 if !k.is_empty() {
986 kind = k;
987 }
988 let s = {
989 let a = f("state");
990 if a.is_empty() {
991 f("status")
992 } else {
993 a
994 }
995 };
996 if !s.is_empty() {
997 st = s;
998 }
999 name = f("name");
1000 }
1001 }
1002 let mut out = format!("{} {}", kind, st);
1003 if forked {
1004 out.push_str(" fork");
1005 }
1006 if !name.is_empty() {
1007 out.push_str(&format!(" \"{}\"", name));
1008 }
1009 if !own.is_empty() {
1010 out.push_str(&format!(" [{}]", own.chars().take(8).collect::<String>()));
1011 }
1012 if !parent.is_empty() {
1013 out.push_str(&format!(
1014 " of [{}]",
1015 parent.chars().take(8).collect::<String>()
1016 ));
1017 }
1018 out
1019}
1020
1021fn base_id(s: &str) -> String {
1023 if s.is_empty() {
1024 return String::new();
1025 }
1026 let b = s.rsplit('/').next().unwrap_or(s);
1027 b.strip_suffix(".jsonl").unwrap_or(b).to_string()
1028}
1029
1030#[cfg(test)]
1031mod nonpane_tests {
1032 use super::*;
1033
1034 fn v(a: &[&str]) -> Vec<String> {
1035 a.iter().map(|s| s.to_string()).collect()
1036 }
1037
1038 #[test]
1039 fn a_session_id_is_read_out_of_a_path_or_taken_as_it_stands() {
1040 assert_eq!(base_id("/a/b/263946b5-9bd7.jsonl"), "263946b5-9bd7");
1041 assert_eq!(base_id("263946b5"), "263946b5");
1042 assert_eq!(base_id(""), "");
1043 }
1044
1045 #[test]
1049 fn the_right_object_comes_back_whole() {
1050 let j = r#"[{"sessionId":"aaa111","kind":"task","meta":{"a":1},"name":"first"},
1051 {"sessionId":"bbb222","kind":"agent","name":"second"}]"#;
1052 let o = json_object_with_prefix(j, "sessionId", "bbb222").expect("found");
1053 assert!(o.contains("second"));
1054 assert!(!o.contains("first"));
1055 let o = json_object_with_prefix(j, "sessionId", "aaa").expect("found by prefix");
1056 assert!(o.contains("first"));
1057 assert!(
1058 o.contains("\"meta\":{\"a\":1}"),
1059 "nested field truncated: {}",
1060 o
1061 );
1062 assert!(json_object_with_prefix(j, "sessionId", "zzz").is_none());
1063 }
1064
1065 #[test]
1066 fn a_process_with_no_argv_is_simply_gone() {
1067 assert_eq!(describe_nonpane(&[], "[]"), "gone");
1068 }
1069
1070 #[test]
1071 fn an_unnamed_session_still_says_what_it_can() {
1072 let d = describe_nonpane(&v(&["claude", "--session-id", "263946b5-9bd7"]), "[]");
1073 assert_eq!(d, "? ? [263946b5]");
1074 }
1075
1076 #[test]
1077 fn a_named_one_says_kind_state_and_name() {
1078 let j =
1079 r#"[{"sessionId":"263946b5-9bd7","kind":"task","state":"running","name":"the thing"}]"#;
1080 let d = describe_nonpane(&v(&["claude", "--session-id", "263946b5-9bd7"]), j);
1081 assert_eq!(d, "task running \"the thing\" [263946b5]");
1082 }
1083
1084 #[test]
1087 fn status_stands_in_for_state() {
1088 let j = r#"[{"sessionId":"aaa11111","kind":"agent","status":"idle"}]"#;
1089 let d = describe_nonpane(&v(&["claude", "--session-id", "aaa11111"]), j);
1090 assert_eq!(d, "agent idle [aaa11111]");
1091 }
1092
1093 #[test]
1096 fn a_fork_names_its_parent_too() {
1097 let d = describe_nonpane(
1098 &v(&[
1099 "claude",
1100 "--session-id",
1101 "child111",
1102 "--fork-session",
1103 "--resume",
1104 "/p/parent22.jsonl",
1105 ]),
1106 "[]",
1107 );
1108 assert_eq!(d, "? ? fork [child111] of [parent22]");
1109 }
1110}
1111
1112#[cfg(test)]
1113mod plan_tests {
1114 use super::*;
1115
1116 struct Fake {
1121 vers: HashMap<i32, String>,
1123 screens: HashMap<String, String>,
1125 resolved: HashMap<String, Result<String, String>>,
1127 zoomed: HashMap<String, String>,
1130 zooms: std::cell::Cell<usize>,
1133 hooks: HashMap<String, String>,
1135 transcript: String,
1136 now: i64,
1137 }
1138
1139 impl Env for Fake {
1140 fn capture(&self, pane: &str) -> String {
1141 self.screens.get(pane).cloned().unwrap_or_default()
1142 }
1143 fn capture_zoomed(&self, pane: &str) -> Option<String> {
1144 let bigger = self.zoomed.get(pane).cloned();
1145 if bigger.is_some() {
1146 self.zooms.set(self.zooms.get() + 1);
1147 }
1148 bigger
1149 }
1150 fn hook_state(&self, pane: &str, _pid: i32) -> Option<String> {
1151 self.hooks.get(pane).cloned()
1152 }
1153 fn version_of_pid(&self, pid: i32) -> Option<String> {
1154 self.vers.get(&pid).cloned()
1155 }
1156 fn cwd_of(&self, _pid: i32) -> Option<String> {
1157 Some("/w".into())
1158 }
1159 fn argv_of(&self, _pid: i32) -> Vec<String> {
1160 vec!["claude".into()]
1161 }
1162 fn resolve(&self, pane: &str, _c: &str, _t: &str, _p: i32) -> Result<String, String> {
1163 self.resolved
1164 .get(pane)
1165 .cloned()
1166 .unwrap_or_else(|| Err("no candidate".into()))
1167 }
1168 fn read_transcript(&self, _path: &str) -> Option<String> {
1169 Some(self.transcript.clone())
1170 }
1171 fn now(&self) -> i64 {
1172 self.now
1173 }
1174 }
1175
1176 fn fake() -> Fake {
1177 let mut vers = HashMap::new();
1178 vers.insert(11, "2.1.100".to_string()); vers.insert(22, "2.1.258".to_string()); let mut screens = HashMap::new();
1181 screens.insert("%1".to_string(), "some output\n❯ \n".to_string());
1183 screens.insert("%2".to_string(), "some output\n❯ \n".to_string());
1184 let mut resolved = HashMap::new();
1185 resolved.insert("%1".to_string(), Ok("/t/a.jsonl\tpane map".to_string()));
1186 Fake {
1187 vers,
1188 screens,
1189 resolved,
1190 zoomed: HashMap::new(),
1191 zooms: std::cell::Cell::new(0),
1192 hooks: HashMap::new(),
1193 transcript: r#"{"type":"user","timestamp":"2020-01-01T00:00:00Z"}"#.to_string(),
1194 now: 1788312225,
1195 }
1196 }
1197
1198 fn opts() -> Opts {
1199 Opts {
1200 include_busy: false,
1201 only_panes: Vec::new(),
1202 force_transcript: None,
1203 self_pane: String::new(),
1204 }
1205 }
1206
1207 const ROWS: &str = "%1\tw:1.1\t/w\tclaude\t11\tclaude\tproj: the stale one\n\
1208 %2\tw:2.1\t/w\tclaude\t22\tclaude\tproj: the current one";
1209
1210 fn plan_of(e: &Fake, o: &Opts) -> Plan {
1211 plan(ROWS, "2.1.258", "/l/claude", o, e, "/nowhere", &|| {
1212 "[]".into()
1213 })
1214 }
1215
1216 #[test]
1217 fn a_stale_pane_is_planned_and_a_current_one_is_not() {
1218 let p = plan_of(&fake(), &opts());
1219 assert_eq!(p.go.len(), 1);
1220 assert_eq!(p.go[0].pane, "%1");
1221 assert_eq!(p.go[0].cmd, "command claude --resume /t/a.jsonl");
1222 assert_eq!(p.go[0].via, "2.1.100 -> 2.1.258, pane map, idle");
1223 assert!(p.skipped.is_empty());
1224 }
1225
1226 #[test]
1229 fn the_rendered_plan_reads_the_way_it_always_did() {
1230 let out = render(&plan_of(&fake(), &opts()));
1231 assert_eq!(
1232 out,
1233 "claude: 2.1.258 installed at /l/claude\n\n\
1234 to restart (1):\n\
1235 \x20 %1 w:1.1 proj: the stale one\n\
1236 \x20 2.1.100 -> 2.1.258, pane map, idle\n\
1237 \x20 command claude --resume /t/a.jsonl\n"
1238 );
1239 }
1240
1241 #[test]
1243 fn this_pane_is_never_restarted() {
1244 let mut o = opts();
1245 o.self_pane = "%1".into();
1246 let p = plan_of(&fake(), &o);
1247 assert!(p.go.is_empty());
1248 assert!(p.skipped[0].contains("this pane"));
1249 assert!(p.skipped[0].contains("killing it would kill taimux"));
1250 }
1251
1252 #[test]
1253 fn a_pane_that_is_not_idle_waits_for_include_busy() {
1254 let mut e = fake();
1255 e.screens
1257 .insert("%1".into(), "Twisting… (35s · ↓ 1.6k tokens)\n❯ \n".into());
1258 let p = plan_of(&e, &opts());
1259 assert!(p.go.is_empty());
1260 assert!(p.skipped[0].contains("rerun when idle, or --include-busy"));
1261
1262 let mut o = opts();
1263 o.include_busy = true;
1264 assert_eq!(plan_of(&e, &o).go.len(), 1);
1265 }
1266
1267 #[test]
1270 fn a_pane_with_work_in_flight_waits_for_include_busy() {
1271 let mut e = fake();
1272 e.screens.insert(
1273 "%1".into(),
1274 "✻ Cogitated for 1m 3s · done 4:55 PM · 2 shells still running\n❯ \n".into(),
1275 );
1276 let p = plan_of(&e, &opts());
1277 assert!(p.go.is_empty());
1278 assert!(
1279 p.skipped[0].contains("work still in flight"),
1280 "{:?}",
1281 p.skipped
1282 );
1283
1284 let mut e = fake();
1286 e.hooks.insert("%1".into(), "bg".into());
1287 let p = plan_of(&e, &opts());
1288 assert!(p.go.is_empty());
1289 assert!(
1290 p.skipped[0].contains("work still in flight"),
1291 "{:?}",
1292 p.skipped
1293 );
1294
1295 let mut o = opts();
1296 o.include_busy = true;
1297 assert_eq!(plan_of(&e, &o).go.len(), 1);
1298 }
1299
1300 #[test]
1303 fn a_dialog_blocks_a_restart_even_with_include_busy() {
1304 let mut e = fake();
1305 e.screens
1306 .insert("%1".into(), "output\n\nDo you want to proceed?\n".into());
1307 let mut o = opts();
1308 o.include_busy = true;
1309 let p = plan_of(&e, &o);
1310 assert!(p.go.is_empty());
1311 assert!(p.skipped[0].contains("a dialog is waiting for an answer"));
1312 }
1313
1314 #[test]
1315 fn an_unsent_draft_is_left_alone() {
1316 let mut e = fake();
1317 e.screens
1318 .insert("%1".into(), "output\n❯ half a thought\n".into());
1319 let p = plan_of(&e, &opts());
1320 assert!(p.skipped[0].contains("unsent text in the prompt box"));
1321 }
1322
1323 #[test]
1327 fn a_pane_too_short_for_its_box_is_read_zoomed() {
1328 let mut e = fake();
1329 e.screens.insert(
1330 "%1".into(),
1331 " current: 2.1.100 · latest…\n────────\n".into(),
1332 );
1333 e.zoomed.insert("%1".into(), "some output\n❯ \n".into());
1334 let p = plan_of(&e, &opts());
1335 assert_eq!(e.zooms.get(), 1);
1336 assert_eq!(p.go.len(), 1);
1337 assert_eq!(p.go[0].pane, "%1");
1338 assert!(p.skipped.is_empty());
1339 }
1340
1341 #[test]
1346 fn a_draft_hidden_by_a_short_pane_still_refuses() {
1347 let mut e = fake();
1348 e.screens
1349 .insert("%1".into(), " current: 2.1.100…\n".into());
1350 e.zoomed
1351 .insert("%1".into(), "output\n❯ half a thought\n".into());
1352 let p = plan_of(&e, &opts());
1353 assert_eq!(e.zooms.get(), 1);
1354 assert!(p.go.is_empty());
1355 assert!(p.skipped[0].contains("unsent text in the prompt box"));
1356 }
1357
1358 #[test]
1362 fn a_dialog_hidden_by_a_short_pane_is_found_by_the_zoom() {
1363 let mut e = fake();
1364 e.screens.insert("%1".into(), " Bash command\n".into());
1365 e.zoomed.insert(
1366 "%1".into(),
1367 "Do you want to proceed?\n❯ 1. Yes\n 2. No\n".into(),
1368 );
1369 let mut o = opts();
1370 o.include_busy = true;
1371 let p = plan_of(&e, &o);
1372 assert!(p.go.is_empty());
1373 assert!(p.skipped[0].contains("a dialog is waiting for an answer"));
1374 }
1375
1376 #[test]
1379 fn a_pane_that_shows_its_box_is_not_zoomed() {
1380 let e = fake();
1381 let p = plan_of(&e, &opts());
1382 assert_eq!(e.zooms.get(), 0);
1383 assert_eq!(p.go.len(), 1);
1384 }
1385
1386 #[test]
1389 fn a_recently_active_transcript_is_left_alone() {
1390 let mut e = fake();
1391 e.transcript = r#"{"type":"user","timestamp":"2026-09-02T01:23:45Z"}"#.into();
1392 e.now = 1788312225 + 10;
1393 let p = plan_of(&e, &opts());
1394 assert!(p.skipped[0].contains("active in the last 45s"));
1395 }
1396
1397 #[test]
1398 fn an_unresolved_pane_says_so_and_earns_the_paragraph() {
1399 let mut e = fake();
1400 e.resolved
1401 .insert("%1".into(), Err("3 transcripts share this title".into()));
1402 let p = plan_of(&e, &opts());
1403 assert!(p.go.is_empty());
1404 assert!(p.unresolved);
1405 assert!(p.skipped[0].contains("unresolved: 3 transcripts share this title"));
1406 assert!(render(&p).contains("restart it by hand"));
1407 }
1408
1409 #[test]
1412 fn one_transcript_is_never_resumed_into_two_panes() {
1413 let mut e = fake();
1414 e.vers.insert(22, "2.1.100".into()); e.resolved
1416 .insert("%2".into(), Ok("/t/a.jsonl\tpane map".into()));
1417 let p = plan_of(&e, &opts());
1418 assert_eq!(p.go.len(), 1);
1419 assert_eq!(p.go[0].pane, "%1");
1420 assert!(p.skipped[0].contains("resolves to the same transcript as %1"));
1421 }
1422
1423 #[test]
1424 fn only_panes_narrows_the_plan_without_changing_the_verdicts() {
1425 let mut o = opts();
1426 o.only_panes = vec!["%2".into()];
1427 let p = plan_of(&fake(), &o);
1428 assert!(p.go.is_empty());
1429 assert!(p.skipped.is_empty()); }
1431
1432 #[test]
1433 fn a_pane_with_no_session_process_is_reported_not_dropped() {
1434 let rows = "%9\tw:9.9\t/w\tclaude\t0\tclaude\tno pid here";
1435 let p = plan(rows, "2.1.258", "/l", &opts(), &fake(), "/nowhere", &|| {
1436 "[]".into()
1437 });
1438 assert!(p.go.is_empty());
1439 assert_eq!(p.skipped.len(), 1);
1440 assert!(p.skipped[0].contains("no session process was found"));
1441 }
1442
1443 #[test]
1444 fn nothing_to_restart_says_so() {
1445 let mut e = fake();
1446 e.vers.insert(11, "2.1.258".into());
1447 let out = render(&plan_of(&e, &opts()));
1448 assert!(out.contains("nothing to restart."));
1449 assert!(!out.contains("to restart ("));
1450 }
1451
1452 #[test]
1455 fn a_given_transcript_overrides_the_ladder() {
1456 let mut e = fake();
1457 e.resolved.insert("%1".into(), Err("no candidate".into()));
1458 let mut o = opts();
1459 o.force_transcript = Some("/given.jsonl".into());
1460 let p = plan_of(&e, &o);
1461 assert_eq!(p.go.len(), 1);
1462 assert!(p.go[0].via.contains("--transcript, given"));
1463 assert!(p.go[0].cmd.contains("--resume /given.jsonl"));
1464 }
1465}