1use anyhow::{Context, Result};
2use tokio::process::Command;
3
4pub(crate) fn socket() -> &'static str {
13 if is_test_binary() { "ninox-test" } else { "ninox" }
14}
15
16fn is_test_binary() -> bool {
26 std::env::current_exe()
27 .ok()
28 .is_some_and(|p| p.components().any(|c| c.as_os_str() == "deps"))
29}
30
31fn parse_tmux_version(raw: &str) -> (u32, u32) {
35 let ver = raw.trim().strip_prefix("tmux ").unwrap_or(raw.trim());
36 let mut parts = ver.split(|c: char| !c.is_ascii_digit());
37 let major: u32 = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0);
38 let minor: u32 = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0);
39 (major, minor)
40}
41
42pub fn detected_version_sync() -> (u32, u32) {
47 std::process::Command::new("tmux")
48 .arg("-V")
49 .output()
50 .ok()
51 .filter(|o| o.status.success())
52 .map(|o| parse_tmux_version(&String::from_utf8_lossy(&o.stdout)))
53 .unwrap_or((0, 0))
54}
55
56fn supports_extended_keys_format((major, minor): (u32, u32)) -> bool {
59 (major, minor) >= (3, 5)
60}
61
62fn server_config_for_version(version: (u32, u32)) -> String {
66 let mut cfg = String::from("# Managed by ninox — rewritten on every app start. Do not edit.\n");
67 cfg.push_str("set -g default-terminal \"tmux-256color\"\n");
68 cfg.push_str("set -as terminal-features \"xterm*:RGB:usstyle:extkeys:hyperlinks\"\n");
69 cfg.push_str("set -s extended-keys always\n");
70 if supports_extended_keys_format(version) {
71 cfg.push_str("set -s extended-keys-format csi-u\n");
72 }
73 cfg.push_str("set -g history-limit 100000\n");
74 cfg.push_str("set -g status off\n");
75 cfg.push_str("set -s escape-time 0\n");
76 cfg.push_str("set -g window-size latest\n");
77 cfg.push_str("set -g allow-passthrough on\n");
78 cfg.push_str("set -g focus-events on\n");
79 cfg.push_str("set -g exit-empty off\n");
83 cfg
84}
85
86fn config_path() -> std::path::PathBuf {
87 let file = if is_test_binary() { "tmux-test.conf" } else { "tmux.conf" };
88 dirs::config_dir()
89 .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
90 .join("ninox")
91 .join(file)
92}
93
94pub fn write_server_config() -> Result<std::path::PathBuf> {
98 let path = config_path();
99 if let Some(dir) = path.parent() {
100 std::fs::create_dir_all(dir)?;
101 }
102 std::fs::write(&path, server_config_for_version(detected_version_sync()))?;
103 Ok(path)
104}
105
106fn socket_args() -> Vec<String> {
111 vec!["-L".into(), socket().into()]
112}
113
114pub async fn require_version() -> Result<()> {
116 let out = Command::new("tmux").arg("-V").output().await
117 .context("tmux not found — install tmux (brew install tmux / apt install tmux)")?;
118 let v = String::from_utf8_lossy(&out.stdout);
119 let ver = v.trim().strip_prefix("tmux ").unwrap_or(v.trim());
120 let version = parse_tmux_version(&v);
121 anyhow::ensure!(
122 version >= (3, 2),
123 "ninox requires tmux >= 3.2 for extended keyboard support; found {ver}"
124 );
125 if !supports_extended_keys_format(version) {
126 tracing::warn!(
127 "tmux {ver} detected — extended-keys-format csi-u requires tmux >= 3.5; \
128 Shift+Enter and other disambiguated keys may not reach apps correctly \
129 on this version"
130 );
131 }
132 Ok(())
133}
134
135async fn ensure_server_ready() {
156 static READY: tokio::sync::OnceCell<()> = tokio::sync::OnceCell::const_new();
157 READY.get_or_init(|| async {
158 if let Err(e) = write_server_config() {
159 tracing::warn!("failed to write tmux config: {e}");
160 }
161 let conf = config_path().display().to_string();
162 let _ = run_raw(&["-L", socket(), "-f", &conf, "start-server"]).await;
169 let _ = run_raw(&["-L", socket(), "source-file", &conf]).await;
170 }).await;
171}
172
173fn is_missing_session(e: &anyhow::Error) -> bool {
174 let msg = e.to_string();
175 msg.contains("can't find session")
176 || msg.contains("session not found")
177 || msg.contains("no server running")
178 || msg.contains("no sessions")
179 || msg.contains("no current target")
186}
187
188#[derive(Debug, Clone)]
190pub struct TmuxSession {
191 pub id: String,
192 pub created_ms: i64,
193 pub pid: Option<u32>,
194 pub tty: Option<String>,
195}
196
197async fn run(args: &[&str]) -> Result<String> {
199 ensure_server_ready().await;
200 let prefix = socket_args();
201 let mut full: Vec<&str> = prefix.iter().map(String::as_str).collect();
202 full.extend_from_slice(args);
203 run_raw(&full).await
204}
205
206async fn run_default(args: &[&str]) -> Result<String> {
209 run_raw(args).await
210}
211
212async fn run_raw(args: &[&str]) -> Result<String> {
214 let out = Command::new("tmux")
215 .args(args)
216 .kill_on_drop(true)
217 .output()
218 .await
219 .context("tmux not found — install tmux (brew install tmux / apt install tmux)")?;
220 if !out.status.success() {
221 let stderr = String::from_utf8_lossy(&out.stderr);
222 anyhow::bail!("tmux {:?} failed: {}", args, stderr.trim());
223 }
224 Ok(String::from_utf8_lossy(&out.stdout).trim_end().to_string())
225}
226
227async fn run_session_scoped(args: &[&str]) -> Result<String> {
230 match run(args).await {
231 Err(e) if is_missing_session(&e) => run_default(args).await,
232 other => other,
233 }
234}
235
236async fn run_best_effort(args: &[&str]) -> String {
239 match run(args).await {
240 Ok(result) => result,
241 Err(e) => {
242 tracing::warn!("tmux {:?} failed (ignored): {}", args, e);
243 String::new()
244 }
245 }
246}
247
248async fn run_best_effort_default(args: &[&str]) -> String {
251 match run_default(args).await {
252 Ok(result) => result,
253 Err(e) => {
254 tracing::warn!("tmux (default socket) {:?} failed (ignored): {}", args, e);
255 String::new()
256 }
257 }
258}
259
260fn shell_quote(s: &str) -> String {
263 format!("'{}'", s.replace('\'', "'\\''"))
264}
265
266pub async fn create_session(
269 id: &str,
270 workspace: &str,
271 cmd: &str,
272 env: &[(&str, &str)],
273) -> Result<()> {
274 let mut env_pairs: Vec<String> = Vec::new();
276 for (k, v) in env {
277 anyhow::ensure!(!k.contains('='), "env key must not contain '=': {k}");
278 env_pairs.push(format!("{k}={v}"));
279 }
280 let mut extra: Vec<&str> = Vec::new();
281 for pair in &env_pairs {
282 extra.push("-e");
284 extra.push(pair.as_str());
285 }
286
287 let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/bash".to_string());
291 let shell_cmd = format!("{shell} -l -c {}", shell_quote(cmd));
292
293 let mut base = vec!["new-session", "-d", "-s", id, "-x", "140", "-y", "50", "-c", workspace];
298 base.extend_from_slice(&extra);
299 base.push(&shell_cmd);
300
301 run(&base).await.map(|_| ())
306}
307
308pub async fn kill_session(id: &str) -> Result<()> {
312 match run_session_scoped(&["kill-session", "-t", id]).await {
313 Ok(_) => Ok(()),
314 Err(e) => {
315 if is_missing_session(&e) {
316 Ok(())
317 } else {
318 Err(e)
319 }
320 }
321 }
322}
323
324pub async fn has_session(id: &str) -> bool {
326 run_session_scoped(&["has-session", "-t", id]).await.is_ok()
327}
328
329pub async fn list_sessions() -> Result<Vec<TmuxSession>> {
333 const SEP: &str = "|";
340 let fmt = format!("#{{session_name}}{SEP}#{{session_created}}{SEP}#{{pane_pid}}{SEP}#{{pane_tty}}");
341 let ninox_raw = run_best_effort(&["list-sessions", "-F", &fmt]).await;
342 let default_raw = run_best_effort_default(&["list-sessions", "-F", &fmt]).await;
343
344 let mut seen = std::collections::HashSet::new();
345 let mut sessions = Vec::new();
346 for raw in [ninox_raw, default_raw] {
347 for line in raw.lines().filter(|l| !l.is_empty()) {
348 let mut cols = line.splitn(4, SEP);
349 let Some(id) = cols.next().map(str::to_string) else { continue };
350 if !seen.insert(id.clone()) {
351 continue;
352 }
353 let sec = cols.next().and_then(|s| s.parse::<i64>().ok()).unwrap_or(0);
354 let pid = cols.next().and_then(|s| s.parse::<u32>().ok());
355 let tty = cols.next().map(str::to_string).filter(|s| !s.is_empty());
356 sessions.push(TmuxSession { id, created_ms: sec * 1000, pid, tty });
357 }
358 }
359 Ok(sessions)
360}
361
362pub async fn get_pane_tty(id: &str) -> Result<Option<String>> {
364 let out = run_session_scoped(&["list-panes", "-t", id, "-F", "#{pane_tty}"]).await?;
365 Ok(out
366 .lines()
367 .next()
368 .map(|s| s.trim().to_string())
369 .filter(|s| !s.is_empty()))
370}
371
372pub async fn pipe_pane(id: &str, dest_path: &str) -> Result<()> {
375 run_session_scoped(&["pipe-pane", "-t", id, &format!("cat > {}", shell_quote(dest_path))]).await?;
376 Ok(())
377}
378
379pub async fn attach_args(session_id: &str) -> Vec<String> {
382 let mut argv = vec!["tmux".to_string()];
383 if run(&["has-session", "-t", session_id]).await.is_ok() {
384 argv.extend(socket_args());
385 } else {
386 tracing::warn!(
387 "session {session_id} predates the ninox socket — attaching on the \
388 legacy default tmux server without the managed config (extended \
389 keys / resize guarantees are degraded until it terminates naturally)"
390 );
391 }
392 argv.extend(["attach-session", "-t", session_id].map(String::from));
393 argv
394}
395
396pub async fn history_size(session_id: &str) -> i64 {
398 run_session_scoped(&["display-message", "-p", "-t", session_id, "#{history_size}"])
399 .await
400 .ok()
401 .and_then(|s| s.trim().parse().ok())
402 .unwrap_or(0)
403}
404
405pub async fn capture_history(session_id: &str, start: i64, end: i64) -> Vec<u8> {
409 run_session_scoped(&[
410 "capture-pane", "-p", "-e", "-t", session_id,
411 "-S", &start.to_string(), "-E", &end.to_string(),
412 ])
413 .await
414 .map(|s| s.into_bytes())
415 .unwrap_or_default()
416}
417
418pub async fn send_keys(session_id: &str, text: &str) -> Result<()> {
423 run_session_scoped(&["send-keys", "-t", session_id, "-l", text]).await?;
425 run_session_scoped(&["send-keys", "-t", session_id, "Enter"]).await?;
427 Ok(())
428}
429
430pub async fn paste_buffer(session_id: &str, buf_name: &str, tmp_path: &str, bytes: &[u8]) -> Result<()> {
436 std::fs::write(tmp_path, bytes)?;
437 let result = run_session_scoped(&[
438 "load-buffer", "-b", buf_name, tmp_path, ";",
439 "paste-buffer", "-b", buf_name, "-t", session_id, "-d",
440 ]).await;
441 let _ = std::fs::remove_file(tmp_path);
442 result.map(|_| ())
443}
444
445#[cfg(test)]
446mod tests {
447 use super::*;
448 use tokio::time::{sleep, Duration};
449
450 fn tmux_available() -> bool {
451 std::process::Command::new("tmux")
452 .args(["-V"])
453 .output()
454 .map(|o| o.status.success())
455 .unwrap_or(false)
456 }
457
458 fn unique_id() -> String {
459 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
464 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
465 format!(
466 "test-{}-{n}",
467 std::time::SystemTime::now()
468 .duration_since(std::time::UNIX_EPOCH)
469 .unwrap()
470 .as_millis()
471 )
472 }
473
474 #[test]
480 fn tests_resolve_to_the_isolated_socket_not_the_real_apps() {
481 assert!(is_test_binary(), "the test binary itself must be detected as a test binary");
482 assert_eq!(socket(), "ninox-test");
483 assert_ne!(socket(), "ninox");
484 }
485
486 #[tokio::test]
487 async fn create_and_has_and_kill() {
488 if !tmux_available() { return; }
489 let id = unique_id();
490 create_session(&id, "/tmp", "sleep 30", &[]).await.unwrap();
491 assert!(has_session(&id).await);
492 kill_session(&id).await.unwrap();
493 assert!(!has_session(&id).await);
494 }
495
496 #[tokio::test]
497 async fn list_includes_created() {
498 if !tmux_available() { return; }
499 let id = unique_id();
500 create_session(&id, "/tmp", "sleep 30", &[]).await.unwrap();
501 let sessions = list_sessions().await.unwrap();
502 assert!(sessions.iter().any(|s| s.id == id));
503 kill_session(&id).await.unwrap();
504 }
505
506 #[tokio::test]
507 async fn get_pane_tty_returns_dev_path() {
508 if !tmux_available() { return; }
509 let id = unique_id();
510 create_session(&id, "/tmp", "sleep 30", &[]).await.unwrap();
511 let tty = get_pane_tty(&id).await.unwrap();
512 assert!(tty.map(|t| t.starts_with("/dev/")).unwrap_or(false));
513 kill_session(&id).await.unwrap();
514 }
515
516 #[tokio::test]
517 async fn send_keys_builds_correct_command() {
518 let quoted = shell_quote("hello world");
521 assert_eq!(quoted, "'hello world'");
522 let with_apostrophe = shell_quote("don't");
523 assert_eq!(with_apostrophe, "'don'\\''t'");
524 }
525
526 #[test]
527 fn server_config_is_written_and_contains_required_settings() {
528 let path = write_server_config().unwrap();
529 let body = std::fs::read_to_string(&path).unwrap();
530 for required in [
531 "default-terminal \"tmux-256color\"",
532 "extended-keys always",
533 "history-limit 100000",
534 "status off",
535 "window-size latest",
536 "allow-passthrough on",
537 "exit-empty off",
538 ] {
539 assert!(body.contains(required), "config missing {required:?}\n{body}");
540 }
541 if supports_extended_keys_format(detected_version_sync()) {
544 assert!(body.contains("extended-keys-format csi-u"),
545 "config missing extended-keys-format on tmux >= 3.5\n{body}");
546 } else {
547 assert!(!body.contains("extended-keys-format"),
548 "config must omit extended-keys-format on tmux < 3.5 (rejected as invalid)\n{body}");
549 }
550 }
551
552 #[tokio::test]
553 async fn require_version_passes_on_installed_tmux() {
554 if !tmux_available() { return; }
555 require_version().await.unwrap();
556 }
557
558 #[tokio::test]
559 async fn sessions_are_created_on_the_ninox_socket() {
560 if !tmux_available() { return; }
561 let id = unique_id();
562 create_session(&id, "/tmp", "sleep 30", &[]).await.unwrap();
563 assert!(has_session(&id).await);
565 let default_out = std::process::Command::new("tmux")
567 .args(["has-session", "-t", &id])
568 .output()
569 .unwrap();
570 assert!(!default_out.status.success(), "session leaked onto the default socket");
571 kill_session(&id).await.unwrap();
572 }
573
574 #[tokio::test]
575 async fn legacy_default_socket_sessions_are_still_reachable() {
576 if !tmux_available() { return; }
577 let id = unique_id();
578 let st = std::process::Command::new("tmux")
580 .args(["new-session", "-d", "-s", &id, "-x", "80", "-y", "24", "sleep 30"])
581 .status()
582 .unwrap();
583 assert!(st.success());
584 assert!(has_session(&id).await, "has_session must fall back to the default socket");
585 let argv = attach_args(&id).await;
586 assert!(!argv.contains(&"-L".to_string()), "legacy session must attach without -L: {argv:?}");
587 kill_session(&id).await.unwrap(); assert!(!has_session(&id).await);
589 }
590
591 #[tokio::test]
592 async fn capture_history_returns_scrolled_off_lines() {
593 if !tmux_available() { return; }
594 let id = unique_id();
595 create_session(&id, "/tmp", "bash -c 'for i in $(seq 1 80); do echo line-$i; done; sleep 30'", &[]).await.unwrap();
597 sleep(Duration::from_millis(500)).await;
598 let hist = history_size(&id).await;
599 assert!(hist > 0, "expected history to accumulate, got {hist}");
600 let bytes = capture_history(&id, -hist, -1).await;
601 let text = String::from_utf8_lossy(&bytes);
602 assert!(text.contains("line-1"), "oldest line missing from history capture: {text}");
603 kill_session(&id).await.unwrap();
604 }
605}