rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
use std::{num::NonZeroU16, num::NonZeroU32, path::Path, time::Duration};

use base64::Engine as _;
use pretty_assertions::assert_eq;
#[cfg(target_os = "linux")]
use rho_protocol::methods::HostShellForegroundParams;
#[cfg(unix)]
use rho_protocol::methods::{HostShellResizeParams, ShellInputLimit, HOST_SHELL_INPUT_MAX_BYTES};
use rho_protocol::{
    methods::{
        HostPath, HostShellInputParams, HostShellOpenParams, HostStreamEnd, HostStreamId,
        HostStreamReadParams,
    },
    Caller, ClientEnvironment, ErrorCode, ShellService as _,
};

use super::super::{
    machine::Machine,
    machine_test_support::{caller, caller_on, host, machine_in},
};
use crate::pty::{QueryReply, QueryWatch};

/// Failure bound for each wait on what a shell prints. The tests
/// synchronize on the output itself, never on time; this only turns a hang
/// into a failure that shows what was printed.
const DEADLINE: Duration = Duration::from_secs(20);

/// ConPTY's query for the cursor, which it waits on before printing
/// anything, and a terminal's answer to it.
const CURSOR_QUERY: &[u8] = b"\x1b[6n";
const CURSOR_ANSWER: &[u8] = b"\x1b[1;1R";

/// A machine whose shell is `/bin/sh` in a home of its own, or on Windows
/// `cmd.exe` with the test's environment.
fn shell_machine(home: &Path) -> Machine {
    if cfg!(windows) {
        return Machine::with_environment(
            Path::new("/nonexistent/.rho"),
            ClientEnvironment::of_this_process(),
        );
    }
    let path = std::env::var("PATH").unwrap();
    machine_in(&[
        ("PATH", &path),
        ("SHELL", "/bin/sh"),
        ("HOME", home.to_str().unwrap()),
    ])
}

/// A shell opened through the machine, and what it printed so far.
struct Shell<'a> {
    machine: &'a Machine,
    caller: Caller,
    id: HostStreamId,
    printed: Vec<u8>,
    /// Answers ConPTY's cursor queries.
    queries: QueryWatch,
}

impl<'a> Shell<'a> {
    /// Opens a shell in `folder`, of 80 by 24 cells, with `GREETING=hi`.
    async fn open(machine: &'a Machine, caller: Caller, folder: &Path) -> Self {
        let variables = [("GREETING".to_owned(), "hi".to_owned())]
            .into_iter()
            .collect();
        let params = HostShellOpenParams::new(host(folder), "xterm-test", cells(80), cells(24))
            .with_variables(variables);
        let id = machine.open(caller.clone(), params).await.unwrap().shell;
        Self {
            machine,
            caller,
            id,
            printed: Vec::new(),
            queries: QueryWatch::new(vec![QueryReply {
                query: CURSOR_QUERY.to_vec(),
                reply: CURSOR_ANSWER.to_vec(),
            }]),
        }
    }

    fn type_in(&self, text: &str) {
        self.machine
            .input(
                &self.caller,
                HostShellInputParams::new(self.id.clone(), text.as_bytes()),
            )
            .unwrap();
    }

    /// Reads once, answering ConPTY's cursor queries: what the read
    /// answered, and its ending.
    async fn read(&mut self) -> Option<HostStreamEnd> {
        let params = HostStreamReadParams::new(
            self.id.clone(),
            self.printed.len() as u64,
            NonZeroU32::new(1 << 20).unwrap(),
        );
        let read = tokio::time::timeout(DEADLINE, self.caller.read_stream(params))
            .await
            .unwrap_or_else(|_| {
                panic!(
                    "the shell printed nothing more in {DEADLINE:?}; so far: {}",
                    self.text()
                )
            })
            .unwrap();
        let bytes = base64::engine::general_purpose::STANDARD
            .decode(read.data)
            .unwrap();
        self.printed.extend(&bytes);
        let replies = self.queries.replies_for(&bytes);
        if !replies.is_empty() && read.end.is_none() {
            self.machine
                .input(
                    &self.caller,
                    HostShellInputParams::new(self.id.clone(), &replies),
                )
                .unwrap();
        }
        read.end
    }

    /// Reads until the shell printed `wanted`.
    async fn wait_for(&mut self, wanted: &str) {
        while !self.text().contains(wanted) {
            let end = self.read().await;
            assert!(
                end.is_none(),
                "the shell ended {end:?} before printing {wanted:?}: {}",
                self.text()
            );
        }
    }

