Skip to main content

orch/sys/
tmux.rs

1//! tmux session manager — create, monitor, and interact with agent sessions.
2//!
3//! Each task gets a tmux session named `orch-{issue_number}`.
4//! The engine creates sessions, monitors them, captures output for streaming,
5//! and cleans them up when tasks complete.
6//!
7//! This module is the foundation for live session streaming to any channel.
8
9use 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/// Info about an active orch tmux session.
33#[derive(Debug, Clone)]
34pub struct Session {
35    pub name: String,
36    /// The task id (preserving internal/external marker), e.g. "internal-21116" or "1775189963034"
37    pub task_id: String,
38    /// Project short name derived from repo slug (owner/repo -> repo)
39    pub project: String,
40    pub created_at: Option<u64>, // Unix timestamp from tmux #{session_created}
41}
42
43/// macOS `sockaddr_un.sun_path` is 104 bytes including the NUL
44const MAX_SOCK_PATH: usize = 103;
45
46static ISOLATED_SEQ: AtomicU64 = AtomicU64::new(0);
47
48/// Test tmux server: socket in a temp dir, empty config, killed when the last clone drops
49#[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        // kill-session leaves the server up when a config sets exit-empty off
81        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/// Manage tmux sessions for agent tasks.
89#[derive(Clone, Debug)]
90pub struct TmuxManager {
91    /// Prefix for session names (e.g. "orch-")
92    prefix: String,
93    /// Test-only server. None talks to the default tmux server
94    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    /// A tmux server of its own with its own prefix, for tests. `cfg(test)` is unset when
110    /// tests/*.rs link the library, so those tests call this directly. The socket lives in a
111    /// temp dir, `-f /dev/null` skips the user's config, and Drop kills the server
112    pub fn isolated() -> Self {
113        Self {
114            prefix: "orch-test-".to_string(),
115            isolated: Some(Arc::new(IsolatedServer::new())),
116        }
117    }
118
119    /// Build a `tmux` command scoped to this manager's server
120    pub(crate) fn command(&self) -> Command {
121        let mut cmd = Command::new("tmux");
122        cmd.args(self.server_args());
123        cmd
124    }
125
126    /// A blocking `tmux` command scoped to this manager's server, for `Drop`
127    #[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    /// Session name for a task: `orch-{project}-{task_id}`.
141    ///
142    /// The project name is derived from the repo slug (e.g. `owner/repo` → `repo`).
143    /// This prevents collisions between projects with the same issue number.
144    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    /// Create a new tmux session for a task and run a command in it.
155    ///
156    /// Environment variables in `env_vars` are injected into the session via
157    /// `tmux new-session -e KEY=VALUE` — they are not written to disk.
158    ///
159    /// The session is detached — the agent runs in the background.
160    /// Returns the session name.
161    ///
162    /// Note: GH_TOKEN is passed here via `-e` like all other env vars. Do NOT
163    /// use `create_session_detached` + `set_env` + `create_window` to avoid
164    /// exposing secrets in process args — that creates a 2-window session which
165    /// breaks all tmux monitoring (completion detection, output capture, silence
166    /// detection) because they target the default window (the idle shell), not
167    /// the agent window. See the revert of PR #2903.
168    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        // Suppress oh-my-zsh update prompts that can intercept agent input.
182        cmd.arg("-e").arg("DISABLE_AUTO_UPDATE=true");
183
184        // Inject non-secret environment variables into the new session if provided.
185        // For secrets like GH_TOKEN, callers should use `set_env()` after
186        // session creation to avoid exposing them in process arguments.
187        for (key, value) in env_vars {
188            // tmux accepts -e KEY=VALUE to inject environment into the session.
189            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    /// Check if a session exists.
209    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    /// Kill a session.
218    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    /// Capture the current pane content (last N lines).
240    ///
241    /// Returns `Ok(String::new())` if the session or pane is not found — this is
242    /// an expected teardown race when the session was cleaned up between the caller's
243    /// `is_session_active()` check and this capture.
244    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            // "can't find pane" / "can't find session" / "no server running" are expected
255            // teardown races — the session was cleaned up between the caller's activity
256            // check and this call, or the tmux server exited entirely.
257            // "error connecting to" is the same race on a `tmux -S` socket that was never started
258            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    /// Check if the process in a session's pane is still running.
275    /// Returns false if the session doesn't exist or the pane has no active process.
276    pub async fn is_session_active(&self, session: &str) -> bool {
277        // Check pane_dead flag
278        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" // 0 = alive, 1 = dead
288            }
289            _ => false,
290        }
291    }
292
293    /// Check whether a session exists and still has a live pane process.
294    #[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    /// Return whether a session should block a new dispatch.
300    ///
301    /// `known` is a session map from `batch_session_active()`, or `None` to ask tmux. A missing
302    /// session does not block and a live pane does. A dead pane is cleaned up eagerly, so it does
303    /// not block reclaim/re-dispatch loops or cause `new-session` name collisions
304    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    /// Parse a session name into (project, task_id).
331    ///
332    /// Session names follow the format `orch-{project}-{task_id}`, where
333    /// `{project}` may contain hyphens (e.g. `my-repo`) and `{task_id}` is one of:
334    /// - numeric (external): `1234`
335    /// - internal: `internal-{n}`
336    /// - review variant: `{id}-review` or `internal-{n}-review`
337    ///
338    /// Parsing works right-to-left since task_id formats are well-defined,
339    /// avoiding ambiguity when the project name contains hyphens.
340    ///
341    /// Returns `None` if the name does not start with the orch prefix or
342    /// cannot be parsed into a valid (project, task_id) pair.
343    pub(crate) fn parse_session_name(&self, name: &str) -> Option<(String, String)> {
344        let after_prefix = name.strip_prefix(&self.prefix)?;
345
346        // Strip optional "-review" suffix, reattach to the task_id later.
347        let (base, is_review) = match after_prefix.strip_suffix("-review") {
348            Some(stripped) => (stripped, true),
349            None => (after_prefix, false),
350        };
351
352        // Try internal task: {project}-internal-{digits}
353        if let Some(idx) = base.rfind("-internal-") {
354            let project = &base[..idx];
355            let task_base = &base[idx + 1..]; // "internal-{digits}"
356            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        // External task: {project}-{digits}
371        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    /// Get pane_dead status for all sessions in a single tmux call.
391    ///
392    /// Returns a map from session name → alive (true = alive, false = dead/missing).
393    /// Uses `list-panes -a` to avoid one subprocess per session.
394    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    /// List all orch-prefixed sessions with metadata including creation time.
427    pub async fn list_sessions(&self) -> anyhow::Result<Vec<Session>> {
428        // Get both name and creation timestamp in one call
429        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    /// Kill all orch-prefixed sessions created before a given timestamp.
462    /// Returns the number of sessions killed.
463    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                // If we can't determine creation time, be conservative and don't kill
471                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    /// Wait for multiple sessions to be fully dead (no longer exist).
499    /// Polls every `poll_interval` up to `timeout`.
500    /// Returns the number of sessions that were still alive after timeout.
501    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    /// Wait for a session to finish (pane process exits).
537    /// Returns the captured output from the last N lines.
538    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                // Process finished — capture final output. `capture_pane` returns empty
550                // for "can't find pane/session" teardown races; only unexpected failures
551                // reach this error path and are logged at ERROR level.
552                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    /// Snapshot all orch-prefixed sessions — for engine tick monitoring.
566    ///
567    /// Returns a vector of (Session, alive) so callers can operate on the
568    /// actual session name instead of reconstructing one from repo+task_id.
569    ///
570    /// Uses `batch_session_active()` internally to fetch all pane-dead statuses
571    /// in a single subprocess call instead of one call per session (N+1 → 2).
572    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        // Fetch all pane-dead statuses in a single `list-panes -a` call.
581        let active_map = self.batch_session_active().await;
582        sessions
583            .into_iter()
584            .map(|s| {
585                // Sessions absent from the map are treated as dead (pane missing).
586                let active = active_map.get(&s.name).copied().unwrap_or(false);
587                (s, active)
588            })
589            .collect()
590    }
591
592    // ── Environment variable helpers ───────────────────────────────────
593
594    /// Set an environment variable in a tmux session.
595    ///
596    /// This updates the tmux session environment, which will be inherited
597    /// by processes started in new windows/panes within the session.
598    /// Note: does NOT affect the initial pane — use `-e` in `create_session` for that.
599    #[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    /// Unset (remove) an environment variable from the tmux **global** environment.
617    ///
618    /// Uses: `tmux set-environment -gu <key>`
619    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/// RAII guard that kills a tmux session on drop, even if the test panics.
647#[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    /// Verify set_env runs the correct tmux set-environment command.
781    /// This test creates a temporary session, sets an env var, and verifies it was set.
782    #[tokio::test]
783    async fn test_set_env() {
784        let tmux = TmuxManager::new();
785        let session = test_session_name();
786
787        // Create a temporary detached session for testing
788        let create_result = tmux
789            .command()
790            .args(["new-session", "-d", "-s", &session, "-c", "/tmp"])
791            .output()
792            .await;
793
794        // Skip test if tmux is not available or fails to create test session.
795        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        // Use our helper to set an environment variable
805        let result = tmux.set_env(&session, "TEST_VAR", "test_value").await;
806        assert!(result.is_ok(), "set_env should succeed");
807
808        // Verify the variable was set by reading it back
809        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        // respawn-pane -k runs `false` in place of the shell so the pane dies without
881        // waiting for an interactive prompt, which a cold `tmux -S` server may not have yet
882        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        // Poll until pane is dead (up to 2s), fixed sleep is unreliable under load
893        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    /// Regression test: capture_pane returns empty string (not an error) when the
907    /// session/pane is already gone — this is an expected teardown race, not an error.
908    /// https://github.com/gabrielkoerich/orch/issues/2083
909    #[tokio::test]
910    async fn capture_pane_returns_empty_for_gone_session() {
911        let tmux = TmuxManager::new();
912        // Call capture_pane on a session that never existed — should return Ok(""), not an error.
913        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    /// Regression test: wait_for_completion returns empty string (not an error) when
928    /// the session is already gone.
929    /// https://github.com/gabrielkoerich/orch/issues/2083
930    #[tokio::test]
931    async fn wait_for_completion_returns_empty_for_gone_session() {
932        let tmux = TmuxManager::new();
933        // Call wait_for_completion on a session that never existed — should return Ok(""), not an error.
934        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    /// A test TmuxManager must create sessions on `tmux -S <temp>/tmux.sock`, never on
949    /// the operator's default server. The suite runs on the same machine as live agents.
950    #[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}