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 anyhow::ensure!(
280 std::path::Path::new(workspace).is_dir(),
281 "workspace directory does not exist: {workspace}"
282 );
283 let mut env_pairs: Vec<String> = Vec::new();
285 for (k, v) in env {
286 anyhow::ensure!(!k.contains('='), "env key must not contain '=': {k}");
287 env_pairs.push(format!("{k}={v}"));
288 }
289 let mut extra: Vec<&str> = Vec::new();
290 for pair in &env_pairs {
291 extra.push("-e");
293 extra.push(pair.as_str());
294 }
295
296 let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/bash".to_string());
300 let shell_cmd = format!("{shell} -l -c {}", shell_quote(cmd));
301
302 let mut base = vec!["new-session", "-d", "-s", id, "-x", "140", "-y", "50", "-c", workspace];
307 base.extend_from_slice(&extra);
308 base.push(&shell_cmd);
309
310 run(&base).await.map(|_| ())
315}
316
317pub async fn kill_session(id: &str) -> Result<()> {
321 match run_session_scoped(&["kill-session", "-t", id]).await {
322 Ok(_) => Ok(()),
323 Err(e) => {
324 if is_missing_session(&e) {
325 Ok(())
326 } else {
327 Err(e)
328 }
329 }
330 }
331}
332
333pub async fn has_session(id: &str) -> bool {
335 run_session_scoped(&["has-session", "-t", id]).await.is_ok()
336}
337
338pub async fn list_sessions() -> Result<Vec<TmuxSession>> {
342 const SEP: &str = "|";
349 let fmt = format!("#{{session_name}}{SEP}#{{session_created}}{SEP}#{{pane_pid}}{SEP}#{{pane_tty}}");
350 let ninox_raw = run_best_effort(&["list-sessions", "-F", &fmt]).await;
351 let default_raw = run_best_effort_default(&["list-sessions", "-F", &fmt]).await;
352
353 let mut seen = std::collections::HashSet::new();
354 let mut sessions = Vec::new();
355 for raw in [ninox_raw, default_raw] {
356 for line in raw.lines().filter(|l| !l.is_empty()) {
357 let mut cols = line.splitn(4, SEP);
358 let Some(id) = cols.next().map(str::to_string) else { continue };
359 if !seen.insert(id.clone()) {
360 continue;
361 }
362 let sec = cols.next().and_then(|s| s.parse::<i64>().ok()).unwrap_or(0);
363 let pid = cols.next().and_then(|s| s.parse::<u32>().ok());
364 let tty = cols.next().map(str::to_string).filter(|s| !s.is_empty());
365 sessions.push(TmuxSession { id, created_ms: sec * 1000, pid, tty });
366 }
367 }
368 Ok(sessions)
369}
370
371pub async fn get_pane_tty(id: &str) -> Result<Option<String>> {
373 let out = run_session_scoped(&["list-panes", "-t", id, "-F", "#{pane_tty}"]).await?;
374 Ok(out
375 .lines()
376 .next()
377 .map(|s| s.trim().to_string())
378 .filter(|s| !s.is_empty()))
379}
380
381pub async fn pipe_pane(id: &str, dest_path: &str) -> Result<()> {
384 run_session_scoped(&["pipe-pane", "-t", id, &format!("cat > {}", shell_quote(dest_path))]).await?;
385 Ok(())
386}
387
388pub async fn attach_args(session_id: &str) -> Vec<String> {
391 let mut argv = vec!["tmux".to_string()];
392 if run(&["has-session", "-t", session_id]).await.is_ok() {
393 argv.extend(socket_args());
394 } else {
395 tracing::warn!(
396 "session {session_id} predates the ninox socket — attaching on the \
397 legacy default tmux server without the managed config (extended \
398 keys / resize guarantees are degraded until it terminates naturally)"
399 );
400 }
401 argv.extend(["attach-session", "-t", session_id].map(String::from));
402 argv
403}
404
405pub async fn history_size(session_id: &str) -> i64 {
407 run_session_scoped(&["display-message", "-p", "-t", session_id, "#{history_size}"])
408 .await
409 .ok()
410 .and_then(|s| s.trim().parse().ok())
411 .unwrap_or(0)
412}
413
414pub async fn capture_history(session_id: &str, start: i64, end: i64) -> Vec<u8> {
418 run_session_scoped(&[
419 "capture-pane", "-p", "-e", "-t", session_id,
420 "-S", &start.to_string(), "-E", &end.to_string(),
421 ])
422 .await
423 .map(|s| s.into_bytes())
424 .unwrap_or_default()
425}
426
427pub async fn send_keys(session_id: &str, text: &str) -> Result<()> {
432 run_session_scoped(&["send-keys", "-t", session_id, "-l", text]).await?;
434 run_session_scoped(&["send-keys", "-t", session_id, "Enter"]).await?;
436 Ok(())
437}
438
439pub async fn paste_buffer(session_id: &str, buf_name: &str, tmp_path: &str, bytes: &[u8]) -> Result<()> {
445 std::fs::write(tmp_path, bytes)?;
446 let result = run_session_scoped(&[
447 "load-buffer", "-b", buf_name, tmp_path, ";",
448 "paste-buffer", "-b", buf_name, "-t", session_id, "-d",
449 ]).await;
450 let _ = std::fs::remove_file(tmp_path);
451 result.map(|_| ())
452}
453
454#[cfg(test)]
455mod tests {
456 use super::*;
457 use tokio::time::{sleep, Duration};
458
459 fn tmux_available() -> bool {
460 std::process::Command::new("tmux")
461 .args(["-V"])
462 .output()
463 .map(|o| o.status.success())
464 .unwrap_or(false)
465 }
466
467 fn unique_id() -> String {
468 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
473 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
474 format!(
475 "test-{}-{n}",
476 std::time::SystemTime::now()
477 .duration_since(std::time::UNIX_EPOCH)
478 .unwrap()
479 .as_millis()
480 )
481 }
482
483 #[test]
489 fn tests_resolve_to_the_isolated_socket_not_the_real_apps() {
490 assert!(is_test_binary(), "the test binary itself must be detected as a test binary");
491 assert_eq!(socket(), "ninox-test");
492 assert_ne!(socket(), "ninox");
493 }
494
495 #[tokio::test]
496 async fn create_session_fails_when_workspace_dir_is_missing() {
497 if !tmux_available() { return; }
498 let id = unique_id();
499 let result = create_session(&id, "/definitely/not/a/real/dir", "sleep 30", &[]).await;
504 assert!(result.is_err(), "missing workspace must be an error, not a silent $HOME fallback");
505 assert!(!has_session(&id).await, "no session may be left behind on failure");
506 }
507
508 #[tokio::test]
509 async fn create_and_has_and_kill() {
510 if !tmux_available() { return; }
511 let id = unique_id();
512 create_session(&id, "/tmp", "sleep 30", &[]).await.unwrap();
513 assert!(has_session(&id).await);
514 kill_session(&id).await.unwrap();
515 assert!(!has_session(&id).await);
516 }
517
518 #[tokio::test]
519 async fn list_includes_created() {
520 if !tmux_available() { return; }
521 let id = unique_id();
522 create_session(&id, "/tmp", "sleep 30", &[]).await.unwrap();
523 let sessions = list_sessions().await.unwrap();
524 assert!(sessions.iter().any(|s| s.id == id));
525 kill_session(&id).await.unwrap();
526 }
527
528 #[tokio::test]
529 async fn get_pane_tty_returns_dev_path() {
530 if !tmux_available() { return; }
531 let id = unique_id();
532 create_session(&id, "/tmp", "sleep 30", &[]).await.unwrap();
533 let tty = get_pane_tty(&id).await.unwrap();
534 assert!(tty.map(|t| t.starts_with("/dev/")).unwrap_or(false));
535 kill_session(&id).await.unwrap();
536 }
537
538 #[tokio::test]
539 async fn send_keys_builds_correct_command() {
540 let quoted = shell_quote("hello world");
543 assert_eq!(quoted, "'hello world'");
544 let with_apostrophe = shell_quote("don't");
545 assert_eq!(with_apostrophe, "'don'\\''t'");
546 }
547
548 #[test]
549 fn server_config_is_written_and_contains_required_settings() {
550 let path = write_server_config().unwrap();
551 let body = std::fs::read_to_string(&path).unwrap();
552 for required in [
553 "default-terminal \"tmux-256color\"",
554 "extended-keys always",
555 "history-limit 100000",
556 "status off",
557 "window-size latest",
558 "allow-passthrough on",
559 "exit-empty off",
560 ] {
561 assert!(body.contains(required), "config missing {required:?}\n{body}");
562 }
563 if supports_extended_keys_format(detected_version_sync()) {
566 assert!(body.contains("extended-keys-format csi-u"),
567 "config missing extended-keys-format on tmux >= 3.5\n{body}");
568 } else {
569 assert!(!body.contains("extended-keys-format"),
570 "config must omit extended-keys-format on tmux < 3.5 (rejected as invalid)\n{body}");
571 }
572 }
573
574 #[tokio::test]
575 async fn require_version_passes_on_installed_tmux() {
576 if !tmux_available() { return; }
577 require_version().await.unwrap();
578 }
579
580 #[tokio::test]
581 async fn sessions_are_created_on_the_ninox_socket() {
582 if !tmux_available() { return; }
583 let id = unique_id();
584 create_session(&id, "/tmp", "sleep 30", &[]).await.unwrap();
585 assert!(has_session(&id).await);
587 let default_out = std::process::Command::new("tmux")
589 .args(["has-session", "-t", &id])
590 .output()
591 .unwrap();
592 assert!(!default_out.status.success(), "session leaked onto the default socket");
593 kill_session(&id).await.unwrap();
594 }
595
596 #[tokio::test]
597 async fn legacy_default_socket_sessions_are_still_reachable() {
598 if !tmux_available() { return; }
599 let id = unique_id();
600 let st = std::process::Command::new("tmux")
602 .args(["new-session", "-d", "-s", &id, "-x", "80", "-y", "24", "sleep 30"])
603 .status()
604 .unwrap();
605 assert!(st.success());
606 assert!(has_session(&id).await, "has_session must fall back to the default socket");
607 let argv = attach_args(&id).await;
608 assert!(!argv.contains(&"-L".to_string()), "legacy session must attach without -L: {argv:?}");
609 kill_session(&id).await.unwrap(); assert!(!has_session(&id).await);
611 }
612
613 #[tokio::test]
614 async fn capture_history_returns_scrolled_off_lines() {
615 if !tmux_available() { return; }
616 let id = unique_id();
617 create_session(&id, "/tmp", "bash -c 'for i in $(seq 1 80); do echo line-$i; done; sleep 30'", &[]).await.unwrap();
619 sleep(Duration::from_millis(500)).await;
620 let hist = history_size(&id).await;
621 assert!(hist > 0, "expected history to accumulate, got {hist}");
622 let bytes = capture_history(&id, -hist, -1).await;
623 let text = String::from_utf8_lossy(&bytes);
624 assert!(text.contains("line-1"), "oldest line missing from history capture: {text}");
625 kill_session(&id).await.unwrap();
626 }
627}