    /// Reads to the stream's end.
    async fn ending(&mut self) -> HostStreamEnd {
        loop {
            if let Some(end) = self.read().await {
                return end;
            }
        }
    }

    fn text(&self) -> String {
        String::from_utf8_lossy(&self.printed).into_owned()
    }
}

fn cells(count: u16) -> NonZeroU16 {
    NonZeroU16::new(count).unwrap()
}

/// What echoes `TERM` and the client's `GREETING`, then exits with 7.
fn echo_then_exit() -> [&'static str; 2] {
    if cfg!(windows) {
        ["echo %TERM% %GREETING%\r", "exit 7\r"]
    } else {
        ["echo \"$TERM $GREETING\"\r", "exit 7\r"]
    }
}

// Covers: a shell starts in its folder with the login environment, `TERM`
// and the client's variables, prints what typing into it runs, and ends
// its stream with its exit code after the last of what it printed.
// Owner: daemon host shell (ConPTY on Windows).
#[tokio::test]
async fn a_shell_runs_what_is_typed_and_ends_with_its_exit_code() {
    let home = tempfile::tempdir().unwrap();
    let machine = shell_machine(home.path());
    let mut shell = Shell::open(&machine, caller(), home.path()).await;
    let [echo, exit] = echo_then_exit();

    shell.type_in(echo);
    shell.wait_for("xterm-test hi").await;
    shell.type_in(exit);

    assert_eq!(shell.ending().await, HostStreamEnd::exited(7));
}

// Covers: a resize reaches the shell's terminal in order with what is
// typed after it, so a program asking its size then sees the new one.
// Owner: daemon host shell.
#[cfg(unix)]
#[tokio::test]
async fn a_resize_reaches_the_shells_terminal_before_later_input() {
    let home = tempfile::tempdir().unwrap();
    let machine = shell_machine(home.path());
    let mut shell = Shell::open(&machine, caller(), home.path()).await;

    machine
        .resize(
            &shell.caller,
            HostShellResizeParams::new(shell.id.clone(), cells(100), cells(30)),
        )
        .unwrap();
    shell.type_in("echo \"size: $(stty size)\"\r");

    shell.wait_for("size: 30 100").await;
}

// Covers: a shell that exits ends its stream though a job it left in the
// background still holds its terminal, as ssh ends the session, so a
// client closes the shell's pane.
// Owner: daemon host shell.
#[cfg(unix)]
#[tokio::test]
async fn a_shell_ends_on_exit_though_a_background_job_holds_its_terminal() {
    let home = tempfile::tempdir().unwrap();
    let machine = shell_machine(home.path());
    let mut shell = Shell::open(&machine, caller(), home.path()).await;

    // `$!` before a space: bash 3.2, macOS's `sh`, takes `!.` for a
    // history event and refuses the whole line.
    shell.type_in("sleep 1000 & echo job=$! ; exit 3\r");
    let end = shell.ending().await;
    let job = printed_pid(&shell.text(), "job");
    let job_ran = running(job);
    // SAFETY: kill takes no pointers; the job is this test's.
    unsafe { libc::kill(job, libc::SIGKILL) };

    assert_eq!(end, HostStreamEnd::exited(3));
    assert!(job_ran, "the job should still hold the terminal");
}

// Covers: once a shell's stream ended, the daemon lets go of its terminal,
// its reader and writer threads included, though a silent job the shell
// left still holds it: the job then finds it hung up, as when ssh closes
// it, and no thread or descriptor of the daemon's waits on the job.
// Owner: daemon host shell.
#[cfg(target_os = "linux")]
#[tokio::test]
async fn a_shell_that_ended_lets_go_of_the_terminal_a_job_it_left_holds() {
    let home = tempfile::tempdir().unwrap();
    let machine = shell_machine(home.path());
    let mut shell = Shell::open(&machine, caller(), home.path()).await;
    std::fs::write(
        home.path().join("job.sh"),
        // Outside the shell's session, so its hang-up is no signal; reads
        // the terminal raw, so no end-of-file typed into it ends the read,
        // which answers once the last copy of its master closed.
        "trap '' HUP\n\
         exec 3<>\"$1\"\n\
         stty raw -echo <&3\n\
         touch ready\n\
         cat <&3 >/dev/null\n\
         echo let-go > hung\n",
    )
    .unwrap();

    shell.type_in(
        "setsid sh job.sh \"$(tty)\" & while [ ! -e ready ]; do sleep 0.01; done; exit 4\r",
    );
    let end = shell.ending().await;
    let hung = home.path().join("hung");
    let deadline = tokio::time::Instant::now() + DEADLINE;
    while !hung.exists() {
        assert!(
            tokio::time::Instant::now() < deadline,
            "the job's terminal is still open"
        );
        tokio::time::sleep(Duration::from_millis(10)).await;
    }

    assert_eq!(end, HostStreamEnd::exited(4));
}

