use trusty_mpm_core::external_session::ExternalSession;
use trusty_mpm_core::session::Session;
use trusty_mpm_core::tmux::TmuxTarget;
use crate::error::DaemonError;
use crate::tmux::{AdoptedSession, SessionSnapshot, TmuxDriver};
pub struct TmuxService;
impl TmuxService {
pub fn capture(session: &Session, lines: u32) -> String {
match TmuxDriver::discover() {
Ok(driver) => {
let target = TmuxTarget::session(&session.tmux_name);
match driver.capture(&target, Some(lines)) {
Ok(text) => text,
Err(e) => {
tracing::warn!("tmux capture failed for {}: {e}", session.tmux_name);
String::new()
}
}
}
Err(_) => {
tracing::info!(
"tmux unavailable; capture for {} skipped",
session.tmux_name
);
String::new()
}
}
}
pub fn send_command(session: &Session, command: &str) {
match TmuxDriver::discover() {
Ok(driver) => {
let target = TmuxTarget::session(&session.tmux_name);
if let Err(e) = driver.send_line(&target, command) {
tracing::warn!("tmux send_line failed for {}: {e}", session.tmux_name);
}
}
Err(_) => {
tracing::info!(
"tmux unavailable; command for {} not sent",
session.tmux_name
);
}
}
}
pub fn list_all() -> Vec<ExternalSession> {
match TmuxDriver::discover() {
Ok(driver) => driver.list_all_sessions().unwrap_or_else(|e| {
tracing::warn!("tmux list_all_sessions failed: {e}");
Vec::new()
}),
Err(_) => {
tracing::info!("tmux unavailable; tmux session list is empty");
Vec::new()
}
}
}
pub fn adopt(name: &str) -> Result<AdoptedSession, DaemonError> {
let driver = TmuxDriver::discover().map_err(|_| DaemonError::SessionNotFound {
id: name.to_string(),
})?;
driver.adopt_session(name).map_err(|e| {
tracing::warn!("tmux adopt {name} failed: {e}");
DaemonError::SessionNotFound {
id: name.to_string(),
}
})
}
pub fn snapshot(name: &str, lines: u32) -> Result<SessionSnapshot, DaemonError> {
let driver = TmuxDriver::discover().map_err(|_| DaemonError::SessionNotFound {
id: name.to_string(),
})?;
driver.monitor_session(name, lines).map_err(|e| {
tracing::warn!("tmux snapshot for {name} failed: {e}");
DaemonError::SessionNotFound {
id: name.to_string(),
}
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use trusty_mpm_core::session::{ControlModel, SessionId};
#[test]
fn capture_without_tmux_is_empty() {
let session = Session::new(SessionId::new(), "/tmp/p", ControlModel::Tmux, None);
let _ = TmuxService::capture(&session, 10);
}
#[test]
fn list_all_without_tmux_is_empty() {
let _ = TmuxService::list_all();
}
#[test]
fn adopt_missing_session_is_not_found() {
let result = TmuxService::adopt("tmpm-definitely-no-such-session-xyz");
assert!(result.is_err());
}
#[test]
fn snapshot_missing_session_is_not_found() {
let result = TmuxService::snapshot("no-such-session-xyz", 10);
assert!(result.is_err());
}
}