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 plan = plan_of(exe, &["-n", "--pane", pane]);
273 if plan.contains("\nto restart (") || plan.starts_with("to restart (") {
274 restart_detached(exe, pane, false);
275 return;
276 }
277
278 clear(&mut out);
279 println!("\x1b[1mtaimux: {} will not restart cleanly\x1b[0m\n", pane);
280 let Some(why) = why_for(&plan, pane) else {
281 println!(" Nothing to do: it is already on the installed version, or it is");
282 println!(" not a claude pane.\n");
283 any_key();
284 return;
285 };
286 println!(" {}", why);
287
288 let forced = plan_of(exe, &["-n", "--pane", pane, "--include-busy"]);
292 if !(forced.contains("\nto restart (") || forced.starts_with("to restart (")) {
293 println!(
294 "\n Forcing would not help:\n {}",
295 why_for(&forced, pane).unwrap_or_else(|| "same refusal".into())
296 );
297 println!();
298 any_key();
299 return;
300 }
301
302 println!("\n Forcing accepts losing an in-flight turn. A pane holding a");
303 println!(" permission dialog is still refused, so nothing gets answered for you.");
304 print!("\n\x1b[1mForce the restart?\x1b[0m [Y/n] ");
305 let _ = out.flush();
306 let go = match read_one_key() {
310 Pressed::Key(c) => restart::confirm_yes(&c.to_string()),
311 Pressed::Unreadable => {
312 print!("\r\n (no readable terminal to answer on, so nothing was restarted)");
313 false
314 }
315 };
316 println!();
317 if go {
318 restart_detached(exe, pane, true);
319 println!(
320 "\n Forced, detached. Watch the version, or read\n {}",
321 taimux_core::paths::runtime_dir()
322 .join("restart.log")
323 .display()
324 );
325 std::thread::sleep(std::time::Duration::from_millis(1200));
326 } else {
327 println!("\n Left alone.");
328 std::thread::sleep(std::time::Duration::from_millis(600));
329 }
330}
331
332pub fn sweep(exe: &str) {
339 let mut out = std::io::stdout();
340 let at = std::time::Instant::now();
347 let plan = plan_of(exe, &["-n"]);
348 let planned = at.elapsed();
349 let n = count_in(&plan, "to restart (");
350 let skipped = count_in(&plan, "skipped (");
351
352 clear(&mut out);
353 println!("\x1b[1mtaimux: restart every outdated session\x1b[0m\n");
354
355 let Some(n) = n.filter(|n| *n >= 1) else {
356 println!("Nothing to restart. Either every session is already on the");
357 println!("installed version, or the ones behind it are busy.");
358 if let Some(s) = skipped {
359 println!("\n {} left alone.", s);
360 }
361 println!();
362 any_key();
363 return;
364 };
365
366 for l in plan_panes(&plan) {
367 println!("{}", l);
368 }
369 if let Some(s) = skipped {
370 println!("\n {} left alone (working, waiting, or unidentified).", s);
371 }
372 print!("\n\x1b[1mRestart {} session(s)?\x1b[0m [Y/n] ", n);
373 let _ = out.flush();
374 let go = match read_one_key() {
378 Pressed::Key(c) => restart::confirm_yes(&c.to_string()),
379 Pressed::Unreadable => {
380 print!("\r\n (no readable terminal to answer on, so nothing was restarted)");
381 false
382 }
383 };
384 println!();
385 if go {
386 note(&format!(
387 "sweep: {} to restart, plan took {:.1}s, {:.1}s from keypress to firing",
388 n,
389 planned.as_secs_f32(),
390 at.elapsed().as_secs_f32()
391 ));
392 restart_detached(exe, "", false);
393 println!(
394 "\nStarted, detached. Watch the version column, or read\n{}",
395 taimux_core::paths::runtime_dir()
396 .join("restart.log")
397 .display()
398 );
399 std::thread::sleep(std::time::Duration::from_millis(1200));
400 } else {
401 println!("\nNothing restarted.");
402 std::thread::sleep(std::time::Duration::from_millis(700));
403 }
404}
405
406fn plan_of(exe: &str, args: &[&str]) -> String {
412 std::process::Command::new(exe)
413 .arg("restart")
414 .args(args)
415 .output()
416 .map(|o| {
417 let mut s = String::from_utf8_lossy(&o.stdout).into_owned();
418 s.push_str(&String::from_utf8_lossy(&o.stderr));
419 s
420 })
421 .unwrap_or_default()
422}
423
424pub fn conversation_of(pane: &str) -> Result<(String, String), String> {
435 if let Some((agent, key)) = taimux_core::index::split_past_id(pane) {
436 return Ok((agent.to_string(), key.to_string()));
437 }
438 if pane == "dead:!" {
439 return Err("that row is a note, not a conversation".into());
440 }
441 if remote::pane_host(pane).is_some() {
442 return Err(format!(
443 "{} is on another host, and a handoff reads its transcript and starts \
444 an agent in its directory, both of which have to happen over there",
445 remote::pane_local(pane)
446 ));
447 }
448 let rows = taimux_core::panes::agent_rows();
449 let row = rows
450 .lines()
451 .map(|l| l.split('\t').collect::<Vec<_>>())
452 .find(|f| f.len() >= 5 && f[0] == pane)
453 .ok_or_else(|| format!("{} is not running an agent, or is not there any more", pane))?;
458 if row[3] != "claude" {
459 return Err(format!(
460 "taimux cannot tell which conversation a {} pane is on, so there is \
461 nothing to hand over. Only claude publishes that",
462 row[3]
463 ));
464 }
465 let pid: i32 = row[4].parse().unwrap_or(0);
466 let cwd = std::fs::read_link(format!("/proc/{}/cwd", pid))
467 .map(|p| p.to_string_lossy().into_owned())
468 .unwrap_or_else(|_| row[2].to_string());
469 match taimux_core::conv::resolve_from_pane(pane, &cwd, pid) {
470 Some(r) => Ok(("claude".into(), r.transcript.to_string_lossy().into_owned())),
471 None => Err("that pane's conversation could not be identified".into()),
472 }
473}
474
475pub fn handoff_one(pane: &str) {
477 let mut out = std::io::stdout();
478 clear(&mut out);
479
480 let (agent, key) = match conversation_of(pane) {
481 Ok(v) => v,
482 Err(why) => {
483 println!("\x1b[1mtaimux: nothing to hand off here\x1b[0m\n");
484 println!(" {}.\n", why);
485 any_key();
486 return;
487 }
488 };
489
490 let targets: Vec<&str> = taimux_core::handoff::installed()
494 .into_iter()
495 .filter(|t| *t != agent)
496 .collect();
497 if targets.is_empty() {
498 println!("\x1b[1mtaimux: no other agent is installed\x1b[0m\n");
499 println!(" A handoff starts a DIFFERENT tool on this conversation, and");
500 println!(" {} is the only one on your PATH.\n", agent);
501 any_key();
502 return;
503 }
504
505 let meta = taimux_core::agents::meta(&agent, &key);
506 let title = if meta.title.is_empty() {
507 "(no title)"
508 } else {
509 &meta.title
510 };
511 println!(
512 "\x1b[1mtaimux: continue this {} conversation elsewhere\x1b[0m\n",
513 taimux_core::handoff::display_name(&agent)
514 );
515 println!(" \x1b[1;36m{}\x1b[0m", title);
516 println!(
517 " \x1b[90m{}\x1b[0m\n",
518 if meta.cwd.is_empty() { "?" } else { &meta.cwd }
519 );
520 println!(" The prompt carries the task, the repository's state and the last");
521 println!(" few turns, and points at the transcript for the rest.\n");
522 for (i, t) in targets.iter().enumerate() {
523 println!(
524 " \x1b[1m{}\x1b[0m {}",
525 i + 1,
526 taimux_core::handoff::display_name(t)
527 );
528 }
529 println!("\n Anything else cancels.");
530 let _ = out.flush();
531
532 let Pressed::Key(c) = read_one_key() else {
533 println!("\r\n (no readable terminal to ask on)");
534 return;
535 };
536 let Some(target) = c
537 .to_digit(10)
538 .and_then(|n| targets.get(n as usize - 1).copied())
539 else {
540 return; };
542
543 let turns = taimux_core::env::var("TAIMUX_HANDOFF_TURNS")
546 .and_then(|v| v.parse().ok())
547 .unwrap_or(taimux_core::handoff::DEFAULT_TURNS);
548 let prompt = taimux_core::handoff::build(&agent, &key, turns);
549 let cmd = match taimux_core::handoff::launch(target, &prompt) {
550 Ok(c) => c,
551 Err(why) => {
552 println!("\r\n\r\n {}.\r\n", why);
553 any_key();
554 return;
555 }
556 };
557 let cwd = if std::path::Path::new(&meta.cwd).is_dir() {
560 meta.cwd.clone()
561 } else {
562 clear(&mut out);
563 println!(
564 "\x1b[1mtaimux: {} is gone\x1b[0m\n",
565 if meta.cwd.is_empty() {
566 "its directory"
567 } else {
568 &meta.cwd
569 }
570 );
571 println!(" A handoff starts an agent in the directory the conversation ran");
572 println!(" in, and that one is no longer there.\n");
573 any_key();
574 return;
575 };
576
577 if taimux_core::tmux::run(&["new-window", "-c", &cwd, &cmd]) {
578 return; }
580 clear(&mut out);
581 println!("\x1b[1mtaimux: tmux would not open a window\x1b[0m\n");
582 any_key();
583}
584
585#[cfg(test)]
586mod tests {
587
588 #[test]
596 fn a_detached_job_does_not_hold_the_terminal() {
597 let dir = std::env::temp_dir().join(format!("taimux-detached-{}", std::process::id()));
598 std::fs::create_dir_all(&dir).unwrap();
599 let logp = dir.join("log");
600 let out = std::fs::File::create(&logp).unwrap();
601 let err = out.try_clone().unwrap();
602
603 let mut cmd = std::process::Command::new("sleep");
604 cmd.arg("30");
605 let had_tty = match std::fs::File::open("/dev/tty") {
610 Ok(tty) => {
611 cmd.stdin(std::process::Stdio::from(tty));
612 true
613 }
614 Err(_) => false,
615 };
616 let mut child = detached(&mut cmd, out, err).spawn().expect("spawn sleep");
617
618 let fd0 = std::fs::read_link(format!("/proc/{}/fd/0", child.id()));
619 let _ = child.kill();
620 let _ = child.wait();
621 let _ = std::fs::remove_dir_all(&dir);
622
623 let Ok(fd0) = fd0 else { return };
625 if !had_tty {
626 eprintln!("no /dev/tty in this environment, so this proves nothing");
629 return;
630 }
631 let fd0 = fd0.to_string_lossy().into_owned();
632 assert!(
633 !fd0.contains("/pts/") && !fd0.contains("/dev/tty"),
634 "a detached job kept a terminal on stdin: {fd0}"
635 );
636 assert!(
637 fd0.contains("null"),
638 "expected /dev/null on stdin, got {fd0}"
639 );
640 }
641
642 use super::*;
643
644 const PLAN: &str = "claude: 2.1.258 installed at /l/claude\n\
645 \n\
646 to restart (3):\n\
647 \x20 %19 platform:4.1 a title\n\
648 \x20 2.1.100 -> 2.1.258, pane map, idle\n\
649 \x20 command claude --resume /t.jsonl\n\
650 \x20 %23 platform:4.5 another\n\
651 \x20 2.1.100 -> 2.1.258, pane map, idle\n\
652 \x20 command claude\n\
653 \x20 f3836aef background a job\n\
654 \x20 2.1.100 -> 2.1.258, no pane, idle\n\
655 \x20 claude respawn f3836aef\n\
656 \n\
657 skipped (3):\n\
658 \x20 %77 main:1.1 2.1.100, run: rerun when idle\n";
659
660 #[test]
665 fn only_the_pane_lines_of_the_plan_are_shown() {
666 assert_eq!(
667 plan_panes(PLAN),
668 vec![
669 " %19 platform:4.1 a title",
670 " %23 platform:4.5 another",
671 " f3836aef background a job"
672 ]
673 );
674 }
675
676 #[test]
677 fn the_counts_come_off_the_headings() {
678 assert_eq!(count_in(PLAN, "to restart ("), Some(3));
679 assert_eq!(count_in(PLAN, "skipped ("), Some(3));
680 assert_eq!(count_in("nothing to restart.\n", "to restart ("), None);
681 }
682
683 #[test]
684 fn a_panes_own_reason_is_picked_out_of_the_skip_list() {
685 assert_eq!(
686 why_for(PLAN, "%77").as_deref(),
687 Some("%77 main:1.1 2.1.100, run: rerun when idle")
688 );
689 assert_eq!(why_for(PLAN, "%99"), None);
690 }
691
692 #[test]
695 fn an_empty_plan_is_not_mistaken_for_a_full_one() {
696 let empty = "claude: 2.1.258 installed at /l\n\nnothing to restart.\n";
697 assert!(plan_panes(empty).is_empty());
698 assert_eq!(count_in(empty, "to restart ("), None);
699 }
700}