marver 0.0.11

A TUI workspace for AI agent sessions: tmux orchestration, git worktree management, and repo control in one place.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
//! tmux session lifecycle.
//!
//! Two layers. This one shells out to `tmux` for one-shot operations — create a
//! session, check it exists, kill it — which needs no terminal and no long-lived
//! connection. [`control`] and [`client`] handle the streaming side, where panes
//! are read and typed into.
//!
//! Every call is scoped to a [`Socket`]. Tests always select a private one, so a
//! test run can never see, disturb, or kill a session on the user's real tmux
//! server — including when it panics.

pub mod client;
pub mod control;

use std::ffi::{OsStr, OsString};
use std::path::Path;
use std::process::Command;

pub use client::ControlClient;
pub use control::{Decoder, Event};

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("could not run tmux: {0}")]
    Spawn(#[source] std::io::Error),
    #[error("tmux {args} failed: {stderr}")]
    Failed { args: String, stderr: String },
    #[error("session {0} does not exist")]
    NoSuchSession(String),
}

pub type Result<T> = std::result::Result<T, Error>;

/// Detached sessions default to 80x24; anything wider is clipped until a client
/// attaches. Panes are created at this size so early output is not reflowed.
pub const DEFAULT_SIZE: (u16, u16) = (200, 50);

/// The tmux session backing a task.
pub fn session_name(task_id: i64) -> String {
    format!("marver-{task_id}")
}

/// Which tmux server to talk to.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Socket {
    /// The user's ordinary server.
    #[default]
    Default,
    /// A named socket in tmux's socket directory (`-L`).
    Name(String),
    /// An explicit socket path (`-S`).
    ///
    /// Preferred for tests: tmux leaves the socket inode behind after
    /// `kill-server`, so a path inside a temporary directory is removed with it
    /// rather than accumulating in `/tmp`.
    Path(std::path::PathBuf),
}

impl Socket {
    /// Arguments that select this server, to prepend to any tmux invocation.
    pub fn args(&self) -> Vec<std::ffi::OsString> {
        match self {
            Self::Default => Vec::new(),
            Self::Name(name) => vec!["-L".into(), name.into()],
            Self::Path(path) => vec!["-S".into(), path.clone().into_os_string()],
        }
    }
}

#[derive(Debug, Clone)]
pub struct Tmux {
    socket: Socket,
    /// The binary to invoke. Overridable so the "tmux will not run at all"
    /// failure mode -- which must not be confused with "no such session" -- is
    /// reachable from a test.
    binary: String,
}

impl Default for Tmux {
    fn default() -> Self {
        Self {
            socket: Socket::default(),
            binary: "tmux".to_string(),
        }
    }
}

impl Tmux {
    pub fn new() -> Self {
        Self::default()
    }

    /// Talk to a named socket instead of the default server.
    pub fn with_socket(name: impl Into<String>) -> Self {
        Self {
            socket: Socket::Name(name.into()),
            ..Self::default()
        }
    }

    /// Talk to a server at an explicit socket path.
    pub fn with_socket_path(path: impl Into<std::path::PathBuf>) -> Self {
        Self {
            socket: Socket::Path(path.into()),
            ..Self::default()
        }
    }

    /// Invoke a different binary.
    ///
    /// Test-only. It exists so "tmux cannot be run at all" is reachable —
    /// a state [`Tmux::session_exists`] must not confuse with "no such
    /// session", and one there is otherwise no way to produce.
    #[cfg(test)]
    pub(crate) fn with_binary(binary: impl Into<String>) -> Self {
        Self {
            binary: binary.into(),
            ..Self::default()
        }
    }

    pub fn socket(&self) -> &Socket {
        &self.socket
    }

    /// The `tmux [-L name | -S path]` prefix every invocation shares.
    pub fn command(&self) -> Command {
        let mut cmd = Command::new(&self.binary);
        cmd.args(self.socket.args());
        cmd
    }

