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, _screen: &str) -> Option<state::State> {
343 None
344 }
345 fn elsewhere(&self, _pane: &str, _pid: i32) -> Option<Elsewhere> {
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 struct Elsewhere {
361 pub id: String,
363 pub pid: i32,
365 pub version: Option<String>,
367 pub moved: bool,
369}
370
371pub fn plan(
377 rows: &str,
378 newver: &str,
379 launcher: &str,
380 o: &Opts,
381 e: &dyn Env,
382 versions_dir: &str,
383 agents: &dyn Fn() -> String,
384) -> Plan {
385 let mut p = Plan {
386 newver: newver.to_string(),
387 launcher: launcher.to_string(),
388 go: Vec::new(),
389 skipped: Vec::new(),
390 unresolved: false,
391 };
392 let mut claimed: HashMap<String, String> = HashMap::new();
393 let mut matched: Vec<i32> = Vec::new();
396
397 for line in rows.lines() {
398 let f: Vec<&str> = line.split('\t').collect();
399 if f.len() < 7 || f[3] != "claude" {
400 continue;
401 }
402 let (id, tgt, cwd, title) = (f[0], f[1], f[2], f[6]);
403 let pid: i32 = f[4].parse().unwrap_or(0);
404
405 let Some(ver) = (pid != 0).then(|| e.version_of_pid(pid)).flatten() else {
406 p.skipped.push(format!(
407 "{} {} looks like claude but no session process was found under the pane",
408 id, tgt
409 ));
410 continue;
411 };
412 matched.push(pid);
413 if !o.only_panes.is_empty() && !o.only_panes.iter().any(|w| w == id) {
414 continue;
415 }
416
417 if let Some(away) = e.elsewhere(id, pid) {
424 matched.push(away.pid);
425 let aver = away.version.as_deref().unwrap_or("?");
426 if aver == newver {
427 continue;
428 }
429 p.skipped.push(if away.moved {
430 format!(
431 "{} {} {}, its conversation moved to background session {}: claude attach {}",
432 id, tgt, aver, away.id, away.id
433 )
434 } else {
435 format!(
436 "{} {} {}, attached to background session {}, which agent view only restarts with nothing attached",
437 id, tgt, aver, away.id
438 )
439 });
440 continue;
441 }
442
443 if ver == newver {
444 continue; }
446 if id == o.self_pane {
447 p.skipped.push(format!(
448 "{} {} {}, this pane: restart it by hand (killing it would kill taimux)",
449 id, tgt, ver
450 ));
451 continue;
452 }
453
454 let mut screen = e.capture(id);
455 if !screen.contains('❯') {
464 if let Some(bigger) = e.capture_zoomed(id) {
465 screen = bigger;
466 }
467 }
468 let hook = e.hook_state(id, pid);
469 let st = state::reading(&screen, e.own_state(pid, &screen), hook.as_deref());
470 if st.as_str() != "idle" && !o.include_busy {
471 p.skipped.push(format!(
472 "{} {} {}, {}: rerun when idle, or --include-busy",
473 id,
474 tgt,
475 ver,
476 st.as_str()
477 ));
478 continue;
479 }
480 if state::background(&screen, hook.as_deref()) && !o.include_busy {
486 p.skipped.push(format!(
487 "{} {} {}, work still in flight: rerun once it reports back, or --include-busy",
488 id, tgt, ver
489 ));
490 continue;
491 }
492
493 let ccwd = e.cwd_of(pid).unwrap_or_else(|| cwd.to_string());
494 let (transcript, via) = match &o.force_transcript {
495 Some(t) => (t.clone(), "--transcript, given".to_string()),
496 None => match e.resolve(id, &ccwd, title, pid) {
497 Ok(t) => {
498 let (path, why) = t.split_once('\t').unwrap_or((t.as_str(), ""));
500 (path.to_string(), why.to_string())
501 }
502 Err(why) => {
503 p.skipped
504 .push(format!("{} {} {}, unresolved: {}", id, tgt, ver, why));
505 p.unresolved = true;
506 continue;
507 }
508 },
509 };
510
511 if let Err(why) = screen_has_no_dialog(&screen) {
512 p.skipped
513 .push(format!("{} {} {}, not settled: {}", id, tgt, ver, why));
514 continue;
515 }
516 if !o.include_busy {
517 let settled =
518 screen_has_no_draft(&screen).and_then(|()| match e.read_transcript(&transcript) {
519 Some(text) => transcript_is_settled(&text, e.now()),
520 None => Ok(()),
521 });
522 if let Err(why) = settled {
523 p.skipped
524 .push(format!("{} {} {}, not settled: {}", id, tgt, ver, why));
525 continue;
526 }
527 }
528
529 if let Some(first) = claimed.get(&transcript) {
530 p.skipped.push(format!(
531 "{} {} {}, resolves to the same transcript as {}",
532 id, tgt, ver, first
533 ));
534 continue;
535 }
536 claimed.insert(transcript.clone(), id.to_string());
537
538 let Some(cmd) = conv::build_cmd(&e.argv_of(pid), &transcript, &ccwd, cwd) else {
539 p.skipped
540 .push(format!("{} {} {}, could not read its argv", id, tgt, ver));
541 continue;
542 };
543 p.go.push(Planned {
544 pane: id.to_string(),
545 target: tgt.to_string(),
546 pid,
547 cmd,
548 title: title.to_string(),
549 via: format!("{} -> {}, {}, {}", ver, newver, via, st.as_str()),
550 });
551 }
552
553 let mut agents_json: Option<String> = None;
558 for np in nonpane_pids(&matched, versions_dir) {
559 let Some(ver) = e.version_of_pid(np) else {
560 continue;
561 };
562 if ver == newver {
563 continue;
564 }
565 let j = agents_json.get_or_insert_with(agents);
566 p.skipped.push(format!(
567 "pid {} {}, not a tmux pane: {}",
568 np,
569 ver,
570 describe_nonpane(&e.argv_of(np), j)
571 ));
572 }
573 p
574}
575
576pub fn render(p: &Plan) -> String {
579 let mut s = format!("claude: {} installed at {}\n\n", p.newver, p.launcher);
580 if p.go.is_empty() {
581 s.push_str("nothing to restart.\n");
582 } else {
583 s.push_str(&format!("to restart ({}):\n", p.go.len()));
584 for g in &p.go {
585 s.push_str(&format!(" {:<5} {:<14} {}\n", g.pane, g.target, g.title));
586 s.push_str(&format!(" {}\n", g.via));
587 s.push_str(&format!(" {}\n", g.cmd));
588 }
589 }
590 if !p.skipped.is_empty() {
591 s.push_str(&format!("\nskipped ({}):\n", p.skipped.len()));
592 for k in &p.skipped {
593 s.push_str(&format!(" {}\n", k));
594 }
595 }
596 if p.unresolved {
597 s.push_str(
598 "\nAn unresolved pane means guessing, so it was left alone: restart it by hand\n\
599 with `claude -c` in that pane, or from its /resume picker. Each session records\n\
600 its pane at the next SessionStart, so a pane resolves cleanly once restarted.\n",
601 );
602 }
603 s
604}
605
606pub fn restart_pane(pane: &str, pid: i32, cmd: &str) -> bool {
613 use std::thread::sleep;
614 use std::time::Duration;
615
616 tmux::run(&["send-keys", "-t", pane, "C-c"]);
617 sleep(Duration::from_millis(300));
618 tmux::run(&["send-keys", "-t", pane, "C-c"]);
619
620 let mut waited = 0;
621 let mut sent_exit = false;
622 while alive(pid) {
623 sleep(Duration::from_millis(400));
624 waited += 1;
625 if waited >= 6 && !sent_exit {
626 tmux::run(&["send-keys", "-t", pane, "/exit", "Enter"]);
627 sent_exit = true;
628 }
629 if waited >= 30 {
630 return false;
631 }
632 }
633 sleep(Duration::from_millis(500));
634 tmux::run(&["send-keys", "-t", pane, "C-c"]);
635 sleep(Duration::from_millis(200));
636 tmux::run(&["send-keys", "-t", pane, cmd, "Enter"])
637}
638
639fn alive(pid: i32) -> bool {
642 std::path::Path::new(&format!("/proc/{}", pid)).exists()
643}
644
645pub fn confirm_yes(answer: &str) -> bool {
648 matches!(answer.trim(), "" | "y" | "Y" | "yes" | "YES" | "Yes")
649}
650
651pub struct Live {
653 pub versions_dir: String,
654}
655
656impl Env for Live {
657 fn capture(&self, pane: &str) -> String {
658 tmux::ask_raw(&["capture-pane", "-p", "-t", pane]).unwrap_or_default()
659 }
660 fn capture_zoomed(&self, pane: &str) -> Option<String> {
661 capture_zoomed(pane)
662 }
663 fn hook_state(&self, pane: &str, pid: i32) -> Option<String> {
664 taimux_core::hook::hook_state_of(pane, pid)
665 }
666 fn own_state(&self, pid: i32, screen: &str) -> Option<state::State> {
667 taimux_core::status::of(pid, &|| screen.to_string()).and_then(|o| o.state())
668 }
669 fn elsewhere(&self, pane: &str, pid: i32) -> Option<Elsewhere> {
670 let o =
672 taimux_core::status::of(pid, &|| self.capture(pane)).filter(|o| o.via.elsewhere())?;
673 let id = if o.job.is_empty() {
674 o.session_id.get(..8).unwrap_or(&o.session_id)
675 } else {
676 &o.job
677 };
678 Some(Elsewhere {
679 id: id.to_string(),
680 pid: o.pid,
681 version: version_of_pid(o.pid, &self.versions_dir),
682 moved: o.via == taimux_core::status::Via::MovedTo,
683 })
684 }
685 fn version_of_pid(&self, pid: i32) -> Option<String> {
686 version_of_pid(pid, &self.versions_dir)
687 }
688 fn cwd_of(&self, pid: i32) -> Option<String> {
689 std::fs::read_link(format!("/proc/{}/cwd", pid))
690 .ok()
691 .map(|p| p.to_string_lossy().into_owned())
692 .filter(|s| !s.is_empty())
693 }
694 fn argv_of(&self, pid: i32) -> Vec<String> {
695 conv::argv_of(pid)
696 }
697 fn resolve(&self, pane: &str, cwd: &str, title: &str, pid: i32) -> Result<String, String> {
698 conv::resolve(pane, cwd, title, pid)
699 .map(|r| format!("{}\t{}", r.transcript.display(), r.why))
700 }
701 fn read_transcript(&self, path: &str) -> Option<String> {
702 std::fs::read_to_string(path).ok()
703 }
704 fn now(&self) -> i64 {
705 std::time::SystemTime::now()
706 .duration_since(std::time::UNIX_EPOCH)
707 .map(|d| d.as_secs() as i64)
708 .unwrap_or(0)
709 }
710}
711
712pub fn installed(launcher: &str, versions_dir: &str) -> Result<String, String> {
715 let target = std::fs::canonicalize(launcher)
716 .map(|p| p.to_string_lossy().into_owned())
717 .unwrap_or_default();
718 let prefix = format!("{}/", versions_dir);
719 match target.strip_prefix(&prefix) {
720 Some(rest) if !rest.is_empty() => Ok(rest.split('/').next().unwrap_or(rest).to_string()),
721 _ => Err(format!(
722 "restart: {} does not point into {} (got '{}')",
723 launcher,
724 versions_dir,
725 if target.is_empty() {
726 "nothing"
727 } else {
728 &target
729 }
730 )),
731 }
732}
733
734pub fn versions_dir() -> String {
735 format!(
736 "{}/.local/share/claude/versions",
737 std::env::var("HOME").unwrap_or_default()
738 )
739}
740
741pub fn launcher() -> String {
742 format!(
743 "{}/.local/bin/claude",
744 std::env::var("HOME").unwrap_or_default()
745 )
746}
747
748#[cfg(test)]
749mod tests {
750 use super::*;
751
752 #[test]
753 fn a_timestamp_becomes_epoch_seconds() {
754 assert_eq!(parse_iso8601("2026-09-02T01:23:45.678Z"), Some(1788312225));
756 assert_eq!(parse_iso8601("1970-01-01T00:00:00Z"), Some(0));
757 assert_eq!(parse_iso8601("2024-02-29T00:00:00Z"), Some(1709164800));
759 }
760
761 #[test]
765 fn an_unparseable_timestamp_is_no_answer() {
766 assert_eq!(parse_iso8601(""), None);
767 assert_eq!(parse_iso8601("yesterday"), None);
768 assert_eq!(parse_iso8601("2026-09-02 01:23:45"), None);
769 assert_eq!(parse_iso8601("2026-13-02T01:23:45Z"), None);
770 }
771
772 #[test]
773 fn a_tool_call_still_running_is_not_settled() {
774 let t = r#"{"type":"assistant","message":{"content":[{"type":"tool_use"}]},"timestamp":"2020-01-01T00:00:00Z"}"#;
775 assert_eq!(
776 transcript_is_settled(t, 1788312225),
777 Err("a tool call is still running".into())
778 );
779 }
780
781 #[test]
783 fn recent_activity_is_not_settled_whatever_the_screen_said() {
784 let t = r#"{"type":"user","timestamp":"2026-09-02T01:23:45Z"}"#;
785 assert!(transcript_is_settled(t, 1788312225 + 10).is_err());
786 assert!(transcript_is_settled(t, 1788312225 + 100).is_ok());
787 }
788
789 #[test]
790 fn an_empty_or_odd_transcript_does_not_block() {
791 assert!(transcript_is_settled("", 0).is_ok());
792 assert!(transcript_is_settled("not json at all\n", 0).is_ok());
793 assert!(transcript_is_settled(r#"{"type":"user"}"#, 0).is_ok());
795 }
796
797 #[test]
801 fn a_dialog_on_screen_blocks_a_restart() {
802 let footer = "some output\n\nDo you want to proceed?\n";
803 assert_eq!(
804 screen_has_no_dialog(footer),
805 Err("a dialog is waiting for an answer".into())
806 );
807 let choice = "some output\n1. Yes\n2. No\n❯ 1. Yes\n";
808 assert_eq!(
809 screen_has_no_dialog(choice),
810 Err("a dialog is waiting for an answer".into())
811 );
812 assert!(screen_has_no_dialog("some output\n❯ \n").is_ok());
814 }
815
816 #[test]
819 fn a_half_pressed_ctrl_c_blocks_a_restart() {
820 let screen = "work\n\nPress Ctrl-C again to exit\n";
821 assert_eq!(
822 screen_has_no_dialog(screen),
823 Err("a Ctrl-C is already half-pressed".into())
824 );
825 }
826
827 #[test]
828 fn an_empty_prompt_box_is_no_draft() {
829 assert!(screen_has_no_draft("stuff\n❯ \n").is_ok());
830 assert!(screen_has_no_draft("stuff\n❯ \u{a0}\u{a0}\n").is_ok());
832 assert_eq!(
833 screen_has_no_draft("stuff\n❯ half a thought\n"),
834 Err("unsent text in the prompt box".into())
835 );
836 }
837
838 #[test]
841 fn a_pane_tall_enough_to_read_is_left_alone() {
842 assert!(zoom_steps("%1", false, 6, 40, "%2", "%3").is_none());
844 assert!(zoom_steps("%1", false, 40, 40, "%2", "%3").is_none());
845 assert!(zoom_steps("%1", false, 3, 3, "%2", "%3").is_none());
847 assert!(zoom_steps("%1", false, 3, 5, "%2", "%3").is_none());
848 }
849
850 #[test]
854 fn a_short_pane_is_zoomed_and_the_selection_put_back() {
855 let (go, back) = zoom_steps("%1", false, 3, 17, "%2", "%3").unwrap();
856 assert_eq!(go, vec![vec!["resize-pane", "-Z", "-t", "%1"]]);
857 assert_eq!(
858 back,
859 vec![
860 vec!["resize-pane", "-Z", "-t", "%1"],
861 vec!["select-pane", "-t", "%3"],
862 vec!["select-pane", "-t", "%2"],
863 ]
864 );
865 }
866
867 #[test]
871 fn a_window_zoomed_elsewhere_is_handed_back_zoomed() {
872 let (go, back) = zoom_steps("%1", true, 3, 17, "%2", "%3").unwrap();
873 assert_eq!(
874 go,
875 vec![
876 vec!["resize-pane", "-Z", "-t", "%1"],
877 vec!["resize-pane", "-Z", "-t", "%1"],
878 ]
879 );
880 assert_eq!(
881 back,
882 vec![
883 vec!["resize-pane", "-Z", "-t", "%1"],
884 vec!["select-pane", "-t", "%3"],
885 vec!["select-pane", "-t", "%2"],
886 vec!["resize-pane", "-Z", "-t", "%2"],
887 ]
888 );
889 }
890
891 #[test]
894 fn an_active_short_pane_has_no_selection_to_restore() {
895 let (go, back) = zoom_steps("%1", false, 3, 17, "%1", "%3").unwrap();
896 assert_eq!(go.len(), 1);
897 assert_eq!(back, vec![vec!["resize-pane", "-Z", "-t", "%1"]]);
898 }
899
900 #[test]
903 fn no_prompt_box_is_a_refusal() {
904 assert_eq!(
905 screen_has_no_draft("just some text\n"),
906 Err("no prompt box on screen".into())
907 );
908 assert!(screen_has_no_draft("").is_ok());
910 assert!(screen_has_no_draft(" \n\n").is_ok());
911 }
912
913 #[test]
914 fn a_bare_enter_confirms() {
915 assert!(confirm_yes(""));
916 assert!(confirm_yes("y"));
917 assert!(confirm_yes("YES"));
918 assert!(!confirm_yes("n"));
919 assert!(!confirm_yes("no"));
920 assert!(!confirm_yes("maybe"));
921 }
922
923 #[test]
924 fn the_launcher_must_point_into_the_versions_dir() {
925 let root = std::env::temp_dir().join(format!("jmrs{}", std::process::id()));
926 let vers = root.join("versions");
927 std::fs::create_dir_all(&vers).unwrap();
928 std::fs::write(vers.join("2.1.258"), "x").unwrap();
929 let link = root.join("claude");
930 std::os::unix::fs::symlink(vers.join("2.1.258"), &link).unwrap();
931 assert_eq!(
932 installed(&link.to_string_lossy(), &vers.to_string_lossy()),
933 Ok("2.1.258".into())
934 );
935 std::fs::write(root.join("elsewhere"), "x").unwrap();
937 std::fs::remove_file(&link).unwrap();
938 std::os::unix::fs::symlink(root.join("elsewhere"), &link).unwrap();
939 let e = installed(&link.to_string_lossy(), &vers.to_string_lossy()).expect_err("refused");
940 assert!(e.contains("elsewhere"));
941 let _ = std::fs::remove_dir_all(&root);
942 }
943}
944
945pub fn nonpane_pids(matched: &[i32], versions_dir: &str) -> Vec<i32> {
951 let mut out = Vec::new();
952 for e in std::fs::read_dir("/proc").into_iter().flatten().flatten() {
953 let Some(pid) = e.file_name().to_str().and_then(|s| s.parse::<i32>().ok()) else {
954 continue;
955 };
956 if matched.contains(&pid) {
957 continue;
958 }
959 let comm = std::fs::read_to_string(format!("/proc/{}/comm", pid)).unwrap_or_default();
962 let argv = conv::argv_of(pid);
963 let is_claude = comm.trim() == "claude"
964 || argv
965 .first()
966 .map(|a| a.starts_with(&format!("{}/", versions_dir)))
967 .unwrap_or(false);
968 if is_claude {
969 out.push(pid);
970 }
971 }
972 out.sort_unstable();
973 out
974}
975
976fn json_object_with_prefix(text: &str, key: &str, prefix: &str) -> Option<String> {
984 let needle = format!("\"{}\":\"{}", key, prefix);
985 let at = text.find(&needle).or_else(|| {
986 let spaced = format!("\"{}\": \"{}", key, prefix);
987 text.find(&spaced)
988 })?;
989 let mut depth = 0i32;
991 let bytes = text.as_bytes();
992 let mut start = None;
993 for i in (0..at).rev() {
994 match bytes[i] {
995 b'}' => depth += 1,
996 b'{' => {
997 if depth == 0 {
998 start = Some(i);
999 break;
1000 }
1001 depth -= 1;
1002 }
1003 _ => {}
1004 }
1005 }
1006 let start = start?;
1007 let mut depth = 0i32;
1009 for i in start..bytes.len() {
1010 match bytes[i] {
1011 b'{' => depth += 1,
1012 b'}' => {
1013 depth -= 1;
1014 if depth == 0 {
1015 return Some(text[start..=i].to_string());
1016 }
1017 }
1018 _ => {}
1019 }
1020 }
1021 None
1022}
1023
1024pub fn describe_nonpane(argv: &[String], agents_json: &str) -> String {
1031 if argv.is_empty() {
1032 return "gone".into();
1033 }
1034 let (mut sid, mut res, mut forked) = (String::new(), String::new(), false);
1035 for i in 1..argv.len() {
1036 match argv[i].as_str() {
1037 "--fork-session" => forked = true,
1038 "--session-id" => sid = argv.get(i + 1).cloned().unwrap_or_default(),
1039 "-r" | "--resume" => res = argv.get(i + 1).cloned().unwrap_or_default(),
1040 _ => {}
1041 }
1042 }
1043 let own = base_id(if sid.is_empty() { &res } else { &sid });
1044 let parent = if forked && !res.is_empty() {
1045 base_id(&res)
1046 } else {
1047 String::new()
1048 };
1049
1050 let (mut kind, mut st, mut name) = ("?".to_string(), "?".to_string(), String::new());
1051 if !own.is_empty() {
1052 if let Some(obj) = json_object_with_prefix(agents_json, "sessionId", &own) {
1053 let f = |k: &str| taimux_core::json::field(&obj, k);
1054 let k = f("kind");
1055 if !k.is_empty() {
1056 kind = k;
1057 }
1058 let s = {
1059 let a = f("state");
1060 if a.is_empty() {
1061 f("status")
1062 } else {
1063 a
1064 }
1065 };
1066 if !s.is_empty() {
1067 st = s;
1068 }
1069 name = f("name");
1070 }
1071 }
1072 let mut out = format!("{} {}", kind, st);
1073 if forked {
1074 out.push_str(" fork");
1075 }
1076 if !name.is_empty() {
1077 out.push_str(&format!(" \"{}\"", name));
1078 }
1079 if !own.is_empty() {
1080 out.push_str(&format!(" [{}]", own.chars().take(8).collect::<String>()));
1081 }
1082 if !parent.is_empty() {
1083 out.push_str(&format!(
1084 " of [{}]",
1085 parent.chars().take(8).collect::<String>()
1086 ));
1087 }
1088 out
1089}
1090
1091fn base_id(s: &str) -> String {
1093 if s.is_empty() {
1094 return String::new();
1095 }
1096 let b = s.rsplit('/').next().unwrap_or(s);
1097 b.strip_suffix(".jsonl").unwrap_or(b).to_string()
1098}
1099
1100#[cfg(test)]
1101mod nonpane_tests {
1102 use super::*;
1103
1104 fn v(a: &[&str]) -> Vec<String> {
1105 a.iter().map(|s| s.to_string()).collect()
1106 }
1107
1108 #[test]
1109 fn a_session_id_is_read_out_of_a_path_or_taken_as_it_stands() {
1110 assert_eq!(base_id("/a/b/263946b5-9bd7.jsonl"), "263946b5-9bd7");
1111 assert_eq!(base_id("263946b5"), "263946b5");
1112 assert_eq!(base_id(""), "");
1113 }
1114
1115 #[test]
1119 fn the_right_object_comes_back_whole() {
1120 let j = r#"[{"sessionId":"aaa111","kind":"task","meta":{"a":1},"name":"first"},
1121 {"sessionId":"bbb222","kind":"agent","name":"second"}]"#;
1122 let o = json_object_with_prefix(j, "sessionId", "bbb222").expect("found");
1123 assert!(o.contains("second"));
1124 assert!(!o.contains("first"));
1125 let o = json_object_with_prefix(j, "sessionId", "aaa").expect("found by prefix");
1126 assert!(o.contains("first"));
1127 assert!(
1128 o.contains("\"meta\":{\"a\":1}"),
1129 "nested field truncated: {}",
1130 o
1131 );
1132 assert!(json_object_with_prefix(j, "sessionId", "zzz").is_none());
1133 }
1134
1135 #[test]
1136 fn a_process_with_no_argv_is_simply_gone() {
1137 assert_eq!(describe_nonpane(&[], "[]"), "gone");
1138 }
1139
1140 #[test]
1141 fn an_unnamed_session_still_says_what_it_can() {
1142 let d = describe_nonpane(&v(&["claude", "--session-id", "263946b5-9bd7"]), "[]");
1143 assert_eq!(d, "? ? [263946b5]");
1144 }
1145
1146 #[test]
1147 fn a_named_one_says_kind_state_and_name() {
1148 let j =
1149 r#"[{"sessionId":"263946b5-9bd7","kind":"task","state":"running","name":"the thing"}]"#;
1150 let d = describe_nonpane(&v(&["claude", "--session-id", "263946b5-9bd7"]), j);
1151 assert_eq!(d, "task running \"the thing\" [263946b5]");
1152 }
1153
1154 #[test]
1157 fn status_stands_in_for_state() {
1158 let j = r#"[{"sessionId":"aaa11111","kind":"agent","status":"idle"}]"#;
1159 let d = describe_nonpane(&v(&["claude", "--session-id", "aaa11111"]), j);
1160 assert_eq!(d, "agent idle [aaa11111]");
1161 }
1162
1163 #[test]
1166 fn a_fork_names_its_parent_too() {
1167 let d = describe_nonpane(
1168 &v(&[
1169 "claude",
1170 "--session-id",
1171 "child111",
1172 "--fork-session",
1173 "--resume",
1174 "/p/parent22.jsonl",
1175 ]),
1176 "[]",
1177 );
1178 assert_eq!(d, "? ? fork [child111] of [parent22]");
1179 }
1180}
1181
1182#[cfg(test)]
1183mod plan_tests {
1184 use super::*;
1185
1186 struct Fake {
1191 vers: HashMap<i32, String>,
1193 screens: HashMap<String, String>,
1195 resolved: HashMap<String, Result<String, String>>,
1197 zoomed: HashMap<String, String>,
1200 zooms: std::cell::Cell<usize>,
1203 hooks: HashMap<String, String>,
1205 own: HashMap<i32, state::State>,
1207 away: HashMap<i32, (String, String, bool)>,
1210 transcript: String,
1211 now: i64,
1212 }
1213
1214 impl Env for Fake {
1215 fn capture(&self, pane: &str) -> String {
1216 self.screens.get(pane).cloned().unwrap_or_default()
1217 }
1218 fn capture_zoomed(&self, pane: &str) -> Option<String> {
1219 let bigger = self.zoomed.get(pane).cloned();
1220 if bigger.is_some() {
1221 self.zooms.set(self.zooms.get() + 1);
1222 }
1223 bigger
1224 }
1225 fn hook_state(&self, pane: &str, _pid: i32) -> Option<String> {
1226 self.hooks.get(pane).cloned()
1227 }
1228 fn own_state(&self, pid: i32, _screen: &str) -> Option<state::State> {
1229 self.own.get(&pid).copied()
1230 }
1231 fn elsewhere(&self, _pane: &str, pid: i32) -> Option<Elsewhere> {
1232 self.away.get(&pid).map(|(id, ver, moved)| Elsewhere {
1233 id: id.clone(),
1234 pid: 1000 + pid,
1235 version: Some(ver.clone()),
1236 moved: *moved,
1237 })
1238 }
1239 fn version_of_pid(&self, pid: i32) -> Option<String> {
1240 self.vers.get(&pid).cloned()
1241 }
1242 fn cwd_of(&self, _pid: i32) -> Option<String> {
1243 Some("/w".into())
1244 }
1245 fn argv_of(&self, _pid: i32) -> Vec<String> {
1246 vec!["claude".into()]
1247 }
1248 fn resolve(&self, pane: &str, _c: &str, _t: &str, _p: i32) -> Result<String, String> {
1249 self.resolved
1250 .get(pane)
1251 .cloned()
1252 .unwrap_or_else(|| Err("no candidate".into()))
1253 }
1254 fn read_transcript(&self, _path: &str) -> Option<String> {
1255 Some(self.transcript.clone())
1256 }
1257 fn now(&self) -> i64 {
1258 self.now
1259 }
1260 }
1261
1262 fn fake() -> Fake {
1263 let mut vers = HashMap::new();
1264 vers.insert(11, "2.1.100".to_string()); vers.insert(22, "2.1.258".to_string()); let mut screens = HashMap::new();
1267 screens.insert("%1".to_string(), "some output\n❯ \n".to_string());
1269 screens.insert("%2".to_string(), "some output\n❯ \n".to_string());
1270 let mut resolved = HashMap::new();
1271 resolved.insert("%1".to_string(), Ok("/t/a.jsonl\tpane map".to_string()));
1272 Fake {
1273 vers,
1274 screens,
1275 resolved,
1276 zoomed: HashMap::new(),
1277 zooms: std::cell::Cell::new(0),
1278 hooks: HashMap::new(),
1279 own: HashMap::new(),
1280 away: HashMap::new(),
1281 transcript: r#"{"type":"user","timestamp":"2020-01-01T00:00:00Z"}"#.to_string(),
1282 now: 1788312225,
1283 }
1284 }
1285
1286 fn opts() -> Opts {
1287 Opts {
1288 include_busy: false,
1289 only_panes: Vec::new(),
1290 force_transcript: None,
1291 self_pane: String::new(),
1292 }
1293 }
1294
1295 const ROWS: &str = "%1\tw:1.1\t/w\tclaude\t11\tclaude\tproj: the stale one\n\
1296 %2\tw:2.1\t/w\tclaude\t22\tclaude\tproj: the current one";
1297
1298 fn plan_of(e: &Fake, o: &Opts) -> Plan {
1299 plan(ROWS, "2.1.258", "/l/claude", o, e, "/nowhere", &|| {
1300 "[]".into()
1301 })
1302 }
1303
1304 #[test]
1305 fn a_stale_pane_is_planned_and_a_current_one_is_not() {
1306 let p = plan_of(&fake(), &opts());
1307 assert_eq!(p.go.len(), 1);
1308 assert_eq!(p.go[0].pane, "%1");
1309 assert_eq!(p.go[0].cmd, "command claude --resume /t/a.jsonl");
1310 assert_eq!(p.go[0].via, "2.1.100 -> 2.1.258, pane map, idle");
1311 assert!(p.skipped.is_empty());
1312 }
1313
1314 #[test]
1317 fn the_rendered_plan_reads_the_way_it_always_did() {
1318 let out = render(&plan_of(&fake(), &opts()));
1319 assert_eq!(
1320 out,
1321 "claude: 2.1.258 installed at /l/claude\n\n\
1322 to restart (1):\n\
1323 \x20 %1 w:1.1 proj: the stale one\n\
1324 \x20 2.1.100 -> 2.1.258, pane map, idle\n\
1325 \x20 command claude --resume /t/a.jsonl\n"
1326 );
1327 }
1328
1329 #[test]
1331 fn this_pane_is_never_restarted() {
1332 let mut o = opts();
1333 o.self_pane = "%1".into();
1334 let p = plan_of(&fake(), &o);
1335 assert!(p.go.is_empty());
1336 assert!(p.skipped[0].contains("this pane"));
1337 assert!(p.skipped[0].contains("killing it would kill taimux"));
1338 }
1339
1340 #[test]
1341 fn a_pane_that_is_not_idle_waits_for_include_busy() {
1342 let mut e = fake();
1343 e.screens
1345 .insert("%1".into(), "Twisting… (35s · ↓ 1.6k tokens)\n❯ \n".into());
1346 let p = plan_of(&e, &opts());
1347 assert!(p.go.is_empty());
1348 assert!(p.skipped[0].contains("rerun when idle, or --include-busy"));
1349
1350 let mut o = opts();
1351 o.include_busy = true;
1352 assert_eq!(plan_of(&e, &o).go.len(), 1);
1353 }
1354
1355 #[test]
1359 fn a_session_that_says_it_is_busy_is_busy() {
1360 let mut e = fake();
1361 e.hooks.insert("%1".into(), "input".into());
1362 e.own.insert(11, state::State::Run);
1363 let p = plan_of(&e, &opts());
1364 assert!(p.go.is_empty());
1365 assert!(
1366 p.skipped[0].contains("run: rerun when idle"),
1367 "{:?}",
1368 p.skipped
1369 );
1370 e.hooks.insert("%1".into(), "run".into());
1372 e.own.insert(11, state::State::Idle);
1373 assert_eq!(plan_of(&e, &opts()).go.len(), 1);
1374 }
1375
1376 #[test]
1380 fn a_pane_whose_conversation_moved_to_the_background_is_left_alone() {
1381 let mut e = fake();
1382 e.own.insert(11, state::State::Idle);
1383 e.away
1384 .insert(11, ("2447b564".into(), "2.1.100".into(), true));
1385 let mut o = opts();
1386 o.include_busy = true; let p = plan_of(&e, &o);
1388 assert!(p.go.is_empty());
1389 assert!(
1390 p.skipped[0].contains("moved to background session 2447b564: claude attach 2447b564"),
1391 "{:?}",
1392 p.skipped
1393 );
1394 }
1395
1396 #[test]
1400 fn an_attached_pane_is_judged_by_its_workers_version() {
1401 let mut e = fake();
1402 e.away
1403 .insert(22, ("880ae832".into(), "2.1.250".into(), false));
1404 let p = plan_of(&e, &opts());
1405 assert_eq!(p.go.len(), 1, "{:?}", p.skipped);
1406 assert_eq!(p.go[0].pane, "%1");
1407 assert!(
1408 p.skipped.iter().any(
1409 |s| s.starts_with("%2 w:2.1 2.1.250, attached to background session 880ae832")
1410 ),
1411 "{:?}",
1412 p.skipped
1413 );
1414
1415 let mut e = fake();
1416 e.away
1417 .insert(11, ("880ae832".into(), "2.1.258".into(), false));
1418 let p = plan_of(&e, &opts());
1419 assert!(p.go.is_empty());
1420 assert!(
1421 p.skipped.iter().all(|s| !s.starts_with("%1")),
1422 "{:?}",
1423 p.skipped
1424 );
1425 }
1426
1427 #[test]
1430 fn a_pane_with_work_in_flight_waits_for_include_busy() {
1431 let mut e = fake();
1432 e.screens.insert(
1433 "%1".into(),
1434 "✻ Cogitated for 1m 3s · done 4:55 PM · 2 shells still running\n❯ \n".into(),
1435 );
1436 let p = plan_of(&e, &opts());
1437 assert!(p.go.is_empty());
1438 assert!(
1439 p.skipped[0].contains("work still in flight"),
1440 "{:?}",
1441 p.skipped
1442 );
1443
1444 let mut e = fake();
1446 e.hooks.insert("%1".into(), "bg".into());
1447 let p = plan_of(&e, &opts());
1448 assert!(p.go.is_empty());
1449 assert!(
1450 p.skipped[0].contains("work still in flight"),
1451 "{:?}",
1452 p.skipped
1453 );
1454
1455 let mut o = opts();
1456 o.include_busy = true;
1457 assert_eq!(plan_of(&e, &o).go.len(), 1);
1458 }
1459
1460 #[test]
1463 fn a_dialog_blocks_a_restart_even_with_include_busy() {
1464 let mut e = fake();
1465 e.screens
1466 .insert("%1".into(), "output\n\nDo you want to proceed?\n".into());
1467 let mut o = opts();
1468 o.include_busy = true;
1469 let p = plan_of(&e, &o);
1470 assert!(p.go.is_empty());
1471 assert!(p.skipped[0].contains("a dialog is waiting for an answer"));
1472 }
1473
1474 #[test]
1475 fn an_unsent_draft_is_left_alone() {
1476 let mut e = fake();
1477 e.screens
1478 .insert("%1".into(), "output\n❯ half a thought\n".into());
1479 let p = plan_of(&e, &opts());
1480 assert!(p.skipped[0].contains("unsent text in the prompt box"));
1481 }
1482
1483 #[test]
1487 fn a_pane_too_short_for_its_box_is_read_zoomed() {
1488 let mut e = fake();
1489 e.screens.insert(
1490 "%1".into(),
1491 " current: 2.1.100 · latest…\n────────\n".into(),
1492 );
1493 e.zoomed.insert("%1".into(), "some output\n❯ \n".into());
1494 let p = plan_of(&e, &opts());
1495 assert_eq!(e.zooms.get(), 1);
1496 assert_eq!(p.go.len(), 1);
1497 assert_eq!(p.go[0].pane, "%1");
1498 assert!(p.skipped.is_empty());
1499 }
1500
1501 #[test]
1506 fn a_draft_hidden_by_a_short_pane_still_refuses() {
1507 let mut e = fake();
1508 e.screens
1509 .insert("%1".into(), " current: 2.1.100…\n".into());
1510 e.zoomed
1511 .insert("%1".into(), "output\n❯ half a thought\n".into());
1512 let p = plan_of(&e, &opts());
1513 assert_eq!(e.zooms.get(), 1);
1514 assert!(p.go.is_empty());
1515 assert!(p.skipped[0].contains("unsent text in the prompt box"));
1516 }
1517
1518 #[test]
1522 fn a_dialog_hidden_by_a_short_pane_is_found_by_the_zoom() {
1523 let mut e = fake();
1524 e.screens.insert("%1".into(), " Bash command\n".into());
1525 e.zoomed.insert(
1526 "%1".into(),
1527 "Do you want to proceed?\n❯ 1. Yes\n 2. No\n".into(),
1528 );
1529 let mut o = opts();
1530 o.include_busy = true;
1531 let p = plan_of(&e, &o);
1532 assert!(p.go.is_empty());
1533 assert!(p.skipped[0].contains("a dialog is waiting for an answer"));
1534 }
1535
1536 #[test]
1539 fn a_pane_that_shows_its_box_is_not_zoomed() {
1540 let e = fake();
1541 let p = plan_of(&e, &opts());
1542 assert_eq!(e.zooms.get(), 0);
1543 assert_eq!(p.go.len(), 1);
1544 }
1545
1546 #[test]
1549 fn a_recently_active_transcript_is_left_alone() {
1550 let mut e = fake();
1551 e.transcript = r#"{"type":"user","timestamp":"2026-09-02T01:23:45Z"}"#.into();
1552 e.now = 1788312225 + 10;
1553 let p = plan_of(&e, &opts());
1554 assert!(p.skipped[0].contains("active in the last 45s"));
1555 }
1556
1557 #[test]
1558 fn an_unresolved_pane_says_so_and_earns_the_paragraph() {
1559 let mut e = fake();
1560 e.resolved
1561 .insert("%1".into(), Err("3 transcripts share this title".into()));
1562 let p = plan_of(&e, &opts());
1563 assert!(p.go.is_empty());
1564 assert!(p.unresolved);
1565 assert!(p.skipped[0].contains("unresolved: 3 transcripts share this title"));
1566 assert!(render(&p).contains("restart it by hand"));
1567 }
1568
1569 #[test]
1572 fn one_transcript_is_never_resumed_into_two_panes() {
1573 let mut e = fake();
1574 e.vers.insert(22, "2.1.100".into()); e.resolved
1576 .insert("%2".into(), Ok("/t/a.jsonl\tpane map".into()));
1577 let p = plan_of(&e, &opts());
1578 assert_eq!(p.go.len(), 1);
1579 assert_eq!(p.go[0].pane, "%1");
1580 assert!(p.skipped[0].contains("resolves to the same transcript as %1"));
1581 }
1582
1583 #[test]
1584 fn only_panes_narrows_the_plan_without_changing_the_verdicts() {
1585 let mut o = opts();
1586 o.only_panes = vec!["%2".into()];
1587 let p = plan_of(&fake(), &o);
1588 assert!(p.go.is_empty());
1589 assert!(p.skipped.is_empty()); }
1591
1592 #[test]
1593 fn a_pane_with_no_session_process_is_reported_not_dropped() {
1594 let rows = "%9\tw:9.9\t/w\tclaude\t0\tclaude\tno pid here";
1595 let p = plan(rows, "2.1.258", "/l", &opts(), &fake(), "/nowhere", &|| {
1596 "[]".into()
1597 });
1598 assert!(p.go.is_empty());
1599 assert_eq!(p.skipped.len(), 1);
1600 assert!(p.skipped[0].contains("no session process was found"));
1601 }
1602
1603 #[test]
1604 fn nothing_to_restart_says_so() {
1605 let mut e = fake();
1606 e.vers.insert(11, "2.1.258".into());
1607 let out = render(&plan_of(&e, &opts()));
1608 assert!(out.contains("nothing to restart."));
1609 assert!(!out.contains("to restart ("));
1610 }
1611
1612 #[test]
1615 fn a_given_transcript_overrides_the_ladder() {
1616 let mut e = fake();
1617 e.resolved.insert("%1".into(), Err("no candidate".into()));
1618 let mut o = opts();
1619 o.force_transcript = Some("/given.jsonl".into());
1620 let p = plan_of(&e, &o);
1621 assert_eq!(p.go.len(), 1);
1622 assert!(p.go[0].via.contains("--transcript, given"));
1623 assert!(p.go[0].cmd.contains("--resume /given.jsonl"));
1624 }
1625}