vessel-pty 0.17.5

PTY-based runtime for orchestrating interactive terminal processes over Unix sockets
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! Test framework for agent orchestration scenarios.
//!
//! Provides ergonomic APIs for testing multi-agent TUI interactions:
//!
//! ```ignore
//! let harness = TestHarness::new().await;
//! let agent = harness.spawn(&["bash"]).await?;
//!
//! agent.send("echo hello").await?;
//! agent.wait_for_content("hello", Duration::from_secs(5)).await?;
//!
//! let snapshot = agent.snapshot().await?;
//! assert!(snapshot.contains("hello"));
//! ```

use crate::runtime::sync::Mutex;
use crate::runtime::task::JoinHandle;
use crate::runtime::time::Instant;
use crate::{Client, Request, Response, Server};
use regex::Regex;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;
use thiserror::Error;

static TEST_COUNTER: AtomicU32 = AtomicU32::new(0);

/// Errors from the test framework.
#[derive(Debug, Error)]
pub enum TestError {
    #[error("timeout waiting for condition")]
    Timeout,

    #[error("agent not found: {0}")]
    AgentNotFound(String),

    #[error("spawn failed: {0}")]
    SpawnFailed(String),

    #[error("request failed: {0}")]
    RequestFailed(String),

    #[error("server error: {0}")]
    ServerError(String),
}

/// Test harness that manages server lifecycle and provides agent spawning.
pub struct TestHarness {
    socket_path: PathBuf,
    client: Arc<Mutex<Client>>,
    server_handle: JoinHandle<()>,
}

impl TestHarness {
    /// Create a new test harness with a unique socket path.
    pub async fn new() -> Self {
        let socket_path = Self::unique_socket_path();

        // Start server in background
        let server_socket = socket_path.clone();
        let server_handle = crate::runtime::task::spawn(async move {
            let mut server = Server::new(server_socket);
            let _ = server.run().await;
        });

        // Give server time to start
        crate::runtime::time::sleep(Duration::from_millis(100)).await;

        let client = Client::new(socket_path.clone());

        Self {
            socket_path,
            client: Arc::new(Mutex::new(client)),
            server_handle,
        }
    }

    /// Generate a unique socket path for this test.
    fn unique_socket_path() -> PathBuf {
        let id = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
        let pid = std::process::id();
        PathBuf::from(format!("/tmp/vessel-test-{pid}-{id}.sock"))
    }

    /// Spawn a new agent with the given command.
    pub async fn spawn(&self, cmd: &[&str]) -> Result<AgentHandle, TestError> {
        self.spawn_with_size(cmd, 24, 80).await
    }

    /// Spawn a new agent with custom terminal size.
    pub async fn spawn_with_size(
        &self,
        cmd: &[&str],
        rows: u16,
        cols: u16,
    ) -> Result<AgentHandle, TestError> {
        let request = Request::Spawn {
            cmd: cmd.iter().map(std::string::ToString::to_string).collect(),
            rows,
            cols,
            name: None,
            labels: vec![],
            timeout: None,
            max_output: None,
            env: vec![],
            cwd: None,
            no_resize: false,
            record: false,
            memory_limit: None,
        };

        let response = self
            .client
            .lock()
            .await
            .request(request)
            .await
            .map_err(|e| TestError::RequestFailed(e.to_string()))?;

        match response {
            Response::Spawned { id, .. } => Ok(AgentHandle {
                id,
                client: Arc::clone(&self.client),
            }),
            Response::Error { message } => Err(TestError::SpawnFailed(message)),
            _ => Err(TestError::SpawnFailed("unexpected response".into())),
        }
    }

    /// List all agents.
    pub async fn list(&self) -> Result<Vec<String>, TestError> {
        let response = self
            .client
            .lock()
            .await
            .request(Request::List { labels: vec![] })
            .await
            .map_err(|e| TestError::RequestFailed(e.to_string()))?;

        match response {
            Response::Agents { agents } => Ok(agents.into_iter().map(|a| a.id).collect()),
            Response::Error { message } => Err(TestError::RequestFailed(message)),
            _ => Err(TestError::RequestFailed("unexpected response".into())),
        }
    }

    /// Get the socket path (useful for direct connections).
    #[must_use]
    pub const fn socket_path(&self) -> &PathBuf {
        &self.socket_path
    }

    /// Shutdown the server gracefully.
    pub async fn shutdown(self) {
        let _ = self.client.lock().await.request(Request::Shutdown).await;
        self.server_handle.abort();
        // Clean up socket file
        std::fs::remove_file(&self.socket_path).ok();
    }
}

impl Drop for TestHarness {
    fn drop(&mut self) {
        // Best effort cleanup
        std::fs::remove_file(&self.socket_path).ok();
    }
}

/// Handle for interacting with a spawned agent.
#[derive(Clone)]
pub struct AgentHandle {
    id: String,
    client: Arc<Mutex<Client>>,
}

