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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
//! Sessions another session starts (#1714): the daemon records the job
//! writing the starting session as the new session's parent, and the new
//! session's turns wait for capacity in the daemon-wide agent budget, as
//! subagent runs do. A new session opens in the permission mode and on the
//! model a person chose for the sessions its parent starts, and keeps that
//! choice for the sessions it starts.

use pretty_assertions::assert_eq;
use rho_protocol::{
    methods::{JobList, SessionCancel, SessionConfigure, SessionList, SessionNew},
    AgentRuntime, Budget, ChildInfo, ChildRole, Client, JobListParams, JobState, JobSummary,
    PermissionMode, QueuePlace, SessionCancelParams, SessionChange, SessionConfigureParams,
    SessionEvent, SessionId, SessionListParams, SessionNewParams, SessionNewResponse,
    SessionOptions, SessionSetup, StartedSessionDefaults,
};

use super::sessions::{answer, blue, settled, settled_job, Follower, Sandbox};

/// A `tool-call` fixture prompt that runs bash until `go` exists in its
/// workspace.
fn blocked() -> serde_json::Value {
    serde_json::json!({
        "id": "bash",
        "name": "bash",
        "arguments": {"command": "while [ ! -e go ]; do sleep 0.02; done"},
    })
}

/// Opens a session in the workspace that `parent` starts.
async fn start_child(sandbox: &Sandbox, client: &Client, parent: &SessionId) -> SessionId {
    open_child(sandbox, client, parent).await.session
}

/// Opens a session in the workspace that `parent` starts; the daemon's
/// answer.
async fn open_child(sandbox: &Sandbox, client: &Client, parent: &SessionId) -> SessionNewResponse {
    client
        .request::<SessionNew>(&SessionNewParams {
            cwd: sandbox.workspace.clone(),
            environment: sandbox.client_environment(),
            agent: None,
            setup: SessionSetup::default(),
            parent: Some(parent.clone()),
            grant: None,
            worktree: false,
        })
        .await
        .unwrap()
}

/// Applies `change` to `session`; its options then.
async fn configure(client: &Client, session: &SessionId, change: SessionChange) -> SessionOptions {
    client
        .request::<SessionConfigure>(&SessionConfigureParams {
            session: session.clone(),
            change,
        })
        .await
        .unwrap()
        .options
}

/// Attaches to `session`: its options, and the event its reset replay
/// sends right after the agent it runs as.
async fn attached(
    sandbox: &Sandbox,
    session: &SessionId,
) -> (SessionOptions, Option<SessionEvent>) {
    let (mut follower, attached) = Follower::attach(sandbox, session, Vec::new(), None).await;
    follower
        .read_until(|event| !matches!(event, SessionEvent::Agent { .. }))
        .await;
    let after_agent = follower.events.pop().map(|(_, event)| event);
    (attached.options, after_agent)
}

/// The job of `session`'s turns, as `rho/job/list` reports it now.
async fn job_of(client: &Client, session: &SessionId) -> JobSummary {
    client
        .request::<JobList>(&JobListParams {})
        .await
        .unwrap()
        .jobs
        .into_iter()
        .find(|job| job.session.as_ref() == Some(session))
        .expect("the daemon lists the session's job")
}

