rho-coding-agent 3.11.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
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
use std::{num::NonZeroU32, path::PathBuf, sync::Mutex, time::Duration};

use base64::Engine as _;
use futures_util::FutureExt as _;
use pretty_assertions::assert_eq;
use rho_protocol::{HostStreamEnd, HostStreamReadParams};
use tokio::sync::mpsc;

use super::*;
use crate::daemon::Ending;

/// What the stand-in installer does next.
enum Step {
    /// Says each line of the text, in one go.
    Say(String),
    End(anyhow::Result<Unattended>),
    /// Panics, as a bug in the installer would.
    Panic,
}

/// An installer the test drives a step at a time, so it can look at the
/// update while it runs. It runs one update.
struct Driven {
    steps: Mutex<Option<mpsc::UnboundedReceiver<Step>>>,
    /// What the update was told already replaced the daemon's executable.
    replaced: Mutex<Option<Option<String>>>,
}

impl Install for Driven {
    fn install<'a>(
        &'a self,
        _: ClientEnvironment,
        replaced: Option<String>,
        progress: &'a mut Progress,
    ) -> impl Future<Output = anyhow::Result<Unattended>> + Send + 'a {
        *self.replaced.lock().unwrap() = Some(replaced);
        let steps = self.steps.lock().unwrap().take();
        async move {
            let mut steps = steps.expect("the test drives one update");
            while let Some(step) = steps.recv().await {
                match step {
                    Step::Say(text) => text.lines().for_each(|line| progress.say(line)),
                    Step::End(done) => return done,
                    Step::Panic => panic!("the stand-in installer broke"),
                }
            }
            anyhow::bail!("the test stopped driving the update")
        }
    }
}

/// An update with a driven installer, of a daemon with `in_progress` work
/// a restart would cut short and a replaced executable of `replaced`'s
/// version.
struct Driving {
    updates: Updates<Driven>,
    steps: mpsc::UnboundedSender<Step>,
    shutdown: Shutdown,
}

fn driving(in_progress: u64, replaced: Option<&str>) -> Driving {
    let (steps, driven) = mpsc::unbounded_channel();
    let shutdown = Shutdown::default();
    let replaced = replaced.map(str::to_owned);
    let daemon = Daemon {
        in_progress: Arc::new(move || in_progress),
        replaced: Arc::new(move || replaced.clone()),
        shutdown: shutdown.clone(),
    };
    let install = Driven {
        steps: Mutex::new(Some(driven)),
        replaced: Mutex::default(),
    };
    Driving {
        updates: Updates::new(install, daemon),
        steps,
        shutdown,
    }
}

impl Driving {
    fn send(&self, step: Step) {
        self.steps.send(step).unwrap();
    }
}

fn caller(connection: u64, name: &str) -> Caller {
    Caller::new(
        ConnectionId::new(connection),
        ClientInfo {
            name: name.to_owned(),
            version: "0.4.0".to_owned(),
        },
    )
}

/// Starts an update for `caller`, returning its progress stream.
fn start(updates: &Updates<Driven>, caller: &Caller, restart: UpdateRestart) -> HostStreamId {
    updates
        .start(
            caller.clone(),
            DaemonUpdateParams::new(restart),
            ClientEnvironment::default(),
        )
        .unwrap()
        .progress
}

fn result_of(progress: &HostStreamId) -> DaemonUpdateResultParams {
    DaemonUpdateResultParams::new(progress.clone())
}

fn installed(lands: Lands) -> Unattended {
    Unattended::Installed {
        to: "3.11.0".to_owned(),
        method: InstallMethod::Script,
        lands,
    }
}

/// Reads `progress` from byte `offset` to its end: the text and how it
/// ended.
async fn read_to_end(
    caller: &Caller,
    progress: &HostStreamId,
    offset: u64,
) -> (String, HostStreamEnd) {
    let mut offset = offset;
    let mut bytes = Vec::new();
    loop {
        let read = caller
            .read_stream(HostStreamReadParams::new(
                progress.clone(),
                offset,
                NonZeroU32::MAX,
            ))
            .await
            .unwrap();
        let data = base64::engine::general_purpose::STANDARD
            .decode(read.data)
            .unwrap();
        offset += data.len() as u64;
        bytes.extend(data);
        if let Some(end) = read.end {
            return (String::from_utf8(bytes).unwrap(), end);
        }
    }
}