impl AgentHandle {
    /// Get the agent ID.
    #[must_use]
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Send text input to the agent (with newline).
    pub async fn send(&self, text: &str) -> Result<(), TestError> {
        self.send_raw(text, true).await
    }

    /// Send text input without trailing newline.
    pub async fn send_no_newline(&self, text: &str) -> Result<(), TestError> {
        self.send_raw(text, false).await
    }

    /// Send text with explicit newline control.
    async fn send_raw(&self, text: &str, newline: bool) -> Result<(), TestError> {
        let request = Request::Send {
            id: self.id.clone(),
            data: text.to_string(),
            newline,
            enter: false,
        };

        let response = self
            .client
            .lock()
            .await
            .request(request)
            .await
            .map_err(|e| TestError::RequestFailed(e.to_string()))?;

        match response {
            Response::Ok => Ok(()),
            Response::Error { message } => {
                if message.contains("not found") {
                    Err(TestError::AgentNotFound(self.id.clone()))
                } else {
                    Err(TestError::RequestFailed(message))
                }
            }
            _ => Err(TestError::RequestFailed("unexpected response".into())),
        }
    }

    /// Send raw bytes to the agent.
    pub async fn send_bytes(&self, data: &[u8]) -> Result<(), TestError> {
        let request = Request::SendBytes {
            id: self.id.clone(),
            data: data.to_vec(),
        };

        let response = self
            .client
            .lock()
            .await
            .request(request)
            .await
            .map_err(|e| TestError::RequestFailed(e.to_string()))?;

        match response {
            Response::Ok => Ok(()),
            Response::Error { message } => Err(TestError::RequestFailed(message)),
            _ => Err(TestError::RequestFailed("unexpected response".into())),
        }
    }

    /// Get a snapshot of the agent's screen.
    pub async fn snapshot(&self) -> Result<String, TestError> {
        let request = Request::Snapshot {
            id: self.id.clone(),
            strip_colors: true,
        };

        let response = self
            .client
            .lock()
            .await
            .request(request)
            .await
            .map_err(|e| TestError::RequestFailed(e.to_string()))?;

        match response {
            Response::Snapshot { content, .. } => Ok(content),
            Response::Error { message } => {
                if message.contains("not found") {
                    Err(TestError::AgentNotFound(self.id.clone()))
                } else {
                    Err(TestError::RequestFailed(message))
                }
            }
            _ => Err(TestError::RequestFailed("unexpected response".into())),
        }
    }

    /// Wait until the screen contains the given substring.
    pub async fn wait_for_content(
        &self,
        needle: &str,
        timeout_duration: Duration,
    ) -> Result<String, TestError> {
        let deadline = Instant::now() + timeout_duration;
        let poll_interval = Duration::from_millis(50);

        while Instant::now() < deadline {
            let snapshot = self.snapshot().await?;
            if snapshot.contains(needle) {
                return Ok(snapshot);
            }
            crate::runtime::time::sleep(poll_interval).await;
        }

        Err(TestError::Timeout)
    }

    /// Wait until the screen matches the given regex pattern.
    pub async fn wait_for_pattern(
        &self,
        pattern: &str,
        timeout_duration: Duration,
    ) -> Result<String, TestError> {
        let re = Regex::new(pattern).map_err(|e| TestError::RequestFailed(e.to_string()))?;
        let deadline = Instant::now() + timeout_duration;
        let poll_interval = Duration::from_millis(50);

        while Instant::now() < deadline {
            let snapshot = self.snapshot().await?;
            if re.is_match(&snapshot) {
                return Ok(snapshot);
            }
            crate::runtime::time::sleep(poll_interval).await;
        }

        Err(TestError::Timeout)
    }

    /// Wait until the screen hasn't changed for the given duration.
    ///
    /// Useful for waiting for TUI animations/rendering to complete.
    pub async fn wait_for_stable(
        &self,
        stable_duration: Duration,
        timeout_duration: Duration,
    ) -> Result<String, TestError> {
        let deadline = Instant::now() + timeout_duration;
        let poll_interval = Duration::from_millis(50);

        let mut last_snapshot = self.snapshot().await?;
        let mut stable_since = Instant::now();

        while Instant::now() < deadline {
            crate::runtime::time::sleep(poll_interval).await;

            let current = self.snapshot().await?;
            if current == last_snapshot {
                if stable_since.elapsed() >= stable_duration {
                    return Ok(current);
                }
            } else {
                last_snapshot = current;
                stable_since = Instant::now();
            }
        }

        Err(TestError::Timeout)
    }

    /// Wait for a shell prompt (common patterns like $, >, #).
    ///
    /// This uses a heuristic pattern that matches common shell prompts.
    /// For custom prompts, use `wait_for_pattern` or `wait_for_prompt_custom`.
    pub async fn wait_for_prompt(&self, timeout_duration: Duration) -> Result<String, TestError> {
        // Common shell prompts: ends with $, #, >, or % followed by optional whitespace
        // Also matches things like "user@host:~$ " or "(venv) $ "
        self.wait_for_pattern(r"[$#>%]\s*$", timeout_duration).await
    }