// Covers: the sessions a session starts are child jobs of its job, and
// their turns queue on `behavior.agent_concurrency` in the order they were
// prompted, each prompt answering once its turn queued: one runs, the next
// waits first in line, a queued turn cancelled ends `cancelled` without
// running, and the waiting turn runs once the running one frees its slot.
// Owner: daemon session jobs and the shared agent budget.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn sessions_a_session_starts_are_its_children_and_share_the_agent_budget() {
    let sandbox = Sandbox::new();
    sandbox.set_config("bypass", "agent_concurrency = 1\n");
    let client = sandbox.start_daemon("tool-call").await;
    let parent = sandbox.new_session(&client).await;
    let [running, waiting, cancelled] = [
        start_child(&sandbox, &client, &parent).await,
        start_child(&sandbox, &client, &parent).await,
        start_child(&sandbox, &client, &parent).await,
    ];
    for child in [&running, &waiting, &cancelled] {
        sandbox.prompt_tool_call(&client, child, &blocked()).await;
    }
    let queued = sandbox
        .poll_until("the first turn to run", async || {
            let jobs = [
                job_of(&client, &running).await,
                job_of(&client, &waiting).await,
                job_of(&client, &cancelled).await,
            ];
            (jobs[0].state == JobState::Running).then_some(jobs)
        })
        .await;
    let parent_job = job_of(&client, &parent).await.id;
    let place = |position| {
        Some(QueuePlace {
            budget: Budget::AgentConcurrency,
            limit: 1,
            position,
        })
    };
    // A session opened with no agent named runs as the default agent, and
    // shows as its prompt from the moment it queues, cut at a word to 80
    // characters.
    let started = || {
        Some(
            ChildInfo::new(ChildRole::Started)
                .running_as("default", AgentRuntime::Rho)
                .titled(
                    r#"{"id":"bash","name":"bash","arguments":{"command":"while [ ! -e go ]; do sleep…"#
                        .to_owned(),
                ),
        )
    };
    assert_eq!(
        queued.map(|job| (job.parent, job.child, job.state, job.queue)),
        [
            (Some(parent_job.clone()), started(), JobState::Running, None),
            (
                Some(parent_job.clone()),
                started(),
                JobState::Queued,
                place(1)
            ),
            (
                Some(parent_job.clone()),
                started(),
                JobState::Queued,
                place(2)
            ),
        ],
        "log:\n{}",
        sandbox.isolated.daemon_log()
    );

    client
        .request::<SessionCancel>(&SessionCancelParams {
            session: cancelled.clone(),
        })
        .await
        .unwrap();
    let withdrawn = settled_job(&sandbox, &client, &cancelled).await;
    let still_waiting = job_of(&client, &waiting).await;
    std::fs::write(sandbox.workspace.join("go"), "").unwrap();
    let ended = [
        settled_job(&sandbox, &client, &running).await,
        settled_job(&sandbox, &client, &waiting).await,
    ];
    assert_eq!(
        (
            (withdrawn.state, withdrawn.queue),
            (still_waiting.state, still_waiting.queue),
            ended.map(|job| (job.state, job.queue)),
        ),
        (
            (JobState::Cancelled, None),
            (JobState::Queued, place(1)),
            [(JobState::Completed, None), (JobState::Completed, None)],
        ),
        "log:\n{}",
        sandbox.isolated.daemon_log()
    );
}

// Covers: a session a `sessions new` call starts shows in the job list as
// the first line of its prompt, as plain text, until it is titled, and
// keeps it when no title lands; the session list labels it with its first
// message as plain text too. A miss lists the child untitled, so clients
// fall back to the raw prompt, Markdown and all.
// Owner: daemon session jobs, session catalog.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_started_session_shows_its_prompts_plain_first_line_until_titled() {
    let sandbox = Sandbox::new();
    // Its title model titles no first message holding
    // `fixture-untitled-session`.
    let client = sandbox.start_titling_daemon("tool-call").await;
    let parent = sandbox.new_session(&client).await;
    let prompt = "# Fix the **parser** in `lexer.rs`\n\nSee [the issue](https://example.com/1). \
                  fixture-untitled-session";
    let start = serde_json::json!({
        "id": "start",
        "name": "sessions",
        "arguments": {"action": "new", "workspace": sandbox.workspace, "prompt": prompt},
    });
    sandbox.prompt_tool_call(&client, &parent, &start).await;
    let parent_job = settled_job(&sandbox, &client, &parent).await.id;
    let started = settled(&sandbox, &client, |job| {
        job.parent.as_ref() == Some(&parent_job)
            && job.child.as_ref().map(|child| child.role) == Some(ChildRole::Started)
    })
    .await;
    let session = started.session.clone().expect("a session job");
    let listed = client
        .request::<SessionList>(&SessionListParams::default())
        .await
        .unwrap()
        .sessions
        .into_iter()
        .find(|summary| summary.session == session)
        .and_then(|summary| summary.first_user_message);

    assert_eq!(
        (started.child.and_then(|child| child.title), listed),
        (
            Some("Fix the parser in lexer.rs".to_owned()),
            Some("Fix the parser in lexer.rs See the issue. fixture-untitled-session".to_owned()),
        ),
        "log:\n{}",
        sandbox.isolated.daemon_log()
    );
}

