atm-tmux 0.2.3

Tmux CLI wrapper for the Agent Tmux Manager
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
//! Mock tmux client for testing.
//!
//! Records all method calls and returns configurable results.

use std::sync::{Arc, Mutex};

use async_trait::async_trait;

use crate::{PaneDirection, PaneInfo, TmuxClient, TmuxError};

/// A recorded call to the mock tmux client.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MockCall {
    SplitWindow {
        target: String,
        size: String,
        direction: PaneDirection,
        command: Option<String>,
    },
    NewWindow {
        session: String,
        command: Option<String>,
    },
    KillPane {
        pane: String,
    },
    ResizePane {
        pane: String,
        width: Option<u16>,
        height: Option<u16>,
    },
    SendKeys {
        pane: String,
        keys: String,
    },
    ListPanes,
    DisplayPopup {
        width: String,
        height: String,
        command: String,
    },
    SelectPane {
        pane: String,
    },
    CapturePane {
        pane: String,
    },
    NewSession {
        name: String,
    },
    GetPaneCwd {
        pane: String,
    },
}

/// Mock tmux client that records calls for test verification.
///
/// Thread-safe via `Arc<Mutex<_>>` interior mutability so it satisfies
/// `Send + Sync` required by `TmuxClient`.
///
/// # Example
///
/// ```no_run
/// use atm_tmux::{MockTmuxClient, PaneDirection, TmuxClient};
/// use atm_tmux::mock::MockCall;
///
/// # async fn example() {
/// let mock = MockTmuxClient::new();
/// mock.set_next_pane_id("%10");
///
/// let pane_id = mock.split_window("%5", "30%", PaneDirection::Below, None).await.unwrap();
/// assert_eq!(pane_id, "%10");
///
/// let calls = mock.calls();
/// assert_eq!(calls.len(), 1);
/// assert!(matches!(&calls[0], MockCall::SplitWindow { target, .. } if target == "%5"));
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct MockTmuxClient {
    inner: Arc<Mutex<MockState>>,
}

#[derive(Debug)]
struct MockState {
    calls: Vec<MockCall>,
    /// Queue of pane IDs returned by split_window/new_window.
    /// Pops from front. Falls back to "%99" when empty.
    pane_id_queue: Vec<String>,
    /// Panes returned by list_panes.
    panes: Vec<PaneInfo>,
    /// Content returned by capture_pane, keyed by pane ID.
    pane_content: std::collections::HashMap<String, Vec<String>>,
    /// Working directory returned by get_pane_cwd, keyed by pane ID.
    pane_cwd: std::collections::HashMap<String, String>,
    /// If set, the next call will return this error.
    next_error: Option<TmuxError>,
}

impl MockTmuxClient {
    /// Creates a new mock with empty state.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(MockState {
                calls: Vec::new(),
                pane_id_queue: Vec::new(),
                panes: Vec::new(),
                pane_content: std::collections::HashMap::new(),
                pane_cwd: std::collections::HashMap::new(),
                next_error: None,
            })),
        }
    }

    /// Queues a pane ID to be returned by the next `split_window` or `new_window` call.
    pub fn set_next_pane_id(&self, pane_id: &str) {
        if let Ok(mut state) = self.inner.lock() {
            state.pane_id_queue.push(pane_id.to_string());
        }
    }

    /// Sets the panes returned by `list_panes`.
    pub fn set_panes(&self, panes: Vec<PaneInfo>) {
        if let Ok(mut state) = self.inner.lock() {
            state.panes = panes;
        }
    }

    /// Sets the content returned by `capture_pane` for a specific pane.
    pub fn set_pane_content(&self, pane: &str, content: Vec<String>) {
        if let Ok(mut state) = self.inner.lock() {
            state.pane_content.insert(pane.to_string(), content);
        }
    }

    /// Sets the working directory returned by `get_pane_cwd` for a specific pane.
    pub fn set_pane_cwd(&self, pane: &str, cwd: &str) {
        if let Ok(mut state) = self.inner.lock() {
            state.pane_cwd.insert(pane.to_string(), cwd.to_string());
        }
    }

    /// Makes the next call return an error.
    pub fn set_next_error(&self, error: TmuxError) {
        if let Ok(mut state) = self.inner.lock() {
            state.next_error = Some(error);
        }
    }

    /// Returns all recorded calls.
    pub fn calls(&self) -> Vec<MockCall> {
        self.inner
            .lock()
            .map(|state| state.calls.clone())
            .unwrap_or_default()
    }

    /// Returns the number of recorded calls.
    pub fn call_count(&self) -> usize {
        self.inner
            .lock()
            .map(|state| state.calls.len())
            .unwrap_or(0)
    }

    /// Clears all recorded calls.
    pub fn clear_calls(&self) {
        if let Ok(mut state) = self.inner.lock() {
            state.calls.clear();
        }
    }

    /// Records a call and checks for a queued error.
    fn record(&self, call: MockCall) -> Result<(), TmuxError> {
        if let Ok(mut state) = self.inner.lock() {
            state.calls.push(call);
            if let Some(err) = state.next_error.take() {
                return Err(err);
            }
        }
        Ok(())
    }

    /// Pops the next pane ID from the queue, defaulting to "%99".
    fn next_pane_id(&self) -> String {
        self.inner
            .lock()
            .ok()
            .and_then(|mut state| {
                if state.pane_id_queue.is_empty() {
                    None
                } else {
                    Some(state.pane_id_queue.remove(0))
                }
            })
            .unwrap_or_else(|| "%99".to_string())
    }
}