// Covers: what the installer says reaches the client while it still runs,
// not once the update is over, and the stream ends done after its last
// line.
// Owner: daemon update host calls.
#[tokio::test]
async fn progress_streams_while_the_update_runs() {
    let driving = driving(0, None);
    let asking = caller(1, "rho-ui");
    let progress = start(&driving.updates, &asking, UpdateRestart::WhenIdle);
    let said = "downloading rho 3.11.0\n";

    driving.send(Step::Say(said.to_owned()));
    let read = asking
        .read_stream(HostStreamReadParams::new(
            progress.clone(),
            0,
            NonZeroU32::MAX,
        ))
        .await
        .unwrap();
    let data = base64::engine::general_purpose::STANDARD
        .decode(&read.data)
        .unwrap();
    driving.send(Step::End(Ok(Unattended::UpToDate)));
    let answer = driving
        .updates
        .result(&asking, result_of(&progress))
        .await
        .unwrap();

    assert_eq!(
        (String::from_utf8(data).unwrap(), read.end),
        (said.to_owned(), None)
    );
    assert_eq!(answer.outcome, UpdateOutcome::UpToDate);
    assert_eq!(
        read_to_end(&asking, &progress, said.len() as u64).await,
        (String::new(), HostStreamEnd::Done)
    );
}

// Covers: one update at a time: another asked meanwhile, from another
// connection, fails with who asked for the one under way, saying whether
// it still runs or is over and waits for its result, and starts no
// installer.
// Owner: daemon update host calls.
#[tokio::test]
async fn a_second_update_meanwhile_is_refused_with_who_asked() {
    let driving = driving(0, None);
    let asking = caller(1, "rho-ui");
    let progress = start(&driving.updates, &asking, UpdateRestart::WhenIdle);
    let again = || {
        driving
            .updates
            .start(
                caller(2, "rho-cli"),
                DaemonUpdateParams::new(UpdateRestart::Now),
                ClientEnvironment::default(),
            )
            .unwrap_err()
    };

    let running = again();
    driving.send(Step::End(Ok(Unattended::UpToDate)));
    // Its stream ends as it is over.
    read_to_end(&asking, &progress, 0).await;
    let over = again();

    assert_eq!(
        [(running.code, running.message), (over.code, over.message)],
        [
            (
                ErrorCode::HostCallFailed.code(),
                "an update is already running, asked for by rho-ui 0.4.0".to_owned()
            ),
            (
                ErrorCode::HostCallFailed.code(),
                "an update is over and waits for its result, asked for by rho-ui 0.4.0".to_owned()
            ),
        ]
    );
}

// Covers: the version of a rho that already replaced the daemon's
// executable, which the upgrade watch probed, reaches the update, so it
// answers from it rather than installing again.
// Owner: daemon update host calls.
#[tokio::test]
async fn the_replacement_the_watch_probed_reaches_the_update() {
    let driving = driving(0, Some("3.11.0"));

    start(&driving.updates, &caller(1, "rho-ui"), UpdateRestart::Now);
    driving.send(Step::End(Ok(Unattended::UpToDate)));
    // The installer took its steps once it holds none.
    driving.steps.closed().await;

    assert_eq!(
        *driving.updates.install.replaced.lock().unwrap(),
        Some(Some("3.11.0".to_owned()))
    );
}

// Covers: how the daemon moves onto the rho an update installed, and what
// it tells the client, for each place it lands and restart asked: a
// restart onto rho at the daemon's path now, or once idle as the watch
// does for any replaced executable; a stop for rho at another path, now,
// or once idle naming the work it waits for, none when nothing is in
// progress.
// Owner: daemon update host calls.
#[test]
fn the_move_follows_where_rho_landed_and_the_restart_asked() {
    let at = PathBuf::from("/home/me/.local/share/mise/installs/rho/3.11.0/bin/rho");
    let named = || HostPath::new(at.to_str().unwrap());
    let another = || Lands::AtAnotherPath(at.clone());
    let cases = [
        (
            Lands::AtItsPath,
            UpdateRestart::Now,
            2,
            UpdateRestarting::Now,
            Follow::RestartNow,
        ),
        (
            Lands::AtItsPath,
            UpdateRestart::WhenIdle,
            2,
            UpdateRestarting::when_idle(2),
            Follow::Watch,
        ),
        (
            Lands::AtItsPath,
            UpdateRestart::WhenIdle,
            0,
            UpdateRestarting::when_idle(0),
            Follow::Watch,
        ),
        (
            another(),
            UpdateRestart::Now,
            2,
            UpdateRestarting::replaced(named(), None),
            Follow::Replace { once_idle: false },
        ),
        (
            another(),
            UpdateRestart::WhenIdle,
            2,
            UpdateRestarting::replaced(named(), Some(2)),
            Follow::Replace { once_idle: true },
        ),
        (
            another(),
            UpdateRestart::WhenIdle,
            0,
            UpdateRestarting::replaced(named(), None),
            Follow::Replace { once_idle: true },
        ),
    ];
    for (lands, restart, in_progress, restarting, follow) in cases {
        let case = format!("{lands:?} {restart:?} {in_progress}");
        assert_eq!(
            next_move(lands, restart, in_progress),
            (restarting, follow),
            "{case}"
        );
    }
}