// Covers: a started session's turn lends its slot while subagents it started
// are under way, so with a one-slot budget its subagent runs and the turn,
// which waits for that subagent's result, completes instead of holding the
// only slot its child needs (#1714).
// Owner: daemon shared agent budget, started-session turns.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_started_session_lends_its_slot_to_the_subagents_it_waits_on() {
    let sandbox = Sandbox::new();
    sandbox.set_config("bypass", "agent_concurrency = 1\n");
    let client = sandbox.start_daemon("tool-call").await;
    let parent = sandbox.new_session(&client).await;
    let child = start_child(&sandbox, &client, &parent).await;
    let delegate = serde_json::json!({
        "id": "delegate",
        "name": "agent",
        "arguments": {"agent_id": "explorer", "prompt": "Look around."},
    });

    sandbox.prompt_tool_call(&client, &child, &delegate).await;
    let ended = settled_job(&sandbox, &client, &child).await;
    let subagent = client
        .request::<JobList>(&JobListParams {})
        .await
        .unwrap()
        .jobs
        .into_iter()
        .find(|job| job.parent.as_ref() == Some(&ended.id))
        .map(|job| job.state);

    assert_eq!(
        (ended.state, subagent),
        (JobState::Completed, Some(JobState::Completed)),
        "log:\n{}",
        sandbox.isolated.daemon_log()
    );
}

// Covers: a started session's turn that lent its slot to a subagent it
// started takes a slot again before its next model request: with a one-slot
// budget, while the subagent runs, the turn's job is `queued` again, first
// in line, and the turn ends once the subagent frees the slot.
// Owner: daemon shared agent budget, started-session model requests.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_started_sessions_model_request_waits_for_a_slot() {
    let sandbox = Sandbox::new();
    sandbox.set_config("bypass", "agent_concurrency = 1\n");
    let client = sandbox.start_daemon("tool-call").await;
    let parent = sandbox.new_session(&client).await;
    let child = start_child(&sandbox, &client, &parent).await;
    let delegate = serde_json::json!({
        "id": "delegate",
        "name": "agent",
        "arguments": {"agent_id": "default", "prompt": blocked().to_string()},
    });

    sandbox.prompt_tool_call(&client, &child, &delegate).await;
    let waiting = sandbox
        .poll_until(
            "the turn to wait for a slot while its subagent runs",
            async || {
                let jobs = client
                    .request::<JobList>(&JobListParams {})
                    .await
                    .unwrap()
                    .jobs;
                let turn = jobs
                    .iter()
                    .find(|job| job.session.as_ref() == Some(&child))?;
                let subagent = jobs
                    .iter()
                    .find(|job| job.parent.as_ref() == Some(&turn.id))?;
                (subagent.state == JobState::Running && turn.state == JobState::Queued)
                    .then_some(turn.queue)
            },
        )
        .await;
    std::fs::write(sandbox.workspace.join("go"), "").unwrap();
    let ended = settled_job(&sandbox, &client, &child).await;

    assert_eq!(
        (waiting, ended.state),
        (
            Some(QueuePlace {
                budget: Budget::AgentConcurrency,
                limit: 1,
                position: 1,
            }),
            JobState::Completed,
        ),
        "log:\n{}",
        sandbox.isolated.daemon_log()
    );
}

