1use crate::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(&self, session: &str) -> bool {
304 if !self.session_exists(session).await {
305 return false;
306 }
307
308 if self.is_session_active(session).await {
309 return true;
310 }
311
312 tracing::warn!(
313 session,
314 "found stale tmux session with dead pane; cleaning up"
315 );
316 if let Err(err) = self.kill_session(session).await {
317 tracing::debug!(session, error = %err, "failed to clean up stale tmux session");
318 }
319
320 false
321 }
322
323 pub async fn session_blocks_dispatch_from_map(
329 &self,
330 session: &str,
331 session_map: &HashMap<String, bool>,
332 ) -> bool {
333 match session_map.get(session).copied() {
334 None => false, Some(true) => true, Some(false) => {
337 tracing::warn!(
339 session,
340 "found stale tmux session with dead pane; cleaning up"
341 );
342 if let Err(err) = self.kill_session(session).await {
343 tracing::debug!(
344 session,
345 error = %err,
346 "failed to clean up stale tmux session"
347 );
348 }
349 false
350 }
351 }
352 }
353
354 pub(crate) fn parse_session_name(&self, name: &str) -> Option<(String, String)> {
368 let after_prefix = name.strip_prefix(&self.prefix)?;
369
370 let (base, is_review) = match after_prefix.strip_suffix("-review") {
372 Some(stripped) => (stripped, true),
373 None => (after_prefix, false),
374 };
375
376 if let Some(idx) = base.rfind("-internal-") {
378 let project = &base[..idx];
379 let task_base = &base[idx + 1..]; let after_internal = &task_base["internal-".len()..];
381 if !project.is_empty()
382 && !after_internal.is_empty()
383 && after_internal.chars().all(|c| c.is_ascii_digit())
384 {
385 let task_id = if is_review {
386 format!("{task_base}-review")
387 } else {
388 task_base.to_string()
389 };
390 return Some((project.to_string(), task_id));
391 }
392 }
393
394 if let Some(idx) = base.rfind('-') {
396 let project = &base[..idx];
397 let digits = &base[idx + 1..];
398 if !project.is_empty()
399 && !digits.is_empty()
400 && digits.chars().all(|c| c.is_ascii_digit())
401 {
402 let task_id = if is_review {
403 format!("{digits}-review")
404 } else {
405 digits.to_string()
406 };
407 return Some((project.to_string(), task_id));
408 }
409 }
410
411 None
412 }
413
414 pub async fn batch_session_active(&self) -> HashMap<String, bool> {
419 let mut map = HashMap::new();
420 let o = match self
421 .command()
422 .args(["list-panes", "-a", "-F", "#{session_name} #{pane_dead}"])
423 .output_with_context()
424 .await
425 {
426 Ok(o) => o,
427 Err(e) => {
428 tracing::warn!(error = %e, "batch_session_active: failed to spawn tmux");
429 return map;
430 }
431 };
432 if !o.status.success() {
433 let stderr = String::from_utf8_lossy(&o.stderr);
434 tracing::warn!(
435 status = ?o.status,
436 stderr = %stderr.trim(),
437 "batch_session_active: tmux list-panes exited non-zero"
438 );
439 return map;
440 }
441 for line in String::from_utf8_lossy(&o.stdout).lines() {
442 let mut parts = line.trim().splitn(2, ' ');
443 if let (Some(session), Some(dead)) = (parts.next(), parts.next()) {
444 map.insert(session.to_string(), dead.trim() == "0");
445 }
446 }
447 map
448 }
449
450 pub async fn list_sessions(&self) -> anyhow::Result<Vec<Session>> {
452 let output = self
454 .command()
455 .args(["list-sessions", "-F", "#{session_name} #{session_created}"])
456 .output_with_context()
457 .await?;
458
459 if !output.status.success() {
460 return Ok(vec![]);
461 }
462
463 let mut sessions = Vec::new();
464 for line in String::from_utf8_lossy(&output.stdout).lines() {
465 let parts: Vec<&str> = line.trim().splitn(2, ' ').collect();
466 if parts.is_empty() {
467 continue;
468 }
469 let name = parts[0].to_string();
470 let created_at = parts.get(1).and_then(|s| s.parse::<u64>().ok());
471
472 if let Some((project, task_id)) = self.parse_session_name(&name) {
473 sessions.push(Session {
474 name,
475 task_id,
476 project,
477 created_at,
478 });
479 }
480 }
481
482 Ok(sessions)
483 }
484
485 pub async fn kill_stale_sessions(&self, before_timestamp: u64) -> anyhow::Result<usize> {
488 let sessions = self.list_sessions().await?;
489 let mut killed = 0;
490
491 for session in sessions {
492 let should_kill = match session.created_at {
493 Some(created) => created < before_timestamp,
494 None => false,
496 };
497
498 if should_kill {
499 tracing::info!(
500 session = %session.name,
501 created_at = session.created_at,
502 "killing stale tmux session from previous run"
503 );
504 match self.kill_session(&session.name).await {
505 Err(e) => {
506 tracing::warn!(session = %session.name, error = %e, "failed to kill stale session");
507 }
508 _ => {
509 killed += 1;
510 }
511 }
512 }
513 }
514
515 if killed > 0 {
516 tracing::info!(killed, "killed stale tmux sessions on startup");
517 }
518
519 Ok(killed)
520 }
521
522 pub async fn wait_for_sessions_dead(
526 &self,
527 sessions: &[String],
528 poll_interval: Duration,
529 timeout: Duration,
530 ) -> usize {
531 let start = Instant::now();
532 let mut remaining: HashSet<String> = sessions.iter().cloned().collect();
533
534 while !remaining.is_empty() && start.elapsed() < timeout {
535 let mut to_remove = Vec::new();
536 for session in &remaining {
537 if !self.session_exists(session).await {
538 to_remove.push(session.clone());
539 }
540 }
541 for session in to_remove {
542 remaining.remove(&session);
543 }
544 if !remaining.is_empty() {
545 time::sleep(poll_interval).await;
546 }
547 }
548
549 let still_alive = remaining.len();
550 if still_alive > 0 {
551 tracing::warn!(
552 still_alive,
553 sessions = ?remaining.iter().collect::<Vec<_>>(),
554 "tmux sessions did not terminate within timeout"
555 );
556 }
557 still_alive
558 }
559
560 pub async fn wait_for_completion(
563 &self,
564 session: &str,
565 poll_interval: Duration,
566 ) -> anyhow::Result<String> {
567 loop {
568 if !self.session_exists(session).await {
569 return Ok(String::new());
570 }
571
572 if !self.is_session_active(session).await {
573 match self.capture_pane(session, 500).await {
577 Ok(output) => return Ok(output),
578 Err(err) => {
579 tracing::error!(session = %session, error = %err, "failed to capture final pane output");
580 return Ok(String::new());
581 }
582 }
583 }
584
585 time::sleep(poll_interval).await;
586 }
587 }
588
589 pub async fn snapshot(&self) -> Vec<(Session, bool)> {
597 let sessions = match self.list_sessions().await {
598 Ok(s) => s,
599 Err(err) => {
600 tracing::error!(error = %err, "failed to list tmux sessions — returning empty snapshot");
601 Vec::new()
602 }
603 };
604 let active_map = self.batch_session_active().await;
606 sessions
607 .into_iter()
608 .map(|s| {
609 let active = active_map.get(&s.name).copied().unwrap_or(false);
611 (s, active)
612 })
613 .collect()
614 }
615
616 #[cfg(test)]
624 pub async fn set_env(&self, session: &str, key: &str, value: &str) -> anyhow::Result<()> {
625 let output = self
626 .command()
627 .args(["set-environment", "-t", session, key, value])
628 .output_with_context()
629 .await?;
630
631 if !output.status.success() {
632 let stderr = String::from_utf8_lossy(&output.stderr);
633 anyhow::bail!("tmux set-environment failed for {session}: {stderr}");
634 }
635
636 tracing::debug!(session, key, "set tmux environment variable");
637 Ok(())
638 }
639
640 pub async fn unset_global_env(&self, key: &str) -> anyhow::Result<()> {
644 let output = self
645 .command()
646 .args(["set-environment", "-gu", key])
647 .output_with_context()
648 .await?;
649
650 if !output.status.success() {
651 let stderr = String::from_utf8_lossy(&output.stderr);
652 anyhow::bail!("tmux unset-global-environment failed for {key}: {stderr}");
653 }
654
655 tracing::debug!(key, "unset tmux global environment variable");
656 Ok(())
657 }
658}
659
660#[cfg(test)]
661pub(crate) fn test_session_name() -> String {
662 format!(
663 "orch-test-{}",
664 SystemTime::now()
665 .duration_since(std_time::UNIX_EPOCH)
666 .map_or_else(|_| 0, |d| d.as_millis())
667 )
668}
669
670#[cfg(test)]
672pub(crate) struct SessionGuard {
673 session: String,
674 tmux: TmuxManager,
675}
676
677#[cfg(test)]
678impl SessionGuard {
679 pub(crate) fn new(tmux: &TmuxManager, session: String) -> Self {
680 Self {
681 session,
682 tmux: tmux.clone(),
683 }
684 }
685}
686
687#[cfg(test)]
688impl Drop for SessionGuard {
689 fn drop(&mut self) {
690 let mut cmd = self.tmux.blocking_command();
691 cmd.args(["kill-session", "-t", &self.session]);
692 let _ = cmd.output();
693 }
694}
695
696#[cfg(test)]
697mod tests {
698 use super::*;
699
700 #[test]
701 fn session_name_internal_task_id_is_sanitized() {
702 let tmux = TmuxManager::new();
703 let name = tmux.session_name("owner/repo", "internal:8");
704 assert!(!name.contains(':'), "colon must be sanitized for tmux");
705 assert_eq!(
706 tmux.parse_session_name(&name),
707 Some(("repo".to_string(), "internal-8".to_string()))
708 );
709 }
710
711 #[test]
712 fn task_id_from_session_name_parses_external_task() {
713 let tmux = TmuxManager::new();
714 let name = tmux.session_name("owner/repo", "1234");
715 assert_eq!(
716 tmux.parse_session_name(&name),
717 Some(("repo".to_string(), "1234".to_string()))
718 );
719 }
720
721 #[test]
722 fn task_id_from_session_name_parses_internal_task() {
723 let tmux = TmuxManager::new();
724 let name = tmux.session_name("owner/orch", "internal:21116");
725 assert_eq!(
726 tmux.parse_session_name(&name),
727 Some(("orch".to_string(), "internal-21116".to_string()))
728 );
729 }
730
731 #[test]
732 fn task_id_from_session_name_parses_internal_task_small_id() {
733 let tmux = TmuxManager::new();
734 let name = tmux.session_name("owner/repo", "internal:8");
735 assert_eq!(
736 tmux.parse_session_name(&name),
737 Some(("repo".to_string(), "internal-8".to_string()))
738 );
739 }
740
741 #[test]
742 fn task_id_from_session_name_returns_none_for_non_orch_session() {
743 let tmux = TmuxManager::new();
744 assert_eq!(tmux.parse_session_name("some-other-session"), None);
745 }
746
747 #[test]
748 fn parse_session_name_ignores_production_prefix_in_tests() {
749 let tmux = TmuxManager::new();
750 assert_eq!(tmux.parse_session_name("orch-repo-1234"), None);
751 }
752
753 #[test]
754 fn parse_session_name_hyphenated_project_external() {
755 let tmux = TmuxManager::new();
756 let name = tmux.session_name("owner/my-repo", "1234");
757 assert_eq!(
758 tmux.parse_session_name(&name),
759 Some(("my-repo".to_string(), "1234".to_string()))
760 );
761 }
762
763 #[test]
764 fn parse_session_name_hyphenated_project_internal() {
765 let tmux = TmuxManager::new();
766 let name = tmux.session_name("owner/my-repo", "internal:8");
767 assert_eq!(
768 tmux.parse_session_name(&name),
769 Some(("my-repo".to_string(), "internal-8".to_string()))
770 );
771 }
772
773 #[test]
774 fn parse_session_name_hyphenated_project_review() {
775 let tmux = TmuxManager::new();
776 let name = tmux.session_name("owner/my-repo", "1234-review");
777 assert_eq!(
778 tmux.parse_session_name(&name),
779 Some(("my-repo".to_string(), "1234-review".to_string()))
780 );
781 }
782
783 #[test]
784 fn parse_session_name_multi_hyphen_project() {
785 let tmux = TmuxManager::new();
786 let name = tmux.session_name("owner/my-cool-repo", "42");
787 assert_eq!(
788 tmux.parse_session_name(&name),
789 Some(("my-cool-repo".to_string(), "42".to_string()))
790 );
791 }
792
793 #[test]
794 fn parse_session_name_roundtrip_hyphenated_project() {
795 let tmux = TmuxManager::new();
796 let name = tmux.session_name("owner/my-repo", "1793");
797 assert!(name.ends_with("my-repo-1793"));
798 assert_eq!(
799 tmux.parse_session_name(&name),
800 Some(("my-repo".to_string(), "1793".to_string()))
801 );
802 }
803
804 #[tokio::test]
807 async fn test_set_env() {
808 let tmux = TmuxManager::new();
809 let session = test_session_name();
810
811 let create_result = tmux
813 .command()
814 .args(["new-session", "-d", "-s", &session, "-c", "/tmp"])
815 .output()
816 .await;
817
818 match create_result {
820 Ok(o) if o.status.success() => {}
821 _ => {
822 eprintln!("Skipping test: tmux not available or failed to create test session");
823 return;
824 }
825 }
826 let _guard = SessionGuard::new(&tmux, session.clone());
827
828 let result = tmux.set_env(&session, "TEST_VAR", "test_value").await;
830 assert!(result.is_ok(), "set_env should succeed");
831
832 let check_result = tmux
834 .command()
835 .args(["show-environment", "-t", &session, "TEST_VAR"])
836 .output()
837 .await;
838
839 let Ok(output) = check_result else {
840 eprintln!("Skipping test: unable to check tmux environment");
841 return;
842 };
843 let stdout = String::from_utf8_lossy(&output.stdout);
844 assert!(
845 stdout.contains("TEST_VAR=test_value"),
846 "Expected TEST_VAR=test_value, got: {stdout}"
847 );
848 }
849
850 #[tokio::test]
851 async fn session_blocks_dispatch_keeps_live_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 assert!(tmux.session_blocks_dispatch(&session).await);
871 assert!(tmux.session_exists(&session).await);
872 }
873
874 #[tokio::test]
875 async fn session_blocks_dispatch_cleans_dead_session() {
876 let tmux = TmuxManager::new();
877 let session = test_session_name();
878
879 let create_result = tmux
880 .command()
881 .args(["new-session", "-d", "-s", &session, "-c", "/tmp"])
882 .output()
883 .await;
884
885 match create_result {
886 Ok(o) if o.status.success() => {}
887 _ => {
888 eprintln!("Skipping test: tmux not available or failed to create test session");
889 return;
890 }
891 }
892 let _guard = SessionGuard::new(&tmux, session.clone());
893
894 let set_option_result = tmux
895 .command()
896 .args(["set-option", "-t", &session, "remain-on-exit", "on"])
897 .output()
898 .await;
899 if !matches!(set_option_result, Ok(ref o) if o.status.success()) {
900 eprintln!("Skipping test: unable to set tmux remain-on-exit option");
901 return;
902 }
903
904 let respawn_result = tmux
907 .command()
908 .args(["respawn-pane", "-k", "-t", &session, "false"])
909 .output()
910 .await;
911 if !matches!(respawn_result, Ok(ref o) if o.status.success()) {
912 eprintln!("Skipping test: unable to exit tmux pane");
913 return;
914 }
915
916 for _ in 0..20 {
918 time::sleep(Duration::from_millis(100)).await;
919 if !tmux.session_is_running(&session).await {
920 break;
921 }
922 }
923
924 assert!(tmux.session_exists(&session).await);
925 assert!(!tmux.session_is_running(&session).await);
926 assert!(!tmux.session_blocks_dispatch(&session).await);
927 assert!(!tmux.session_exists(&session).await);
928 }
929
930 #[tokio::test]
934 async fn capture_pane_returns_empty_for_gone_session() {
935 let tmux = TmuxManager::new();
936 let result = tmux
938 .capture_pane("orch-nonexistent-session-99999", 100)
939 .await;
940 assert!(
941 result.is_ok(),
942 "capture_pane should return Ok for non-existent session, got: {result:?}"
943 );
944 assert_eq!(
945 result.unwrap(),
946 "",
947 "capture_pane should return empty string for non-existent session"
948 );
949 }
950
951 #[tokio::test]
955 async fn wait_for_completion_returns_empty_for_gone_session() {
956 let tmux = TmuxManager::new();
957 let result = tmux
959 .wait_for_completion("orch-nonexistent-session-99999", Duration::from_millis(50))
960 .await;
961 assert!(
962 result.is_ok(),
963 "wait_for_completion should return Ok for non-existent session, got: {result:?}"
964 );
965 assert_eq!(
966 result.unwrap(),
967 "",
968 "wait_for_completion should return empty string for non-existent session"
969 );
970 }
971
972 #[tokio::test]
975 async fn test_manager_does_not_touch_the_default_server() {
976 let tmux = TmuxManager::new();
977 let Ok(name) = tmux
978 .create_session("owner/repo", "isolation", "/tmp", "sleep 30", &[])
979 .await
980 else {
981 eprintln!("Skipping test: tmux not available or failed to create test session");
982 return;
983 };
984 let _guard = SessionGuard::new(&tmux, name.clone());
985
986 assert!(
987 tmux.session_exists(&name).await,
988 "session must exist on the isolated test server"
989 );
990
991 let on_default = Command::new("tmux")
992 .args(["has-session", "-t", &name])
993 .output()
994 .await
995 .is_ok_and(|o| o.status.success());
996 assert!(
997 !on_default,
998 "TmuxManager under cfg(test) must not create sessions on the default tmux server"
999 );
1000 }
1001
1002 #[test]
1003 fn isolated_socket_lives_in_a_temp_dir() {
1004 let tmux = TmuxManager::isolated();
1005 let isolated = tmux.isolated.as_ref().expect("isolated server");
1006 assert!(
1007 isolated.socket.ends_with("/tmux.sock"),
1008 "socket path: {}",
1009 isolated.socket
1010 );
1011 assert!(
1012 isolated.dir.starts_with(env::temp_dir()) || isolated.dir.starts_with("/tmp"),
1013 "dir {} must be under {} or /tmp",
1014 isolated.dir.display(),
1015 env::temp_dir().display()
1016 );
1017 assert!(
1018 isolated.dir.is_dir(),
1019 "socket dir must exist while the manager is alive"
1020 );
1021 assert!(
1022 isolated.socket.len() < MAX_SOCK_PATH,
1023 "unix socket path must fit sockaddr_un, got {} bytes: {}",
1024 isolated.socket.len(),
1025 isolated.socket
1026 );
1027 }
1028
1029 #[tokio::test]
1030 async fn isolated_manager_kills_server_and_removes_socket_dir_on_drop() {
1031 let tmux = TmuxManager::isolated();
1032 let (socket, dir) = {
1033 let isolated = tmux.isolated.as_ref().expect("isolated server");
1034 (isolated.socket.clone(), isolated.dir.clone())
1035 };
1036
1037 let Ok(name) = tmux
1038 .create_session("owner/repo", "drop-server", "/tmp", "sleep 30", &[])
1039 .await
1040 else {
1041 eprintln!("Skipping test: tmux not available or failed to create test session");
1042 return;
1043 };
1044 assert!(
1045 tmux.session_exists(&name).await,
1046 "session must exist before drop"
1047 );
1048 assert!(
1049 dir.is_dir(),
1050 "socket dir must exist while the manager is alive"
1051 );
1052
1053 drop(tmux);
1054
1055 let list = process::Command::new("tmux")
1056 .args(["-S", &socket, "-f", "/dev/null", "list-sessions"])
1057 .output()
1058 .expect("list-sessions after drop");
1059 assert!(
1060 !list.status.success(),
1061 "kill-server on drop must leave no server, stderr: {}",
1062 String::from_utf8_lossy(&list.stderr)
1063 );
1064 assert!(!dir.exists(), "socket dir must be removed on drop");
1065 }
1066
1067 #[tokio::test]
1068 async fn isolated_server_does_not_load_user_tmux_conf() {
1069 let home = tempfile::tempdir().expect("temp home");
1070 fs::write(
1071 home.path().join(".tmux.conf"),
1072 "set -g @orch_test_marker 1\nset -g exit-empty off\n",
1073 )
1074 .expect("write tmux.conf");
1075
1076 let tmux = TmuxManager::isolated();
1077 let session = test_session_name();
1078 let create = tmux
1079 .command()
1080 .env("HOME", home.path())
1081 .args([
1082 "new-session",
1083 "-d",
1084 "-s",
1085 &session,
1086 "-c",
1087 "/tmp",
1088 "sleep 30",
1089 ])
1090 .output()
1091 .await;
1092 match create {
1093 Ok(o) if o.status.success() => {}
1094 _ => {
1095 eprintln!("Skipping test: tmux not available or failed to create test session");
1096 return;
1097 }
1098 }
1099 let _guard = SessionGuard::new(&tmux, session);
1100
1101 let marker = tmux
1102 .command()
1103 .env("HOME", home.path())
1104 .args(["show-options", "-gv", "@orch_test_marker"])
1105 .output()
1106 .await
1107 .expect("show-options marker");
1108 let stdout = String::from_utf8_lossy(&marker.stdout);
1109 assert!(
1110 stdout.trim().is_empty(),
1111 "isolated tmux must not load ~/.tmux.conf, got: {stdout}"
1112 );
1113
1114 let exit_empty = tmux
1115 .command()
1116 .args(["show-options", "-gv", "exit-empty"])
1117 .output()
1118 .await
1119 .expect("exit-empty");
1120 let value = String::from_utf8_lossy(&exit_empty.stdout);
1121 assert_eq!(
1122 value.trim(),
1123 "on",
1124 "isolated tmux must keep the default exit-empty, got: {value}"
1125 );
1126 }
1127}