agentty 0.12.5

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
use std::future::Future;
use std::io;
use std::path::PathBuf;
use std::pin::Pin;
use std::process::Output;

/// Boxed async result returned by [`TmuxClient`] methods.
pub type TmuxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;

/// Async tmux boundary used by app orchestration.
#[cfg_attr(test, mockall::automock)]
pub trait TmuxClient: Send + Sync {
    /// Opens one tmux window rooted at `session_folder`.
    ///
    /// Returns the tmux window id when creation succeeds.
    fn open_window_for_folder(&self, session_folder: PathBuf) -> TmuxFuture<Option<String>>;

    /// Sends `command` followed by Enter to the target tmux `window_id`.
    fn run_command_in_window(&self, window_id: String, command: String) -> TmuxFuture<()>;
}

/// Captured tmux subprocess result used by injected command runners.
#[derive(Debug, Eq, PartialEq)]
struct TmuxCommandOutput {
    status_success: bool,
    stdout: Vec<u8>,
}

impl TmuxCommandOutput {
    /// Converts one subprocess output into the reduced tmux result shape.
    fn from_process_output(output: Output) -> Self {
        Self {
            status_success: output.status.success(),
            stdout: output.stdout,
        }
    }
}

/// Async tmux command boundary used to test multi-command flows
/// deterministically.
#[cfg_attr(test, mockall::automock)]
trait TmuxCommandRunner: Send + Sync {
    /// Opens one tmux window rooted at `session_folder`.
    fn open_window(&self, session_folder: PathBuf) -> TmuxFuture<io::Result<TmuxCommandOutput>>;

    /// Sends literal `command` bytes to the target tmux `window_id`.
    fn send_literal_keys(
        &self,
        window_id: String,
        command: String,
    ) -> TmuxFuture<io::Result<TmuxCommandOutput>>;

    /// Sends Enter to the target tmux `window_id`.
    fn send_enter_key(&self, window_id: String) -> TmuxFuture<io::Result<TmuxCommandOutput>>;
}

/// Production tmux command runner backed by subprocess calls.
struct ProcessTmuxCommandRunner;

impl ProcessTmuxCommandRunner {
    /// Builds the `tmux new-window` command for one session folder.
    fn open_window_command(session_folder: PathBuf) -> tokio::process::Command {
        let mut command = tokio::process::Command::new("tmux");
        command
            .arg("new-window")
            .arg("-P")
            .arg("-F")
            .arg("#{window_id}")
            .arg("-c")
            .arg(session_folder);

        command
    }

    /// Opens one tmux window in `session_folder`.
    async fn open_window_impl(session_folder: PathBuf) -> io::Result<TmuxCommandOutput> {
        let mut command = Self::open_window_command(session_folder);
        let output = command.output().await?;

        Ok(TmuxCommandOutput::from_process_output(output))
    }

    /// Builds the `tmux send-keys -l` command for one literal command string.
    fn send_literal_keys_command(window_id: String, command: String) -> tokio::process::Command {
        let mut tmux_command = tokio::process::Command::new("tmux");
        tmux_command
            .arg("send-keys")
            .arg("-t")
            .arg(window_id)
            .arg("-l")
            .arg(command);

        tmux_command
    }

    /// Sends literal `command` bytes to one tmux `window_id`.
    async fn send_literal_keys_impl(
        window_id: String,
        command: String,
    ) -> io::Result<TmuxCommandOutput> {
        let mut tmux_command = Self::send_literal_keys_command(window_id, command);
        let output = tmux_command.output().await?;

        Ok(TmuxCommandOutput::from_process_output(output))
    }

    /// Builds the `tmux send-keys C-m` command for one window id.
    fn send_enter_key_command(window_id: String) -> tokio::process::Command {
        let mut tmux_command = tokio::process::Command::new("tmux");
        tmux_command
            .arg("send-keys")
            .arg("-t")
            .arg(window_id)
            .arg("C-m");

        tmux_command
    }

    /// Sends Enter to one tmux `window_id`.
    async fn send_enter_key_impl(window_id: String) -> io::Result<TmuxCommandOutput> {
        let mut tmux_command = Self::send_enter_key_command(window_id);
        let output = tmux_command.output().await?;

        Ok(TmuxCommandOutput::from_process_output(output))
    }
}

impl TmuxCommandRunner for ProcessTmuxCommandRunner {
    fn open_window(&self, session_folder: PathBuf) -> TmuxFuture<io::Result<TmuxCommandOutput>> {
        Box::pin(async move { Self::open_window_impl(session_folder).await })
    }

    fn send_literal_keys(
        &self,
        window_id: String,
        command: String,
    ) -> TmuxFuture<io::Result<TmuxCommandOutput>> {
        Box::pin(async move { Self::send_literal_keys_impl(window_id, command).await })
    }

    fn send_enter_key(&self, window_id: String) -> TmuxFuture<io::Result<TmuxCommandOutput>> {
        Box::pin(async move { Self::send_enter_key_impl(window_id).await })
    }
}

/// Production [`TmuxClient`] implementation backed by tmux subprocess calls.
pub struct RealTmuxClient;