// Covers: a subagent waiting for an answer to its question gives its slot
// back, so with a one-slot budget another started session runs meanwhile;
// once answered, the subagent waits first in line for the slot that session
// holds, its job queued with its place, and both sessions complete.
// Owner: daemon shared agent budget, subagent questions.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_subagent_waiting_for_an_answer_gives_its_slot_back() {
    let sandbox = Sandbox::new();
    sandbox.set_config("bypass", "agent_concurrency = 1\n");
    let client = sandbox.start_daemon("tool-call").await;
    let parent = sandbox.new_session(&client).await;
    let [asking, other] = [
        start_child(&sandbox, &client, &parent).await,
        start_child(&sandbox, &client, &parent).await,
    ];
    let ask = serde_json::json!({
        "id": "ask",
        "name": "questionnaire",
        "arguments": {
            "questions": [{
                "id": "color",
                "question": "Which color?",
                "choices": ["Red", "Blue"],
            }],
        },
    });
    let delegate = serde_json::json!({
        "id": "delegate",
        "name": "agent",
        "arguments": {"agent_id": "default", "prompt": ask.to_string()},
    });

    sandbox.prompt_tool_call(&client, &asking, &delegate).await;
    let request = sandbox
        .poll_until("the subagent to ask", async || {
            job_of(&client, &asking)
                .await
                .live?
                .inputs
                .first()
                .map(|input| input.id)
        })
        .await;
    sandbox.prompt_tool_call(&client, &other, &blocked()).await;
    sandbox
        .poll_until("the other session to take the slot", async || {
            (job_of(&client, &other).await.state == JobState::Running).then_some(())
        })
        .await;
    answer(&client, &asking, request, blue()).await.unwrap();
    let requeued = sandbox
        .poll_until("the answered subagent to wait for the slot", async || {
            let jobs = client
                .request::<JobList>(&JobListParams {})
                .await
                .unwrap()
                .jobs;
            let turn = jobs
                .iter()
                .find(|job| job.session.as_ref() == Some(&asking))?;
            let subagent = jobs
                .iter()
                .find(|job| job.parent.as_ref() == Some(&turn.id))?;
            (subagent.state == JobState::Queued).then_some(subagent.queue)
        })
        .await;
    std::fs::write(sandbox.workspace.join("go"), "").unwrap();
    let ended = [
        settled_job(&sandbox, &client, &other).await.state,
        settled_job(&sandbox, &client, &asking).await.state,
    ];

    assert_eq!(
        (requeued, ended),
        (
            Some(QueuePlace {
                budget: Budget::AgentConcurrency,
                limit: 1,
                position: 1,
            }),
            [JobState::Completed, JobState::Completed],
        ),
        "log:\n{}",
        sandbox.isolated.daemon_log()
    );
}

// Covers: a started session's turn waiting for a person lends its slot, so
// with a one-slot budget another started session runs meanwhile, while the
// first still waits for its answer (#1714).
// Owner: daemon shared agent budget, started-session turns.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_started_session_waiting_for_a_person_lends_its_slot() {
    let sandbox = Sandbox::new();
    sandbox.set_config("supervised", "agent_concurrency = 1\n");
    let client = sandbox.start_daemon("tool-call").await;
    let parent = sandbox.new_session(&client).await;
    let [asking, other] = [
        start_child(&sandbox, &client, &parent).await,
        start_child(&sandbox, &client, &parent).await,
    ];
    let write = serde_json::json!({
        "id": "edit",
        "name": "write",
        "arguments": {"path": "note.txt", "content": "approved"},
    });

    sandbox.prompt_tool_call(&client, &asking, &write).await;
    sandbox
        .poll_until("the write to ask for approval", async || {
            (job_of(&client, &asking).await.state == JobState::WaitingForInput).then_some(())
        })
        .await;
    sandbox.prompt(&client, &other).await.unwrap();
    let ran = settled_job(&sandbox, &client, &other).await;

    assert_eq!(
        (ran.state, job_of(&client, &asking).await.state),
        (JobState::Completed, JobState::WaitingForInput),
        "log:\n{}",
        sandbox.isolated.daemon_log()
    );
}

