use super::{Channel, IncomingMessage, OutgoingMessage};
use crate::channels::transport::Transport;
use crate::sys::cmd::CommandErrorContext;
use crate::sys::tmux;
use async_trait::async_trait;
use std::fmt;
use std::fmt::Debug;
use std::fmt::Formatter;
use std::sync::Arc;
use tokio::sync::mpsc;
use tokio::sync::mpsc::Receiver;
pub struct TmuxChannel {
transport: Option<Arc<Transport>>,
}
impl Debug for TmuxChannel {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("TmuxChannel")
.field("has_transport", &self.transport.is_some())
.finish()
}
}
impl TmuxChannel {
pub fn with_transport(transport: Arc<Transport>) -> Self {
Self {
transport: Some(transport),
}
}
}
#[async_trait]
impl Channel for TmuxChannel {
fn name(&self) -> &'static str {
"tmux"
}
async fn start(&self) -> anyhow::Result<Receiver<IncomingMessage>> {
let (_tx, rx) = mpsc::channel(64);
tracing::info!("tmux channel started");
if self.transport.is_none() {
tracing::warn!("tmux channel started without transport - output streaming disabled");
}
Ok(rx)
}
async fn send(&self, msg: &OutgoingMessage) -> anyhow::Result<()> {
let session = &msg.thread_id; send_keys(session, &msg.body).await
}
async fn health_check(&self) -> anyhow::Result<()> {
let output = tmux::default_server()
.command()
.args(["list-sessions"])
.output_with_context()
.await?;
if !output.status.success() {
anyhow::bail!("tmux server not running");
}
Ok(())
}
}
pub async fn send_keys(session: &str, text: &str) -> anyhow::Result<()> {
Ok(tmux::default_server().send_keys(session, text).await?)
}
pub async fn capture_pane(session: &str) -> anyhow::Result<String> {
let output = tmux::default_server()
.command()
.args(["capture-pane", "-t", session, "-p", "-S", "-"])
.output_with_context()
.await?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("tmux capture-pane failed: {stderr}");
}
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
pub async fn list_orch_sessions() -> anyhow::Result<Vec<String>> {
let sessions = tmux::default_server().list().await?;
Ok(sessions.into_iter().map(|session| session.name).collect())
}
pub async fn is_session_dead(session: &str) -> bool {
!tmux::default_server().exists(session).await
}