impl RealTmuxClient {
    /// Opens one tmux window in `session_folder` and returns its window id.
    async fn open_window_for_folder_impl(session_folder: PathBuf) -> Option<String> {
        let command_runner = ProcessTmuxCommandRunner;

        Self::open_window_for_folder_with_runner(&command_runner, session_folder).await
    }

    /// Sends `command` and Enter to one tmux `window_id`.
    async fn run_command_in_window_impl(window_id: String, command: String) {
        let command_runner = ProcessTmuxCommandRunner;

        Self::run_command_in_window_with_runner(&command_runner, window_id, command).await;
    }

    /// Opens one tmux window using the provided command runner.
    async fn open_window_for_folder_with_runner(
        command_runner: &dyn TmuxCommandRunner,
        session_folder: PathBuf,
    ) -> Option<String> {
        let output = command_runner.open_window(session_folder).await.ok()?;
        if !output.status_success {
            return None;
        }

        Self::parse_tmux_window_id(&output.stdout)
    }

    /// Sends `command` and Enter using the provided command runner.
    async fn run_command_in_window_with_runner(
        command_runner: &dyn TmuxCommandRunner,
        window_id: String,
        command: String,
    ) {
        let send_literal_output = command_runner
            .send_literal_keys(window_id.clone(), command)
            .await;

        let Ok(send_literal_output) = send_literal_output else {
            return;
        };
        if !send_literal_output.status_success {
            return;
        }

        // Best-effort: tmux window may have already been closed.
        let _ = command_runner.send_enter_key(window_id).await;
    }

    /// Parses a tmux window id from command output bytes.
    fn parse_tmux_window_id(stdout: &[u8]) -> Option<String> {
        let window_id = std::str::from_utf8(stdout).ok()?.trim();
        if window_id.is_empty() {
            return None;
        }

        Some(window_id.to_string())
    }
}

impl TmuxClient for RealTmuxClient {
    fn open_window_for_folder(&self, session_folder: PathBuf) -> TmuxFuture<Option<String>> {
        Box::pin(async move { Self::open_window_for_folder_impl(session_folder).await })
    }