    pub fn run<S: AsRef<OsStr>>(&self, args: &[S]) -> Result<String> {
        let output = self.command().args(args).output().map_err(Error::Spawn)?;
        if !output.status.success() {
            return Err(Error::Failed {
                args: args
                    .iter()
                    .map(|a| a.as_ref().to_string_lossy().into_owned())
                    .collect::<Vec<_>>()
                    .join(" "),
                stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
            });
        }
        Ok(String::from_utf8_lossy(&output.stdout)
            .trim_end()
            .to_string())
    }

    /// Whether a server is listening on this socket at all.
    pub fn server_running(&self) -> bool {
        self.run(&["list-sessions", "-F", "#{session_name}"])
            .is_ok()
    }

    pub fn has_session(&self, name: &str) -> bool {
        self.session_exists(name).unwrap_or(false)
    }

    /// Whether a session exists, distinguishing "no" from "could not ask".
    ///
    /// [`Tmux::has_session`] collapses both into `false`, which is fine for a
    /// caller about to create a session and dangerous for one about to conclude
    /// an agent has died. tmux exiting non-zero is an answer — no server is
    /// running, or no such session — but failing to *spawn* tmux at all, a
    /// missing binary or an unset PATH under a service manager, is not.
    pub fn session_exists(&self, name: &str) -> Result<bool> {
        match self.run(&["has-session", "-t", &exact(name)]) {
            Ok(_) => Ok(true),
            Err(Error::Failed { .. }) => Ok(false),
            Err(other) => Err(other),
        }
    }

    /// Create a detached session with its working directory set.
    ///
    /// Fails if the name is taken; callers that want idempotence should check
    /// [`Tmux::has_session`] first, so an existing session is never silently
    /// adopted as if it were new.
    pub fn new_session(&self, name: &str, cwd: &Path, size: (u16, u16)) -> Result<()> {
        self.new_session_running(name, cwd, size, &[])
    }

    /// Open a session, optionally running `argv` instead of a shell.
    ///
    /// With two or more trailing arguments tmux execs them directly — no shell,
    /// no line discipline. That distinction is the whole point: typing a command
    /// into an interactive shell means control bytes in the text are consumed by
    /// the terminal before the shell ever parses the quoting, so no amount of
    /// quoting can make `\x03` in a prompt safe. Handing over an argv sidesteps
    /// the question rather than answering it.
    pub fn new_session_running(
        &self,
        name: &str,
        cwd: &Path,
        size: (u16, u16),
        argv: &[OsString],
    ) -> Result<()> {
        let (cols, rows) = size;
        let (cols, rows) = (cols.to_string(), rows.to_string());
        let mut args: Vec<&OsStr> = vec![
            OsStr::new("new-session"),
            OsStr::new("-d"),
            OsStr::new("-s"),
            OsStr::new(name),
            OsStr::new("-c"),
            cwd.as_os_str(),
            OsStr::new("-x"),
            OsStr::new(&cols),
            OsStr::new("-y"),
            OsStr::new(&rows),
        ];
        if !argv.is_empty() {
            args.push(OsStr::new("--"));
            args.extend(argv.iter().map(OsString::as_os_str));
        }
        self.run(&args)?;
        Ok(())
    }

    pub fn kill_session(&self, name: &str) -> Result<()> {
        if !self.has_session(name) {
            return Err(Error::NoSuchSession(name.to_string()));
        }
        self.run(&["kill-session", "-t", &exact(name)])?;
        Ok(())
    }

    /// Stop the whole server on this socket. Tests use it; production should not.
    pub fn kill_server(&self) -> Result<()> {
        match self.run(&["kill-server"]) {
            Ok(_) => Ok(()),
            // No server running is the state we wanted anyway.
            Err(Error::Failed { .. }) => Ok(()),
            Err(other) => Err(other),
        }
    }

    pub fn list_sessions(&self) -> Result<Vec<String>> {
        match self.run(&["list-sessions", "-F", "#{session_name}"]) {
            Ok(out) => Ok(non_empty_lines(&out)),
            // tmux exits non-zero when no server is running.
            Err(Error::Failed { .. }) => Ok(Vec::new()),
            Err(other) => Err(other),
        }
    }