    /// Wait for a custom prompt pattern.
    pub async fn wait_for_prompt_custom(
        &self,
        prompt_pattern: &str,
        timeout_duration: Duration,
    ) -> Result<String, TestError> {
        self.wait_for_pattern(prompt_pattern, timeout_duration)
            .await
    }

    /// Wait for content to NOT be present (useful for waiting for spinners/loading to finish).
    pub async fn wait_for_absence(
        &self,
        needle: &str,
        timeout_duration: Duration,
    ) -> Result<String, TestError> {
        let deadline = Instant::now() + timeout_duration;
        let poll_interval = Duration::from_millis(50);

        while Instant::now() < deadline {
            let snapshot = self.snapshot().await?;
            if !snapshot.contains(needle) {
                return Ok(snapshot);
            }
            crate::runtime::time::sleep(poll_interval).await;
        }

        Err(TestError::Timeout)
    }

    /// Check if the screen currently contains the given text.
    pub async fn contains(&self, needle: &str) -> Result<bool, TestError> {
        let snapshot = self.snapshot().await?;
        Ok(snapshot.contains(needle))
    }

    /// Kill the agent.
    pub async fn kill(&self) -> Result<(), TestError> {
        self.signal(9).await
    }

    /// Send a signal to the agent.
    pub async fn signal(&self, signal: i32) -> Result<(), TestError> {
        let request = Request::Kill {
            id: Some(self.id.clone()),
            labels: vec![],
            all: false,
            signal,
            proc_filter: None,
        };

        let response = self
            .client
            .lock()
            .await
            .request(request)
            .await
            .map_err(|e| TestError::RequestFailed(e.to_string()))?;

        match response {
            Response::Ok => Ok(()),
            Response::Error { message } => Err(TestError::RequestFailed(message)),
            _ => Err(TestError::RequestFailed("unexpected response".into())),
        }
    }
}

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

    crate::async_test! {
        async fn test_harness_spawn_and_snapshot() {
            let harness = TestHarness::new().await;

            let agent = harness
                .spawn(&["sh", "-c", "echo HARNESS_TEST; sleep 10"])
                .await
                .expect("spawn failed");

            // Wait for output
            let snapshot = agent
                .wait_for_content("HARNESS_TEST", Duration::from_secs(5))
                .await
                .expect("wait failed");

            assert!(snapshot.contains("HARNESS_TEST"));

            agent.kill().await.expect("kill failed");
            harness.shutdown().await;
        }
    }

    crate::async_test! {
        async fn test_harness_wait_for_stable() {
            let harness = TestHarness::new().await;

            // Spawn something that produces output then stops
            let agent = harness
                .spawn(&["sh", "-c", "echo LINE1; echo LINE2; sleep 10"])
                .await
                .expect("spawn failed");

            // Wait for screen to stabilize
            let snapshot = agent
                .wait_for_stable(Duration::from_millis(200), Duration::from_secs(5))
                .await
                .expect("wait failed");

            assert!(snapshot.contains("LINE1"));
            assert!(snapshot.contains("LINE2"));

            agent.kill().await.expect("kill failed");
            harness.shutdown().await;
        }
    }

    crate::async_test! {
        async fn test_harness_multiple_agents() {
            let harness = TestHarness::new().await;

            // Spawn two agents
            let agent1 = harness
                .spawn(&["sh", "-c", "echo AGENT_ONE; sleep 10"])
                .await
                .expect("spawn 1 failed");

            let agent2 = harness
                .spawn(&["sh", "-c", "echo AGENT_TWO; sleep 10"])
                .await
                .expect("spawn 2 failed");

            // Wait for both
            agent1
                .wait_for_content("AGENT_ONE", Duration::from_secs(5))
                .await
                .expect("wait 1 failed");

            agent2
                .wait_for_content("AGENT_TWO", Duration::from_secs(5))
                .await
                .expect("wait 2 failed");

            // Verify list shows both
            let agents = harness.list().await.expect("list failed");
            assert_eq!(agents.len(), 2);

            agent1.kill().await.ok();
            agent2.kill().await.ok();
            harness.shutdown().await;
        }
    }

    crate::async_test! {
        async fn test_harness_send_and_receive() {
            let harness = TestHarness::new().await;

            let agent = harness.spawn(&["bash"]).await.expect("spawn failed");

            // Wait for prompt
            crate::runtime::time::sleep(Duration::from_millis(200)).await;

            // Send command
            agent.send("echo INTERACTIVE_TEST").await.expect("send failed");

            // Wait for output
            let snapshot = agent
                .wait_for_content("INTERACTIVE_TEST", Duration::from_secs(5))
                .await
                .expect("wait failed");

            assert!(snapshot.contains("INTERACTIVE_TEST"));

            agent.kill().await.ok();
            harness.shutdown().await;
        }
    }
}