vtcode-core 0.98.7

Core library for VT Code - a Rust-based terminal coding agent
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
use std::time::Duration;

use anyhow::Result;
use portable_pty::PtySize;
use tempfile::tempdir;

use vtcode_core::config::{PtyConfig, PtyEmulationBackend};
use vtcode_core::tools::{PtyCommandRequest, PtyManager};

fn shell_command(script: &str) -> Vec<String> {
    if cfg!(windows) {
        let cmd = std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_string());
        vec![cmd, "/C".to_string(), script.to_string()]
    } else {
        vec!["sh".to_string(), "-c".to_string(), script.to_string()]
    }
}

#[tokio::test]
async fn run_pty_command_captures_output() -> Result<()> {
    let temp_dir = tempdir()?;
    let manager = PtyManager::new(temp_dir.path().to_path_buf(), PtyConfig::default());

    let working_dir = manager.resolve_working_dir(Some(".")).await?;
    let request = PtyCommandRequest {
        command: vec![
            "sh".to_string(),
            "-c".to_string(),
            "printf 'hello from pty'".to_string(),
        ],
        working_dir,
        timeout: Duration::from_secs(5),
        size: PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        },
        max_tokens: None,
        output_callback: None,
    };

    let result = manager.run_command(request).await?;
    assert_eq!(result.exit_code, 0);
    assert!(result.output.contains("hello from pty"));

    Ok(())
}

#[tokio::test]
async fn create_list_and_close_session_preserves_screen_contents() -> Result<()> {
    let temp_dir = tempdir()?;
    let manager = PtyManager::new(temp_dir.path().to_path_buf(), PtyConfig::default());

    let working_dir = manager.resolve_working_dir(Some(".")).await?;
    let size = PtySize {
        rows: 24,
        cols: 80,
        pixel_width: 0,
        pixel_height: 0,
    };

    let session_id = "session-test".to_string();
    manager.create_session(
        session_id.clone(),
        vec![
            "sh".to_string(),
            "-c".to_string(),
            "printf ready && sleep 0.1".to_string(),
        ],
        working_dir,
        size,
    )?;

    std::thread::sleep(Duration::from_millis(150));

    let sessions = manager.list_sessions();
    assert_eq!(sessions.len(), 1);
    let snapshot = &sessions[0];
    assert_eq!(snapshot.id, session_id);
    assert!(
        snapshot
            .screen_contents
            .as_deref()
            .map(|contents| contents.contains("ready"))
            .unwrap_or(false)
    );
    assert!(
        snapshot
            .scrollback
            .as_deref()
            .map(|contents| contents.contains("ready"))
            .unwrap_or(false)
    );

    let closed = manager.close_session(&session_id)?;
    assert!(
        closed
            .screen_contents
            .as_deref()
            .map(|contents| contents.contains("ready"))
            .unwrap_or(false)
    );
    assert!(
        closed
            .scrollback
            .as_deref()
            .map(|contents| contents.contains("ready"))
            .unwrap_or(false)
    );

    Ok(())
}

#[tokio::test]
async fn resolve_working_dir_rejects_missing_directory() {
    let temp_dir = tempdir().unwrap();
    let manager = PtyManager::new(temp_dir.path().to_path_buf(), PtyConfig::default());

    let error = manager.resolve_working_dir(Some("missing")).await;
    assert!(error.unwrap_err().to_string().contains("does not exist"));
}

#[tokio::test]
async fn session_input_roundtrip_and_resize() -> Result<()> {
    let temp_dir = tempdir()?;
    let config = PtyConfig {
        scrollback_lines: 200,
        ..Default::default()
    };
    let manager = PtyManager::new(temp_dir.path().to_path_buf(), config);

    let working_dir = manager.resolve_working_dir(Some(".")).await?;
    let size = PtySize {
        rows: 24,
        cols: 80,
        pixel_width: 0,
        pixel_height: 0,
    };

    let session_id = "roundtrip".to_string();
    manager.create_session(
        session_id.clone(),
        vec![
            "sh".to_string(),
            "-c".to_string(),
            "while read line; do if [ \"$line\" = \"exit\" ]; then break; fi; printf 'got:%s\\n' \"$line\"; done".to_string(),
        ],
        working_dir,
        size,
    )?;

    std::thread::sleep(Duration::from_millis(150));

    manager.send_input_to_session(&session_id, b"hello", true)?;
    std::thread::sleep(Duration::from_millis(150));

    let drained = manager.read_session_output(&session_id, true)?;
    let drained_text = drained.as_deref().expect("expected drained output");
    assert!(drained_text.contains("got:hello"));

    assert!(manager.read_session_output(&session_id, false)?.is_none());

    manager.send_input_to_session(&session_id, b"world", true)?;
    std::thread::sleep(Duration::from_millis(150));

    let peek = manager.read_session_output(&session_id, false)?;
    let peek_text = peek
        .as_deref()
        .expect("expected pending output")
        .to_string();
    assert!(peek_text.contains("got:world"));

    let drained_again = manager.read_session_output(&session_id, true)?;
    let drained_again_text = drained_again
        .as_deref()
        .expect("expected drained output after peek");
    assert!(drained_again_text.contains("got:world"));

    let updated = manager.resize_session(
        &session_id,
        PtySize {
            rows: 48,
            cols: 120,
            pixel_width: 0,
            pixel_height: 0,
        },
    )?;
    assert_eq!(updated.rows, 48);
    assert_eq!(updated.cols, 120);

    let snapshot = manager.snapshot_session(&session_id)?;
    let scrollback = snapshot
        .scrollback
        .as_deref()
        .expect("scrollback should be present");
    assert!(scrollback.contains("got:hello"));
    assert!(scrollback.contains("got:world"));

    manager.close_session(&session_id)?;

    Ok(())
}