// Covers: the result answers only once the update is over, with what it
// did, and until then the upgrade watch is held; an update that changed
// nothing leaves the watch as it was, and one that installed leaves it the
// move it asked for.
// Owner: daemon update host calls.
#[tokio::test]
async fn the_result_waits_for_the_update_and_holds_the_watch_until_then() {
    let cases = [
        (Unattended::UpToDate, UpdateOutcome::UpToDate, Follow::Watch),
        (
            Unattended::NeedsTerminal {
                latest: "3.11.0".to_owned(),
                command: "sudo pacman -Sy rho-coding-agent".to_owned(),
            },
            UpdateOutcome::needs_terminal("3.11.0", "sudo pacman -Sy rho-coding-agent"),
            Follow::Watch,
        ),
        (
            installed(Lands::AtItsPath),
            UpdateOutcome::installed("3.11.0", UpdateMethod::Script, UpdateRestarting::Now),
            Follow::RestartNow,
        ),
    ];
    for (done, outcome, follow) in cases {
        let driving = driving(0, None);
        let asking = caller(1, "rho-ui");
        let progress = start(&driving.updates, &asking, UpdateRestart::Now);
        let mut result = std::pin::pin!(driving.updates.result(&asking, result_of(&progress)));

        let waited = result.as_mut().now_or_never().is_none();
        let held = driving.updates.follow();
        driving.send(Step::End(Ok(done)));
        let answer = result.await.unwrap();

        assert_eq!(
            (waited, held, answer.outcome, driving.updates.follow()),
            (true, Follow::Held, outcome.clone(), follow),
            "{outcome:?}"
        );
    }
}

// Covers: a failed update answers an error that says why and ends with the
// last OUTPUT_TAIL_BYTES of its output, not its first, marked cut, and
// leaves the daemon as it was: nothing for the upgrade watch to do. The
// stream, which carried every line, ends failed with why.
// Owner: daemon update host calls.
#[tokio::test]
async fn a_failed_update_answers_why_with_the_end_of_its_output() {
    let why = "install script update command exited with exit status: 1";
    let driving = driving(0, None);
    let asking = caller(1, "rho-ui");
    let progress = start(&driving.updates, &asking, UpdateRestart::Now);
    // 100 lines of 50 bytes with their newlines: 5000 bytes, past the
    // 4 KiB the message keeps.
    let output: String = (1..=100)
        .map(|n| format!("line {n:03} {}\n", "x".repeat(40)))
        .collect();

    driving.send(Step::Say(output.clone()));
    driving.send(Step::End(Err(anyhow::anyhow!(why))));
    let error = driving
        .updates
        .result(&asking, result_of(&progress))
        .await
        .unwrap_err();

    let kept = output[output.len() - 4096..].trim();
    assert_eq!(
        (error.code, error.message),
        (
            ErrorCode::HostCallFailed.code(),
            format!(
                "could not update rho: {why}\nthe end of its output, at most 4096 bytes:\n…{kept}"
            )
        )
    );
    assert_eq!(driving.updates.follow(), Follow::Watch);
    assert_eq!(
        read_to_end(&asking, &progress, 0).await,
        (output, HostStreamEnd::failed(why))
    );
}

