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
use std::{num::NonZeroUsize, sync::Arc, time::Duration};

use pretty_assertions::assert_eq;
use rho_protocol::{
    self as wire, ContentBlock, SessionChange, SessionConfigureParams, SessionPromptParams,
};
use tempfile::TempDir;
use tokio::time::timeout;

use crate::app::daemon_host::{
    jobs::{JobRegistry, JobState, JobStore},
    sessions::{
        stopping,
        test_sessions::{load, Load},
        Hold, LoadedSession, Sessions,
    },
    wire::session_to_wire,
};
use crate::app::pull_requests::ScriptedForge;

/// Bounds each wait on an explicit signal; never the way a test syncs.
const TEST_BUDGET: Duration = Duration::from_secs(5);

/// A daemon's sessions with nothing loaded, recording jobs under `home`.
fn new_sessions(home: &TempDir) -> Arc<Sessions> {
    Sessions::new(
        Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap())),
        home.path(),
        ScriptedForge::new(),
    )
}

/// A change of `session` to plan mode, away from the config's bypass.
fn plan_mode(session: &LoadedSession) -> SessionConfigureParams {
    SessionConfigureParams {
        session: session_to_wire(session.id.clone()),
        change: SessionChange::PermissionMode {
            mode: wire::PermissionMode::Plan,
        },
    }
}

/// What clients saw, in the order they saw it.
#[derive(Debug, PartialEq)]
enum Seen {
    Options(wire::PermissionMode),
    Prompt,
}

// Covers: a change sent while the session's runtime is held, as by a turn
// that recorded its end but has not let go of it yet, queues and counts in
// the session's hold; a prompt sent meanwhile starts its turn rather than
// being refused busy, and that turn waits behind the change, so clients see
// the options change before the prompt (#1685).
// Owner: daemon session settings.
#[tokio::test]
async fn a_prompt_sent_while_a_change_waits_runs_after_it() {
    let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
    let sessions = new_sessions(&home);
    let session = load(&sessions, &root, Load::Saved).await;
    let ended_turn = session.engine.try_lock().unwrap();

    let configure = sessions.configure(plan_mode(&session));
    tokio::pin!(configure);
    // Nothing in a configure of a loaded session waits before the runtime.
    assert!(futures_util::poll!(configure.as_mut()).is_pending());
    let queued = session.turn().hold;
    let prompt = sessions.prompt(SessionPromptParams {
        author: rho_protocol::PromptAuthor::Person,
        session: session_to_wire(session.id.clone()),
        content: vec![ContentBlock::Text {
            text: "hello".into(),
        }],
        timeout_ms: None,
        environment: std::iter::empty::<(String, String)>().collect(),
        idempotency_key: None,
        grant: None,
    });
    tokio::pin!(prompt);
    // Pending until its turn, behind the change, saves the prompt.
    assert!(futures_util::poll!(prompt.as_mut()).is_pending());
    let job = sessions.jobs.get(&session.job).unwrap();
    let (started, turn) = (job.state, job.turn.map(|turn| turn.id));
    drop(ended_turn);
    let changed = timeout(TEST_BUDGET, configure)
        .await
        .expect("the change applies once the runtime is free")
        .map(|changed| changed.options.permission_mode.current);
    let prompted = timeout(TEST_BUDGET, prompt)
        .await
        .expect("the turn saves its prompt once the change applied")
        .map(|prompted| Some(prompted.response.turn));

    let seen: Vec<_> = session
        .feed
        .buffered_for_tests()
        .into_iter()
        .filter_map(|event| match event {
            wire::SessionEvent::OptionsChanged { options } => {
                Some(Seen::Options(options.permission_mode.current))
            }
            wire::SessionEvent::UserMessage { .. } => Some(Seen::Prompt),
            _ => None,
        })
        .collect();
    // The turn's model call waits for a cancel: end it before the test does.
    session.cancel_turn();
    let _ended = timeout(TEST_BUDGET, session.engine.lock())
        .await
        .expect("the cancelled turn lets go of the runtime");
    assert_eq!(
        (queued, started, changed, prompted, seen),
        (
            Some(Hold::Configuring(NonZeroUsize::MIN)),
            JobState::Running,
            Ok(wire::PermissionMode::Plan),
            // The prompt answers with the turn its job recorded.
            Ok(turn),
            vec![Seen::Options(wire::PermissionMode::Plan), Seen::Prompt],
        )
    );
}

