Skip to main content

orch/sys/
tmux.rs

1//! orch's tmux sessions: the `orch-{project}-{task_id}` names, and which session blocks a dispatch.
2//! Running tmux itself is the `tmux-sessions` crate
3
4use std::collections::HashMap;
5use std::process;
6#[cfg(test)]
7use std::time as std_time;
8use std::time::Duration;
9#[cfg(test)]
10use std::time::SystemTime;
11use tmux_sessions::{Error, Tmux};
12#[cfg(test)]
13use tokio::process::Command;
14
15/// The prefix of every session orch creates
16const PREFIX: &str = "orch-";
17
18/// Info about an active orch tmux session.
19#[derive(Debug, Clone)]
20pub struct Session {
21    pub name: String,
22    /// The task id (preserving internal/external marker), e.g. "internal-21116" or "1775189963034"
23    pub task_id: String,
24    /// Project short name derived from repo slug (owner/repo -> repo)
25    pub project: String,
26    pub created_at: Option<u64>, // Unix timestamp from tmux #{session_created}
27}
28
29/// An error with tmux's own stderr in its text, since callers print errors with `{}`
30fn tmux_failed(err: Error, what: impl FnOnce() -> String) -> anyhow::Error {
31    match err {
32        Error::Tmux { stderr, .. } => anyhow::anyhow!("{}: {stderr}", what()),
33        err => err.into(),
34    }
35}
36
37/// The user's default tmux server, also under test. For code that works on a session by name
38pub fn default_server() -> Tmux {
39    Tmux::new(PREFIX)
40}
41
42/// Manage tmux sessions for agent tasks.
43#[derive(Clone, Debug)]
44pub struct TmuxManager {
45    tmux: Tmux,
46}
47
48impl TmuxManager {
49    pub fn new() -> Self {
50        if cfg!(test) {
51            return Self::isolated();
52        }
53
54        Self {
55            tmux: default_server(),
56        }
57    }
58
59    /// A tmux server of its own with its own prefix, for tests. `cfg(test)` is unset when
60    /// tests/*.rs link the library, so those tests call this directly
61    pub fn isolated() -> Self {
62        Self {
63            tmux: Tmux::isolated("orch-test-").expect("isolated tmux socket dir"),
64        }
65    }
66
67    /// Build a `tmux` command scoped to this manager's server
68    #[cfg(test)]
69    pub(crate) fn command(&self) -> Command {
70        self.tmux.command()
71    }
72
73    /// A blocking `tmux` command scoped to this manager's server, for `Drop`
74    #[cfg(test)]
75    fn blocking_command(&self) -> process::Command {
76        self.tmux.blocking_command()
77    }
78
79    /// `tmux attach-session` on this manager's server, for a CLI to run at a terminal
80    pub fn attach_command(&self, session: &str) -> process::Command {
81        self.tmux.attach_command(session)
82    }
83
84    /// Session name for a task: `orch-{project}-{task_id}`.
85    ///
86    /// The project name is derived from the repo slug (e.g. `owner/repo` → `repo`).
87    /// This prevents collisions between projects with the same issue number.
88    pub fn session_name(&self, project: &str, task_id: &str) -> String {
89        let project_name = project
90            .rsplit('/')
91            .next()
92            .unwrap_or(project)
93            .trim_end_matches(".git");
94        let safe_task_id = task_id.replace(':', "-");
95        format!("{}{project_name}-{safe_task_id}", self.tmux.prefix())
96    }
97
98    /// Create a new tmux session for a task and run a command in it.
99    ///
100    /// Environment variables in `env_vars` are injected into the session via
101    /// `tmux new-session -e KEY=VALUE` — they are not written to disk.
102    ///
103    /// The session is detached — the agent runs in the background.
104    /// Returns the session name.
105    ///
106    /// Note: GH_TOKEN is passed here via `-e` like all other env vars. Do NOT
107    /// use `create_session_detached` + `set_env` + `create_window` to avoid
108    /// exposing secrets in process args — that creates a 2-window session which
109    /// breaks all tmux monitoring (completion detection, output capture, silence
110    /// detection) because they target the default window (the idle shell), not
111    /// the agent window. See the revert of PR #2903.
112    pub async fn create_session(
113        &self,
114        repo: &str,
115        task_id: &str,
116        working_dir: &str,
117        command: &str,
118        env_vars: &[(&str, &str)],
119    ) -> anyhow::Result<String> {
120        let name = self.session_name(repo, task_id);
121
122        // Suppress oh-my-zsh update prompts that can intercept agent input.
123        let mut env = vec![("DISABLE_AUTO_UPDATE", "true")];
124        env.extend_from_slice(env_vars);
125
126        // Callers print the error with `{}`, so tmux's own message must be the outer text
127        match self.tmux.create(&name, working_dir, command, &env).await {
128            Ok(()) => {}
129            Err(err @ Error::Spawn(_)) => {
130                return Err(anyhow::Error::new(err).context("spawning tmux session"));
131            }
132            Err(err) => return Err(err.into()),
133        }
134
135        tracing::info!(session = %name, task_id, "created tmux session");
136        Ok(name)
137    }
138
139    /// Check if a session exists.
140    pub async fn session_exists(&self, session: &str) -> bool {
141        self.tmux.exists(session).await
142    }
143
144    /// Kill a session. One that is already gone is not an error
145    pub async fn kill_session(&self, session: &str) -> anyhow::Result<()> {
146        match self.tmux.kill(session).await {
147            Ok(()) => Ok(()),
148            Err(Error::Tmux { stderr, .. }) => {
149                tracing::warn!(session, %stderr, "kill-session failed unexpectedly");
150                Ok(())
151            }
152            Err(err) => Err(err.into()),
153        }
154    }
155
156    /// Capture the current pane content (last N lines).
157    ///
158    /// Returns `Ok(String::new())` if the session or pane is not found — this is
159    /// an expected teardown race when the session was cleaned up between the caller's
160    /// `is_session_active()` check and this capture.
161    pub async fn capture_pane(&self, session: &str, lines: u32) -> anyhow::Result<String> {
162        self.tmux
163            .capture(session, lines)
164            .await
165            .map_err(|err| tmux_failed(err, || format!("capture-pane failed for {session}")))
166    }
167
168    /// Check if the process in a session's pane is still running.
169    /// Returns false if the session doesn't exist or the pane has no active process.
170    pub async fn is_session_active(&self, session: &str) -> bool {
171        self.tmux.is_active(session).await
172    }
173
174    /// Check whether a session exists and still has a live pane process.
175    #[cfg(test)]
176    pub async fn session_is_running(&self, session: &str) -> bool {
177        self.session_exists(session).await && self.is_session_active(session).await
178    }
179
180    /// Return whether a session should block a new dispatch.
181    ///
182    /// `known` is a session map from `batch_session_active()`, or `None` to ask tmux. A missing
183    /// session does not block and a live pane does. A dead pane is cleaned up eagerly, so it does
184    /// not block reclaim/re-dispatch loops or cause `new-session` name collisions
185    pub async fn session_blocks_dispatch(
186        &self,
187        session: &str,
188        known: Option<&HashMap<String, bool>>,
189    ) -> bool {
190        let alive = match known {
191            Some(map) => map.get(session).copied(),
192            None if !self.session_exists(session).await => None,
193            None => Some(self.is_session_active(session).await),
194        };
195        match alive {
196            None => false,
197            Some(true) => true,
198            Some(false) => {
199                tracing::warn!(
200                    session,
201                    "found stale tmux session with dead pane; cleaning up"
202                );
203                if let Err(err) = self.kill_session(session).await {
204                    tracing::debug!(session, error = %err, "failed to clean up stale tmux session");
205                }
206                false
207            }
208        }
209    }
210
211    /// Parse a session name into (project, task_id).
212    ///
213    /// Session names follow the format `orch-{project}-{task_id}`, where
214    /// `{project}` may contain hyphens (e.g. `my-repo`) and `{task_id}` is one of:
215    /// - numeric (external): `1234`
216    /// - internal: `internal-{n}`
217    /// - review variant: `{id}-review` or `internal-{n}-review`
218    ///
219    /// Parsing works right-to-left since task_id formats are well-defined,
220    /// avoiding ambiguity when the project name contains hyphens.
221    ///
222    /// Returns `None` if the name does not start with the orch prefix or
223    /// cannot be parsed into a valid (project, task_id) pair.
224    pub(crate) fn parse_session_name(&self, name: &str) -> Option<(String, String)> {
225        let after_prefix = name.strip_prefix(self.tmux.prefix())?;
226
227        // Strip optional "-review" suffix, reattach to the task_id later.
228        let (base, is_review) = match after_prefix.strip_suffix("-review") {
229            Some(stripped) => (stripped, true),
230            None => (after_prefix, false),
231        };
232
233        // Try internal task: {project}-internal-{digits}
234        if let Some(idx) = base.rfind("-internal-") {
235            let project = &base[..idx];
236            let task_base = &base[idx + 1..]; // "internal-{digits}"
237            let after_internal = &task_base["internal-".len()..];
238            if !project.is_empty()
239                && !after_internal.is_empty()
240                && after_internal.chars().all(|c| c.is_ascii_digit())
241            {
242                let task_id = if is_review {
243                    format!("{task_base}-review")
244                } else {
245                    task_base.to_string()
246                };
247                return Some((project.to_string(), task_id));
248            }
249        }
250
251        // External task: {project}-{digits}
252        if let Some(idx) = base.rfind('-') {
253            let project = &base[..idx];
254            let digits = &base[idx + 1..];
255            if !project.is_empty()
256                && !digits.is_empty()
257                && digits.chars().all(|c| c.is_ascii_digit())
258            {
259                let task_id = if is_review {
260                    format!("{digits}-review")
261                } else {
262                    digits.to_string()
263                };
264                return Some((project.to_string(), task_id));
265            }
266        }
267
268        None
269    }
270
271    /// Get pane_dead status for all sessions in a single tmux call.
272    ///
273    /// Returns a map from session name → alive (true = alive, false = dead/missing).
274    /// Uses `list-panes -a` to avoid one subprocess per session.
275    pub async fn batch_session_active(&self) -> HashMap<String, bool> {
276        self.tmux.active_map().await.unwrap_or_else(|e| {
277            tracing::warn!(error = %e, "batch_session_active: failed to spawn tmux");
278            HashMap::new()
279        })
280    }
281
282    /// List all orch-prefixed sessions with metadata including creation time.
283    pub async fn list_sessions(&self) -> anyhow::Result<Vec<Session>> {
284        let sessions = self.tmux.list().await?;
285        Ok(sessions
286            .into_iter()
287            .filter_map(|session| {
288                let (project, task_id) = self.parse_session_name(&session.name)?;
289                Some(Session {
290                    name: session.name,
291                    task_id,
292                    project,
293                    created_at: session.created_at,
294                })
295            })
296            .collect())
297    }
298
299    /// Kill all orch-prefixed sessions created before a given timestamp.
300    /// Returns the number of sessions killed.
301    pub async fn kill_stale_sessions(&self, before_timestamp: u64) -> anyhow::Result<usize> {
302        let sessions = self.list_sessions().await?;
303        let mut killed = 0;
304
305        for session in sessions {
306            // If we can't determine creation time, be conservative and don't kill
307            let Some(created) = session.created_at else {
308                continue;
309            };
310            if created >= before_timestamp {
311                continue;
312            }
313            tracing::info!(
314                session = %session.name,
315                created_at = session.created_at,
316                "killing stale tmux session from previous run"
317            );
318            match self.kill_session(&session.name).await {
319                Err(e) => {
320                    tracing::warn!(session = %session.name, error = %e, "failed to kill stale session");
321                }
322                _ => {
323                    killed += 1;
324                }
325            }
326        }
327
328        if killed > 0 {
329            tracing::info!(killed, "killed stale tmux sessions on startup");
330        }
331
332        Ok(killed)
333    }
334
335    /// Wait for multiple sessions to be fully dead (no longer exist).
336    /// Polls every `poll_interval` up to `timeout`.
337    /// Returns the number of sessions that were still alive after timeout.
338    pub async fn wait_for_sessions_dead(
339        &self,
340        sessions: &[String],
341        poll_interval: Duration,
342        timeout: Duration,
343    ) -> usize {
344        let remaining = self
345            .tmux
346            .wait_until_gone(sessions, poll_interval, timeout)
347            .await;
348        if !remaining.is_empty() {
349            tracing::warn!(
350                still_alive = remaining.len(),
351                sessions = ?remaining,
352                "tmux sessions did not terminate within timeout"
353            );
354        }
355        remaining.len()
356    }
357
358    /// Wait for a session to finish (pane process exits).
359    /// Returns the captured output from the last N lines.
360    pub async fn wait_for_completion(
361        &self,
362        session: &str,
363        poll_interval: Duration,
364    ) -> anyhow::Result<String> {
365        match self.tmux.wait_for_completion(session, poll_interval).await {
366            Ok(output) => Ok(output),
367            Err(err) => {
368                tracing::error!(session = %session, error = %err, "failed to capture final pane output");
369                Ok(String::new())
370            }
371        }
372    }
373
374    /// Snapshot all orch-prefixed sessions — for engine tick monitoring.
375    ///
376    /// Returns a vector of (Session, alive) so callers can operate on the
377    /// actual session name instead of reconstructing one from repo+task_id.
378    ///
379    /// Uses `batch_session_active()` internally to fetch all pane-dead statuses
380    /// in a single subprocess call instead of one call per session (N+1 → 2).
381    pub async fn snapshot(&self) -> Vec<(Session, bool)> {
382        let sessions = match self.list_sessions().await {
383            Ok(s) => s,
384            Err(err) => {
385                tracing::error!(error = %err, "failed to list tmux sessions — returning empty snapshot");
386                Vec::new()
387            }
388        };
389        // Fetch all pane-dead statuses in a single `list-panes -a` call.
390        let active_map = self.batch_session_active().await;
391        sessions
392            .into_iter()
393            .map(|s| {
394                // Sessions absent from the map are treated as dead (pane missing).
395                let active = active_map.get(&s.name).copied().unwrap_or(false);
396                (s, active)
397            })
398            .collect()
399    }
400
401    /// Set an environment variable in a tmux session. It reaches new windows and panes, not the
402    /// initial pane, which takes its variables from `create_session`
403    #[cfg(test)]
404    pub async fn set_env(&self, session: &str, key: &str, value: &str) -> anyhow::Result<()> {
405        self.tmux
406            .set_env(session, key, value)
407            .await
408            .map_err(|err| {
409                tmux_failed(err, || format!("tmux set-environment failed for {session}"))
410            })?;
411        tracing::debug!(session, key, "set tmux environment variable");
412        Ok(())
413    }
414
415    /// Unset (remove) an environment variable from the tmux **global** environment.
416    pub async fn unset_global_env(&self, key: &str) -> anyhow::Result<()> {
417        self.tmux.unset_global_env(key).await.map_err(|err| {
418            tmux_failed(err, || {
419                format!("tmux unset-global-environment failed for {key}")
420            })
421        })?;
422        tracing::debug!(key, "unset tmux global environment variable");
423        Ok(())
424    }
425}
426
427#[cfg(test)]
428pub(crate) fn test_session_name() -> String {
429    format!(
430        "orch-test-{}",
431        SystemTime::now()
432            .duration_since(std_time::UNIX_EPOCH)
433            .map_or_else(|_| 0, |d| d.as_millis())
434    )
435}
436
437/// RAII guard that kills a tmux session on drop, even if the test panics.
438#[cfg(test)]
439pub(crate) struct SessionGuard {
440    session: String,
441    tmux: TmuxManager,
442}
443
444#[cfg(test)]
445impl SessionGuard {
446    pub(crate) fn new(tmux: &TmuxManager, session: String) -> Self {
447        Self {
448            session,
449            tmux: tmux.clone(),
450        }
451    }
452}
453
454#[cfg(test)]
455impl Drop for SessionGuard {
456    fn drop(&mut self) {
457        let mut cmd = self.tmux.blocking_command();
458        cmd.args(["kill-session", "-t", &self.session]);
459        let _ = cmd.output();
460    }
461}
462
463#[cfg(test)]
464mod tests {
465    use std::env;
466    use std::fs;
467    use std::path::PathBuf;
468
469    use super::*;
470    use tokio::time;
471
472    /// macOS `sockaddr_un.sun_path` is 104 bytes including the NUL
473    const MAX_SOCK_PATH: usize = 103;
474
475    #[tokio::test]
476    async fn a_refused_session_reports_what_tmux_said() {
477        let tmux = TmuxManager::isolated();
478        let Ok(name) = tmux
479            .create_session("owner/repo", "dup", "/tmp", "sleep 30", &[])
480            .await
481        else {
482            eprintln!("Skipping test: tmux not available or failed to create test session");
483            return;
484        };
485        let _guard = SessionGuard::new(&tmux, name);
486
487        let err = tmux
488            .create_session("owner/repo", "dup", "/tmp", "sleep 30", &[])
489            .await
490            .expect_err("the name is taken");
491        let text = err.to_string();
492        assert!(
493            text.starts_with("tmux new-session failed: ") && text.contains("duplicate session"),
494            "the outer error text must be tmux's own: {text}"
495        );
496
497        let err = tmux
498            .unset_global_env("")
499            .await
500            .expect_err("an empty variable name is refused");
501        assert!(
502            err.to_string()
503                .starts_with("tmux unset-global-environment failed for : "),
504            "{err}"
505        );
506    }
507
508    /// The socket of an isolated manager, read from the `-S` argument of its commands
509    fn socket_of(tmux: &TmuxManager) -> PathBuf {
510        let cmd = tmux.blocking_command();
511        let args: Vec<_> = cmd.get_args().collect();
512        assert_eq!(args[0], "-S", "an isolated manager names its socket");
513        PathBuf::from(args[1])
514    }
515
516    #[test]
517    fn session_name_internal_task_id_is_sanitized() {
518        let tmux = TmuxManager::new();
519        let name = tmux.session_name("owner/repo", "internal:8");
520        assert!(!name.contains(':'), "colon must be sanitized for tmux");
521        assert_eq!(
522            tmux.parse_session_name(&name),
523            Some(("repo".to_string(), "internal-8".to_string()))
524        );
525    }
526
527    #[test]
528    fn task_id_from_session_name_parses_external_task() {
529        let tmux = TmuxManager::new();
530        let name = tmux.session_name("owner/repo", "1234");
531        assert_eq!(
532            tmux.parse_session_name(&name),
533            Some(("repo".to_string(), "1234".to_string()))
534        );
535    }
536
537    #[test]
538    fn task_id_from_session_name_parses_internal_task() {
539        let tmux = TmuxManager::new();
540        let name = tmux.session_name("owner/orch", "internal:21116");
541        assert_eq!(
542            tmux.parse_session_name(&name),
543            Some(("orch".to_string(), "internal-21116".to_string()))
544        );
545    }
546
547    #[test]
548    fn task_id_from_session_name_parses_internal_task_small_id() {
549        let tmux = TmuxManager::new();
550        let name = tmux.session_name("owner/repo", "internal:8");
551        assert_eq!(
552            tmux.parse_session_name(&name),
553            Some(("repo".to_string(), "internal-8".to_string()))
554        );
555    }
556
557    #[test]
558    fn task_id_from_session_name_returns_none_for_non_orch_session() {
559        let tmux = TmuxManager::new();
560        assert_eq!(tmux.parse_session_name("some-other-session"), None);
561    }
562
563    #[test]
564    fn parse_session_name_ignores_production_prefix_in_tests() {
565        let tmux = TmuxManager::new();
566        assert_eq!(tmux.parse_session_name("orch-repo-1234"), None);
567    }
568
569    #[test]
570    fn parse_session_name_hyphenated_project_external() {
571        let tmux = TmuxManager::new();
572        let name = tmux.session_name("owner/my-repo", "1234");
573        assert_eq!(
574            tmux.parse_session_name(&name),
575            Some(("my-repo".to_string(), "1234".to_string()))
576        );
577    }
578
579    #[test]
580    fn parse_session_name_hyphenated_project_internal() {
581        let tmux = TmuxManager::new();
582        let name = tmux.session_name("owner/my-repo", "internal:8");
583        assert_eq!(
584            tmux.parse_session_name(&name),
585            Some(("my-repo".to_string(), "internal-8".to_string()))
586        );
587    }
588
589    #[test]
590    fn parse_session_name_hyphenated_project_review() {
591        let tmux = TmuxManager::new();
592        let name = tmux.session_name("owner/my-repo", "1234-review");
593        assert_eq!(
594            tmux.parse_session_name(&name),
595            Some(("my-repo".to_string(), "1234-review".to_string()))
596        );
597    }
598
599    #[test]
600    fn parse_session_name_multi_hyphen_project() {
601        let tmux = TmuxManager::new();
602        let name = tmux.session_name("owner/my-cool-repo", "42");
603        assert_eq!(
604            tmux.parse_session_name(&name),
605            Some(("my-cool-repo".to_string(), "42".to_string()))
606        );
607    }
608
609    #[test]
610    fn parse_session_name_roundtrip_hyphenated_project() {
611        let tmux = TmuxManager::new();
612        let name = tmux.session_name("owner/my-repo", "1793");
613        assert!(name.ends_with("my-repo-1793"));
614        assert_eq!(
615            tmux.parse_session_name(&name),
616            Some(("my-repo".to_string(), "1793".to_string()))
617        );
618    }
619
620    /// Verify set_env runs the correct tmux set-environment command.
621    /// This test creates a temporary session, sets an env var, and verifies it was set.
622    #[tokio::test]
623    async fn test_set_env() {
624        let tmux = TmuxManager::new();
625        let session = test_session_name();
626
627        // Create a temporary detached session for testing
628        let create_result = tmux
629            .command()
630            .args(["new-session", "-d", "-s", &session, "-c", "/tmp"])
631            .output()
632            .await;
633
634        // Skip test if tmux is not available or fails to create test session.
635        match create_result {
636            Ok(o) if o.status.success() => {}
637            _ => {
638                eprintln!("Skipping test: tmux not available or failed to create test session");
639                return;
640            }
641        }
642        let _guard = SessionGuard::new(&tmux, session.clone());
643
644        // Use our helper to set an environment variable
645        let result = tmux.set_env(&session, "TEST_VAR", "test_value").await;
646        assert!(result.is_ok(), "set_env should succeed");
647
648        // Verify the variable was set by reading it back
649        let check_result = tmux
650            .command()
651            .args(["show-environment", "-t", &session, "TEST_VAR"])
652            .output()
653            .await;
654
655        let Ok(output) = check_result else {
656            eprintln!("Skipping test: unable to check tmux environment");
657            return;
658        };
659        let stdout = String::from_utf8_lossy(&output.stdout);
660        assert!(
661            stdout.contains("TEST_VAR=test_value"),
662            "Expected TEST_VAR=test_value, got: {stdout}"
663        );
664    }
665
666    #[tokio::test]
667    async fn session_blocks_dispatch_keeps_live_session() {
668        let tmux = TmuxManager::new();
669        let session = test_session_name();
670
671        let create_result = tmux
672            .command()
673            .args(["new-session", "-d", "-s", &session, "-c", "/tmp"])
674            .output()
675            .await;
676
677        match create_result {
678            Ok(o) if o.status.success() => {}
679            _ => {
680                eprintln!("Skipping test: tmux not available or failed to create test session");
681                return;
682            }
683        }
684        let _guard = SessionGuard::new(&tmux, session.clone());
685
686        assert!(tmux.session_blocks_dispatch(&session, None).await);
687        assert!(tmux.session_exists(&session).await);
688    }
689
690    #[tokio::test]
691    async fn session_blocks_dispatch_cleans_dead_session() {
692        let tmux = TmuxManager::new();
693        let session = test_session_name();
694
695        let create_result = tmux
696            .command()
697            .args(["new-session", "-d", "-s", &session, "-c", "/tmp"])
698            .output()
699            .await;
700
701        match create_result {
702            Ok(o) if o.status.success() => {}
703            _ => {
704                eprintln!("Skipping test: tmux not available or failed to create test session");
705                return;
706            }
707        }
708        let _guard = SessionGuard::new(&tmux, session.clone());
709
710        let set_option_result = tmux
711            .command()
712            .args(["set-option", "-t", &session, "remain-on-exit", "on"])
713            .output()
714            .await;
715        if !matches!(set_option_result, Ok(ref o) if o.status.success()) {
716            eprintln!("Skipping test: unable to set tmux remain-on-exit option");
717            return;
718        }
719
720        // respawn-pane -k runs `false` in place of the shell so the pane dies without
721        // waiting for an interactive prompt, which a cold `tmux -S` server may not have yet
722        let respawn_result = tmux
723            .command()
724            .args(["respawn-pane", "-k", "-t", &session, "false"])
725            .output()
726            .await;
727        if !matches!(respawn_result, Ok(ref o) if o.status.success()) {
728            eprintln!("Skipping test: unable to exit tmux pane");
729            return;
730        }
731
732        // Poll until pane is dead (up to 2s), fixed sleep is unreliable under load
733        for _ in 0..20 {
734            time::sleep(Duration::from_millis(100)).await;
735            if !tmux.session_is_running(&session).await {
736                break;
737            }
738        }
739
740        assert!(tmux.session_exists(&session).await);
741        assert!(!tmux.session_is_running(&session).await);
742        assert!(!tmux.session_blocks_dispatch(&session, None).await);
743        assert!(!tmux.session_exists(&session).await);
744    }
745
746    /// Regression test: capture_pane returns empty string (not an error) when the
747    /// session/pane is already gone — this is an expected teardown race, not an error.
748    /// https://github.com/gabrielkoerich/orch/issues/2083
749    #[tokio::test]
750    async fn capture_pane_returns_empty_for_gone_session() {
751        let tmux = TmuxManager::new();
752        // Call capture_pane on a session that never existed — should return Ok(""), not an error.
753        let result = tmux
754            .capture_pane("orch-nonexistent-session-99999", 100)
755            .await;
756        assert!(
757            result.is_ok(),
758            "capture_pane should return Ok for non-existent session, got: {result:?}"
759        );
760        assert_eq!(
761            result.unwrap(),
762            "",
763            "capture_pane should return empty string for non-existent session"
764        );
765    }
766
767    /// Regression test: wait_for_completion returns empty string (not an error) when
768    /// the session is already gone.
769    /// https://github.com/gabrielkoerich/orch/issues/2083
770    #[tokio::test]
771    async fn wait_for_completion_returns_empty_for_gone_session() {
772        let tmux = TmuxManager::new();
773        // Call wait_for_completion on a session that never existed — should return Ok(""), not an error.
774        let result = tmux
775            .wait_for_completion("orch-nonexistent-session-99999", Duration::from_millis(50))
776            .await;
777        assert!(
778            result.is_ok(),
779            "wait_for_completion should return Ok for non-existent session, got: {result:?}"
780        );
781        assert_eq!(
782            result.unwrap(),
783            "",
784            "wait_for_completion should return empty string for non-existent session"
785        );
786    }
787
788    /// A test TmuxManager must create sessions on `tmux -S <temp>/tmux.sock`, never on
789    /// the operator's default server. The suite runs on the same machine as live agents.
790    #[tokio::test]
791    async fn test_manager_does_not_touch_the_default_server() {
792        let tmux = TmuxManager::new();
793        let Ok(name) = tmux
794            .create_session("owner/repo", "isolation", "/tmp", "sleep 30", &[])
795            .await
796        else {
797            eprintln!("Skipping test: tmux not available or failed to create test session");
798            return;
799        };
800        let _guard = SessionGuard::new(&tmux, name.clone());
801
802        assert!(
803            tmux.session_exists(&name).await,
804            "session must exist on the isolated test server"
805        );
806
807        let on_default = Command::new("tmux")
808            .args(["has-session", "-t", &name])
809            .output()
810            .await
811            .is_ok_and(|o| o.status.success());
812        assert!(
813            !on_default,
814            "TmuxManager under cfg(test) must not create sessions on the default tmux server"
815        );
816    }
817
818    #[test]
819    fn isolated_socket_lives_in_a_temp_dir() {
820        let tmux = TmuxManager::isolated();
821        let socket = socket_of(&tmux);
822        let dir = socket.parent().expect("socket dir");
823        assert!(
824            socket.ends_with("tmux.sock"),
825            "socket path: {}",
826            socket.display()
827        );
828        assert!(
829            dir.starts_with(env::temp_dir()) || dir.starts_with("/tmp"),
830            "dir {} must be under {} or /tmp",
831            dir.display(),
832            env::temp_dir().display()
833        );
834        assert!(
835            dir.is_dir(),
836            "socket dir must exist while the manager is alive"
837        );
838        let len = socket.to_string_lossy().len();
839        assert!(
840            len < MAX_SOCK_PATH,
841            "unix socket path must fit sockaddr_un, got {len} bytes: {}",
842            socket.display()
843        );
844    }
845
846    #[tokio::test]
847    async fn isolated_manager_kills_server_and_removes_socket_dir_on_drop() {
848        let tmux = TmuxManager::isolated();
849        let socket = socket_of(&tmux);
850        let dir = socket.parent().expect("socket dir").to_path_buf();
851        let socket = socket.to_string_lossy().into_owned();
852
853        let Ok(name) = tmux
854            .create_session("owner/repo", "drop-server", "/tmp", "sleep 30", &[])
855            .await
856        else {
857            eprintln!("Skipping test: tmux not available or failed to create test session");
858            return;
859        };
860        assert!(
861            tmux.session_exists(&name).await,
862            "session must exist before drop"
863        );
864        assert!(
865            dir.is_dir(),
866            "socket dir must exist while the manager is alive"
867        );
868
869        drop(tmux);
870
871        let list = process::Command::new("tmux")
872            .args(["-S", &socket, "-f", "/dev/null", "list-sessions"])
873            .output()
874            .expect("list-sessions after drop");
875        assert!(
876            !list.status.success(),
877            "kill-server on drop must leave no server, stderr: {}",
878            String::from_utf8_lossy(&list.stderr)
879        );
880        assert!(!dir.exists(), "socket dir must be removed on drop");
881    }
882
883    #[tokio::test]
884    async fn isolated_server_does_not_load_user_tmux_conf() {
885        let home = tempfile::tempdir().expect("temp home");
886        fs::write(
887            home.path().join(".tmux.conf"),
888            "set -g @orch_test_marker 1\nset -g exit-empty off\n",
889        )
890        .expect("write tmux.conf");
891
892        let tmux = TmuxManager::isolated();
893        let session = test_session_name();
894        let create = tmux
895            .command()
896            .env("HOME", home.path())
897            .args([
898                "new-session",
899                "-d",
900                "-s",
901                &session,
902                "-c",
903                "/tmp",
904                "sleep 30",
905            ])
906            .output()
907            .await;
908        match create {
909            Ok(o) if o.status.success() => {}
910            _ => {
911                eprintln!("Skipping test: tmux not available or failed to create test session");
912                return;
913            }
914        }
915        let _guard = SessionGuard::new(&tmux, session);
916
917        let marker = tmux
918            .command()
919            .env("HOME", home.path())
920            .args(["show-options", "-gv", "@orch_test_marker"])
921            .output()
922            .await
923            .expect("show-options marker");
924        let stdout = String::from_utf8_lossy(&marker.stdout);
925        assert!(
926            stdout.trim().is_empty(),
927            "isolated tmux must not load ~/.tmux.conf, got: {stdout}"
928        );
929
930        let exit_empty = tmux
931            .command()
932            .args(["show-options", "-gv", "exit-empty"])
933            .output()
934            .await
935            .expect("exit-empty");
936        let value = String::from_utf8_lossy(&exit_empty.stdout);
937        assert_eq!(
938            value.trim(),
939            "on",
940            "isolated tmux must keep the default exit-empty, got: {value}"
941        );
942    }
943}