#[cfg(target_os = "linux")]
impl Shell<'_> {
    fn foreground(&self) -> Option<String> {
        self.machine
            .foreground(
                &self.caller,
                HostShellForegroundParams::new(self.id.clone()),
            )
            .unwrap()
            .program
    }

    /// Asks for the shell's foreground program until it is `wanted`.
    async fn wait_for_foreground(&self, wanted: &str) {
        let deadline = tokio::time::Instant::now() + DEADLINE;
        loop {
            let program = self.foreground();
            if program.as_deref() == Some(wanted) {
                return;
            }
            assert!(
                tokio::time::Instant::now() < deadline,
                "the foreground is {program:?}, not {wanted}"
            );
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    }
}

// Covers: the daemon names the program in a shell's foreground as it
// changes, a silent one included, and the shell's own at its prompt, and
// names none once the shell ended.
// Owner: daemon host shell.
#[cfg(target_os = "linux")]
#[tokio::test]
async fn the_daemon_names_the_program_in_a_shells_foreground() {
    let home = tempfile::tempdir().unwrap();
    let machine = shell_machine(home.path());
    let mut shell = Shell::open(&machine, caller(), home.path()).await;
    shell.type_in("echo \"ready$((6*7))\"\r");
    shell.wait_for("ready42").await;

    shell.wait_for_foreground("sh").await;
    shell.type_in("sleep 1000\r");
    shell.wait_for_foreground("sleep").await;
    shell.type_in("\x03");
    shell.wait_for_foreground("sh").await;
    shell.type_in("exit 0\r");
    let end = shell.ending().await;

    assert_eq!(end, HostStreamEnd::exited(0));
    assert_eq!(shell.foreground(), None);
}

/// Whether process `pid` runs; on Linux, a zombie not counted.
#[cfg(unix)]
fn running(pid: i32) -> bool {
    // SAFETY: kill with signal 0 only checks the process exists.
    let exists = unsafe { libc::kill(pid, 0) } == 0;
    let zombie = cfg!(target_os = "linux")
        && std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|stat| {
            stat.rsplit(") ")
                .next()
                .is_some_and(|rest| rest.starts_with('Z'))
        });
    exists && !zombie
}

/// The number `text` prints after `label=`.
#[cfg(unix)]
fn printed_pid(text: &str, label: &str) -> i32 {
    let marker = format!("{label}=");
    text.match_indices(&marker)
        .filter_map(|(at, _)| {
            let digits: String = text[at + marker.len()..]
                .chars()
                .take_while(char::is_ascii_digit)
                .collect();
            digits.parse().ok()
        })
        .next()
        .unwrap_or_else(|| panic!("no {marker} in {text}"))
}