// Covers: a stopping daemon starts no update, and answers that it is
// stopping both to a result waiting on an update that runs, rather than
// holding the call until the transport drops it, and to one asked once its
// update is over, rather than an outcome whose move will not happen.
// Owner: daemon update host calls.
#[tokio::test]
async fn a_stopping_daemon_starts_no_update_and_answers_results_so() {
    let (running, over) = (driving(0, None), driving(0, None));
    let (waits, asks) = (caller(1, "rho-ui"), caller(2, "rho-ui"));
    let progress = start(&running.updates, &waits, UpdateRestart::Now);
    let finished = start(&over.updates, &asks, UpdateRestart::Now);
    over.send(Step::End(Ok(installed(Lands::AtItsPath))));
    // Its stream ends as it is over.
    read_to_end(&asks, &finished, 0).await;
    let mut waiting = std::pin::pin!(running.updates.result(&waits, result_of(&progress)));
    assert!(waiting.as_mut().now_or_never().is_none());

    running.shutdown.request(Ending::Stop, |_| {});
    over.shutdown.request(Ending::Stop, |_| {});
    let waited = waiting.await.unwrap_err();
    let asked = over
        .updates
        .result(&asks, result_of(&finished))
        .await
        .unwrap_err();
    let refused = running
        .updates
        .start(
            caller(3, "rho-ui"),
            DaemonUpdateParams::new(UpdateRestart::Now),
            ClientEnvironment::default(),
        )
        .unwrap_err();

    let stopping = |does: &str| {
        (
            ErrorCode::HostCallFailed.code(),
            format!("the daemon is stopping, so it {does}; ask again once it runs"),
        )
    };
    assert_eq!(
        [
            (waited.code, waited.message),
            (asked.code, asked.message),
            (refused.code, refused.message)
        ],
        [
            stopping("will not answer the update"),
            stopping("will not answer the update"),
            stopping("updates nothing"),
        ]
    );
}

// Covers: once the upgrade watch committed the daemon to a move, no update
// starts, saying why, so none runs into the restart; the watch commits, and
// claims the daemon idle, nothing while an update holds it, nor once
// updates moved on from what its check saw.
// Owner: daemon update host calls.
#[tokio::test]
async fn no_update_starts_once_the_watch_committed_to_a_move() {
    let driving = driving(0, None);
    let asking = caller(1, "rho-ui");
    let progress = start(&driving.updates, &asking, UpdateRestart::Now);
    let mut claims = 0;

    let held = driving.updates.commit(Follow::Held, || {
        claims += 1;
        true
    });
    let while_running = driving.updates.commit(Follow::Watch, || {
        claims += 1;
        true
    });
    driving.send(Step::End(Ok(installed(Lands::AtItsPath))));
    driving
        .updates
        .result(&asking, result_of(&progress))
        .await
        .unwrap();
    let stale = driving.updates.commit(Follow::Watch, || {
        claims += 1;
        true
    });
    let committed = driving.updates.commit(Follow::RestartNow, || {
        claims += 1;
        true
    });
    let refused = driving
        .updates
        .start(
            caller(2, "rho-ui"),
            DaemonUpdateParams::new(UpdateRestart::Now),
            ClientEnvironment::default(),
        )
        .unwrap_err();

    assert_eq!(
        (held, while_running, stale, committed, claims),
        (false, false, false, true, 1)
    );
    assert_eq!(
        (refused.code, refused.message.as_str()),
        (
            ErrorCode::HostCallFailed.code(),
            "the daemon is moving onto a new rho, so it starts no update; ask again once it runs"
        )
    );
}

// Covers: an update whose task ends before it is over, as a panic in the
// installer ends it, answers the result that waits for it that it stopped,
// and lets go of the slot and the upgrade watch, which would otherwise
// wait for an answer that never comes.
// Owner: daemon update host calls.
#[tokio::test]
async fn an_update_whose_task_panics_answers_and_lets_go() {
    let driving = driving(0, None);
    let asking = caller(1, "rho-ui");
    let progress = start(&driving.updates, &asking, UpdateRestart::Now);
    let mut result = std::pin::pin!(driving.updates.result(&asking, result_of(&progress)));
    assert!(result.as_mut().now_or_never().is_none());

    driving.send(Step::Panic);
    let error = result.await.unwrap_err();

    assert_eq!(
        (error.code, error.message.as_str()),
        (
            ErrorCode::HostCallFailed.code(),
            "could not update rho: the update stopped unexpectedly"
        )
    );
    assert_eq!(driving.updates.follow(), Follow::Watch);
}