    /// Pane ids in a session, e.g. `%0`.
    pub fn list_panes(&self, session: &str) -> Result<Vec<String>> {
        let out = self.run(&["list-panes", "-t", &exact(session), "-F", "#{pane_id}"])?;
        Ok(non_empty_lines(&out))
    }

    /// Send literal text to a target, as if typed.
    pub fn send_keys(&self, target: &str, keys: &str) -> Result<()> {
        self.run(&["send-keys", "-t", target, "-l", keys])?;
        Ok(())
    }

    /// Send a named key such as `Enter` or `C-c`.
    pub fn send_key(&self, target: &str, key: &str) -> Result<()> {
        self.run(&["send-keys", "-t", target, key])?;
        Ok(())
    }

    /// Current visible contents of a pane.
    pub fn capture_pane(&self, target: &str) -> Result<String> {
        self.run(&["capture-pane", "-p", "-t", target])
    }

    /// The working directory of a session's first pane.
    ///
    /// Uses `list-panes` rather than `display-message`: the latter's `-t` does
    /// not accept the `=` exact-match prefix and answers with an empty string
    /// and a zero exit status when the target does not resolve, which would
    /// read as "the session is at the root" instead of as an error.
    pub fn session_cwd(&self, session: &str) -> Result<String> {
        let out = self.run(&[
            "list-panes",
            "-t",
            &exact(session),
            "-F",
            "#{pane_current_path}",
        ])?;
        non_empty_lines(&out)
            .into_iter()
            .next()
            .ok_or_else(|| Error::NoSuchSession(session.to_string()))
    }
}

/// Anchor a *session* name so `marver-1` cannot match `marver-12`.
///
/// tmux treats target names as patterns unless prefixed with `=`. The prefix is
/// only understood for session and window targets: passing `=name` where a pane
/// is expected fails with `can't find pane: =name`. Pane-targeted calls such as
/// [`Tmux::send_keys`] therefore take the caller's target verbatim and should be
/// given a pane id from [`Tmux::list_panes`].
fn exact(name: &str) -> String {
    format!("={name}")
}

fn non_empty_lines(out: &str) -> Vec<String> {
    out.lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .map(str::to_string)
        .collect()
}

#[cfg(test)]
pub(crate) mod testing {
    use super::*;
    use tempfile::TempDir;

    /// A tmux server on a private socket, killed when the guard drops.
    ///
    /// Uses an explicit socket path inside a temporary directory rather than a
    /// `-L` name. Two reasons: a test run can never reach the user's real
    /// server even if it panics, and tmux leaves the socket inode behind after
    /// `kill-server`, so putting it in a `TempDir` means it is cleaned up
    /// instead of accumulating in the shared socket directory.
    pub struct TestServer {
        pub tmux: Tmux,
        _dir: TempDir,
    }

    impl TestServer {
        pub fn new() -> Self {
            let dir = TempDir::new().expect("socket dir");
            Self {
                tmux: Tmux::with_socket_path(dir.path().join("sock")),
                _dir: dir,
            }
        }
    }