// Covers: closing a shell's stream, as a closed terminal or connection
// does, hangs up on the shell and the job in its foreground: the job's
// hang-up handler gets its grace to finish, and what is left once it is
// over is killed, so nothing the shell ran outlives its terminal.
// Owner: daemon host shell.
#[cfg(unix)]
#[tokio::test]
async fn closing_a_shells_stream_hangs_up_on_the_shell_and_its_foreground_job() {
    let home = tempfile::tempdir().unwrap();
    let machine = shell_machine(home.path());
    let mut shell = Shell::open(&machine, caller(), home.path()).await;
    std::fs::write(
        home.path().join("job.sh"),
        // On SIGHUP it cleans up for 200 ms, then ignores the rest.
        "trap 'sleep 0.2; echo done > cleaned; trap \"\" HUP; sleep 1000' HUP\n\
         echo \"job=$$.\"\n\
         sleep 1000\n",
    )
    .unwrap();

    shell.type_in("echo \"shell=$$\"; sh job.sh\r");
    // Only the job's output ends its pid with `.`.
    shell.wait_for(".\r\n").await;
    let text = shell.text();
    let pids = [printed_pid(&text, "shell"), printed_pid(&text, "job")];
    assert!(pids.iter().all(|pid| running(*pid)), "{text}");
    shell.caller.close_stream(&shell.id);

    let deadline = tokio::time::Instant::now() + DEADLINE;
    while pids.iter().any(|pid| running(*pid)) {
        assert!(tokio::time::Instant::now() < deadline, "{pids:?} still run");
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    assert_eq!(
        std::fs::read_to_string(home.path().join("cleaned")).ok(),
        Some("done\n".to_owned())
    );
}

// Covers: input a shell is not reading waits in the daemon up to
// HOST_SHELL_INPUT_MAX_BYTES; input past it is refused whole, naming the
// limit and the bytes asked.
// Owner: daemon host shell.
#[cfg(unix)]
#[tokio::test]
async fn input_past_what_the_daemon_holds_unread_is_refused() {
    let home = tempfile::tempdir().unwrap();
    let machine = shell_machine(home.path());
    let mut shell = Shell::open(&machine, caller(), home.path()).await;
    shell.type_in("echo \"ready$((6*7))\"; sleep 1000\r");
    shell.wait_for("ready42").await;
    let paste = vec![b'x'; HOST_SHELL_INPUT_MAX_BYTES as usize];
    let input = |bytes: &[u8]| {
        machine.input(
            &shell.caller,
            HostShellInputParams::new(shell.id.clone(), bytes),
        )
    };

    let first = input(&paste);
    let second = input(&paste).unwrap_err();
    shell.caller.close_stream(&shell.id);

    assert!(first.is_ok(), "{first:?}");
    assert_eq!(second.error_code(), Some(ErrorCode::ShellInputFull));
    assert_eq!(
        second.data,
        Some(
            serde_json::to_value(ShellInputLimit::new(
                HOST_SHELL_INPUT_MAX_BYTES,
                u64::from(HOST_SHELL_INPUT_MAX_BYTES)
            ))
            .unwrap()
        )
    );
}

// Covers: stream ids repeat across connections, and what one connection
// types reaches only its own shell; another stream of it, such as a
// file's, is no shell, while a shell that ended takes input and does
// nothing.
// Owner: daemon host shell.
#[tokio::test]
async fn input_reaches_only_the_shell_of_its_own_connection() {
    let home = tempfile::tempdir().unwrap();
    let machine = shell_machine(home.path());
    let mut mine = Shell::open(&machine, caller_on(1), home.path()).await;
    let mut theirs = Shell::open(&machine, caller_on(2), home.path()).await;
    assert_eq!(mine.id, theirs.id);
    let [_, exit] = echo_then_exit();

    mine.type_in("echo mine\r");
    theirs.type_in(exit);
    let their_end = theirs.ending().await;
    mine.wait_for("mine").await;
    let file = theirs.caller.open_stream().unwrap();
    let not_a_shell = machine
        .input(
            &theirs.caller,
            HostShellInputParams::new(file.id().clone(), b"x"),
        )
        .unwrap_err();
    let after_exit = machine.input(
        &theirs.caller,
        HostShellInputParams::new(theirs.id.clone(), b"x"),
    );
    mine.caller.close_stream(&mine.id);

    assert_eq!(their_end, HostStreamEnd::exited(7));
    assert!(!theirs.text().contains("mine"), "{}", theirs.text());
    assert_eq!(not_a_shell.error_code(), Some(ErrorCode::InvalidParams));
    assert!(after_exit.is_ok(), "{after_exit:?}");
}

// Covers: a shell asked for in a relative folder is refused as the
// client's mistake, and one in a folder that is not there as the
// machine's.
// Owner: daemon host shell.
#[tokio::test]
async fn a_shell_outside_a_folder_does_not_start() {
    let home = tempfile::tempdir().unwrap();
    let machine = shell_machine(home.path());
    let missing = home.path().join("missing");
    let caller = caller();

    let mut refused = Vec::new();
    for folder in [HostPath::new("relative"), host(&missing)] {
        let params = HostShellOpenParams::new(folder, "xterm", cells(80), cells(24));
        refused.push(
            machine
                .open(caller.clone(), params)
                .await
                .unwrap_err()
                .error_code(),
        );
    }

    assert_eq!(
        refused,
        [
            Some(ErrorCode::InvalidParams),
            Some(ErrorCode::HostCallFailed)
        ]
    );
}