#[tokio::test]
async fn legacy_vt100_backend_keeps_session_snapshots_working() -> Result<()> {
    let temp_dir = tempdir()?;
    let manager = PtyManager::new(
        temp_dir.path().to_path_buf(),
        PtyConfig {
            emulation_backend: PtyEmulationBackend::LegacyVt100,
            ..Default::default()
        },
    );

    let working_dir = manager.resolve_working_dir(Some(".")).await?;
    let size = PtySize {
        rows: 24,
        cols: 80,
        pixel_width: 0,
        pixel_height: 0,
    };

    let session_id = "legacy-backend".to_string();
    manager.create_session(
        session_id.clone(),
        vec![
            "sh".to_string(),
            "-c".to_string(),
            "printf legacy-ready && sleep 0.1".to_string(),
        ],
        working_dir,
        size,
    )?;

    std::thread::sleep(Duration::from_millis(150));

    let snapshot = manager.snapshot_session(&session_id)?;
    assert!(
        snapshot
            .screen_contents
            .as_deref()
            .map(|contents| contents.contains("legacy-ready"))
            .unwrap_or(false)
    );
    assert!(
        snapshot
            .scrollback
            .as_deref()
            .map(|contents| contents.contains("legacy-ready"))
            .unwrap_or(false)
    );

    manager.close_session(&session_id)?;

    Ok(())
}

#[tokio::test]
async fn ghostty_backend_falls_back_to_legacy_when_runtime_library_is_missing() -> Result<()> {
    let temp_dir = tempdir()?;
    let manager = PtyManager::new(
        temp_dir.path().to_path_buf(),
        PtyConfig {
            emulation_backend: PtyEmulationBackend::Ghostty,
            ..Default::default()
        },
    );

    let working_dir = manager.resolve_working_dir(Some(".")).await?;
    let size = PtySize {
        rows: 24,
        cols: 80,
        pixel_width: 0,
        pixel_height: 0,
    };

    let session_id = "ghostty-fallback".to_string();
    manager.create_session(
        session_id.clone(),
        vec![
            "sh".to_string(),
            "-c".to_string(),
            "printf ghostty-fallback && sleep 0.1".to_string(),
        ],
        working_dir,
        size,
    )?;

    std::thread::sleep(Duration::from_millis(150));

    let snapshot = manager.snapshot_session(&session_id)?;
    assert!(
        snapshot
            .screen_contents
            .as_deref()
            .map(|contents| contents.contains("ghostty-fallback"))
            .unwrap_or(false)
    );
    assert!(
        snapshot
            .scrollback
            .as_deref()
            .map(|contents| contents.contains("ghostty-fallback"))
            .unwrap_or(false)
    );

    manager.close_session(&session_id)?;

    Ok(())
}

#[tokio::test]
async fn run_pty_command_applies_max_tokens_truncation() -> Result<()> {
    let temp_dir = tempdir()?;
    let manager = PtyManager::new(temp_dir.path().to_path_buf(), PtyConfig::default());

    let working_dir = manager.resolve_working_dir(Some(".")).await?;
    let script = if cfg!(windows) {
        "echo 012345678901234567890123456789012345678901234567890123456789"
    } else {
        "printf '012345678901234567890123456789012345678901234567890123456789'"
    };
    let request = PtyCommandRequest {
        command: shell_command(script),
        working_dir,
        timeout: Duration::from_secs(5),
        size: PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        },
        max_tokens: Some(8),
        output_callback: None,
    };

    let result = manager.run_command(request).await?;
    assert_eq!(result.exit_code, 0);
    assert!(result.output.contains("[... truncated by max_tokens ...]"));

    Ok(())
}

