1use crate::sys::cmd::CommandErrorContext;
10use anyhow::Context;
11use std::collections::HashMap;
12use std::collections::HashSet;
13use std::env;
14use std::fs;
15use std::fs::DirBuilder;
16use std::io::ErrorKind;
17use std::os::unix::fs::DirBuilderExt;
18use std::path::PathBuf;
19use std::process;
20use std::sync::Arc;
21use std::sync::atomic::AtomicU64;
22use std::sync::atomic::Ordering;
23#[cfg(test)]
24use std::time as std_time;
25use std::time::Duration;
26use std::time::Instant;
27#[cfg(test)]
28use std::time::SystemTime;
29use tokio::process::Command;
30use tokio::time;
31
32#[derive(Debug, Clone)]
34pub struct Session {
35 pub name: String,
36 pub task_id: String,
38 pub project: String,
40 pub created_at: Option<u64>, }
42
43const MAX_SOCK_PATH: usize = 103;
45
46static ISOLATED_SEQ: AtomicU64 = AtomicU64::new(0);
47
48#[derive(Debug)]
50struct IsolatedServer {
51 dir: PathBuf,
52 socket: String,
53}
54
55impl IsolatedServer {
56 fn new() -> Self {
57 loop {
58 let seq = ISOLATED_SEQ.fetch_add(1, Ordering::Relaxed);
59 let name = format!("ot-{}-{seq}", process::id());
60 let mut dir = env::temp_dir().join(&name);
61 if dir.join("tmux.sock").to_string_lossy().len() >= MAX_SOCK_PATH {
62 dir = PathBuf::from("/tmp").join(&name);
63 }
64 match DirBuilder::new().mode(0o700).create(&dir) {
65 Ok(()) => {
66 let socket = dir.join("tmux.sock").to_string_lossy().into_owned();
67 return Self { dir, socket };
68 }
69 Err(e) if e.kind() != ErrorKind::AlreadyExists => {
70 panic!("isolated tmux socket dir: {e}");
71 }
72 Err(_) => {}
73 }
74 }
75 }
76}
77
78impl Drop for IsolatedServer {
79 fn drop(&mut self) {
80 let _ = process::Command::new("tmux")
82 .args(["-S", &self.socket, "-f", "/dev/null", "kill-server"])
83 .output();
84 let _ = fs::remove_dir_all(&self.dir);
85 }
86}
87
88#[derive(Clone, Debug)]
90pub struct TmuxManager {
91 prefix: String,
93 isolated: Option<Arc<IsolatedServer>>,
95}
96
97impl TmuxManager {
98 pub fn new() -> Self {
99 if cfg!(test) {
100 return Self::isolated();
101 }
102
103 Self {
104 prefix: "orch-".to_string(),
105 isolated: None,
106 }
107 }
108
109 pub fn isolated() -> Self {
113 Self {
114 prefix: "orch-test-".to_string(),
115 isolated: Some(Arc::new(IsolatedServer::new())),
116 }
117 }
118
119 pub(crate) fn command(&self) -> Command {
121 let mut cmd = Command::new("tmux");
122 cmd.args(self.server_args());
123 cmd
124 }
125
126 #[cfg(test)]
128 fn blocking_command(&self) -> process::Command {
129 let mut cmd = process::Command::new("tmux");
130 cmd.args(self.server_args());
131 cmd
132 }
133
134 fn server_args(&self) -> Vec<&str> {
135 self.isolated.as_ref().map_or_else(Vec::new, |i| {
136 vec!["-S", i.socket.as_str(), "-f", "/dev/null"]
137 })
138 }
139
140 pub fn session_name(&self, project: &str, task_id: &str) -> String {
145 let project_name = project
146 .rsplit('/')
147 .next()
148 .unwrap_or(project)
149 .trim_end_matches(".git");
150 let safe_task_id = task_id.replace(':', "-");
151 format!("{}{project_name}-{safe_task_id}", self.prefix)
152 }
153
154 pub async fn create_session(
169 &self,
170 repo: &str,
171 task_id: &str,
172 working_dir: &str,
173 command: &str,
174 env_vars: &[(&str, &str)],
175 ) -> anyhow::Result<String> {
176 let name = self.session_name(repo, task_id);
177
178 let mut cmd = self.command();
179 cmd.args(["new-session", "-d", "-s", &name, "-c", working_dir]);
180
181 cmd.arg("-e").arg("DISABLE_AUTO_UPDATE=true");
183
184 for (key, value) in env_vars {
188 cmd.arg("-e").arg(format!("{key}={value}"));
190 }
191
192 cmd.arg(command);
193
194 let output = cmd
195 .output_with_context()
196 .await
197 .context("spawning tmux session")?;
198
199 if !output.status.success() {
200 let stderr = String::from_utf8_lossy(&output.stderr);
201 anyhow::bail!("tmux new-session failed: {stderr}");
202 }
203
204 tracing::info!(session = %name, task_id, "created tmux session");
205 Ok(name)
206 }
207
208 pub async fn session_exists(&self, session: &str) -> bool {
210 self.command()
211 .args(["has-session", "-t", session])
212 .output_with_context()
213 .await
214 .is_ok_and(|o| o.status.success())
215 }
216
217 pub async fn kill_session(&self, session: &str) -> anyhow::Result<()> {
219 let output = self
220 .command()
221 .args(["kill-session", "-t", session])
222 .output_with_context()
223 .await?;
224
225 if !output.status.success() {
226 let stderr = String::from_utf8_lossy(&output.stderr);
227 if stderr.contains("can't find session")
228 || stderr.contains("no server running")
229 || stderr.contains("error connecting to")
230 {
231 tracing::debug!(session, %stderr, "kill-session: session already gone");
232 } else {
233 tracing::warn!(session, %stderr, "kill-session failed unexpectedly");
234 }
235 }
236 Ok(())
237 }
238
239 pub async fn capture_pane(&self, session: &str, lines: i32) -> anyhow::Result<String> {
245 let start = format!("-{lines}");
246 let output = self
247 .command()
248 .args(["capture-pane", "-t", session, "-p", "-S", &start])
249 .output_with_context()
250 .await?;
251
252 if !output.status.success() {
253 let stderr = String::from_utf8_lossy(&output.stderr);
254 if stderr.contains("can't find pane")
259 || stderr.contains("can't find session")
260 || stderr.contains("no server running")
261 || stderr.contains("error connecting to")
262 {
263 tracing::debug!(
264 session,
265 "capture_pane: session/pane already gone (teardown race)"
266 );
267 return Ok(String::new());
268 }
269 anyhow::bail!("capture-pane failed for {session}: {stderr}");
270 }
271 Ok(String::from_utf8_lossy(&output.stdout).to_string())
272 }
273
274 pub async fn is_session_active(&self, session: &str) -> bool {
277 let output = self
279 .command()
280 .args(["list-panes", "-t", session, "-F", "#{pane_dead}"])
281 .output_with_context()
282 .await;
283
284 match output {
285 Ok(o) if o.status.success() => {
286 let flag = String::from_utf8_lossy(&o.stdout);
287 flag.trim() == "0" }
289 _ => false,
290 }
291 }
292
293 #[cfg(test)]
295 pub async fn session_is_running(&self, session: &str) -> bool {
296 self.session_exists(session).await && self.is_session_active(session).await
297 }
298
299 pub async fn session_blocks_dispatch(
305 &self,
306 session: &str,
307 known: Option<&HashMap<String, bool>>,
308 ) -> bool {
309 let alive = match known {
310 Some(map) => map.get(session).copied(),
311 None if !self.session_exists(session).await => None,
312 None => Some(self.is_session_active(session).await),
313 };
314 match alive {
315 None => false,
316 Some(true) => true,
317 Some(false) => {
318 tracing::warn!(
319 session,
320 "found stale tmux session with dead pane; cleaning up"
321 );
322 if let Err(err) = self.kill_session(session).await {
323 tracing::debug!(session, error = %err, "failed to clean up stale tmux session");
324 }
325 false
326 }
327 }
328 }
329
330 pub(crate) fn parse_session_name(&self, name: &str) -> Option<(String, String)> {
344 let after_prefix = name.strip_prefix(&self.prefix)?;
345
346 let (base, is_review) = match after_prefix.strip_suffix("-review") {
348 Some(stripped) => (stripped, true),
349 None => (after_prefix, false),
350 };
351
352 if let Some(idx) = base.rfind("-internal-") {
354 let project = &base[..idx];
355 let task_base = &base[idx + 1..]; let after_internal = &task_base["internal-".len()..];
357 if !project.is_empty()
358 && !after_internal.is_empty()
359 && after_internal.chars().all(|c| c.is_ascii_digit())
360 {
361 let task_id = if is_review {
362 format!("{task_base}-review")
363 } else {
364 task_base.to_string()
365 };
366 return Some((project.to_string(), task_id));
367 }
368 }
369
370 if let Some(idx) = base.rfind('-') {
372 let project = &base[..idx];
373 let digits = &base[idx + 1..];
374 if !project.is_empty()
375 && !digits.is_empty()
376 && digits.chars().all(|c| c.is_ascii_digit())
377 {
378 let task_id = if is_review {
379 format!("{digits}-review")
380 } else {
381 digits.to_string()
382 };
383 return Some((project.to_string(), task_id));
384 }
385 }
386
387 None
388 }
389
390 pub async fn batch_session_active(&self) -> HashMap<String, bool> {
395 let mut map = HashMap::new();
396 let o = match self
397 .command()
398 .args(["list-panes", "-a", "-F", "#{session_name} #{pane_dead}"])
399 .output_with_context()
400 .await
401 {
402 Ok(o) => o,
403 Err(e) => {
404 tracing::warn!(error = %e, "batch_session_active: failed to spawn tmux");
405 return map;
406 }
407 };
408 if !o.status.success() {
409 let stderr = String::from_utf8_lossy(&o.stderr);
410 tracing::warn!(
411 status = ?o.status,
412 stderr = %stderr.trim(),
413 "batch_session_active: tmux list-panes exited non-zero"
414 );
415 return map;
416 }
417 for line in String::from_utf8_lossy(&o.stdout).lines() {
418 let mut parts = line.trim().splitn(2, ' ');
419 if let (Some(session), Some(dead)) = (parts.next(), parts.next()) {
420 map.insert(session.to_string(), dead.trim() == "0");
421 }
422 }
423 map
424 }
425
426 pub async fn list_sessions(&self) -> anyhow::Result<Vec<Session>> {
428 let output = self
430 .command()
431 .args(["list-sessions", "-F", "#{session_name} #{session_created}"])
432 .output_with_context()
433 .await?;
434
435 if !output.status.success() {
436 return Ok(vec![]);
437 }
438
439 let mut sessions = Vec::new();
440 for line in String::from_utf8_lossy(&output.stdout).lines() {
441 let parts: Vec<&str> = line.trim().splitn(2, ' ').collect();
442 if parts.is_empty() {
443 continue;
444 }
445 let name = parts[0].to_string();
446 let created_at = parts.get(1).and_then(|s| s.parse::<u64>().ok());
447
448 if let Some((project, task_id)) = self.parse_session_name(&name) {
449 sessions.push(Session {
450 name,
451 task_id,
452 project,
453 created_at,
454 });
455 }
456 }
457
458 Ok(sessions)
459 }
460
461 pub async fn kill_stale_sessions(&self, before_timestamp: u64) -> anyhow::Result<usize> {
464 let sessions = self.list_sessions().await?;
465 let mut killed = 0;
466
467 for session in sessions {
468 let should_kill = match session.created_at {
469 Some(created) => created < before_timestamp,
470 None => false,
472 };
473
474 if should_kill {
475 tracing::info!(
476 session = %session.name,
477 created_at = session.created_at,
478 "killing stale tmux session from previous run"
479 );
480 match self.kill_session(&session.name).await {
481 Err(e) => {
482 tracing::warn!(session = %session.name, error = %e, "failed to kill stale session");
483 }
484 _ => {
485 killed += 1;
486 }
487 }
488 }
489 }
490
491 if killed > 0 {
492 tracing::info!(killed, "killed stale tmux sessions on startup");
493 }
494
495 Ok(killed)
496 }
497
498 pub async fn wait_for_sessions_dead(
502 &self,
503 sessions: &[String],
504 poll_interval: Duration,
505 timeout: Duration,
506 ) -> usize {
507 let start = Instant::now();
508 let mut remaining: HashSet<String> = sessions.iter().cloned().collect();
509
510 while !remaining.is_empty() && start.elapsed() < timeout {
511 let mut to_remove = Vec::new();
512 for session in &remaining {
513 if !self.session_exists(session).await {
514 to_remove.push(session.clone());
515 }
516 }
517 for session in to_remove {
518 remaining.remove(&session);
519 }
520 if !remaining.is_empty() {
521 time::sleep(poll_interval).await;
522 }
523 }
524
525 let still_alive = remaining.len();
526 if still_alive > 0 {
527 tracing::warn!(
528 still_alive,
529 sessions = ?remaining.iter().collect::<Vec<_>>(),
530 "tmux sessions did not terminate within timeout"
531 );
532 }
533 still_alive
534 }
535
536 pub async fn wait_for_completion(
539 &self,
540 session: &str,
541 poll_interval: Duration,
542 ) -> anyhow::Result<String> {
543 loop {
544 if !self.session_exists(session).await {
545 return Ok(String::new());
546 }
547
548 if !self.is_session_active(session).await {
549 match self.capture_pane(session, 500).await {
553 Ok(output) => return Ok(output),
554 Err(err) => {
555 tracing::error!(session = %session, error = %err, "failed to capture final pane output");
556 return Ok(String::new());
557 }
558 }
559 }
560
561 time::sleep(poll_interval).await;
562 }
563 }
564
565 pub async fn snapshot(&self) -> Vec<(Session, bool)> {
573 let sessions = match self.list_sessions().await {
574 Ok(s) => s,
575 Err(err) => {
576 tracing::error!(error = %err, "failed to list tmux sessions — returning empty snapshot");
577 Vec::new()
578 }
579 };
580 let active_map = self.batch_session_active().await;
582 sessions
583 .into_iter()
584 .map(|s| {
585 let active = active_map.get(&s.name).copied().unwrap_or(false);
587 (s, active)
588 })
589 .collect()
590 }
591
592 #[cfg(test)]
600 pub async fn set_env(&self, session: &str, key: &str, value: &str) -> anyhow::Result<()> {
601 let output = self
602 .command()
603 .args(["set-environment", "-t", session, key, value])
604 .output_with_context()
605 .await?;
606
607 if !output.status.success() {
608 let stderr = String::from_utf8_lossy(&output.stderr);
609 anyhow::bail!("tmux set-environment failed for {session}: {stderr}");
610 }
611
612 tracing::debug!(session, key, "set tmux environment variable");
613 Ok(())
614 }
615
616 pub async fn unset_global_env(&self, key: &str) -> anyhow::Result<()> {
620 let output = self
621 .command()
622 .args(["set-environment", "-gu", key])
623 .output_with_context()
624 .await?;
625
626 if !output.status.success() {
627 let stderr = String::from_utf8_lossy(&output.stderr);
628 anyhow::bail!("tmux unset-global-environment failed for {key}: {stderr}");
629 }
630
631 tracing::debug!(key, "unset tmux global environment variable");
632 Ok(())
633 }
634}
635
636#[cfg(test)]
637pub(crate) fn test_session_name() -> String {
638 format!(
639 "orch-test-{}",
640 SystemTime::now()
641 .duration_since(std_time::UNIX_EPOCH)
642 .map_or_else(|_| 0, |d| d.as_millis())
643 )
644}
645
646#[cfg(test)]
648pub(crate) struct SessionGuard {
649 session: String,
650 tmux: TmuxManager,
651}
652
653#[cfg(test)]
654impl SessionGuard {
655 pub(crate) fn new(tmux: &TmuxManager, session: String) -> Self {
656 Self {
657 session,
658 tmux: tmux.clone(),
659 }
660 }
661}
662
663#[cfg(test)]
664impl Drop for SessionGuard {
665 fn drop(&mut self) {
666 let mut cmd = self.tmux.blocking_command();
667 cmd.args(["kill-session", "-t", &self.session]);
668 let _ = cmd.output();
669 }
670}
671
672#[cfg(test)]
673mod tests {
674 use super::*;
675
676 #[test]
677 fn session_name_internal_task_id_is_sanitized() {
678 let tmux = TmuxManager::new();
679 let name = tmux.session_name("owner/repo", "internal:8");
680 assert!(!name.contains(':'), "colon must be sanitized for tmux");
681 assert_eq!(
682 tmux.parse_session_name(&name),
683 Some(("repo".to_string(), "internal-8".to_string()))
684 );
685 }
686
687 #[test]
688 fn task_id_from_session_name_parses_external_task() {
689 let tmux = TmuxManager::new();
690 let name = tmux.session_name("owner/repo", "1234");
691 assert_eq!(
692 tmux.parse_session_name(&name),
693 Some(("repo".to_string(), "1234".to_string()))
694 );
695 }
696
697 #[test]
698 fn task_id_from_session_name_parses_internal_task() {
699 let tmux = TmuxManager::new();
700 let name = tmux.session_name("owner/orch", "internal:21116");
701 assert_eq!(
702 tmux.parse_session_name(&name),
703 Some(("orch".to_string(), "internal-21116".to_string()))
704 );
705 }
706
707 #[test]
708 fn task_id_from_session_name_parses_internal_task_small_id() {
709 let tmux = TmuxManager::new();
710 let name = tmux.session_name("owner/repo", "internal:8");
711 assert_eq!(
712 tmux.parse_session_name(&name),
713 Some(("repo".to_string(), "internal-8".to_string()))
714 );
715 }
716
717 #[test]
718 fn task_id_from_session_name_returns_none_for_non_orch_session() {
719 let tmux = TmuxManager::new();
720 assert_eq!(tmux.parse_session_name("some-other-session"), None);
721 }
722
723 #[test]
724 fn parse_session_name_ignores_production_prefix_in_tests() {
725 let tmux = TmuxManager::new();
726 assert_eq!(tmux.parse_session_name("orch-repo-1234"), None);
727 }
728
729 #[test]
730 fn parse_session_name_hyphenated_project_external() {
731 let tmux = TmuxManager::new();
732 let name = tmux.session_name("owner/my-repo", "1234");
733 assert_eq!(
734 tmux.parse_session_name(&name),
735 Some(("my-repo".to_string(), "1234".to_string()))
736 );
737 }
738
739 #[test]
740 fn parse_session_name_hyphenated_project_internal() {
741 let tmux = TmuxManager::new();
742 let name = tmux.session_name("owner/my-repo", "internal:8");
743 assert_eq!(
744 tmux.parse_session_name(&name),
745 Some(("my-repo".to_string(), "internal-8".to_string()))
746 );
747 }
748
749 #[test]
750 fn parse_session_name_hyphenated_project_review() {
751 let tmux = TmuxManager::new();
752 let name = tmux.session_name("owner/my-repo", "1234-review");
753 assert_eq!(
754 tmux.parse_session_name(&name),
755 Some(("my-repo".to_string(), "1234-review".to_string()))
756 );
757 }
758
759 #[test]
760 fn parse_session_name_multi_hyphen_project() {
761 let tmux = TmuxManager::new();
762 let name = tmux.session_name("owner/my-cool-repo", "42");
763 assert_eq!(
764 tmux.parse_session_name(&name),
765 Some(("my-cool-repo".to_string(), "42".to_string()))
766 );
767 }
768
769 #[test]
770 fn parse_session_name_roundtrip_hyphenated_project() {
771 let tmux = TmuxManager::new();
772 let name = tmux.session_name("owner/my-repo", "1793");
773 assert!(name.ends_with("my-repo-1793"));
774 assert_eq!(
775 tmux.parse_session_name(&name),
776 Some(("my-repo".to_string(), "1793".to_string()))
777 );
778 }
779
780 #[tokio::test]
783 async fn test_set_env() {
784 let tmux = TmuxManager::new();
785 let session = test_session_name();
786
787 let create_result = tmux
789 .command()
790 .args(["new-session", "-d", "-s", &session, "-c", "/tmp"])
791 .output()
792 .await;
793
794 match create_result {
796 Ok(o) if o.status.success() => {}
797 _ => {
798 eprintln!("Skipping test: tmux not available or failed to create test session");
799 return;
800 }
801 }
802 let _guard = SessionGuard::new(&tmux, session.clone());
803
804 let result = tmux.set_env(&session, "TEST_VAR", "test_value").await;
806 assert!(result.is_ok(), "set_env should succeed");
807
808 let check_result = tmux
810 .command()
811 .args(["show-environment", "-t", &session, "TEST_VAR"])
812 .output()
813 .await;
814
815 let Ok(output) = check_result else {
816 eprintln!("Skipping test: unable to check tmux environment");
817 return;
818 };
819 let stdout = String::from_utf8_lossy(&output.stdout);
820 assert!(
821 stdout.contains("TEST_VAR=test_value"),
822 "Expected TEST_VAR=test_value, got: {stdout}"
823 );
824 }
825
826 #[tokio::test]
827 async fn session_blocks_dispatch_keeps_live_session() {
828 let tmux = TmuxManager::new();
829 let session = test_session_name();
830
831 let create_result = tmux
832 .command()
833 .args(["new-session", "-d", "-s", &session, "-c", "/tmp"])
834 .output()
835 .await;
836
837 match create_result {
838 Ok(o) if o.status.success() => {}
839 _ => {
840 eprintln!("Skipping test: tmux not available or failed to create test session");
841 return;
842 }
843 }
844 let _guard = SessionGuard::new(&tmux, session.clone());
845
846 assert!(tmux.session_blocks_dispatch(&session, None).await);
847 assert!(tmux.session_exists(&session).await);
848 }
849
850 #[tokio::test]
851 async fn session_blocks_dispatch_cleans_dead_session() {
852 let tmux = TmuxManager::new();
853 let session = test_session_name();
854
855 let create_result = tmux
856 .command()
857 .args(["new-session", "-d", "-s", &session, "-c", "/tmp"])
858 .output()
859 .await;
860
861 match create_result {
862 Ok(o) if o.status.success() => {}
863 _ => {
864 eprintln!("Skipping test: tmux not available or failed to create test session");
865 return;
866 }
867 }
868 let _guard = SessionGuard::new(&tmux, session.clone());
869
870 let set_option_result = tmux
871 .command()
872 .args(["set-option", "-t", &session, "remain-on-exit", "on"])
873 .output()
874 .await;
875 if !matches!(set_option_result, Ok(ref o) if o.status.success()) {
876 eprintln!("Skipping test: unable to set tmux remain-on-exit option");
877 return;
878 }
879
880 let respawn_result = tmux
883 .command()
884 .args(["respawn-pane", "-k", "-t", &session, "false"])
885 .output()
886 .await;
887 if !matches!(respawn_result, Ok(ref o) if o.status.success()) {
888 eprintln!("Skipping test: unable to exit tmux pane");
889 return;
890 }
891
892 for _ in 0..20 {
894 time::sleep(Duration::from_millis(100)).await;
895 if !tmux.session_is_running(&session).await {
896 break;
897 }
898 }
899
900 assert!(tmux.session_exists(&session).await);
901 assert!(!tmux.session_is_running(&session).await);
902 assert!(!tmux.session_blocks_dispatch(&session, None).await);
903 assert!(!tmux.session_exists(&session).await);
904 }
905
906 #[tokio::test]
910 async fn capture_pane_returns_empty_for_gone_session() {
911 let tmux = TmuxManager::new();
912 let result = tmux
914 .capture_pane("orch-nonexistent-session-99999", 100)
915 .await;
916 assert!(
917 result.is_ok(),
918 "capture_pane should return Ok for non-existent session, got: {result:?}"
919 );
920 assert_eq!(
921 result.unwrap(),
922 "",
923 "capture_pane should return empty string for non-existent session"
924 );
925 }
926
927 #[tokio::test]
931 async fn wait_for_completion_returns_empty_for_gone_session() {
932 let tmux = TmuxManager::new();
933 let result = tmux
935 .wait_for_completion("orch-nonexistent-session-99999", Duration::from_millis(50))
936 .await;
937 assert!(
938 result.is_ok(),
939 "wait_for_completion should return Ok for non-existent session, got: {result:?}"
940 );
941 assert_eq!(
942 result.unwrap(),
943 "",
944 "wait_for_completion should return empty string for non-existent session"
945 );
946 }
947
948 #[tokio::test]
951 async fn test_manager_does_not_touch_the_default_server() {
952 let tmux = TmuxManager::new();
953 let Ok(name) = tmux
954 .create_session("owner/repo", "isolation", "/tmp", "sleep 30", &[])
955 .await
956 else {
957 eprintln!("Skipping test: tmux not available or failed to create test session");
958 return;
959 };
960 let _guard = SessionGuard::new(&tmux, name.clone());
961
962 assert!(
963 tmux.session_exists(&name).await,
964 "session must exist on the isolated test server"
965 );
966
967 let on_default = Command::new("tmux")
968 .args(["has-session", "-t", &name])
969 .output()
970 .await
971 .is_ok_and(|o| o.status.success());
972 assert!(
973 !on_default,
974 "TmuxManager under cfg(test) must not create sessions on the default tmux server"
975 );
976 }
977
978 #[test]
979 fn isolated_socket_lives_in_a_temp_dir() {
980 let tmux = TmuxManager::isolated();
981 let isolated = tmux.isolated.as_ref().expect("isolated server");
982 assert!(
983 isolated.socket.ends_with("/tmux.sock"),
984 "socket path: {}",
985 isolated.socket
986 );
987 assert!(
988 isolated.dir.starts_with(env::temp_dir()) || isolated.dir.starts_with("/tmp"),
989 "dir {} must be under {} or /tmp",
990 isolated.dir.display(),
991 env::temp_dir().display()
992 );
993 assert!(
994 isolated.dir.is_dir(),
995 "socket dir must exist while the manager is alive"
996 );
997 assert!(
998 isolated.socket.len() < MAX_SOCK_PATH,
999 "unix socket path must fit sockaddr_un, got {} bytes: {}",
1000 isolated.socket.len(),
1001 isolated.socket
1002 );
1003 }
1004
1005 #[tokio::test]
1006 async fn isolated_manager_kills_server_and_removes_socket_dir_on_drop() {
1007 let tmux = TmuxManager::isolated();
1008 let (socket, dir) = {
1009 let isolated = tmux.isolated.as_ref().expect("isolated server");
1010 (isolated.socket.clone(), isolated.dir.clone())
1011 };
1012
1013 let Ok(name) = tmux
1014 .create_session("owner/repo", "drop-server", "/tmp", "sleep 30", &[])
1015 .await
1016 else {
1017 eprintln!("Skipping test: tmux not available or failed to create test session");
1018 return;
1019 };
1020 assert!(
1021 tmux.session_exists(&name).await,
1022 "session must exist before drop"
1023 );
1024 assert!(
1025 dir.is_dir(),
1026 "socket dir must exist while the manager is alive"
1027 );
1028
1029 drop(tmux);
1030
1031 let list = process::Command::new("tmux")
1032 .args(["-S", &socket, "-f", "/dev/null", "list-sessions"])
1033 .output()
1034 .expect("list-sessions after drop");
1035 assert!(
1036 !list.status.success(),
1037 "kill-server on drop must leave no server, stderr: {}",
1038 String::from_utf8_lossy(&list.stderr)
1039 );
1040 assert!(!dir.exists(), "socket dir must be removed on drop");
1041 }
1042
1043 #[tokio::test]
1044 async fn isolated_server_does_not_load_user_tmux_conf() {
1045 let home = tempfile::tempdir().expect("temp home");
1046 fs::write(
1047 home.path().join(".tmux.conf"),
1048 "set -g @orch_test_marker 1\nset -g exit-empty off\n",
1049 )
1050 .expect("write tmux.conf");
1051
1052 let tmux = TmuxManager::isolated();
1053 let session = test_session_name();
1054 let create = tmux
1055 .command()
1056 .env("HOME", home.path())
1057 .args([
1058 "new-session",
1059 "-d",
1060 "-s",
1061 &session,
1062 "-c",
1063 "/tmp",
1064 "sleep 30",
1065 ])
1066 .output()
1067 .await;
1068 match create {
1069 Ok(o) if o.status.success() => {}
1070 _ => {
1071 eprintln!("Skipping test: tmux not available or failed to create test session");
1072 return;
1073 }
1074 }
1075 let _guard = SessionGuard::new(&tmux, session);
1076
1077 let marker = tmux
1078 .command()
1079 .env("HOME", home.path())
1080 .args(["show-options", "-gv", "@orch_test_marker"])
1081 .output()
1082 .await
1083 .expect("show-options marker");
1084 let stdout = String::from_utf8_lossy(&marker.stdout);
1085 assert!(
1086 stdout.trim().is_empty(),
1087 "isolated tmux must not load ~/.tmux.conf, got: {stdout}"
1088 );
1089
1090 let exit_empty = tmux
1091 .command()
1092 .args(["show-options", "-gv", "exit-empty"])
1093 .output()
1094 .await
1095 .expect("exit-empty");
1096 let value = String::from_utf8_lossy(&exit_empty.stdout);
1097 assert_eq!(
1098 value.trim(),
1099 "on",
1100 "isolated tmux must keep the default exit-empty, got: {value}"
1101 );
1102 }
1103}