    fn run_command_in_window(&self, window_id: String, command: String) -> TmuxFuture<()> {
        Box::pin(async move { Self::run_command_in_window_impl(window_id, command).await })
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use mockall::Sequence;
    use mockall::predicate::eq;

    use super::*;

    #[tokio::test]
    async fn open_window_for_folder_with_runner_returns_window_id_on_success() {
        // Arrange
        let mut command_runner = MockTmuxCommandRunner::new();
        let session_folder = PathBuf::from("/tmp/agentty-session");

        command_runner
            .expect_open_window()
            .with(eq(session_folder.clone()))
            .times(1)
            .return_once(|_| Box::pin(async { Ok(successful_tmux_output(b"@42\n")) }));

        // Act
        let window_id =
            RealTmuxClient::open_window_for_folder_with_runner(&command_runner, session_folder)
                .await;

        // Assert
        assert_eq!(window_id, Some("@42".to_string()));
    }

    #[tokio::test]
    async fn open_window_for_folder_with_runner_returns_none_when_command_fails() {
        // Arrange
        let mut command_runner = MockTmuxCommandRunner::new();
        let session_folder = PathBuf::from("/tmp/agentty-session");

        command_runner
            .expect_open_window()
            .with(eq(session_folder.clone()))
            .times(1)
            .return_once(|_| Box::pin(async { Err(io::Error::other("tmux unavailable")) }));

        // Act
        let window_id =
            RealTmuxClient::open_window_for_folder_with_runner(&command_runner, session_folder)
                .await;

        // Assert
        assert_eq!(window_id, None);
    }

    #[tokio::test]
    async fn open_window_for_folder_with_runner_returns_none_when_tmux_exits_unsuccessfully() {
        // Arrange
        let mut command_runner = MockTmuxCommandRunner::new();
        let session_folder = PathBuf::from("/tmp/agentty-session");

        command_runner
            .expect_open_window()
            .with(eq(session_folder.clone()))
            .times(1)
            .return_once(|_| Box::pin(async { Ok(failed_tmux_output()) }));

        // Act
        let window_id =
            RealTmuxClient::open_window_for_folder_with_runner(&command_runner, session_folder)
                .await;

        // Assert
        assert_eq!(window_id, None);
    }

    #[tokio::test]
    async fn run_command_in_window_with_runner_sends_enter_after_literal_keys() {
        // Arrange
        let mut command_runner = MockTmuxCommandRunner::new();
        let mut sequence = Sequence::new();

        command_runner
            .expect_send_literal_keys()
            .with(eq("@42".to_string()), eq("git status".to_string()))
            .times(1)
            .in_sequence(&mut sequence)
            .return_once(|_, _| Box::pin(async { Ok(successful_tmux_output(b"")) }));
        command_runner
            .expect_send_enter_key()
            .with(eq("@42".to_string()))
            .times(1)
            .in_sequence(&mut sequence)
            .return_once(|_| Box::pin(async { Ok(successful_tmux_output(b"")) }));

        // Act
        RealTmuxClient::run_command_in_window_with_runner(
            &command_runner,
            "@42".to_string(),
            "git status".to_string(),
        )
        .await;

        // Assert
        // `mockall` verifies the expected literal-send and Enter sequence.
    }

    #[tokio::test]
    async fn run_command_in_window_with_runner_stops_when_literal_send_fails() {
        // Arrange
        let mut command_runner = MockTmuxCommandRunner::new();

        command_runner
            .expect_send_literal_keys()
            .with(eq("@42".to_string()), eq("git status".to_string()))
            .times(1)
            .return_once(|_, _| Box::pin(async { Err(io::Error::other("tmux send-keys failed")) }));
        command_runner.expect_send_enter_key().times(0);

        // Act
        RealTmuxClient::run_command_in_window_with_runner(
            &command_runner,
            "@42".to_string(),
            "git status".to_string(),
        )
        .await;

        // Assert
        // `mockall` verifies that Enter is not sent after a command error.
    }

    #[tokio::test]
    async fn run_command_in_window_with_runner_stops_when_literal_send_exits_unsuccessfully() {
        // Arrange
        let mut command_runner = MockTmuxCommandRunner::new();

        command_runner
            .expect_send_literal_keys()
            .with(eq("@42".to_string()), eq("git status".to_string()))
            .times(1)
            .return_once(|_, _| Box::pin(async { Ok(failed_tmux_output()) }));
        command_runner.expect_send_enter_key().times(0);

        // Act
        RealTmuxClient::run_command_in_window_with_runner(
            &command_runner,
            "@42".to_string(),
            "git status".to_string(),
        )
        .await;

        // Assert
        // `mockall` verifies that Enter is not sent after a failed exit status.
    }

    #[test]
    fn parse_tmux_window_id_returns_none_for_invalid_utf8() {
        // Arrange
        let stdout = [0x80];

        // Act
        let window_id = RealTmuxClient::parse_tmux_window_id(&stdout);

        // Assert
        assert_eq!(window_id, None);
    }

    #[test]
    fn parse_tmux_window_id_trims_newline_and_returns_window_id() {
        // Arrange
        let stdout = b"@42\n";

        // Act
        let window_id = RealTmuxClient::parse_tmux_window_id(stdout);

        // Assert
        assert_eq!(window_id, Some("@42".to_string()));
    }

    #[test]
    fn open_window_command_builds_expected_tmux_invocation() {
        // Arrange
        let session_folder = PathBuf::from("/tmp/agentty-session");

        // Act
        let command = ProcessTmuxCommandRunner::open_window_command(session_folder.clone());
        let (program, arguments) = command_parts(&command);

        // Assert
        assert_eq!(program, "tmux");
        assert_eq!(
            arguments,
            vec![
                "new-window".to_string(),
                "-P".to_string(),
                "-F".to_string(),
                "#{window_id}".to_string(),
                "-c".to_string(),
                session_folder.to_string_lossy().into_owned(),
            ]
        );
    }

    #[test]
    fn send_literal_keys_command_builds_expected_tmux_invocation() {
        // Arrange
        let window_id = "@42".to_string();
        let command_text = "cargo test".to_string();

        // Act
        let command = ProcessTmuxCommandRunner::send_literal_keys_command(
            window_id.clone(),
            command_text.clone(),
        );
        let (program, arguments) = command_parts(&command);

        // Assert
        assert_eq!(program, "tmux");
        assert_eq!(
            arguments,
            vec![
                "send-keys".to_string(),
                "-t".to_string(),
                window_id,
                "-l".to_string(),
                command_text,
            ]
        );
    }

    #[test]
    fn send_enter_key_command_builds_expected_tmux_invocation() {
        // Arrange
        let window_id = "@42".to_string();

        // Act
        let command = ProcessTmuxCommandRunner::send_enter_key_command(window_id.clone());
        let (program, arguments) = command_parts(&command);

        // Assert
        assert_eq!(program, "tmux");
        assert_eq!(
            arguments,
            vec![
                "send-keys".to_string(),
                "-t".to_string(),
                window_id,
                "C-m".to_string(),
            ]
        );
    }

    /// Extracts one command executable and arguments for exact CLI assertions.
    fn command_parts(command: &tokio::process::Command) -> (String, Vec<String>) {
        let std_command = command.as_std();
        let program = std_command.get_program().to_string_lossy().into_owned();
        let arguments = std_command
            .get_args()
            .map(|argument| argument.to_string_lossy().into_owned())
            .collect();

        (program, arguments)
    }

    /// Builds one successful tmux subprocess output payload for tests.
    fn successful_tmux_output(stdout: &[u8]) -> TmuxCommandOutput {
        TmuxCommandOutput {
            status_success: true,
            stdout: stdout.to_vec(),
        }
    }

    /// Builds one failed tmux subprocess output payload for tests.
    fn failed_tmux_output() -> TmuxCommandOutput {
        TmuxCommandOutput {
            status_success: false,
            stdout: vec![],
        }
    }
}