// Covers: the permission mode and model a person chose for the sessions a
// session starts outlast a daemon restart, and a reset replay of that
// session reports them; a session it starts then opens in that mode on
// that model, and keeps them as its own choice, so a session that one
// starts does too. The choosing session itself, and a session it started
// before it chose, keep no settings of their own: after the restart both
// follow the config's new mode.
// Owner: daemon sessions other sessions start.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_started_session_opens_with_what_a_person_chose_for_its_parent() {
    let sandbox = Sandbox::new();
    // Auto needs a classifier model, as a person's config gives it.
    let classifier = r#"[internal_agents.permission-classifier]
provider = "xai"
model = "grok-fixture"
auth = "xai-oauth"
"#;
    sandbox.set_config("bypass", classifier);
    let (mut daemon, client) = sandbox.spawn_daemon(sandbox.rho("fixed"), &[]).await;
    let parent = sandbox.new_session(&client).await;
    let unchosen = start_child(&sandbox, &client, &parent).await;
    // Both saved, so the next daemon has their files to reopen.
    for session in [&parent, &unchosen] {
        sandbox.prompt(&client, session).await.unwrap();
        settled_job(&sandbox, &client, session).await;
    }
    // The one model the fixture surely runs: the config's.
    let configured = open_child(&sandbox, &client, &parent)
        .await
        .options
        .model
        .current;
    configure(
        &client,
        &parent,
        SessionChange::StartedSessionPermissionMode {
            mode: Some(PermissionMode::Auto),
        },
    )
    .await;
    configure(
        &client,
        &parent,
        SessionChange::StartedSessionModel {
            model: Some(configured.clone()),
        },
    )
    .await;
    drop(client);
    let stop = sandbox
        .rho("fixed")
        .args(["daemon", "stop"])
        .status()
        .unwrap();
    assert!(stop.success(), "log:\n{}", sandbox.isolated.daemon_log());
    daemon.wait().unwrap();

    sandbox.set_config("supervised", classifier);
    let client = sandbox.start_daemon("fixed").await;
    // The attach loads the parent again, as its turn that starts a session
    // keeps it loaded.
    let (parent_options, reported) = attached(&sandbox, &parent).await;
    let (unchosen_options, _) = attached(&sandbox, &unchosen).await;
    let started = open_child(&sandbox, &client, &parent).await;
    let started_by_started = open_child(&sandbox, &client, &started.session).await;

    let settings = |options: &SessionOptions| {
        (
            options.permission_mode.current,
            options.model.current.clone(),
        )
    };
    let chosen = (PermissionMode::Auto, configured.clone());
    assert_eq!(
        (
            parent_options.permission_mode.current,
            unchosen_options.permission_mode.current,
            reported,
            settings(&started.options),
            settings(&started_by_started.options),
        ),
        (
            PermissionMode::Supervised,
            PermissionMode::Supervised,
            Some(SessionEvent::StartedSessionDefaults(
                StartedSessionDefaults {
                    permission_mode: Some(PermissionMode::Auto),
                    runtime: None,
                    model: Some(configured),
                }
            )),
            chosen.clone(),
            chosen,
        ),
        "log:\n{}",
        sandbox.isolated.daemon_log()
    );
}