// Covers: the daemon's stop answers a change still queued on the runtime
// `DaemonStopping` and frees its part of the session's hold, rather than
// keeping the request, and so the daemon, waiting on a turn that may
// outlive the stop's drain.
// Owner: daemon session settings.
#[tokio::test]
async fn the_stop_answers_a_queued_change() {
    let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
    let sessions = new_sessions(&home);
    let session = load(&sessions, &root, Load::Saved).await;
    let _turn = session.engine.try_lock().unwrap();
    let configure = sessions.configure(plan_mode(&session));
    tokio::pin!(configure);
    assert!(futures_util::poll!(configure.as_mut()).is_pending());

    sessions.begin_stop(rho_protocol::DetachReason::DaemonStopping);
    let answered = timeout(TEST_BUDGET, configure)
        .await
        .expect("the stop answers the change")
        .map(|_| ());

    assert_eq!((answered, session.turn().hold), (Err(stopping()), None));
}

// Covers: context a client adds between turns reaches the model's history
// as sent and joins the transcript a later attach replays as the row that
// displays it, though no turn ran to save it; it is no settings change, so
// the session goes on following the config; empty context is refused.
// Owner: daemon session settings.
#[tokio::test]
async fn added_context_reaches_the_model_and_a_later_replay() {
    let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
    let sessions = new_sessions(&home);
    let session = load(&sessions, &root, Load::Saved).await;
    let context = |text: &str| SessionConfigureParams {
        session: session_to_wire(session.id.clone()),
        change: SessionChange::Context {
            text: text.into(),
            display: "remembered in AGENTS.md".into(),
        },
    };

    let refused = sessions
        .configure(context("  "))
        .await
        .map(|_| ())
        .map_err(|error| error.code);
    let added = sessions
        .configure(context("Apply it: be brief"))
        .await
        .map(|_| ());

    let replayed: Vec<_> = session
        .feed
        .reset_replay_for_tests()
        .into_iter()
        .filter_map(|event| match event {
            wire::SessionEvent::UserMessage { content, .. } => Some(content),
            _ => None,
        })
        .collect();
    let runtime = session.engine.try_lock().unwrap();
    let runtime = runtime.as_ref().unwrap().as_rho().unwrap();
    let read_by_model = runtime
        .history_for_tests()
        .contains(&rho_sdk::model::Message::user_text("Apply it: be brief"));
    let follows_config = !runtime.keeps_settings_for_tests();
    assert_eq!(
        (refused, added, replayed, read_by_model, follows_config),
        (
            Err(wire::ErrorCode::InvalidParams.code()),
            Ok(()),
            vec![vec![ContentBlock::Text {
                text: "remembered in AGENTS.md".into(),
            }]],
            true,
            true,
        )
    );
}

// Covers: a directory a client adds between turns joins the session's
// scope, which its options report; clients attached now are told, and a
// later attach replays the row that says so. A relative path, and a
// directory the workspace already reaches, are refused.
// Owner: daemon session settings.
#[tokio::test]
async fn an_added_directory_joins_the_sessions_scope() {
    let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
    let (outside, inside) = (TempDir::new().unwrap(), root.path().join("inside"));
    std::fs::create_dir(&inside).unwrap();
    let sessions = new_sessions(&home);
    let session = load(&sessions, &root, Load::Saved).await;
    let add = |path: &std::path::Path| SessionConfigureParams {
        session: session_to_wire(session.id.clone()),
        change: SessionChange::AddDirectory { path: path.into() },
    };
    let code = |answer: Result<wire::SessionConfigureResponse, wire::RpcError>| {
        answer.map(|_| ()).map_err(|error| error.code)
    };

    let relative = code(sessions.configure(add("elsewhere".as_ref())).await);
    let covered = code(
        sessions
            .configure(add(&inside.canonicalize().unwrap()))
            .await,
    );
    let added = sessions
        .configure(add(outside.path()))
        .await
        .map(|added| added.options.added_dirs);

    let dir = outside.path().canonicalize().unwrap();
    let told: Vec<_> = session
        .feed
        .buffered_for_tests()
        .into_iter()
        .filter_map(|event| match event {
            wire::SessionEvent::Notice { text } => Some(text),
            _ => None,
        })
        .collect();
    let replayed = session
        .feed
        .reset_replay_for_tests()
        .into_iter()
        .filter(|event| matches!(event, wire::SessionEvent::UserMessage { .. }))
        .count();
    let invalid = wire::ErrorCode::InvalidParams.code();
    assert_eq!(
        (relative, covered, added, told, replayed),
        (
            Err(invalid),
            Err(invalid),
            Ok(vec![dir.clone()]),
            vec![format!("added directory {}", crate::paths::display(&dir))],
            1,
        )
    );
}