// Covers: an update that installed and is over does not move the daemon
// until its result is answered, so the client hears what it did before the
// restart closes the connection; the answer then restarts it.
// Owner: daemon update host calls.
#[tokio::test]
async fn the_daemon_moves_only_once_the_result_is_answered() {
    let driving = driving(0, None);
    let asking = caller(1, "rho-ui");
    let progress = start(&driving.updates, &asking, UpdateRestart::Now);

    driving.send(Step::End(Ok(installed(Lands::AtItsPath))));
    // The stream ends as the update is over.
    let ended = read_to_end(&asking, &progress, 0).await;
    let before = driving.updates.follow();
    driving
        .updates
        .result(&asking, result_of(&progress))
        .await
        .unwrap();

    assert_eq!(ended, (String::new(), HostStreamEnd::Done));
    assert_eq!(
        (before, driving.updates.follow()),
        (Follow::Held, Follow::RestartNow)
    );
}

// Covers: when the connection that asked closes without asking for the
// result, here before the installer finished, the update still runs to its
// end and then moves the daemon onto the new rho, well before the grace an
// unasked result gets.
// Owner: daemon update host calls.
#[tokio::test(start_paused = true)]
async fn the_daemon_moves_once_the_asking_connection_leaves() {
    let driving = driving(0, None);
    let asking = caller(1, "rho-ui");
    start(&driving.updates, &asking, UpdateRestart::Now);

    // Its last caller gone, the connection's streams go, which is how it
    // leaves.
    drop(asking);
    driving.send(Step::End(Ok(installed(Lands::AtItsPath))));
    // Time is paused: this returns once the update's task waits on
    // nothing but time, a second into the grace.
    tokio::time::sleep(Duration::from_secs(1)).await;

    assert_eq!(driving.updates.follow(), Follow::RestartNow);
}

// Covers: a client that keeps its connection but never asks for the result
// holds the daemon's move only for UNASKED_RESULT_GRACE after the update is
// over; then the update settles as asked, and a late result call finds no
// update to answer.
// Owner: daemon update host calls.
#[tokio::test(start_paused = true)]
async fn an_unasked_result_settles_after_the_grace() {
    let driving = driving(0, None);
    let asking = caller(1, "rho-ui");
    let progress = start(&driving.updates, &asking, UpdateRestart::Now);
    driving.send(Step::End(Ok(installed(Lands::AtItsPath))));

    tokio::time::sleep(UNASKED_RESULT_GRACE - Duration::from_secs(1)).await;
    let within = driving.updates.follow();
    tokio::time::sleep(Duration::from_secs(2)).await;
    let after = driving.updates.follow();
    let late = driving
        .updates
        .result(&asking, result_of(&progress))
        .await
        .unwrap_err();

    assert_eq!((within, after), (Follow::Held, Follow::RestartNow));
    assert_eq!(late.code, ErrorCode::InvalidParams.code());
}

// Covers: a client that leaves the progress unread does not hold the
// update up: the stream keeps the first 1 MiB, the most a host stream
// holds unread (`BUFFER_BYTES`, private to rho-protocol), then ends
// truncated, and the update finishes and answers.
// Owner: daemon update host calls.
#[tokio::test(start_paused = true)]
async fn unread_progress_past_the_buffer_ends_truncated_without_holding_the_update() {
    let driving = driving(0, None);
    let asking = caller(1, "rho-ui");
    let progress = start(&driving.updates, &asking, UpdateRestart::WhenIdle);
    // 1 KiB with its newline: 1024 lines fill the stream, the next finds no
    // room.
    let lines = vec!["x".repeat(1023); 1100].join("\n");

    driving.send(Step::Say(lines));
    driving.send(Step::End(Ok(Unattended::UpToDate)));
    // Time is paused, so a stalled update times out at once.
    let answer = tokio::time::timeout(
        Duration::from_secs(60),
        driving.updates.result(&asking, result_of(&progress)),
    )
    .await
    .expect("the update finishes while nobody reads its progress")
    .unwrap();
    let (text, end) = read_to_end(&asking, &progress, 0).await;

    assert_eq!(answer.outcome, UpdateOutcome::UpToDate);
    assert_eq!((text.len(), end), (1 << 20, HostStreamEnd::Truncated));
}