#[tokio::test]
async fn run_pty_command_returns_timeout_error() -> Result<()> {
    let temp_dir = tempdir()?;
    let manager = PtyManager::new(temp_dir.path().to_path_buf(), PtyConfig::default());

    let working_dir = manager.resolve_working_dir(Some(".")).await?;
    let script = if cfg!(windows) {
        "ping -n 5 127.0.0.1 > nul"
    } else {
        "sleep 2"
    };
    let request = PtyCommandRequest {
        command: shell_command(script),
        working_dir,
        timeout: Duration::from_millis(200),
        size: PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        },
        max_tokens: None,
        output_callback: None,
    };

    let error = match manager.run_command(request).await {
        Ok(_) => anyhow::bail!("expected timeout error"),
        Err(error) => error,
    };
    let message = error.to_string();
    assert!(
        message.contains("timed out"),
        "unexpected timeout error: {message}"
    );

    Ok(())
}

#[cfg(unix)]
#[tokio::test]
async fn pty_terminate_kills_background_children_in_same_process_group() -> Result<()> {
    use nix::sys::signal::kill;
    use nix::unistd::Pid;

    let temp_dir = tempdir()?;
    let manager = PtyManager::new(temp_dir.path().to_path_buf(), PtyConfig::default());

    let working_dir = manager.resolve_working_dir(Some(".")).await?;
    let size = PtySize {
        rows: 24,
        cols: 80,
        pixel_width: 0,
        pixel_height: 0,
    };

    let session_id = "background-test".to_string();
    manager.create_session(
        session_id.clone(),
        vec![
            "sh".to_string(),
            "-c".to_string(),
            "sleep 1000 & echo \"bg_pid:$!\"; wait".to_string(),
        ],
        working_dir,
        size,
    )?;

    // Wait for the background process to be spawned and its PID to be printed
    let mut bg_pid: Option<i32> = None;
    for _ in 0..20 {
        if let Ok(Some(output)) = manager.read_session_output(&session_id, false)
            && let Some(line) = output.lines().find(|l| l.contains("bg_pid:"))
            && let Some(pid_str) = line.split(':').next_back()
            && let Ok(pid) = pid_str.trim().parse::<i32>()
        {
            bg_pid = Some(pid);
            break;
        }
        std::thread::sleep(Duration::from_millis(100));
    }

    let bg_pid = bg_pid.expect("Failed to capture background PID");
    let pid = Pid::from_raw(bg_pid);

    // Verify background process is running
    assert!(
        kill(pid, None).is_ok(),
        "Background process should be running"
    );

    // Close session, which should kill the process group
    manager.close_session(&session_id)?;

    // Verify background process is killed (may need a short wait for signal to propagate)
    let mut killed = false;
    for _ in 0..10 {
        if kill(pid, None).is_err() {
            killed = true;
            break;
        }
        std::thread::sleep(Duration::from_millis(50));
    }

    assert!(killed, "Background process should have been killed");

    Ok(())
}

#[cfg(unix)]
#[tokio::test]
async fn run_pty_command_timeout_kills_background_children() -> Result<()> {
    use nix::sys::signal::kill;
    use nix::unistd::Pid;
    use std::fs;

    let temp_dir = tempdir()?;
    let manager = PtyManager::new(temp_dir.path().to_path_buf(), PtyConfig::default());

    let working_dir = manager.resolve_working_dir(Some(".")).await?;

    // Create a temporary file to store the background PID
    let pid_file = temp_dir.path().join("bg_pid.txt");

    // Script that spawns a background process and writes its PID to a file, then sleeps
    let script = format!("sleep 1000 & echo $! > {}; sleep 5", pid_file.display());

    let request = PtyCommandRequest {
        command: vec!["sh".to_string(), "-c".to_string(), script],
        working_dir,
        timeout: Duration::from_millis(500), // Short timeout to trigger kill
        size: PtySize {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        },
        max_tokens: None,
        output_callback: None,
    };

    // run_command should timeout and kill the process group
    let result = manager.run_command(request).await;
    let err = match result {
        Ok(_) => anyhow::bail!("Expected timeout error"),
        Err(e) => e,
    };
    assert!(err.to_string().contains("timed out"));

    // Give a small amount of time for the background process to write the file if it hasn't yet
    // though the timeout is 500ms, which should be enough for 'echo $! > file'
    std::thread::sleep(Duration::from_millis(100));

    // Read the background PID
    let bg_pid_str = fs::read_to_string(&pid_file).expect("Failed to read PID file");
    let bg_pid = bg_pid_str
        .trim()
        .parse::<i32>()
        .expect("Failed to parse PID");
    let pid = Pid::from_raw(bg_pid);

    // Verify background process is killed
    let mut killed = false;
    for _ in 0..10 {
        if kill(pid, None).is_err() {
            killed = true;
            break;
        }
        std::thread::sleep(Duration::from_millis(100));
    }

    assert!(
        killed,
        "Background process should have been killed by run_command timeout"
    );

    Ok(())
}