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 if let Some(isolated) = &self.isolated {
123 cmd.args(["-S", &isolated.socket, "-f", "/dev/null"]);
124 }
125 cmd
126 }
127
128 pub fn session_name(&self, project: &str, task_id: &str) -> String {
133 let project_name = project
134 .rsplit('/')
135 .next()
136 .unwrap_or(project)
137 .trim_end_matches(".git");
138 let safe_task_id = task_id.replace(':', "-");
139 format!("{}{project_name}-{safe_task_id}", self.prefix)
140 }
141
142 pub async fn create_session(
157 &self,
158 repo: &str,
159 task_id: &str,
160 working_dir: &str,
161 command: &str,
162 env_vars: &[(&str, &str)],
163 ) -> anyhow::Result<String> {
164 let name = self.session_name(repo, task_id);
165
166 let mut cmd = self.command();
167 cmd.args(["new-session", "-d", "-s", &name, "-c", working_dir]);
168
169 cmd.arg("-e").arg("DISABLE_AUTO_UPDATE=true");
171
172 for (key, value) in env_vars {
176 cmd.arg("-e").arg(format!("{key}={value}"));
178 }
179
180 cmd.arg(command);
181
182 let output = cmd
183 .output_with_context()
184 .await
185 .context("spawning tmux session")?;
186
187 if !output.status.success() {
188 let stderr = String::from_utf8_lossy(&output.stderr);
189 anyhow::bail!("tmux new-session failed: {stderr}");
190 }
191
192 tracing::info!(session = %name, task_id, "created tmux session");
193 Ok(name)
194 }
195
196 pub async fn session_exists(&self, session: &str) -> bool {
198 self.command()
199 .args(["has-session", "-t", session])
200 .output_with_context()
201 .await
202 .is_ok_and(|o| o.status.success())
203 }
204
205 pub async fn kill_session(&self, session: &str) -> anyhow::Result<()> {
207 let output = self
208 .command()
209 .args(["kill-session", "-t", session])
210 .output_with_context()
211 .await?;
212
213 if !output.status.success() {
214 let stderr = String::from_utf8_lossy(&output.stderr);
215 if stderr.contains("can't find session")
216 || stderr.contains("no server running")
217 || stderr.contains("error connecting to")
218 {
219 tracing::debug!(session, %stderr, "kill-session: session already gone");
220 } else {
221 tracing::warn!(session, %stderr, "kill-session failed unexpectedly");
222 }
223 }
224 Ok(())
225 }
226
227 pub async fn capture_pane(&self, session: &str, lines: i32) -> anyhow::Result<String> {
233 let start = format!("-{lines}");
234 let output = self
235 .command()
236 .args(["capture-pane", "-t", session, "-p", "-S", &start])
237 .output_with_context()
238 .await?;
239
240 if !output.status.success() {
241 let stderr = String::from_utf8_lossy(&output.stderr);
242 if stderr.contains("can't find pane")
247 || stderr.contains("can't find session")
248 || stderr.contains("no server running")
249 || stderr.contains("error connecting to")
250 {
251 tracing::debug!(
252 session,
253 "capture_pane: session/pane already gone (teardown race)"
254 );
255 return Ok(String::new());
256 }
257 anyhow::bail!("capture-pane failed for {session}: {stderr}");
258 }
259 Ok(String::from_utf8_lossy(&output.stdout).to_string())
260 }
261
262 pub async fn is_session_active(&self, session: &str) -> bool {
265 let output = self
267 .command()
268 .args(["list-panes", "-t", session, "-F", "#{pane_dead}"])
269 .output_with_context()
270 .await;
271
272 match output {
273 Ok(o) if o.status.success() => {
274 let flag = String::from_utf8_lossy(&o.stdout);
275 flag.trim() == "0" }
277 _ => false,
278 }
279 }
280
281 #[cfg(test)]
283 pub async fn session_is_running(&self, session: &str) -> bool {
284 self.session_exists(session).await && self.is_session_active(session).await
285 }
286
287 pub async fn session_blocks_dispatch(&self, session: &str) -> bool {
292 if !self.session_exists(session).await {
293 return false;
294 }
295
296 if self.is_session_active(session).await {
297 return true;
298 }
299
300 tracing::warn!(
301 session,
302 "found stale tmux session with dead pane; cleaning up"
303 );
304 if let Err(err) = self.kill_session(session).await {
305 tracing::debug!(session, error = %err, "failed to clean up stale tmux session");
306 }
307
308 false
309 }
310
311 pub async fn session_blocks_dispatch_from_map(
317 &self,
318 session: &str,
319 session_map: &HashMap<String, bool>,
320 ) -> bool {
321 match session_map.get(session).copied() {
322 None => false, Some(true) => true, Some(false) => {
325 tracing::warn!(
327 session,
328 "found stale tmux session with dead pane; cleaning up"
329 );
330 if let Err(err) = self.kill_session(session).await {
331 tracing::debug!(
332 session,
333 error = %err,
334 "failed to clean up stale tmux session"
335 );
336 }
337 false
338 }
339 }
340 }
341
342 pub(crate) fn parse_session_name(&self, name: &str) -> Option<(String, String)> {
356 let after_prefix = name.strip_prefix(&self.prefix)?;
357
358 let (base, is_review) = match after_prefix.strip_suffix("-review") {
360 Some(stripped) => (stripped, true),
361 None => (after_prefix, false),
362 };
363
364 if let Some(idx) = base.rfind("-internal-") {
366 let project = &base[..idx];
367 let task_base = &base[idx + 1..]; let after_internal = &task_base["internal-".len()..];
369 if !project.is_empty()
370 && !after_internal.is_empty()
371 && after_internal.chars().all(|c| c.is_ascii_digit())
372 {
373 let task_id = if is_review {
374 format!("{task_base}-review")
375 } else {
376 task_base.to_string()
377 };
378 return Some((project.to_string(), task_id));
379 }
380 }
381
382 if let Some(idx) = base.rfind('-') {
384 let project = &base[..idx];
385 let digits = &base[idx + 1..];
386 if !project.is_empty()
387 && !digits.is_empty()
388 && digits.chars().all(|c| c.is_ascii_digit())
389 {
390 let task_id = if is_review {
391 format!("{digits}-review")
392 } else {
393 digits.to_string()
394 };
395 return Some((project.to_string(), task_id));
396 }
397 }
398
399 None
400 }
401
402 pub async fn batch_session_active(&self) -> HashMap<String, bool> {
407 let mut map = HashMap::new();
408 let o = match self
409 .command()
410 .args(["list-panes", "-a", "-F", "#{session_name} #{pane_dead}"])
411 .output_with_context()
412 .await
413 {
414 Ok(o) => o,
415 Err(e) => {
416 tracing::warn!(error = %e, "batch_session_active: failed to spawn tmux");
417 return map;
418 }
419 };
420 if !o.status.success() {
421 let stderr = String::from_utf8_lossy(&o.stderr);
422 tracing::warn!(
423 status = ?o.status,
424 stderr = %stderr.trim(),
425 "batch_session_active: tmux list-panes exited non-zero"
426 );
427 return map;
428 }
429 for line in String::from_utf8_lossy(&o.stdout).lines() {
430 let mut parts = line.trim().splitn(2, ' ');
431 if let (Some(session), Some(dead)) = (parts.next(), parts.next()) {
432 map.insert(session.to_string(), dead.trim() == "0");
433 }
434 }
435 map
436 }
437
438 pub async fn list_sessions(&self) -> anyhow::Result<Vec<Session>> {
440 let output = self
442 .command()
443 .args(["list-sessions", "-F", "#{session_name} #{session_created}"])
444 .output_with_context()
445 .await?;
446
447 if !output.status.success() {
448 return Ok(vec![]);
449 }
450
451 let mut sessions = Vec::new();
452 for line in String::from_utf8_lossy(&output.stdout).lines() {
453 let parts: Vec<&str> = line.trim().splitn(2, ' ').collect();
454 if parts.is_empty() {
455 continue;
456 }
457 let name = parts[0].to_string();
458 let created_at = parts.get(1).and_then(|s| s.parse::<u64>().ok());
459
460 if let Some((project, task_id)) = self.parse_session_name(&name) {
461 sessions.push(Session {
462 name,
463 task_id,
464 project,
465 created_at,
466 });
467 }
468 }
469
470 Ok(sessions)
471 }
472
473 pub async fn kill_stale_sessions(&self, before_timestamp: u64) -> anyhow::Result<usize> {
476 let sessions = self.list_sessions().await?;
477 let mut killed = 0;
478
479 for session in sessions {
480 let should_kill = match session.created_at {
481 Some(created) => created < before_timestamp,
482 None => false,
484 };
485
486 if should_kill {
487 tracing::info!(
488 session = %session.name,
489 created_at = session.created_at,
490 "killing stale tmux session from previous run"
491 );
492 match self.kill_session(&session.name).await {
493 Err(e) => {
494 tracing::warn!(session = %session.name, error = %e, "failed to kill stale session");
495 }
496 _ => {
497 killed += 1;
498 }
499 }
500 }
501 }
502
503 if killed > 0 {
504 tracing::info!(killed, "killed stale tmux sessions on startup");
505 }
506
507 Ok(killed)
508 }
509
510 pub async fn wait_for_sessions_dead(
514 &self,
515 sessions: &[String],
516 poll_interval: Duration,
517 timeout: Duration,
518 ) -> usize {
519 let start = Instant::now();
520 let mut remaining: HashSet<String> = sessions.iter().cloned().collect();
521
522 while !remaining.is_empty() && start.elapsed() < timeout {
523 let mut to_remove = Vec::new();
524 for session in &remaining {
525 if !self.session_exists(session).await {
526 to_remove.push(session.clone());
527 }
528 }
529 for session in to_remove {
530 remaining.remove(&session);
531 }
532 if !remaining.is_empty() {
533 time::sleep(poll_interval).await;
534 }
535 }
536
537 let still_alive = remaining.len();
538 if still_alive > 0 {
539 tracing::warn!(
540 still_alive,
541 sessions = ?remaining.iter().collect::<Vec<_>>(),
542 "tmux sessions did not terminate within timeout"
543 );
544 }
545 still_alive
546 }
547
548 pub async fn wait_for_completion(
551 &self,
552 session: &str,
553 poll_interval: Duration,
554 ) -> anyhow::Result<String> {
555 loop {
556 if !self.session_exists(session).await {
557 return Ok(String::new());
558 }
559
560 if !self.is_session_active(session).await {
561 match self.capture_pane(session, 500).await {
565 Ok(output) => return Ok(output),
566 Err(err) => {
567 tracing::error!(session = %session, error = %err, "failed to capture final pane output");
568 return Ok(String::new());
569 }
570 }
571 }
572
573 time::sleep(poll_interval).await;
574 }
575 }
576
577 pub async fn snapshot(&self) -> Vec<(Session, bool)> {
585 let sessions = match self.list_sessions().await {
586 Ok(s) => s,
587 Err(err) => {
588 tracing::error!(error = %err, "failed to list tmux sessions — returning empty snapshot");
589 Vec::new()
590 }
591 };
592 let active_map = self.batch_session_active().await;
594 sessions
595 .into_iter()
596 .map(|s| {
597 let active = active_map.get(&s.name).copied().unwrap_or(false);
599 (s, active)
600 })
601 .collect()
602 }
603
604 #[cfg(test)]
612 pub async fn set_env(&self, session: &str, key: &str, value: &str) -> anyhow::Result<()> {
613 let output = self
614 .command()
615 .args(["set-environment", "-t", session, key, value])
616 .output_with_context()
617 .await?;
618
619 if !output.status.success() {
620 let stderr = String::from_utf8_lossy(&output.stderr);
621 anyhow::bail!("tmux set-environment failed for {session}: {stderr}");
622 }
623
624 tracing::debug!(session, key, "set tmux environment variable");
625 Ok(())
626 }
627
628 pub async fn unset_global_env(&self, key: &str) -> anyhow::Result<()> {
632 let output = self
633 .command()
634 .args(["set-environment", "-gu", key])
635 .output_with_context()
636 .await?;
637
638 if !output.status.success() {
639 let stderr = String::from_utf8_lossy(&output.stderr);
640 anyhow::bail!("tmux unset-global-environment failed for {key}: {stderr}");
641 }
642
643 tracing::debug!(key, "unset tmux global environment variable");
644 Ok(())
645 }
646}
647
648#[cfg(test)]
649pub(crate) fn test_session_name() -> String {
650 format!(
651 "orch-test-{}",
652 SystemTime::now()
653 .duration_since(std_time::UNIX_EPOCH)
654 .map_or_else(|_| 0, |d| d.as_millis())
655 )
656}
657
658#[cfg(test)]
660pub(crate) struct SessionGuard {
661 session: String,
662 tmux: TmuxManager,
663}
664
665#[cfg(test)]
666impl SessionGuard {
667 pub(crate) fn new(tmux: &TmuxManager, session: String) -> Self {
668 Self {
669 session,
670 tmux: tmux.clone(),
671 }
672 }
673}
674
675#[cfg(test)]
676impl Drop for SessionGuard {
677 fn drop(&mut self) {
678 let mut cmd = process::Command::new("tmux");
679 if let Some(isolated) = &self.tmux.isolated {
680 cmd.args(["-S", &isolated.socket, "-f", "/dev/null"]);
681 }
682 cmd.args(["kill-session", "-t", &self.session]);
683 let _ = cmd.output();
684 }
685}
686
687#[cfg(test)]
688mod tests {
689 use super::*;
690
691 #[test]
692 fn session_name_internal_task_id_is_sanitized() {
693 let tmux = TmuxManager::new();
694 let name = tmux.session_name("owner/repo", "internal:8");
695 assert!(!name.contains(':'), "colon must be sanitized for tmux");
696 assert_eq!(
697 tmux.parse_session_name(&name),
698 Some(("repo".to_string(), "internal-8".to_string()))
699 );
700 }
701
702 #[test]
703 fn task_id_from_session_name_parses_external_task() {
704 let tmux = TmuxManager::new();
705 let name = tmux.session_name("owner/repo", "1234");
706 assert_eq!(
707 tmux.parse_session_name(&name),
708 Some(("repo".to_string(), "1234".to_string()))
709 );
710 }
711
712 #[test]
713 fn task_id_from_session_name_parses_internal_task() {
714 let tmux = TmuxManager::new();
715 let name = tmux.session_name("owner/orch", "internal:21116");
716 assert_eq!(
717 tmux.parse_session_name(&name),
718 Some(("orch".to_string(), "internal-21116".to_string()))
719 );
720 }
721
722 #[test]
723 fn task_id_from_session_name_parses_internal_task_small_id() {
724 let tmux = TmuxManager::new();
725 let name = tmux.session_name("owner/repo", "internal:8");
726 assert_eq!(
727 tmux.parse_session_name(&name),
728 Some(("repo".to_string(), "internal-8".to_string()))
729 );
730 }
731
732 #[test]
733 fn task_id_from_session_name_returns_none_for_non_orch_session() {
734 let tmux = TmuxManager::new();
735 assert_eq!(tmux.parse_session_name("some-other-session"), None);
736 }
737
738 #[test]
739 fn parse_session_name_ignores_production_prefix_in_tests() {
740 let tmux = TmuxManager::new();
741 assert_eq!(tmux.parse_session_name("orch-repo-1234"), None);
742 }
743
744 #[test]
745 fn parse_session_name_hyphenated_project_external() {
746 let tmux = TmuxManager::new();
747 let name = tmux.session_name("owner/my-repo", "1234");
748 assert_eq!(
749 tmux.parse_session_name(&name),
750 Some(("my-repo".to_string(), "1234".to_string()))
751 );
752 }
753
754 #[test]
755 fn parse_session_name_hyphenated_project_internal() {
756 let tmux = TmuxManager::new();
757 let name = tmux.session_name("owner/my-repo", "internal:8");
758 assert_eq!(
759 tmux.parse_session_name(&name),
760 Some(("my-repo".to_string(), "internal-8".to_string()))
761 );
762 }
763
764 #[test]
765 fn parse_session_name_hyphenated_project_review() {
766 let tmux = TmuxManager::new();
767 let name = tmux.session_name("owner/my-repo", "1234-review");
768 assert_eq!(
769 tmux.parse_session_name(&name),
770 Some(("my-repo".to_string(), "1234-review".to_string()))
771 );
772 }
773
774 #[test]
775 fn parse_session_name_multi_hyphen_project() {
776 let tmux = TmuxManager::new();
777 let name = tmux.session_name("owner/my-cool-repo", "42");
778 assert_eq!(
779 tmux.parse_session_name(&name),
780 Some(("my-cool-repo".to_string(), "42".to_string()))
781 );
782 }
783
784 #[test]
785 fn parse_session_name_roundtrip_hyphenated_project() {
786 let tmux = TmuxManager::new();
787 let name = tmux.session_name("owner/my-repo", "1793");
788 assert!(name.ends_with("my-repo-1793"));
789 assert_eq!(
790 tmux.parse_session_name(&name),
791 Some(("my-repo".to_string(), "1793".to_string()))
792 );
793 }
794
795 #[tokio::test]
798 async fn test_set_env() {
799 let tmux = TmuxManager::new();
800 let session = test_session_name();
801
802 let create_result = tmux
804 .command()
805 .args(["new-session", "-d", "-s", &session, "-c", "/tmp"])
806 .output()
807 .await;
808
809 match create_result {
811 Ok(o) if o.status.success() => {}
812 _ => {
813 eprintln!("Skipping test: tmux not available or failed to create test session");
814 return;
815 }
816 }
817 let _guard = SessionGuard::new(&tmux, session.clone());
818
819 let result = tmux.set_env(&session, "TEST_VAR", "test_value").await;
821 assert!(result.is_ok(), "set_env should succeed");
822
823 let check_result = tmux
825 .command()
826 .args(["show-environment", "-t", &session, "TEST_VAR"])
827 .output()
828 .await;
829
830 let Ok(output) = check_result else {
831 eprintln!("Skipping test: unable to check tmux environment");
832 return;
833 };
834 let stdout = String::from_utf8_lossy(&output.stdout);
835 assert!(
836 stdout.contains("TEST_VAR=test_value"),
837 "Expected TEST_VAR=test_value, got: {stdout}"
838 );
839 }
840
841 #[tokio::test]
842 async fn session_blocks_dispatch_keeps_live_session() {
843 let tmux = TmuxManager::new();
844 let session = test_session_name();
845
846 let create_result = tmux
847 .command()
848 .args(["new-session", "-d", "-s", &session, "-c", "/tmp"])
849 .output()
850 .await;
851
852 match create_result {
853 Ok(o) if o.status.success() => {}
854 _ => {
855 eprintln!("Skipping test: tmux not available or failed to create test session");
856 return;
857 }
858 }
859 let _guard = SessionGuard::new(&tmux, session.clone());
860
861 assert!(tmux.session_blocks_dispatch(&session).await);
862 assert!(tmux.session_exists(&session).await);
863 }
864
865 #[tokio::test]
866 async fn session_blocks_dispatch_cleans_dead_session() {
867 let tmux = TmuxManager::new();
868 let session = test_session_name();
869
870 let create_result = tmux
871 .command()
872 .args(["new-session", "-d", "-s", &session, "-c", "/tmp"])
873 .output()
874 .await;
875
876 match create_result {
877 Ok(o) if o.status.success() => {}
878 _ => {
879 eprintln!("Skipping test: tmux not available or failed to create test session");
880 return;
881 }
882 }
883 let _guard = SessionGuard::new(&tmux, session.clone());
884
885 let set_option_result = tmux
886 .command()
887 .args(["set-option", "-t", &session, "remain-on-exit", "on"])
888 .output()
889 .await;
890 if !matches!(set_option_result, Ok(ref o) if o.status.success()) {
891 eprintln!("Skipping test: unable to set tmux remain-on-exit option");
892 return;
893 }
894
895 let respawn_result = tmux
898 .command()
899 .args(["respawn-pane", "-k", "-t", &session, "false"])
900 .output()
901 .await;
902 if !matches!(respawn_result, Ok(ref o) if o.status.success()) {
903 eprintln!("Skipping test: unable to exit tmux pane");
904 return;
905 }
906
907 for _ in 0..20 {
909 time::sleep(Duration::from_millis(100)).await;
910 if !tmux.session_is_running(&session).await {
911 break;
912 }
913 }
914
915 assert!(tmux.session_exists(&session).await);
916 assert!(!tmux.session_is_running(&session).await);
917 assert!(!tmux.session_blocks_dispatch(&session).await);
918 assert!(!tmux.session_exists(&session).await);
919 }
920
921 #[tokio::test]
925 async fn capture_pane_returns_empty_for_gone_session() {
926 let tmux = TmuxManager::new();
927 let result = tmux
929 .capture_pane("orch-nonexistent-session-99999", 100)
930 .await;
931 assert!(
932 result.is_ok(),
933 "capture_pane should return Ok for non-existent session, got: {result:?}"
934 );
935 assert_eq!(
936 result.unwrap(),
937 "",
938 "capture_pane should return empty string for non-existent session"
939 );
940 }
941
942 #[tokio::test]
946 async fn wait_for_completion_returns_empty_for_gone_session() {
947 let tmux = TmuxManager::new();
948 let result = tmux
950 .wait_for_completion("orch-nonexistent-session-99999", Duration::from_millis(50))
951 .await;
952 assert!(
953 result.is_ok(),
954 "wait_for_completion should return Ok for non-existent session, got: {result:?}"
955 );
956 assert_eq!(
957 result.unwrap(),
958 "",
959 "wait_for_completion should return empty string for non-existent session"
960 );
961 }
962
963 #[tokio::test]
966 async fn test_manager_does_not_touch_the_default_server() {
967 let tmux = TmuxManager::new();
968 let Ok(name) = tmux
969 .create_session("owner/repo", "isolation", "/tmp", "sleep 30", &[])
970 .await
971 else {
972 eprintln!("Skipping test: tmux not available or failed to create test session");
973 return;
974 };
975 let _guard = SessionGuard::new(&tmux, name.clone());
976
977 assert!(
978 tmux.session_exists(&name).await,
979 "session must exist on the isolated test server"
980 );
981
982 let on_default = Command::new("tmux")
983 .args(["has-session", "-t", &name])
984 .output()
985 .await
986 .is_ok_and(|o| o.status.success());
987 assert!(
988 !on_default,
989 "TmuxManager under cfg(test) must not create sessions on the default tmux server"
990 );
991 }
992
993 #[test]
994 fn isolated_socket_lives_in_a_temp_dir() {
995 let tmux = TmuxManager::isolated();
996 let isolated = tmux.isolated.as_ref().expect("isolated server");
997 assert!(
998 isolated.socket.ends_with("/tmux.sock"),
999 "socket path: {}",
1000 isolated.socket
1001 );
1002 assert!(
1003 isolated.dir.starts_with(env::temp_dir()) || isolated.dir.starts_with("/tmp"),
1004 "dir {} must be under {} or /tmp",
1005 isolated.dir.display(),
1006 env::temp_dir().display()
1007 );
1008 assert!(
1009 isolated.dir.is_dir(),
1010 "socket dir must exist while the manager is alive"
1011 );
1012 assert!(
1013 isolated.socket.len() < MAX_SOCK_PATH,
1014 "unix socket path must fit sockaddr_un, got {} bytes: {}",
1015 isolated.socket.len(),
1016 isolated.socket
1017 );
1018 }
1019
1020 #[tokio::test]
1021 async fn isolated_manager_kills_server_and_removes_socket_dir_on_drop() {
1022 let tmux = TmuxManager::isolated();
1023 let (socket, dir) = {
1024 let isolated = tmux.isolated.as_ref().expect("isolated server");
1025 (isolated.socket.clone(), isolated.dir.clone())
1026 };
1027
1028 let Ok(name) = tmux
1029 .create_session("owner/repo", "drop-server", "/tmp", "sleep 30", &[])
1030 .await
1031 else {
1032 eprintln!("Skipping test: tmux not available or failed to create test session");
1033 return;
1034 };
1035 assert!(
1036 tmux.session_exists(&name).await,
1037 "session must exist before drop"
1038 );
1039 assert!(
1040 dir.is_dir(),
1041 "socket dir must exist while the manager is alive"
1042 );
1043
1044 drop(tmux);
1045
1046 let list = process::Command::new("tmux")
1047 .args(["-S", &socket, "-f", "/dev/null", "list-sessions"])
1048 .output()
1049 .expect("list-sessions after drop");
1050 assert!(
1051 !list.status.success(),
1052 "kill-server on drop must leave no server, stderr: {}",
1053 String::from_utf8_lossy(&list.stderr)
1054 );
1055 assert!(!dir.exists(), "socket dir must be removed on drop");
1056 }
1057
1058 #[tokio::test]
1059 async fn isolated_server_does_not_load_user_tmux_conf() {
1060 let home = tempfile::tempdir().expect("temp home");
1061 fs::write(
1062 home.path().join(".tmux.conf"),
1063 "set -g @orch_test_marker 1\nset -g exit-empty off\n",
1064 )
1065 .expect("write tmux.conf");
1066
1067 let tmux = TmuxManager::isolated();
1068 let session = test_session_name();
1069 let create = tmux
1070 .command()
1071 .env("HOME", home.path())
1072 .args([
1073 "new-session",
1074 "-d",
1075 "-s",
1076 &session,
1077 "-c",
1078 "/tmp",
1079 "sleep 30",
1080 ])
1081 .output()
1082 .await;
1083 match create {
1084 Ok(o) if o.status.success() => {}
1085 _ => {
1086 eprintln!("Skipping test: tmux not available or failed to create test session");
1087 return;
1088 }
1089 }
1090 let _guard = SessionGuard::new(&tmux, session);
1091
1092 let marker = tmux
1093 .command()
1094 .env("HOME", home.path())
1095 .args(["show-options", "-gv", "@orch_test_marker"])
1096 .output()
1097 .await
1098 .expect("show-options marker");
1099 let stdout = String::from_utf8_lossy(&marker.stdout);
1100 assert!(
1101 stdout.trim().is_empty(),
1102 "isolated tmux must not load ~/.tmux.conf, got: {stdout}"
1103 );
1104
1105 let exit_empty = tmux
1106 .command()
1107 .args(["show-options", "-gv", "exit-empty"])
1108 .output()
1109 .await
1110 .expect("exit-empty");
1111 let value = String::from_utf8_lossy(&exit_empty.stdout);
1112 assert_eq!(
1113 value.trim(),
1114 "on",
1115 "isolated tmux must keep the default exit-empty, got: {value}"
1116 );
1117 }
1118}