// Covers: a model change sent to follow a `/compact` applies only when the
// session's current or last prompted turn compacted; after no compaction, or
// one an earlier turn ran, it is dropped and the session keeps its model.
// The change names a model no catalog lists, so applying it is refused and
// dropping it answers with the options as they were.
// Owner: daemon session settings.
#[tokio::test]
async fn a_model_change_after_compaction_waits_for_the_last_turn_to_compact() {
    let cases = [
        ("no compaction", None, Ok(())),
        (
            "the last turn compacted",
            Some(1),
            Err(wire::ErrorCode::InvalidParams.code()),
        ),
        ("an earlier turn compacted", Some(0), Ok(())),
    ];
    for (name, compacted_prompt, expected) in cases {
        let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
        let sessions = new_sessions(&home);
        let session = load(&sessions, &root, Load::Saved).await;
        {
            let mut turn = session.turn();
            turn.prompts = 1;
            turn.compacted_prompt = compacted_prompt;
        }

        let answered = sessions
            .configure(SessionConfigureParams {
                session: session_to_wire(session.id.clone()),
                change: SessionChange::ModelAfterCompaction {
                    model: wire::ModelRef {
                        provider: "openai".into(),
                        model: "no-such-model".into(),
                    },
                    auth: None,
                },
            })
            .await
            .map(|_| ())
            .map_err(|error| error.code);

        assert_eq!(answered, expected, "{name}");
    }
}

// Covers: each part of what a person chooses for the sessions a session
// starts is set and cleared on its own, each change told to clients, and
// clearing it again tells nothing; an unknown mode, and auto while the
// config has no classifier model, which every session started in it would
// fail to open with, are refused and leave the choice as it was. Another
// runtime is chosen with one of the models it lists, a model it does not
// list or of another runtime is refused, and rho's runtime is reported as
// no runtime. None of it changes the session's own settings, which go on
// following the config.
// Owner: daemon session settings.
#[tokio::test]
async fn each_part_of_the_started_sessions_choice_changes_on_its_own() {
    let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
    let sessions = new_sessions(&home);
    let session = load(&sessions, &root, Load::Saved).await;
    // The one model the session surely runs: its own.
    let model = {
        let runtime = session.engine.try_lock().unwrap();
        let current = runtime.as_ref().unwrap().as_rho().unwrap().current_model();
        wire::ModelRef {
            provider: current.provider,
            model: current.model,
        }
    };
    let configure = |change| SessionConfigureParams {
        session: session_to_wire(session.id.clone()),
        change,
    };
    let mode = |mode| configure(SessionChange::StartedSessionPermissionMode { mode });
    let on = |runtime, model| configure(SessionChange::StartedSessionRuntime { runtime, model });
    let claude = |model: &str| wire::ModelRef {
        provider: "claude-code".to_owned(),
        model: model.to_owned(),
    };
    let invalid = Err(wire::ErrorCode::InvalidParams.code());
    // Each change, with how the daemon answers it.
    let changes = [
        (mode(Some(wire::PermissionMode::Plan)), Ok(())),
        (
            configure(SessionChange::StartedSessionModel {
                model: Some(model.clone()),
            }),
            Ok(()),
        ),
        (
            on(wire::AgentRuntime::ClaudeCli, Some(claude("opus"))),
            Ok(()),
        ),
        (
            on(
                wire::AgentRuntime::ClaudeCli,
                Some(claude("claude-unlisted")),
            ),
            invalid,
        ),
        (
            on(wire::AgentRuntime::ClaudeCli, Some(model.clone())),
            invalid,
        ),
        (on(wire::AgentRuntime::Unknown, None), invalid),
        (on(wire::AgentRuntime::Rho, Some(model.clone())), Ok(())),
        (mode(Some(wire::PermissionMode::Unknown)), invalid),
        (mode(Some(wire::PermissionMode::Auto)), invalid),
        (mode(None), Ok(())),
        (mode(None), Ok(())),
    ];
    let expected: Vec<_> = changes.iter().map(|(_, answer)| *answer).collect();

    let mut answered = Vec::new();
    for (change, _) in changes {
        let answer = sessions.configure(change).await;
        answered.push(answer.map(|_| ()).map_err(|error| error.code));
    }
    let told: Vec<_> = session
        .feed
        .buffered_for_tests()
        .into_iter()
        .filter_map(|event| match event {
            wire::SessionEvent::StartedSessionDefaults(defaults) => Some(defaults),
            _ => None,
        })
        .collect();
    let follows_config = !session
        .engine
        .try_lock()
        .unwrap()
        .as_ref()
        .unwrap()
        .as_rho()
        .unwrap()
        .keeps_settings_for_tests();
    let chosen = |permission_mode, runtime, model| wire::StartedSessionDefaults {
        permission_mode,
        runtime,
        model,
    };
    let plan = Some(wire::PermissionMode::Plan);
    let claude_code = Some(wire::AgentRuntime::ClaudeCli);
    assert_eq!(
        (answered, told, follows_config),
        (
            expected,
            vec![
                chosen(plan, None, None),
                chosen(plan, None, Some(model.clone())),
                chosen(plan, claude_code, Some(claude("opus"))),
                chosen(plan, None, Some(model.clone())),
                chosen(None, None, Some(model)),
            ],
            true,
        )
    );
}