impl Default for MockTmuxClient {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl TmuxClient for MockTmuxClient {
    async fn split_window(
        &self,
        target: &str,
        size: &str,
        direction: PaneDirection,
        command: Option<&str>,
    ) -> Result<String, TmuxError> {
        let pane_id = self.next_pane_id();
        self.record(MockCall::SplitWindow {
            target: target.to_string(),
            size: size.to_string(),
            direction,
            command: command.map(|s| s.to_string()),
        })?;
        Ok(pane_id)
    }

    async fn new_window(&self, session: &str, command: Option<&str>) -> Result<String, TmuxError> {
        let pane_id = self.next_pane_id();
        self.record(MockCall::NewWindow {
            session: session.to_string(),
            command: command.map(|s| s.to_string()),
        })?;
        Ok(pane_id)
    }

    async fn kill_pane(&self, pane: &str) -> Result<(), TmuxError> {
        self.record(MockCall::KillPane {
            pane: pane.to_string(),
        })
    }

    async fn resize_pane(
        &self,
        pane: &str,
        width: Option<u16>,
        height: Option<u16>,
    ) -> Result<(), TmuxError> {
        self.record(MockCall::ResizePane {
            pane: pane.to_string(),
            width,
            height,
        })
    }

    async fn send_keys(&self, pane: &str, keys: &str) -> Result<(), TmuxError> {
        self.record(MockCall::SendKeys {
            pane: pane.to_string(),
            keys: keys.to_string(),
        })
    }

    async fn list_panes(&self) -> Result<Vec<PaneInfo>, TmuxError> {
        self.record(MockCall::ListPanes)?;
        let panes = self
            .inner
            .lock()
            .map(|state| state.panes.clone())
            .unwrap_or_default();
        Ok(panes)
    }

    async fn display_popup(
        &self,
        width: &str,
        height: &str,
        command: &str,
    ) -> Result<(), TmuxError> {
        self.record(MockCall::DisplayPopup {
            width: width.to_string(),
            height: height.to_string(),
            command: command.to_string(),
        })
    }

    async fn select_pane(&self, pane: &str) -> Result<(), TmuxError> {
        self.record(MockCall::SelectPane {
            pane: pane.to_string(),
        })
    }

    async fn capture_pane(&self, pane: &str) -> Result<Vec<String>, TmuxError> {
        self.record(MockCall::CapturePane {
            pane: pane.to_string(),
        })?;
        let content = self
            .inner
            .lock()
            .ok()
            .and_then(|state| state.pane_content.get(pane).cloned())
            .unwrap_or_default();
        Ok(content)
    }

    async fn new_session(&self, name: &str) -> Result<String, TmuxError> {
        let pane_id = self.next_pane_id();
        self.record(MockCall::NewSession {
            name: name.to_string(),
        })?;
        Ok(pane_id)
    }

