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