// Covers: a choice for the sessions a session starts that a person clears
// after the session reopened stays cleared once it reopens again, though
// the reopened session's conversation carried the saved choice: a reset
// replay reports none, and a session it starts opens in the config's mode.
// Owner: daemon sessions other sessions start.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_cleared_choice_stays_cleared_once_the_session_reopens() {
    let sandbox = Sandbox::new();
    sandbox.set_config("bypass", "");
    let client = sandbox
        .start_daemon_with("fixed", &["--unload-idle-after", "200ms"])
        .await;
    let parent = sandbox.new_session(&client).await;
    let mode = |mode| SessionChange::StartedSessionPermissionMode { mode };
    // Kept attached, so the session stays loaded until the change applied.
    let (follower, _) = Follower::attach(&sandbox, &parent, Vec::new(), None).await;
    // Saved, so the unload has a file to reopen.
    sandbox.prompt(&client, &parent).await.unwrap();
    settled_job(&sandbox, &client, &parent).await;
    configure(&client, &parent, mode(Some(PermissionMode::Plan))).await;
    drop(follower);
    sandbox.wait_unloaded(&parent, /*times*/ 1).await;
    let (follower, _) = Follower::attach(&sandbox, &parent, Vec::new(), None).await;
    configure(&client, &parent, mode(None)).await;
    drop(follower);
    sandbox.wait_unloaded(&parent, /*times*/ 2).await;

    let (_, reported) = attached(&sandbox, &parent).await;
    let started = open_child(&sandbox, &client, &parent).await;

    assert_eq!(
        (reported, started.options.permission_mode.current),
        (
            Some(SessionEvent::StartedSessionDefaults(
                StartedSessionDefaults::default()
            )),
            PermissionMode::Bypass,
        ),
        "log:\n{}",
        sandbox.isolated.daemon_log()
    );
}

// Covers: a started session a person rebinds with `/agent:` lists as a
// child running as the agent it was rebound to, still once the daemon
// unloaded it, rather than as the agent it opened as.
// Owner: daemon session jobs.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_rebound_child_lists_its_new_agent_once_it_unloads() {
    let sandbox = Sandbox::new();
    let client = sandbox
        .start_daemon_with("fixed", &["--unload-idle-after", "200ms"])
        .await;
    let parent = sandbox.new_session(&client).await;
    let child = start_child(&sandbox, &client, &parent).await;
    sandbox
        .prompt_text(&client, &child, "/agent:explorer summarize the notes")
        .await
        .unwrap();
    settled_job(&sandbox, &client, &child).await;
    sandbox.wait_unloaded(&child, /*times*/ 1).await;

    assert_eq!(
        job_of(&client, &child).await.child,
        Some(ChildInfo::new(ChildRole::Started).running_as("explorer", AgentRuntime::Rho)),
        "log:\n{}",
        sandbox.isolated.daemon_log()
    );
}

// Covers: a session a subagent starts after the daemon stopped tracking the
// subagent's run, here one that ended, opens with the choice of the session
// that owns the subagent, found through the subagent's file, rather than on
// the config's, which may be looser.
// Owner: daemon sessions other sessions start.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_session_an_ended_subagent_starts_takes_its_owners_choice() {
    let sandbox = Sandbox::new();
    sandbox.set_config("bypass", "");
    // The fixture makes the call the prompt spells out as JSON.
    let client = sandbox.start_daemon("tool-call").await;
    let lead = sandbox.new_session(&client).await;
    configure(
        &client,
        &lead,
        SessionChange::StartedSessionPermissionMode {
            mode: Some(PermissionMode::Plan),
        },
    )
    .await;
    let call = serde_json::json!({
        "id": "delegate",
        "name": "agent",
        "arguments": {"agent_id": "explorer", "prompt": "Look around."},
    });
    sandbox.prompt_tool_call(&client, &lead, &call).await;
    let lead_job = settled_job(&sandbox, &client, &lead).await.id;
    let subagent = sandbox
        .poll_until("the subagent's run to end", async || {
            client
                .request::<JobList>(&JobListParams {})
                .await
                .unwrap()
                .jobs
                .into_iter()
                .find(|job| {
                    job.parent.as_ref() == Some(&lead_job) && job.state == JobState::Completed
                })
                .and_then(|job| job.session)
        })
        .await;

    let started = open_child(&sandbox, &client, &subagent).await;

    assert_eq!(
        started.options.permission_mode.current,
        PermissionMode::Plan,
        "log:\n{}",
        sandbox.isolated.daemon_log()
    );
}