    impl Drop for TestServer {
        fn drop(&mut self) {
            let _ = self.tmux.kill_server();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::testing::TestServer;
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn session_names_are_derived_from_the_task() {
        assert_eq!(session_name(7), "marver-7");
    }

    #[test]
    fn tests_never_use_the_default_socket() {
        let server = TestServer::new();
        assert!(
            matches!(server.tmux.socket(), Socket::Path(_)),
            "a test must not be able to reach the real tmux server"
        );
    }

    #[test]
    fn socket_selection_produces_the_right_flags() {
        assert!(Tmux::new().socket().args().is_empty());
        assert_eq!(Tmux::with_socket("x").socket().args(), ["-L", "x"]);
        assert_eq!(
            Tmux::with_socket_path("/tmp/s").socket().args(),
            ["-S", "/tmp/s"]
        );
    }

    #[test]
    fn a_test_socket_is_removed_with_its_directory() {
        let path = {
            let server = TestServer::new();
            let tmp = TempDir::new().unwrap();
            server
                .tmux
                .new_session("s", tmp.path(), DEFAULT_SIZE)
                .unwrap();
            let Socket::Path(path) = server.tmux.socket().clone() else {
                panic!("expected a path socket");
            };
            assert!(path.exists(), "the socket should exist while running");
            path
        };
        assert!(!path.exists(), "the socket must not outlive the test");
    }

    #[test]
    fn creates_and_kills_a_session() {
        let server = TestServer::new();
        let tmp = TempDir::new().unwrap();

        assert!(!server.tmux.has_session("work"));
        server
            .tmux
            .new_session("work", tmp.path(), DEFAULT_SIZE)
            .unwrap();
        assert!(server.tmux.has_session("work"));
        assert_eq!(server.tmux.list_sessions().unwrap(), ["work"]);

        server.tmux.kill_session("work").unwrap();
        assert!(!server.tmux.has_session("work"));
    }

    #[test]
    fn a_session_starts_in_the_directory_it_was_given() {
        let server = TestServer::new();
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("workspace");
        std::fs::create_dir_all(&dir).unwrap();

        server.tmux.new_session("t", &dir, DEFAULT_SIZE).unwrap();
        let cwd = server.tmux.session_cwd("t").unwrap();

        // macOS reports /private/var for /var; compare the resolved paths.
        assert_eq!(
            std::fs::canonicalize(cwd).unwrap(),
            std::fs::canonicalize(&dir).unwrap()
        );
    }

    #[test]
    fn duplicate_session_names_are_refused() {
        let server = TestServer::new();
        let tmp = TempDir::new().unwrap();
        server
            .tmux
            .new_session("dup", tmp.path(), DEFAULT_SIZE)
            .unwrap();
        assert!(
            server
                .tmux
                .new_session("dup", tmp.path(), DEFAULT_SIZE)
                .is_err(),
            "an existing session must never be silently adopted"
        );
    }

    #[test]
    fn session_targets_are_matched_exactly() {
        let server = TestServer::new();
        let tmp = TempDir::new().unwrap();
        server
            .tmux
            .new_session("marver-12", tmp.path(), DEFAULT_SIZE)
            .unwrap();

        assert!(
            !server.tmux.has_session("marver-1"),
            "marver-1 must not match marver-12"
        );
        assert!(server.tmux.has_session("marver-12"));
    }

    #[test]
    fn killing_a_missing_session_is_an_error_not_a_silent_success() {
        let server = TestServer::new();
        assert!(matches!(
            server.tmux.kill_session("ghost"),
            Err(Error::NoSuchSession(_))
        ));
    }

    #[test]
    fn listing_sessions_with_no_server_is_empty_not_an_error() {
        let server = TestServer::new();
        assert!(!server.tmux.server_running());
        assert_eq!(server.tmux.list_sessions().unwrap(), Vec::<String>::new());
    }

    #[test]
    fn panes_can_be_listed_typed_into_and_captured() {
        let server = TestServer::new();
        let tmp = TempDir::new().unwrap();
        server
            .tmux
            .new_session("io", tmp.path(), DEFAULT_SIZE)
            .unwrap();

        let panes = server.tmux.list_panes("io").unwrap();
        assert_eq!(panes.len(), 1);
        assert!(panes[0].starts_with('%'), "pane ids look like %0");

        server
            .tmux
            .send_keys(&panes[0], "printf MARVERTEST")
            .unwrap();
        server.tmux.send_key(&panes[0], "Enter").unwrap();

        // Wait for the shell rather than assuming a fixed delay.
        let mut captured = String::new();
        for _ in 0..50 {
            captured = server.tmux.capture_pane(&panes[0]).unwrap();
            if captured.contains("MARVERTEST") {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(40));
        }
        assert!(captured.contains("MARVERTEST"), "captured: {captured:?}");
    }

    #[test]
    fn killing_the_server_is_idempotent() {
        let server = TestServer::new();
        server.tmux.kill_server().unwrap();
        server.tmux.kill_server().unwrap();
    }
}