    async fn get_pane_cwd(&self, pane: &str) -> Result<Option<String>, TmuxError> {
        self.record(MockCall::GetPaneCwd {
            pane: pane.to_string(),
        })?;
        let cwd = self
            .inner
            .lock()
            .ok()
            .and_then(|state| state.pane_cwd.get(pane).cloned());
        Ok(cwd)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_mock_records_calls() {
        let mock = MockTmuxClient::new();
        mock.set_next_pane_id("%10");

        let pane_id = mock
            .split_window("%5", "30%", PaneDirection::Below, Some("claude"))
            .await
            .unwrap();
        assert_eq!(pane_id, "%10");

        mock.kill_pane("%10").await.unwrap();
        mock.send_keys("%5", "hello").await.unwrap();

        let calls = mock.calls();
        assert_eq!(calls.len(), 3);
        assert!(matches!(
            &calls[0],
            MockCall::SplitWindow {
                target,
                direction: PaneDirection::Below,
                ..
            } if target == "%5"
        ));
        assert!(matches!(&calls[1], MockCall::KillPane { pane } if pane == "%10"));
        assert!(matches!(&calls[2], MockCall::SendKeys { keys, .. } if keys == "hello"));
    }

    #[tokio::test]
    async fn test_mock_default_pane_id() {
        let mock = MockTmuxClient::new();
        let pane_id = mock
            .split_window("%1", "50%", PaneDirection::Right, None)
            .await
            .unwrap();
        assert_eq!(pane_id, "%99");
    }

    #[tokio::test]
    async fn test_mock_pane_id_queue() {
        let mock = MockTmuxClient::new();
        mock.set_next_pane_id("%10");
        mock.set_next_pane_id("%11");

        let p1 = mock
            .split_window("%1", "50%", PaneDirection::Right, None)
            .await
            .unwrap();
        let p2 = mock.new_window("sess", None).await.unwrap();
        let p3 = mock
            .split_window("%1", "50%", PaneDirection::Right, None)
            .await
            .unwrap();

        assert_eq!(p1, "%10");
        assert_eq!(p2, "%11");
        assert_eq!(p3, "%99"); // exhausted queue
    }

    #[tokio::test]
    async fn test_mock_error_injection() {
        let mock = MockTmuxClient::new();
        mock.set_next_error(TmuxError::PaneNotFound("%999".to_string()));

        let result = mock.kill_pane("%999").await;
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), TmuxError::PaneNotFound(p) if p == "%999"));

        // Next call should succeed (error was consumed)
        let result = mock.kill_pane("%5").await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_mock_list_panes() {
        let mock = MockTmuxClient::new();
        mock.set_panes(vec![
            PaneInfo {
                pane_id: "%1".to_string(),
                session_name: "main".to_string(),
                window_index: 0,
                pane_pid: 1234,
                width: 80,
                height: 24,
                is_active: true,
            },
            PaneInfo {
                pane_id: "%2".to_string(),
                session_name: "main".to_string(),
                window_index: 0,
                pane_pid: 5678,
                width: 80,
                height: 24,
                is_active: false,
            },
        ]);

        let panes = mock.list_panes().await.unwrap();
        assert_eq!(panes.len(), 2);
        assert_eq!(panes[0].pane_id, "%1");
        assert!(panes[0].is_active);
    }

    #[tokio::test]
    async fn test_mock_clear_calls() {
        let mock = MockTmuxClient::new();
        mock.select_pane("%1").await.unwrap();
        assert_eq!(mock.call_count(), 1);

        mock.clear_calls();
        assert_eq!(mock.call_count(), 0);
    }

    #[tokio::test]
    async fn test_mock_display_popup() {
        let mock = MockTmuxClient::new();
        mock.display_popup("80%", "60%", "atm").await.unwrap();

        let calls = mock.calls();
        assert_eq!(calls.len(), 1);
        assert!(matches!(
            &calls[0],
            MockCall::DisplayPopup { command, .. } if command == "atm"
        ));
    }

    #[tokio::test]
    async fn test_mock_resize_pane() {
        let mock = MockTmuxClient::new();
        mock.resize_pane("%5", Some(120), None).await.unwrap();

        let calls = mock.calls();
        assert!(matches!(
            &calls[0],
            MockCall::ResizePane {
                pane,
                width: Some(120),
                height: None,
            } if pane == "%5"
        ));
    }
}