1use std::io::{Read, Write};
13
14use crate::{remote, restart};
15
16fn clear(out: &mut impl Write) {
18 let _ = write!(out, "\x1b[H\x1b[2J");
19}
20
21enum Pressed {
29 Key(char),
30 Unreadable,
32}
33
34fn any_key() {
37 print!(" Press any key…");
38 let _ = std::io::stdout().flush();
39 if let Pressed::Unreadable = read_one_key() {
40 println!("\r\n (no readable terminal to wait on, so this was not held)");
45 let _ = std::io::stdout().flush();
46 }
47}
48
49fn read_one_key() -> Pressed {
50 let Ok(mut tty) = std::fs::File::open("/dev/tty") else {
51 return Pressed::Unreadable;
52 };
53 let raw = crossterm::terminal::enable_raw_mode().is_ok();
55 let mut b = [0u8; 1];
56 let got = match tty.read(&mut b) {
57 Ok(1) => Pressed::Key(b[0] as char),
58 _ => Pressed::Unreadable,
60 };
61 if raw {
62 let _ = crossterm::terminal::disable_raw_mode();
63 }
64 got
65}
66
67pub fn report_failed_child(what: &str, e: &std::io::Error) {
82 let Ok(mut tty) = std::fs::OpenOptions::new().write(true).open("/dev/tty") else {
83 return;
84 };
85 let _ = write!(
89 tty,
90 "\x1b[H\x1b[2J\x1b[1mtaimux: could not run {}\x1b[0m\r\n\r\n {}\r\n\r\n\
91 \x20 The picker re-runs its OWN binary for this, so the usual cause is\r\n\
92 \x20 that binary moving or being rebuilt underneath a running picker.\r\n\
93 \x20 Closing and reopening the picker picks up the new one.\r\n\r\n\
94 \x20 Press any key…",
95 what, e
96 );
97 let _ = tty.flush();
98 let _ = read_one_key();
99}
100
101fn plan_panes(plan: &str) -> Vec<&str> {
108 let mut on = false;
109 let mut out = Vec::new();
110 for l in plan.lines() {
111 if l.starts_with("to restart (") {
112 on = true;
113 continue;
114 }
115 if l.starts_with("skipped (") {
116 on = false;
117 }
118 if on && l.starts_with(" ") && !l.starts_with(" ") {
120 out.push(l);
121 }
122 }
123 out
124}
125
126fn count_in(plan: &str, heading: &str) -> Option<usize> {
127 plan.lines()
128 .find(|l| l.starts_with(heading))
129 .and_then(|l| l.split(['(', ')']).nth(1))
130 .and_then(|n| n.parse().ok())
131}
132
133fn why_for(plan: &str, pane: &str) -> Option<String> {
135 let needle = format!(" {} ", pane);
136 plan.lines()
137 .find(|l| l.contains(&needle))
138 .map(|l| l.trim_start().to_string())
139}
140
141pub fn note(line: &str) {
149 let log = taimux_core::paths::runtime_dir().join("restart.log");
150 if let Some(d) = log.parent() {
151 let _ = std::fs::create_dir_all(d);
152 }
153 if let Ok(mut f) = std::fs::OpenOptions::new()
154 .create(true)
155 .append(true)
156 .open(&log)
157 {
158 let _ = writeln!(f, "--- {} {}", taimux_core::log::stamp(), line);
159 }
160}
161
162fn detached(
176 cmd: &mut std::process::Command,
177 out: std::fs::File,
178 err: std::fs::File,
179) -> &mut std::process::Command {
180 cmd.stdin(std::process::Stdio::null())
181 .stdout(out)
182 .stderr(err)
183}
184
185pub fn restart_detached(exe: &str, pane: &str, force: bool) {
186 let log = taimux_core::paths::runtime_dir().join("restart.log");
187 note(if pane.is_empty() {
188 "all outdated panes"
189 } else {
190 pane
191 });
192 let mut args: Vec<String> = vec!["restart".into(), "-y".into()];
193 if pane.starts_with('%') {
194 args.push("--pane".into());
195 args.push(pane.into());
196 }
197 if force {
198 args.push("--include-busy".into());
199 }
200 let Ok(out) = std::fs::OpenOptions::new()
201 .create(true)
202 .append(true)
203 .open(&log)
204 else {
205 return;
206 };
207 let Ok(err) = out.try_clone() else { return };
208 let Ok(out2) = out.try_clone() else { return };
209 let spawned = detached(
214 std::process::Command::new("setsid").arg(exe).args(&args),
215 out2,
216 err,
217 )
218 .spawn();
219 if spawned.is_err() {
220 let Ok(out3) = std::fs::OpenOptions::new()
221 .create(true)
222 .append(true)
223 .open(&log)
224 else {
225 return;
226 };
227 let Ok(err2) = out3.try_clone() else { return };
228 let _ = detached(std::process::Command::new(exe).args(&args), out3, err2).spawn();
229 }
230}
231
232pub fn restart_one(exe: &str, pane: &str) {
234 let mut out = std::io::stdout();
235
236 if pane.starts_with("dead:") {
240 clear(&mut out);
241 println!("\x1b[1mtaimux: that session has already ended\x1b[0m\n");
242 println!(" There is nothing running to restart. Press Enter on it instead:");
243 println!(" it opens again in a new window, in its own directory.\n");
244 any_key();
245 return;
246 }
247
248 if let Some(host) = remote::pane_host(pane) {
253 clear(&mut out);
254 println!(
255 "\x1b[1mtaimux: {} is on {}\x1b[0m\n",
256 remote::pane_local(pane),
257 host
258 );
259 println!(" Restarting is local-only. From that host, or from here:\n");
260 println!(
261 " ssh {} taimux restart --pane {}\n",
262 host,
263 remote::pane_local(pane)
264 );
265 any_key();
266 return;
267 }
268 if !pane.starts_with('%') {
269 return; }
271
272 let agent = taimux_core::panes::agent_rows()
278 .lines()
279 .any(|l| l.split('\t').next() == Some(pane));
280 if !agent && !taimux_core::restarting::held().contains_key(pane) {
281 clear(&mut out);
282 println!("\x1b[1mtaimux: {} is not running an agent\x1b[0m\n", pane);
283 println!(" There is no session in it to restart.\n");
284 any_key();
285 return;
286 }
287
288 let plan = plan_of(exe, &["-n", "--pane", pane]);
289 if plan.contains("\nto restart (") || plan.starts_with("to restart (") {
290 restart_detached(exe, pane, false);
291 return;
292 }
293
294 clear(&mut out);
295 println!("\x1b[1mtaimux: {} will not restart cleanly\x1b[0m\n", pane);
296 let Some(why) = why_for(&plan, pane) else {
297 println!(" Nothing to do: it is already on the installed version, or it is");
298 println!(" not a claude pane.\n");
299 any_key();
300 return;
301 };
302 println!(" {}", why);
303
304 let forced = plan_of(exe, &["-n", "--pane", pane, "--include-busy"]);
308 if !(forced.contains("\nto restart (") || forced.starts_with("to restart (")) {
309 println!(
310 "\n Forcing would not help:\n {}",
311 why_for(&forced, pane).unwrap_or_else(|| "same refusal".into())
312 );
313 println!();
314 any_key();
315 return;
316 }
317
318 println!("\n Forcing accepts losing an in-flight turn. A pane holding a");
319 println!(" permission dialog is still refused, so nothing gets answered for you.");
320 print!("\n\x1b[1mForce the restart?\x1b[0m [Y/n] ");
321 let _ = out.flush();
322 let go = match read_one_key() {
326 Pressed::Key(c) => restart::confirm_yes(&c.to_string()),
327 Pressed::Unreadable => {
328 print!("\r\n (no readable terminal to answer on, so nothing was restarted)");
329 false
330 }
331 };
332 println!();
333 if go {
334 restart_detached(exe, pane, true);
335 println!(
336 "\n Forced, detached. Watch the version, or read\n {}",
337 taimux_core::paths::runtime_dir()
338 .join("restart.log")
339 .display()
340 );
341 std::thread::sleep(std::time::Duration::from_millis(1200));
342 } else {
343 println!("\n Left alone.");
344 std::thread::sleep(std::time::Duration::from_millis(600));
345 }
346}
347
348pub fn sweep(exe: &str) {
355 let mut out = std::io::stdout();
356 let at = std::time::Instant::now();
363 let plan = plan_of(exe, &["-n"]);
364 let planned = at.elapsed();
365 let n = count_in(&plan, "to restart (");
366 let skipped = count_in(&plan, "skipped (");
367
368 clear(&mut out);
369 println!("\x1b[1mtaimux: restart every outdated session\x1b[0m\n");
370
371 let Some(n) = n.filter(|n| *n >= 1) else {
372 println!("Nothing to restart. Either every session is already on the");
373 println!("installed version, or the ones behind it are busy.");
374 if let Some(s) = skipped {
375 println!("\n {} left alone.", s);
376 }
377 println!();
378 any_key();
379 return;
380 };
381
382 for l in plan_panes(&plan) {
383 println!("{}", l);
384 }
385 if let Some(s) = skipped {
386 println!("\n {} left alone (working, waiting, or unidentified).", s);
387 }
388 print!("\n\x1b[1mRestart {} session(s)?\x1b[0m [Y/n] ", n);
389 let _ = out.flush();
390 let go = match read_one_key() {
394 Pressed::Key(c) => restart::confirm_yes(&c.to_string()),
395 Pressed::Unreadable => {
396 print!("\r\n (no readable terminal to answer on, so nothing was restarted)");
397 false
398 }
399 };
400 println!();
401 if go {
402 note(&format!(
403 "sweep: {} to restart, plan took {:.1}s, {:.1}s from keypress to firing",
404 n,
405 planned.as_secs_f32(),
406 at.elapsed().as_secs_f32()
407 ));
408 restart_detached(exe, "", false);
409 println!(
410 "\nStarted, detached. Watch the version column, or read\n{}",
411 taimux_core::paths::runtime_dir()
412 .join("restart.log")
413 .display()
414 );
415 std::thread::sleep(std::time::Duration::from_millis(1200));
416 } else {
417 println!("\nNothing restarted.");
418 std::thread::sleep(std::time::Duration::from_millis(700));
419 }
420}
421
422fn plan_of(exe: &str, args: &[&str]) -> String {
428 std::process::Command::new(exe)
429 .arg("restart")
430 .args(args)
431 .output()
432 .map(|o| {
433 let mut s = String::from_utf8_lossy(&o.stdout).into_owned();
434 s.push_str(&String::from_utf8_lossy(&o.stderr));
435 s
436 })
437 .unwrap_or_default()
438}
439
440pub fn conversation_of(pane: &str) -> Result<(String, String), String> {
451 if let Some((agent, key)) = taimux_core::index::split_past_id(pane) {
452 return Ok((agent.to_string(), key.to_string()));
453 }
454 if pane == "dead:!" {
455 return Err("that row is a note, not a conversation".into());
456 }
457 if remote::pane_host(pane).is_some() {
458 return Err(format!(
459 "{} is on another host, and a handoff reads its transcript and starts \
460 an agent in its directory, both of which have to happen over there",
461 remote::pane_local(pane)
462 ));
463 }
464 let rows = taimux_core::panes::agent_rows();
465 let row = rows
466 .lines()
467 .map(|l| l.split('\t').collect::<Vec<_>>())
468 .find(|f| f.len() >= 5 && f[0] == pane)
469 .ok_or_else(|| format!("{} is not running an agent, or is not there any more", pane))?;
474 if row[3] != "claude" {
475 return Err(format!(
476 "taimux cannot tell which conversation a {} pane is on, so there is \
477 nothing to hand over. Only claude publishes that",
478 row[3]
479 ));
480 }
481 let pid: i32 = row[4].parse().unwrap_or(0);
482 let cwd = std::fs::read_link(format!("/proc/{}/cwd", pid))
483 .map(|p| p.to_string_lossy().into_owned())
484 .unwrap_or_else(|_| row[2].to_string());
485 match taimux_core::conv::resolve_from_pane(pane, &cwd, pid) {
486 Some(r) => Ok(("claude".into(), r.transcript.to_string_lossy().into_owned())),
487 None => Err("that pane's conversation could not be identified".into()),
488 }
489}
490
491pub fn handoff_one(pane: &str) {
493 let mut out = std::io::stdout();
494 clear(&mut out);
495
496 let (agent, key) = match conversation_of(pane) {
497 Ok(v) => v,
498 Err(why) => {
499 println!("\x1b[1mtaimux: nothing to hand off here\x1b[0m\n");
500 println!(" {}.\n", why);
501 any_key();
502 return;
503 }
504 };
505
506 let targets: Vec<&str> = taimux_core::handoff::installed()
510 .into_iter()
511 .filter(|t| *t != agent)
512 .collect();
513 if targets.is_empty() {
514 println!("\x1b[1mtaimux: no other agent is installed\x1b[0m\n");
515 println!(" A handoff starts a DIFFERENT tool on this conversation, and");
516 println!(" {} is the only one on your PATH.\n", agent);
517 any_key();
518 return;
519 }
520
521 let meta = taimux_core::agents::meta(&agent, &key);
522 let title = if meta.title.is_empty() {
523 "(no title)"
524 } else {
525 &meta.title
526 };
527 println!(
528 "\x1b[1mtaimux: continue this {} conversation elsewhere\x1b[0m\n",
529 taimux_core::handoff::display_name(&agent)
530 );
531 println!(" \x1b[1;36m{}\x1b[0m", title);
532 println!(
533 " \x1b[90m{}\x1b[0m\n",
534 if meta.cwd.is_empty() { "?" } else { &meta.cwd }
535 );
536 println!(" The prompt carries the task, the repository's state and the last");
537 println!(" few turns, and points at the transcript for the rest.\n");
538 for (i, t) in targets.iter().enumerate() {
539 println!(
540 " \x1b[1m{}\x1b[0m {}",
541 i + 1,
542 taimux_core::handoff::display_name(t)
543 );
544 }
545 println!("\n Anything else cancels.");
546 let _ = out.flush();
547
548 let Pressed::Key(c) = read_one_key() else {
549 println!("\r\n (no readable terminal to ask on)");
550 return;
551 };
552 let Some(target) = c
553 .to_digit(10)
554 .and_then(|n| targets.get(n as usize - 1).copied())
555 else {
556 return; };
558
559 let turns = taimux_core::env::var("TAIMUX_HANDOFF_TURNS")
562 .and_then(|v| v.parse().ok())
563 .unwrap_or(taimux_core::handoff::DEFAULT_TURNS);
564 let prompt = taimux_core::handoff::build(&agent, &key, turns);
565 let cmd = match taimux_core::handoff::launch(target, &prompt) {
566 Ok(c) => c,
567 Err(why) => {
568 println!("\r\n\r\n {}.\r\n", why);
569 any_key();
570 return;
571 }
572 };
573 let cwd = if std::path::Path::new(&meta.cwd).is_dir() {
576 meta.cwd.clone()
577 } else {
578 clear(&mut out);
579 println!(
580 "\x1b[1mtaimux: {} is gone\x1b[0m\n",
581 if meta.cwd.is_empty() {
582 "its directory"
583 } else {
584 &meta.cwd
585 }
586 );
587 println!(" A handoff starts an agent in the directory the conversation ran");
588 println!(" in, and that one is no longer there.\n");
589 any_key();
590 return;
591 };
592
593 if taimux_core::tmux::run(&["new-window", "-c", &cwd, &cmd]) {
594 return; }
596 clear(&mut out);
597 println!("\x1b[1mtaimux: tmux would not open a window\x1b[0m\n");
598 any_key();
599}
600
601#[cfg(test)]
602mod tests {
603
604 #[test]
612 fn a_detached_job_does_not_hold_the_terminal() {
613 let dir = std::env::temp_dir().join(format!("taimux-detached-{}", std::process::id()));
614 std::fs::create_dir_all(&dir).unwrap();
615 let logp = dir.join("log");
616 let out = std::fs::File::create(&logp).unwrap();
617 let err = out.try_clone().unwrap();
618
619 let mut cmd = std::process::Command::new("sleep");
620 cmd.arg("30");
621 let had_tty = match std::fs::File::open("/dev/tty") {
626 Ok(tty) => {
627 cmd.stdin(std::process::Stdio::from(tty));
628 true
629 }
630 Err(_) => false,
631 };
632 let mut child = detached(&mut cmd, out, err).spawn().expect("spawn sleep");
633
634 let fd0 = std::fs::read_link(format!("/proc/{}/fd/0", child.id()));
635 let _ = child.kill();
636 let _ = child.wait();
637 let _ = std::fs::remove_dir_all(&dir);
638
639 let Ok(fd0) = fd0 else { return };
641 if !had_tty {
642 eprintln!("no /dev/tty in this environment, so this proves nothing");
645 return;
646 }
647 let fd0 = fd0.to_string_lossy().into_owned();
648 assert!(
649 !fd0.contains("/pts/") && !fd0.contains("/dev/tty"),
650 "a detached job kept a terminal on stdin: {fd0}"
651 );
652 assert!(
653 fd0.contains("null"),
654 "expected /dev/null on stdin, got {fd0}"
655 );
656 }
657
658 use super::*;
659
660 const PLAN: &str = "claude: 2.1.258 installed at /l/claude\n\
661 \n\
662 to restart (3):\n\
663 \x20 %19 platform:4.1 a title\n\
664 \x20 2.1.100 -> 2.1.258, pane map, idle\n\
665 \x20 command claude --resume /t.jsonl\n\
666 \x20 %23 platform:4.5 another\n\
667 \x20 2.1.100 -> 2.1.258, pane map, idle\n\
668 \x20 command claude\n\
669 \x20 f3836aef background a job\n\
670 \x20 2.1.100 -> 2.1.258, no pane, idle\n\
671 \x20 claude respawn f3836aef\n\
672 \n\
673 skipped (3):\n\
674 \x20 %77 main:1.1 2.1.100, run: rerun when idle\n";
675
676 #[test]
681 fn only_the_pane_lines_of_the_plan_are_shown() {
682 assert_eq!(
683 plan_panes(PLAN),
684 vec![
685 " %19 platform:4.1 a title",
686 " %23 platform:4.5 another",
687 " f3836aef background a job"
688 ]
689 );
690 }
691
692 #[test]
693 fn the_counts_come_off_the_headings() {
694 assert_eq!(count_in(PLAN, "to restart ("), Some(3));
695 assert_eq!(count_in(PLAN, "skipped ("), Some(3));
696 assert_eq!(count_in("nothing to restart.\n", "to restart ("), None);
697 }
698
699 #[test]
700 fn a_panes_own_reason_is_picked_out_of_the_skip_list() {
701 assert_eq!(
702 why_for(PLAN, "%77").as_deref(),
703 Some("%77 main:1.1 2.1.100, run: rerun when idle")
704 );
705 assert_eq!(why_for(PLAN, "%99"), None);
706 }
707
708 #[test]
711 fn an_empty_plan_is_not_mistaken_for_a_full_one() {
712 let empty = "claude: 2.1.258 installed at /l\n\nnothing to restart.\n";
713 assert!(plan_panes(empty).is_empty());
714 assert_eq!(count_in(empty, "to restart ("), None);
715 }
716}