Skip to main content

orch/
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::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    /// Dead tmux sessions with the same name are cleaned up eagerly so they do
302    /// not block reclaim/re-dispatch loops or cause `new-session` name collisions.
303    pub async fn session_blocks_dispatch(&self, session: &str) -> bool {
304        if !self.session_exists(session).await {
305            return false;
306        }
307
308        if self.is_session_active(session).await {
309            return true;
310        }
311
312        tracing::warn!(
313            session,
314            "found stale tmux session with dead pane; cleaning up"
315        );
316        if let Err(err) = self.kill_session(session).await {
317            tracing::debug!(session, error = %err, "failed to clean up stale tmux session");
318        }
319
320        false
321    }
322
323    /// Batch variant of `session_blocks_dispatch` that uses a pre-fetched session map.
324    ///
325    /// `session_map` is the result of `batch_session_active()`. Sessions absent from the
326    /// map do not exist (→ no block). Sessions present with `alive=true` block dispatch.
327    /// Sessions present with `alive=false` have a dead pane and are cleaned up eagerly.
328    pub async fn session_blocks_dispatch_from_map(
329        &self,
330        session: &str,
331        session_map: &HashMap<String, bool>,
332    ) -> bool {
333        match session_map.get(session).copied() {
334            None => false,      // session does not exist → no block
335            Some(true) => true, // session exists and pane is alive → block
336            Some(false) => {
337                // Session exists but pane is dead — clean up eagerly.
338                tracing::warn!(
339                    session,
340                    "found stale tmux session with dead pane; cleaning up"
341                );
342                if let Err(err) = self.kill_session(session).await {
343                    tracing::debug!(
344                        session,
345                        error = %err,
346                        "failed to clean up stale tmux session"
347                    );
348                }
349                false
350            }
351        }
352    }
353
354    /// Parse a session name into (project, task_id).
355    ///
356    /// Session names follow the format `orch-{project}-{task_id}`, where
357    /// `{project}` may contain hyphens (e.g. `my-repo`) and `{task_id}` is one of:
358    /// - numeric (external): `1234`
359    /// - internal: `internal-{n}`
360    /// - review variant: `{id}-review` or `internal-{n}-review`
361    ///
362    /// Parsing works right-to-left since task_id formats are well-defined,
363    /// avoiding ambiguity when the project name contains hyphens.
364    ///
365    /// Returns `None` if the name does not start with the orch prefix or
366    /// cannot be parsed into a valid (project, task_id) pair.
367    pub(crate) fn parse_session_name(&self, name: &str) -> Option<(String, String)> {
368        let after_prefix = name.strip_prefix(&self.prefix)?;
369
370        // Strip optional "-review" suffix, reattach to the task_id later.
371        let (base, is_review) = match after_prefix.strip_suffix("-review") {
372            Some(stripped) => (stripped, true),
373            None => (after_prefix, false),
374        };
375
376        // Try internal task: {project}-internal-{digits}
377        if let Some(idx) = base.rfind("-internal-") {
378            let project = &base[..idx];
379            let task_base = &base[idx + 1..]; // "internal-{digits}"
380            let after_internal = &task_base["internal-".len()..];
381            if !project.is_empty()
382                && !after_internal.is_empty()
383                && after_internal.chars().all(|c| c.is_ascii_digit())
384            {
385                let task_id = if is_review {
386                    format!("{task_base}-review")
387                } else {
388                    task_base.to_string()
389                };
390                return Some((project.to_string(), task_id));
391            }
392        }
393
394        // External task: {project}-{digits}
395        if let Some(idx) = base.rfind('-') {
396            let project = &base[..idx];
397            let digits = &base[idx + 1..];
398            if !project.is_empty()
399                && !digits.is_empty()
400                && digits.chars().all(|c| c.is_ascii_digit())
401            {
402                let task_id = if is_review {
403                    format!("{digits}-review")
404                } else {
405                    digits.to_string()
406                };
407                return Some((project.to_string(), task_id));
408            }
409        }
410
411        None
412    }
413
414    /// Get pane_dead status for all sessions in a single tmux call.
415    ///
416    /// Returns a map from session name → alive (true = alive, false = dead/missing).
417    /// Uses `list-panes -a` to avoid one subprocess per session.
418    pub async fn batch_session_active(&self) -> HashMap<String, bool> {
419        let mut map = HashMap::new();
420        let o = match self
421            .command()
422            .args(["list-panes", "-a", "-F", "#{session_name} #{pane_dead}"])
423            .output_with_context()
424            .await
425        {
426            Ok(o) => o,
427            Err(e) => {
428                tracing::warn!(error = %e, "batch_session_active: failed to spawn tmux");
429                return map;
430            }
431        };
432        if !o.status.success() {
433            let stderr = String::from_utf8_lossy(&o.stderr);
434            tracing::warn!(
435                status = ?o.status,
436                stderr = %stderr.trim(),
437                "batch_session_active: tmux list-panes exited non-zero"
438            );
439            return map;
440        }
441        for line in String::from_utf8_lossy(&o.stdout).lines() {
442            let mut parts = line.trim().splitn(2, ' ');
443            if let (Some(session), Some(dead)) = (parts.next(), parts.next()) {
444                map.insert(session.to_string(), dead.trim() == "0");
445            }
446        }
447        map
448    }
449
450    /// List all orch-prefixed sessions with metadata including creation time.
451    pub async fn list_sessions(&self) -> anyhow::Result<Vec<Session>> {
452        // Get both name and creation timestamp in one call
453        let output = self
454            .command()
455            .args(["list-sessions", "-F", "#{session_name} #{session_created}"])
456            .output_with_context()
457            .await?;
458
459        if !output.status.success() {
460            return Ok(vec![]);
461        }
462
463        let mut sessions = Vec::new();
464        for line in String::from_utf8_lossy(&output.stdout).lines() {
465            let parts: Vec<&str> = line.trim().splitn(2, ' ').collect();
466            if parts.is_empty() {
467                continue;
468            }
469            let name = parts[0].to_string();
470            let created_at = parts.get(1).and_then(|s| s.parse::<u64>().ok());
471
472            if let Some((project, task_id)) = self.parse_session_name(&name) {
473                sessions.push(Session {
474                    name,
475                    task_id,
476                    project,
477                    created_at,
478                });
479            }
480        }
481
482        Ok(sessions)
483    }
484
485    /// Kill all orch-prefixed sessions created before a given timestamp.
486    /// Returns the number of sessions killed.
487    pub async fn kill_stale_sessions(&self, before_timestamp: u64) -> anyhow::Result<usize> {
488        let sessions = self.list_sessions().await?;
489        let mut killed = 0;
490
491        for session in sessions {
492            let should_kill = match session.created_at {
493                Some(created) => created < before_timestamp,
494                // If we can't determine creation time, be conservative and don't kill
495                None => false,
496            };
497
498            if should_kill {
499                tracing::info!(
500                    session = %session.name,
501                    created_at = session.created_at,
502                    "killing stale tmux session from previous run"
503                );
504                match self.kill_session(&session.name).await {
505                    Err(e) => {
506                        tracing::warn!(session = %session.name, error = %e, "failed to kill stale session");
507                    }
508                    _ => {
509                        killed += 1;
510                    }
511                }
512            }
513        }
514
515        if killed > 0 {
516            tracing::info!(killed, "killed stale tmux sessions on startup");
517        }
518
519        Ok(killed)
520    }
521
522    /// Wait for multiple sessions to be fully dead (no longer exist).
523    /// Polls every `poll_interval` up to `timeout`.
524    /// Returns the number of sessions that were still alive after timeout.
525    pub async fn wait_for_sessions_dead(
526        &self,
527        sessions: &[String],
528        poll_interval: Duration,
529        timeout: Duration,
530    ) -> usize {
531        let start = Instant::now();
532        let mut remaining: HashSet<String> = sessions.iter().cloned().collect();
533
534        while !remaining.is_empty() && start.elapsed() < timeout {
535            let mut to_remove = Vec::new();
536            for session in &remaining {
537                if !self.session_exists(session).await {
538                    to_remove.push(session.clone());
539                }
540            }
541            for session in to_remove {
542                remaining.remove(&session);
543            }
544            if !remaining.is_empty() {
545                time::sleep(poll_interval).await;
546            }
547        }
548
549        let still_alive = remaining.len();
550        if still_alive > 0 {
551            tracing::warn!(
552                still_alive,
553                sessions = ?remaining.iter().collect::<Vec<_>>(),
554                "tmux sessions did not terminate within timeout"
555            );
556        }
557        still_alive
558    }
559
560    /// Wait for a session to finish (pane process exits).
561    /// Returns the captured output from the last N lines.
562    pub async fn wait_for_completion(
563        &self,
564        session: &str,
565        poll_interval: Duration,
566    ) -> anyhow::Result<String> {
567        loop {
568            if !self.session_exists(session).await {
569                return Ok(String::new());
570            }
571
572            if !self.is_session_active(session).await {
573                // Process finished — capture final output. `capture_pane` returns empty
574                // for "can't find pane/session" teardown races; only unexpected failures
575                // reach this error path and are logged at ERROR level.
576                match self.capture_pane(session, 500).await {
577                    Ok(output) => return Ok(output),
578                    Err(err) => {
579                        tracing::error!(session = %session, error = %err, "failed to capture final pane output");
580                        return Ok(String::new());
581                    }
582                }
583            }
584
585            time::sleep(poll_interval).await;
586        }
587    }
588
589    /// Snapshot all orch-prefixed sessions — for engine tick monitoring.
590    ///
591    /// Returns a vector of (Session, alive) so callers can operate on the
592    /// actual session name instead of reconstructing one from repo+task_id.
593    ///
594    /// Uses `batch_session_active()` internally to fetch all pane-dead statuses
595    /// in a single subprocess call instead of one call per session (N+1 → 2).
596    pub async fn snapshot(&self) -> Vec<(Session, bool)> {
597        let sessions = match self.list_sessions().await {
598            Ok(s) => s,
599            Err(err) => {
600                tracing::error!(error = %err, "failed to list tmux sessions — returning empty snapshot");
601                Vec::new()
602            }
603        };
604        // Fetch all pane-dead statuses in a single `list-panes -a` call.
605        let active_map = self.batch_session_active().await;
606        sessions
607            .into_iter()
608            .map(|s| {
609                // Sessions absent from the map are treated as dead (pane missing).
610                let active = active_map.get(&s.name).copied().unwrap_or(false);
611                (s, active)
612            })
613            .collect()
614    }
615
616    // ── Environment variable helpers ───────────────────────────────────
617
618    /// Set an environment variable in a tmux session.
619    ///
620    /// This updates the tmux session environment, which will be inherited
621    /// by processes started in new windows/panes within the session.
622    /// Note: does NOT affect the initial pane — use `-e` in `create_session` for that.
623    #[cfg(test)]
624    pub async fn set_env(&self, session: &str, key: &str, value: &str) -> anyhow::Result<()> {
625        let output = self
626            .command()
627            .args(["set-environment", "-t", session, key, value])
628            .output_with_context()
629            .await?;
630
631        if !output.status.success() {
632            let stderr = String::from_utf8_lossy(&output.stderr);
633            anyhow::bail!("tmux set-environment failed for {session}: {stderr}");
634        }
635
636        tracing::debug!(session, key, "set tmux environment variable");
637        Ok(())
638    }
639
640    /// Unset (remove) an environment variable from the tmux **global** environment.
641    ///
642    /// Uses: `tmux set-environment -gu <key>`
643    pub async fn unset_global_env(&self, key: &str) -> anyhow::Result<()> {
644        let output = self
645            .command()
646            .args(["set-environment", "-gu", key])
647            .output_with_context()
648            .await?;
649
650        if !output.status.success() {
651            let stderr = String::from_utf8_lossy(&output.stderr);
652            anyhow::bail!("tmux unset-global-environment failed for {key}: {stderr}");
653        }
654
655        tracing::debug!(key, "unset tmux global environment variable");
656        Ok(())
657    }
658}
659
660#[cfg(test)]
661pub(crate) fn test_session_name() -> String {
662    format!(
663        "orch-test-{}",
664        SystemTime::now()
665            .duration_since(std_time::UNIX_EPOCH)
666            .map_or_else(|_| 0, |d| d.as_millis())
667    )
668}
669
670/// RAII guard that kills a tmux session on drop, even if the test panics.
671#[cfg(test)]
672pub(crate) struct SessionGuard {
673    session: String,
674    tmux: TmuxManager,
675}
676
677#[cfg(test)]
678impl SessionGuard {
679    pub(crate) fn new(tmux: &TmuxManager, session: String) -> Self {
680        Self {
681            session,
682            tmux: tmux.clone(),
683        }
684    }
685}
686
687#[cfg(test)]
688impl Drop for SessionGuard {
689    fn drop(&mut self) {
690        let mut cmd = self.tmux.blocking_command();
691        cmd.args(["kill-session", "-t", &self.session]);
692        let _ = cmd.output();
693    }
694}
695
696#[cfg(test)]
697mod tests {
698    use super::*;
699
700    #[test]
701    fn session_name_internal_task_id_is_sanitized() {
702        let tmux = TmuxManager::new();
703        let name = tmux.session_name("owner/repo", "internal:8");
704        assert!(!name.contains(':'), "colon must be sanitized for tmux");
705        assert_eq!(
706            tmux.parse_session_name(&name),
707            Some(("repo".to_string(), "internal-8".to_string()))
708        );
709    }
710
711    #[test]
712    fn task_id_from_session_name_parses_external_task() {
713        let tmux = TmuxManager::new();
714        let name = tmux.session_name("owner/repo", "1234");
715        assert_eq!(
716            tmux.parse_session_name(&name),
717            Some(("repo".to_string(), "1234".to_string()))
718        );
719    }
720
721    #[test]
722    fn task_id_from_session_name_parses_internal_task() {
723        let tmux = TmuxManager::new();
724        let name = tmux.session_name("owner/orch", "internal:21116");
725        assert_eq!(
726            tmux.parse_session_name(&name),
727            Some(("orch".to_string(), "internal-21116".to_string()))
728        );
729    }
730
731    #[test]
732    fn task_id_from_session_name_parses_internal_task_small_id() {
733        let tmux = TmuxManager::new();
734        let name = tmux.session_name("owner/repo", "internal:8");
735        assert_eq!(
736            tmux.parse_session_name(&name),
737            Some(("repo".to_string(), "internal-8".to_string()))
738        );
739    }
740
741    #[test]
742    fn task_id_from_session_name_returns_none_for_non_orch_session() {
743        let tmux = TmuxManager::new();
744        assert_eq!(tmux.parse_session_name("some-other-session"), None);
745    }
746
747    #[test]
748    fn parse_session_name_ignores_production_prefix_in_tests() {
749        let tmux = TmuxManager::new();
750        assert_eq!(tmux.parse_session_name("orch-repo-1234"), None);
751    }
752
753    #[test]
754    fn parse_session_name_hyphenated_project_external() {
755        let tmux = TmuxManager::new();
756        let name = tmux.session_name("owner/my-repo", "1234");
757        assert_eq!(
758            tmux.parse_session_name(&name),
759            Some(("my-repo".to_string(), "1234".to_string()))
760        );
761    }
762
763    #[test]
764    fn parse_session_name_hyphenated_project_internal() {
765        let tmux = TmuxManager::new();
766        let name = tmux.session_name("owner/my-repo", "internal:8");
767        assert_eq!(
768            tmux.parse_session_name(&name),
769            Some(("my-repo".to_string(), "internal-8".to_string()))
770        );
771    }
772
773    #[test]
774    fn parse_session_name_hyphenated_project_review() {
775        let tmux = TmuxManager::new();
776        let name = tmux.session_name("owner/my-repo", "1234-review");
777        assert_eq!(
778            tmux.parse_session_name(&name),
779            Some(("my-repo".to_string(), "1234-review".to_string()))
780        );
781    }
782
783    #[test]
784    fn parse_session_name_multi_hyphen_project() {
785        let tmux = TmuxManager::new();
786        let name = tmux.session_name("owner/my-cool-repo", "42");
787        assert_eq!(
788            tmux.parse_session_name(&name),
789            Some(("my-cool-repo".to_string(), "42".to_string()))
790        );
791    }
792
793    #[test]
794    fn parse_session_name_roundtrip_hyphenated_project() {
795        let tmux = TmuxManager::new();
796        let name = tmux.session_name("owner/my-repo", "1793");
797        assert!(name.ends_with("my-repo-1793"));
798        assert_eq!(
799            tmux.parse_session_name(&name),
800            Some(("my-repo".to_string(), "1793".to_string()))
801        );
802    }
803
804    /// Verify set_env runs the correct tmux set-environment command.
805    /// This test creates a temporary session, sets an env var, and verifies it was set.
806    #[tokio::test]
807    async fn test_set_env() {
808        let tmux = TmuxManager::new();
809        let session = test_session_name();
810
811        // Create a temporary detached session for testing
812        let create_result = tmux
813            .command()
814            .args(["new-session", "-d", "-s", &session, "-c", "/tmp"])
815            .output()
816            .await;
817
818        // Skip test if tmux is not available or fails to create test session.
819        match create_result {
820            Ok(o) if o.status.success() => {}
821            _ => {
822                eprintln!("Skipping test: tmux not available or failed to create test session");
823                return;
824            }
825        }
826        let _guard = SessionGuard::new(&tmux, session.clone());
827
828        // Use our helper to set an environment variable
829        let result = tmux.set_env(&session, "TEST_VAR", "test_value").await;
830        assert!(result.is_ok(), "set_env should succeed");
831
832        // Verify the variable was set by reading it back
833        let check_result = tmux
834            .command()
835            .args(["show-environment", "-t", &session, "TEST_VAR"])
836            .output()
837            .await;
838
839        let Ok(output) = check_result else {
840            eprintln!("Skipping test: unable to check tmux environment");
841            return;
842        };
843        let stdout = String::from_utf8_lossy(&output.stdout);
844        assert!(
845            stdout.contains("TEST_VAR=test_value"),
846            "Expected TEST_VAR=test_value, got: {stdout}"
847        );
848    }
849
850    #[tokio::test]
851    async fn session_blocks_dispatch_keeps_live_session() {
852        let tmux = TmuxManager::new();
853        let session = test_session_name();
854
855        let create_result = tmux
856            .command()
857            .args(["new-session", "-d", "-s", &session, "-c", "/tmp"])
858            .output()
859            .await;
860
861        match create_result {
862            Ok(o) if o.status.success() => {}
863            _ => {
864                eprintln!("Skipping test: tmux not available or failed to create test session");
865                return;
866            }
867        }
868        let _guard = SessionGuard::new(&tmux, session.clone());
869
870        assert!(tmux.session_blocks_dispatch(&session).await);
871        assert!(tmux.session_exists(&session).await);
872    }
873
874    #[tokio::test]
875    async fn session_blocks_dispatch_cleans_dead_session() {
876        let tmux = TmuxManager::new();
877        let session = test_session_name();
878
879        let create_result = tmux
880            .command()
881            .args(["new-session", "-d", "-s", &session, "-c", "/tmp"])
882            .output()
883            .await;
884
885        match create_result {
886            Ok(o) if o.status.success() => {}
887            _ => {
888                eprintln!("Skipping test: tmux not available or failed to create test session");
889                return;
890            }
891        }
892        let _guard = SessionGuard::new(&tmux, session.clone());
893
894        let set_option_result = tmux
895            .command()
896            .args(["set-option", "-t", &session, "remain-on-exit", "on"])
897            .output()
898            .await;
899        if !matches!(set_option_result, Ok(ref o) if o.status.success()) {
900            eprintln!("Skipping test: unable to set tmux remain-on-exit option");
901            return;
902        }
903
904        // respawn-pane -k runs `false` in place of the shell so the pane dies without
905        // waiting for an interactive prompt, which a cold `tmux -S` server may not have yet
906        let respawn_result = tmux
907            .command()
908            .args(["respawn-pane", "-k", "-t", &session, "false"])
909            .output()
910            .await;
911        if !matches!(respawn_result, Ok(ref o) if o.status.success()) {
912            eprintln!("Skipping test: unable to exit tmux pane");
913            return;
914        }
915
916        // Poll until pane is dead (up to 2s), fixed sleep is unreliable under load
917        for _ in 0..20 {
918            time::sleep(Duration::from_millis(100)).await;
919            if !tmux.session_is_running(&session).await {
920                break;
921            }
922        }
923
924        assert!(tmux.session_exists(&session).await);
925        assert!(!tmux.session_is_running(&session).await);
926        assert!(!tmux.session_blocks_dispatch(&session).await);
927        assert!(!tmux.session_exists(&session).await);
928    }
929
930    /// Regression test: capture_pane returns empty string (not an error) when the
931    /// session/pane is already gone — this is an expected teardown race, not an error.
932    /// https://github.com/gabrielkoerich/orch/issues/2083
933    #[tokio::test]
934    async fn capture_pane_returns_empty_for_gone_session() {
935        let tmux = TmuxManager::new();
936        // Call capture_pane on a session that never existed — should return Ok(""), not an error.
937        let result = tmux
938            .capture_pane("orch-nonexistent-session-99999", 100)
939            .await;
940        assert!(
941            result.is_ok(),
942            "capture_pane should return Ok for non-existent session, got: {result:?}"
943        );
944        assert_eq!(
945            result.unwrap(),
946            "",
947            "capture_pane should return empty string for non-existent session"
948        );
949    }
950
951    /// Regression test: wait_for_completion returns empty string (not an error) when
952    /// the session is already gone.
953    /// https://github.com/gabrielkoerich/orch/issues/2083
954    #[tokio::test]
955    async fn wait_for_completion_returns_empty_for_gone_session() {
956        let tmux = TmuxManager::new();
957        // Call wait_for_completion on a session that never existed — should return Ok(""), not an error.
958        let result = tmux
959            .wait_for_completion("orch-nonexistent-session-99999", Duration::from_millis(50))
960            .await;
961        assert!(
962            result.is_ok(),
963            "wait_for_completion should return Ok for non-existent session, got: {result:?}"
964        );
965        assert_eq!(
966            result.unwrap(),
967            "",
968            "wait_for_completion should return empty string for non-existent session"
969        );
970    }
971
972    /// A test TmuxManager must create sessions on `tmux -S <temp>/tmux.sock`, never on
973    /// the operator's default server. The suite runs on the same machine as live agents.
974    #[tokio::test]
975    async fn test_manager_does_not_touch_the_default_server() {
976        let tmux = TmuxManager::new();
977        let Ok(name) = tmux
978            .create_session("owner/repo", "isolation", "/tmp", "sleep 30", &[])
979            .await
980        else {
981            eprintln!("Skipping test: tmux not available or failed to create test session");
982            return;
983        };
984        let _guard = SessionGuard::new(&tmux, name.clone());
985
986        assert!(
987            tmux.session_exists(&name).await,
988            "session must exist on the isolated test server"
989        );
990
991        let on_default = Command::new("tmux")
992            .args(["has-session", "-t", &name])
993            .output()
994            .await
995            .is_ok_and(|o| o.status.success());
996        assert!(
997            !on_default,
998            "TmuxManager under cfg(test) must not create sessions on the default tmux server"
999        );
1000    }
1001
1002    #[test]
1003    fn isolated_socket_lives_in_a_temp_dir() {
1004        let tmux = TmuxManager::isolated();
1005        let isolated = tmux.isolated.as_ref().expect("isolated server");
1006        assert!(
1007            isolated.socket.ends_with("/tmux.sock"),
1008            "socket path: {}",
1009            isolated.socket
1010        );
1011        assert!(
1012            isolated.dir.starts_with(env::temp_dir()) || isolated.dir.starts_with("/tmp"),
1013            "dir {} must be under {} or /tmp",
1014            isolated.dir.display(),
1015            env::temp_dir().display()
1016        );
1017        assert!(
1018            isolated.dir.is_dir(),
1019            "socket dir must exist while the manager is alive"
1020        );
1021        assert!(
1022            isolated.socket.len() < MAX_SOCK_PATH,
1023            "unix socket path must fit sockaddr_un, got {} bytes: {}",
1024            isolated.socket.len(),
1025            isolated.socket
1026        );
1027    }
1028
1029    #[tokio::test]
1030    async fn isolated_manager_kills_server_and_removes_socket_dir_on_drop() {
1031        let tmux = TmuxManager::isolated();
1032        let (socket, dir) = {
1033            let isolated = tmux.isolated.as_ref().expect("isolated server");
1034            (isolated.socket.clone(), isolated.dir.clone())
1035        };
1036
1037        let Ok(name) = tmux
1038            .create_session("owner/repo", "drop-server", "/tmp", "sleep 30", &[])
1039            .await
1040        else {
1041            eprintln!("Skipping test: tmux not available or failed to create test session");
1042            return;
1043        };
1044        assert!(
1045            tmux.session_exists(&name).await,
1046            "session must exist before drop"
1047        );
1048        assert!(
1049            dir.is_dir(),
1050            "socket dir must exist while the manager is alive"
1051        );
1052
1053        drop(tmux);
1054
1055        let list = process::Command::new("tmux")
1056            .args(["-S", &socket, "-f", "/dev/null", "list-sessions"])
1057            .output()
1058            .expect("list-sessions after drop");
1059        assert!(
1060            !list.status.success(),
1061            "kill-server on drop must leave no server, stderr: {}",
1062            String::from_utf8_lossy(&list.stderr)
1063        );
1064        assert!(!dir.exists(), "socket dir must be removed on drop");
1065    }
1066
1067    #[tokio::test]
1068    async fn isolated_server_does_not_load_user_tmux_conf() {
1069        let home = tempfile::tempdir().expect("temp home");
1070        fs::write(
1071            home.path().join(".tmux.conf"),
1072            "set -g @orch_test_marker 1\nset -g exit-empty off\n",
1073        )
1074        .expect("write tmux.conf");
1075
1076        let tmux = TmuxManager::isolated();
1077        let session = test_session_name();
1078        let create = tmux
1079            .command()
1080            .env("HOME", home.path())
1081            .args([
1082                "new-session",
1083                "-d",
1084                "-s",
1085                &session,
1086                "-c",
1087                "/tmp",
1088                "sleep 30",
1089            ])
1090            .output()
1091            .await;
1092        match create {
1093            Ok(o) if o.status.success() => {}
1094            _ => {
1095                eprintln!("Skipping test: tmux not available or failed to create test session");
1096                return;
1097            }
1098        }
1099        let _guard = SessionGuard::new(&tmux, session);
1100
1101        let marker = tmux
1102            .command()
1103            .env("HOME", home.path())
1104            .args(["show-options", "-gv", "@orch_test_marker"])
1105            .output()
1106            .await
1107            .expect("show-options marker");
1108        let stdout = String::from_utf8_lossy(&marker.stdout);
1109        assert!(
1110            stdout.trim().is_empty(),
1111            "isolated tmux must not load ~/.tmux.conf, got: {stdout}"
1112        );
1113
1114        let exit_empty = tmux
1115            .command()
1116            .args(["show-options", "-gv", "exit-empty"])
1117            .output()
1118            .await
1119            .expect("exit-empty");
1120        let value = String::from_utf8_lossy(&exit_empty.stdout);
1121        assert_eq!(
1122            value.trim(),
1123            "on",
1124            "isolated tmux must keep the default exit-empty, got: {value}"
1125        );
1126    }
1127}