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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
//! The run boundary on ACP v2: setup and the mode fence, the turn that ends
//! with the session's `idle` state, cancel, resume, and the fallback to v1
//! for an agent that answers v1.

use super::{
    adapters::{Adapter, Adapters},
    policy::{AcpProtocol, SessionConfigChoice},
    scripted_agent::{Record, Script, ScriptedAgent, Step, V2Script, V2Step},
    session::{run_on_channel, run_on_channels},
    test_support::*,
};
use crate::{
    cli_runtime::parent_messages::{frame_parent_message, message_channel},
    run_artifacts::AttachmentEvent,
    subagent::RunState,
};
use agent_client_protocol::{
    v1::schema::{ContentChunk, SessionUpdate, StopReason},
    v2::schema as v2,
    Channel,
};
use pretty_assertions::assert_eq;
use rho_protocol::display::NotificationDelivery;
use serde_json::{json, Value};
use std::sync::{Arc, Mutex};

/// A select option `id` currently `current`, offering `values`.
fn select(id: &str, current: &str, values: &[&str]) -> v2::SessionConfigOption {
    v2::SessionConfigOption::select(
        id.to_owned(),
        id,
        current.to_owned(),
        values
            .iter()
            .map(|value| v2::SessionConfigSelectOption::new(value.to_string(), *value))
            .collect::<Vec<_>>(),
    )
}

/// A select option `id` currently `current`, offering `values` in one
/// group, as v2 names groups (`groupId`).
fn grouped(id: &str, current: &str, values: &[&str]) -> v2::SessionConfigOption {
    let values = values
        .iter()
        .map(|value| v2::SessionConfigSelectOption::new(value.to_string(), *value))
        .collect();
    v2::SessionConfigOption::select(
        id.to_owned(),
        id,
        current.to_owned(),
        vec![v2::SessionConfigSelectGroup::new("all", "All", values)],
    )
}

/// The mode option claude-agent-acp 0.114.0 offers, starting where the
/// user's own Claude settings put it.
fn mode(current: &str) -> v2::SessionConfigOption {
    select("mode", current, &["default", "plan", "bypassPermissions"])
        .category(v2::SessionConfigOptionCategory::Mode)
}

fn text(text: &str) -> V2Step {
    V2Step::Update {
        session: None,
        update: Box::new(v2::SessionUpdate::AgentMessageChunk(v2::ContentChunk::new(
            text.to_owned().into(),
            "message",
        ))),
    }
}

fn idle() -> V2Step {
    V2Step::Idle {
        stop_reason: Some(v2::StopReason::EndTurn),
    }
}

fn v2_script(config_options: Vec<v2::SessionConfigOption>, turns: Vec<Vec<V2Step>>) -> Script {
    Script {
        v2: Some(V2Script {
            config_options,
            turns,
            ..V2Script::default()
        }),
        ..Script::default()
    }
}

/// A policy that asks for v2, fencing `mode`.
fn policy(dir: &std::path::Path, mode: Option<&str>) -> TestPolicy {
    let mut policy = TestPolicy::new(dir);
    policy.protocol = AcpProtocol::V2;
    policy.mode = mode.map(str::to_owned);
    policy
}

async fn exercise(dir: &std::path::Path, policy: TestPolicy, script: Script) -> Arc<Mutex<Record>> {
    let (record, agent) = exercise_agent(dir, policy, script).await;
    agent.unwrap();
    record
}

/// [`exercise`], with how the fake agent's connection ended.
async fn exercise_agent(
    dir: &std::path::Path,
    policy: TestPolicy,
    script: Script,
) -> (Arc<Mutex<Record>>, Result<(), agent_client_protocol::Error>) {
    let (client, agent) = Channel::duplex();
    let (fake, record, _signals) = ScriptedAgent::new(script);
    let agent = tokio::time::timeout(TEST_BUDGET, async {
        let (client, agent) = tokio::join!(
            run_on_channel(request(dir, None), policy, client),
            fake.run(agent)
        );
        client.unwrap();
        agent
    })
    .await
    .expect("ACP runtime/agent finished");
    (record, agent)
}

/// Each request's method, and the params of the setup ones a test reads.
fn methods(record: &Mutex<Record>) -> Vec<Value> {
    record
        .lock()
        .unwrap()
        .requests
        .iter()
        .map(|request| match request["method"].as_str().unwrap() {
            "initialize" => json!(["initialize", request["params"]["protocolVersion"]]),
            "session/set_config_option" => json!([
                "session/set_config_option",
                request["params"]["configId"],
                request["params"]["value"]
            ]),
            "session/resume" => json!(["session/resume", request["params"].get("replayFrom")]),
            method => json!([method]),
        })
        .collect()
}

// Covers: on v2 the run fences the session's mode, the config option of
// category `mode`, before it prompts, since a new session starts in the mode
// the user's own Claude settings name. The options the agent reported
// while it set up, before rho set the mode, do not fail the run, and a
// config choice offered in groups is set like any other. The turn ends with
// the `idle` state after its work, not with the prompt's acknowledgement.
// Owner: ACP runtime setup and turn boundary.
#[tokio::test]
async fn v2_run_fences_the_mode_before_its_prompt_and_ends_at_idle() {
    let dir = tempfile::tempdir().unwrap();
    let mut policy = policy(dir.path(), Some("default"));
    policy.config = vec![SessionConfigChoice {
        id: "model".to_owned().into(),
        value: "haiku".to_owned().into(),
    }];
    let record = exercise(
        dir.path(),
        policy,
        v2_script(
            vec![
                mode("bypassPermissions"),
                grouped("model", "opus", &["opus", "haiku"]),
            ],
            vec![vec![V2Step::Running, text("answer"), idle()]],
        ),
    )
    .await;
    let (status, events) = read_artifacts(dir.path());
    assert_eq!(
        (
            status.state,
            status.runtime_session_id,
            status.result,
            status.turns,
            terminal_events(&events)
        ),
        (
            RunState::Ok,
            Some("scripted-session".into()),
            Some("answer".into()),
            1,
            vec![AttachmentEvent::Completed]
        )
    );
    assert_eq!(
        methods(&record),
        vec![
            json!(["initialize", 2]),
            json!(["session/new"]),
            json!(["session/set_config_option", "mode", "default"]),
            json!(["session/set_config_option", "model", "haiku"]),
            json!(["session/prompt"]),
        ]
    );
    let record = record.lock().unwrap();
    // Each value is a select's, which v2 tags.
    assert_eq!(
        record.requests[2]["params"]["type"],
        json!("id"),
        "{:?}",
        record.requests[2]
    );
}

/// Whether a run's agent is prompted before the run fails.
enum Prompted {
    Never,
    Always,
    /// It depends on when the agent's message arrives.
    Either,
}

// Covers: the v2 mode fence fails closed. A session without a mode option,
// one that does not offer the policy's mode, an agent that keeps another
// mode when asked, one that moves it right after answering, and one that
// moves it mid-turn each fail the run; none of the first three ever
// prompts. The move after the answer is caught in setup, or in the turn if
// it arrives after setup's last read.
// Owner: ACP runtime setup and turn boundary. Only diagnostic context is checked.
#[tokio::test]
async fn v2_mode_fence_fails_closed() {
    let sticky = |options, turns| {
        let mut script = v2_script(options, turns);
        script.v2.as_mut().unwrap().sticky_config = vec!["mode".into()];
        script
    };
    let moved = v2::SessionUpdate::ConfigOptionUpdate(v2::ConfigOptionUpdate::new(vec![mode(
        "bypassPermissions",
    )]));
    let mut moves_after_set = v2_script(vec![mode("bypassPermissions")], vec![vec![idle()]]);
    moves_after_set.v2.as_mut().unwrap().mode_after_set = Some("bypassPermissions".into());
    // (script, step, detail, whether the agent was prompted)
    let cases = [
        (
            v2_script(vec![select("model", "opus", &["opus"])], vec![]),
            "required mode `default`",
            "category `mode`",
            Prompted::Never,
        ),
        (
            v2_script(
                vec![select("mode", "bypassPermissions", &["bypassPermissions"])
                    .category(v2::SessionConfigOptionCategory::Mode)],
                vec![],
            ),
            "session/set_config_option `mode`",
            "value `default` is not advertised",
            Prompted::Never,
        ),
        (
            sticky(vec![mode("bypassPermissions")], vec![]),
            "acp",
            "agent is in mode `bypassPermissions`, not required mode `default`",
            Prompted::Never,
        ),
        (
            moves_after_set,
            "acp",
            "agent is in mode `bypassPermissions`, not required mode `default`",
            Prompted::Either,
        ),
        (
            v2_script(
                vec![mode("default")],
                vec![vec![
                    V2Step::Running,
                    V2Step::Update {
                        session: None,
                        update: Box::new(moved),
                    },
                    text("edited anyway"),
                    idle(),
                ]],
            ),
            "acp",
            "agent is in mode `bypassPermissions`, not required mode `default`",
            Prompted::Always,
        ),
    ];
    for (script, step, detail, prompted) in cases {
        let dir = tempfile::tempdir().unwrap();
        let (record, agent) =
            exercise_agent(dir.path(), policy(dir.path(), Some("default")), script).await;
        match (&prompted, agent) {
            (_, Ok(())) => {}
            // A fake that writes after its answer may find the run gone.
            (Prompted::Either, Err(closed))
                if format!("{closed:?}").contains("receiver is gone") => {}
            (_, Err(error)) => panic!("{detail}: the fake agent failed: {error:?}"),
        }
        let (status, events) = read_artifacts(dir.path());
        let error = status.error.unwrap();
        assert!(
            error.contains(step) && error.contains(detail),
            "required ACP diagnostic context: {error}"
        );
        assert_eq!(
            (status.state, terminal_events(&events)),
            (RunState::Error, vec![AttachmentEvent::Failed(error)])
        );
        let prompts = methods(&record).contains(&json!(["session/prompt"]));
        let expected = match prompted {
            Prompted::Never => false,
            Prompted::Always => true,
            // Caught in setup, or in the turn if it came after setup's last read.
            Prompted::Either => prompts,
        };
        assert_eq!(
            (prompts, status.runtime_session_id.is_some()),
            (expected, expected),
            "{detail}"
        );
    }
}

// Covers: a v2 turn the agent ends with an `error` stop fails the run with
// the agent's own account of the failure, and still counts as a turn.
// Owner: ACP runtime turn boundary. Only diagnostic context is checked.
#[tokio::test]
async fn v2_error_stop_fails_the_run_with_the_agents_message() {
    let dir = tempfile::tempdir().unwrap();
    let mut failure = v2::Error::internal_error();
    failure.message = "Claude Code stopped".into();
    let failed = V2Step::Idle {
        stop_reason: Some(v2::StopReason::Error(
            v2::ErrorStopReason::new().error(failure),
        )),
    };
    exercise(
        dir.path(),
        policy(dir.path(), None),
        v2_script(vec![], vec![vec![V2Step::Running, failed]]),
    )
    .await;
    let (status, _) = read_artifacts(dir.path());
    let error = status.error.unwrap_or_default();
    assert!(
        error.contains("Claude Code stopped"),
        "the agent's account of the failure: {error}"
    );
    assert_eq!((status.state, status.turns), (RunState::Error, 1));
}

// Covers: a v2 resume asks for no replay, since rho keeps its own
// transcript, and the `idle` state the agent sends as it resumes, before
// the prompt's work starts, does not end the turn.
// Owner: ACP runtime setup and turn boundary.
#[tokio::test]
async fn v2_resume_replays_nothing_and_its_idle_snapshot_ends_no_turn() {
    let dir = tempfile::tempdir().unwrap();
    let mut request = request(dir.path(), None);
    request.overrides.resume = Some("scripted-session".into());
    let (client, agent) = Channel::duplex();
    let (fake, record, _signals) = ScriptedAgent::new(v2_script(
        vec![],
        vec![vec![V2Step::Running, text("resumed"), idle()]],
    ));
    tokio::time::timeout(TEST_BUDGET, async {
        let (client, agent) = tokio::join!(
            run_on_channel(request, policy(dir.path(), None), client),
            fake.run(agent)
        );
        client.unwrap();
        agent.unwrap();
    })
    .await
    .expect("ACP runtime/agent finished");
    let (status, _) = read_artifacts(dir.path());
    assert_eq!(
        (status.state, status.result),
        (RunState::Ok, Some("resumed".into()))
    );
    assert_eq!(
        methods(&record),
        vec![
            json!(["initialize", 2]),
            json!(["session/resume", null]),
            json!(["session/prompt"]),
        ]
    );
}

// Covers: a cancel during a v2 turn sends `session/cancel` and the run
// stops at the agent's `cancelled` idle; an ask about no tool call fails
// closed rather than being approved.
// Owner: ACP runtime turn boundary.
#[tokio::test]
async fn v2_cancel_stops_the_turn_and_permission_asks_are_declined() {
    let dir = tempfile::tempdir().unwrap();
    let request = request(dir.path(), None);
    let cancellation = request.cancellation.clone();
    let (client, agent) = Channel::duplex();
    let (fake, record, mut signals) = ScriptedAgent::new(v2_script(
        vec![],
        vec![vec![
            V2Step::Running,
            V2Step::Permission {
                title: "Edit a.txt".into(),
                call: None,
            },
            V2Step::Hang,
        ]],
    ));
    tokio::time::timeout(TEST_BUDGET, async {
        let cancel = async {
            while let Some(signal) = signals.recv().await {
                if signal == super::scripted_agent::Signal::Waiting {
                    cancellation.cancel();
                    break;
                }
            }
        };
        let (client, agent, ()) = tokio::join!(
            run_on_channel(request, policy(dir.path(), None), client),
            fake.run(agent),
            cancel
        );
        client.unwrap();
        agent.unwrap();
    })
    .await
    .expect("ACP runtime/agent finished");
    let (status, events) = read_artifacts(dir.path());
    assert_eq!(
        (status.state, terminal_events(&events)),
        (RunState::Stopped, vec![AttachmentEvent::Cancelled])
    );
    let record = record.lock().unwrap();
    assert_eq!(
        record.replies,
        vec![json!({
            "method": "session/request_permission",
            "result": {"outcome": {"outcome": "cancelled"}}
        })]
    );
    assert!(record
        .requests
        .iter()
        .any(|request| request["method"] == "session/cancel"));
}

// Covers: an agent that answers v1 to rho's v2 `initialize` is started
// again and runs on v1, so an older agent still works; the process's
// adapter cache remembers it, so the next run of the same adapter starts on
// v1 at once, one process, and says so as the first did.
// Owner: ACP runtime protocol negotiation.
#[tokio::test]
async fn an_agent_that_answers_v1_runs_on_v1_in_a_new_process() {
    let v1_script = Script {
        turns: vec![vec![
            Step::Update {
                update: Box::new(SessionUpdate::AgentMessageChunk(ContentChunk::new(
                    "from v1".to_owned().into(),
                ))),
            },
            Step::Stop {
                reason: StopReason::EndTurn,
            },
        ]],
        ..Script::default()
    };
    let adapters = Adapters::default();
    let adapter = Adapter {
        cache: &adapters,
        path: std::path::Path::new("/bin/v1-adapter"),
    };
    let mut runs = Vec::new();
    for _ in 0..2 {
        let dir = tempfile::tempdir().unwrap();
        let mut agents = Vec::new();
        let mut records = Vec::new();
        let connect = || {
            let (client, agent) = Channel::duplex();
            let (fake, record, _signals) = ScriptedAgent::new(v1_script.clone());
            records.push(record);
            agents.push(tokio::spawn(fake.run(agent)));
            client
        };
        let request = request(dir.path(), None);
        let run = run_on_channels(request, policy(dir.path(), None), Some(adapter), connect);
        tokio::time::timeout(TEST_BUDGET, run)
            .await
            .expect("ACP runtime finished")
            .unwrap();
        for agent in agents {
            tokio::time::timeout(TEST_BUDGET, agent)
                .await
                .expect("agent finished")
                .unwrap()
                .unwrap();
        }
        let (status, events) = read_artifacts(dir.path());
        let notices = events
            .iter()
            .filter(|event| matches!(event, AttachmentEvent::Notice(_)))
            .count();
        let methods: Vec<_> = records.iter().map(|record| methods(record)).collect();
        runs.push((status.state, status.result, notices, methods));
    }
    let on_v1 = vec![
        json!(["initialize", 1]),
        json!(["session/new"]),
        json!(["session/prompt"]),
    ];
    let from_v1 = || Some("from v1".to_owned());
    // (state, answer, notices, each process's requests)
    assert_eq!(
        runs,
        vec![
            // The SDK hands a v1 agent rho's v2 `initialize` as v1.
            (
                RunState::Ok,
                from_v1(),
                1,
                vec![vec![json!(["initialize", 1])], on_v1.clone()]
            ),
            (RunState::Ok, from_v1(), 1, vec![on_v1]),
        ]
    );
}

/// Runs `script` with a parent message sent once the fake waits mid-turn.
async fn steer_mid_turn(dir: &std::path::Path, script: Script) -> Arc<Mutex<Record>> {
    let (handle, inbox) = message_channel();
    let (client, agent) = Channel::duplex();
    let (fake, record, mut signals) = ScriptedAgent::new(script);
    tokio::time::timeout(TEST_BUDGET, async {
        let send = async {
            while let Some(signal) = signals.recv().await {
                if signal == super::scripted_agent::Signal::Waiting {
                    handle.send("course correction".into()).unwrap();
                    break;
                }
            }
        };
        let (client, agent, ()) = tokio::join!(
            run_on_channel(request(dir, Some(inbox)), policy(dir, None), client),
            fake.run(agent),
            send
        );
        client.unwrap();
        agent.unwrap();
    })
    .await
    .expect("run with a mid-turn parent message finished");
    record
}

/// The parent-message cards the run drew.
fn parent_cards(events: Vec<AttachmentEvent>) -> Vec<AttachmentEvent> {
    events
        .into_iter()
        .filter(|event| matches!(event, AttachmentEvent::Message(_)))
        .collect()
}

/// The card of the parent message `course correction`, delivered `how`.
fn course_correction(how: NotificationDelivery, detail: &str) -> AttachmentEvent {
    AttachmentEvent::Message(Box::new(crate::presentation::parent_message_card(
        "course correction".into(),
        how,
        detail.into(),
    )))
}

// Covers: on v2 a parent message that arrives while the turn works is
// steered into it as another `session/prompt`, and the turn's one `idle`
// ends both (as claude-agent-acp 0.114.0 does); a steer the agent refuses
// goes as the next turn instead; and one the agent holds until the turn
// ends, then starts a turn with (`running` before its answer, as the
// adapter does while an input request is open), counts as the next turn.
// None is lost.
// Owner: ACP v2 turn scheduling. The fake signals readiness rather than sleeping.
#[tokio::test]
async fn v2_steers_a_mid_turn_message_by_prompt() {
    let steered_turn = || {
        vec![
            V2Step::Running,
            text("working"),
            V2Step::AwaitSteer,
            text(" steered"),
            idle(),
        ]
    };
    // How the agent treats a steer: (refuses it, holds it).
    let cases = [
        (
            (false, false),
            vec![steered_turn()],
            (1, 2),
            course_correction(
                NotificationDelivery::Received,
                "steered into the running turn",
            ),
        ),
        (
            (true, false),
            vec![steered_turn(), vec![V2Step::Running, text(" next"), idle()]],
            // The refused steer, then the same message as the next turn.
            (2, 3),
            course_correction(NotificationDelivery::Queued, "sent as the next agent turn"),
        ),
        (
            (false, true),
            // The fake reports the held prompt's `running` itself.
            vec![steered_turn(), vec![text(" next"), idle()]],
            (2, 2),
            course_correction(NotificationDelivery::Queued, "sent as the next agent turn"),
        ),
    ];
    for ((refuse_steers, hold_steers), turns, expected_turns, delivery) in cases {
        let dir = tempfile::tempdir().unwrap();
        let mut script = v2_script(vec![], turns);
        let v2 = script.v2.as_mut().unwrap();
        (v2.refuse_steers, v2.hold_steers) = (refuse_steers, hold_steers);
        let record = steer_mid_turn(dir.path(), script).await;
        let prompts: Vec<_> = record
            .lock()
            .unwrap()
            .requests
            .iter()
            .filter(|request| request["method"] == "session/prompt")
            .map(|request| request["params"]["prompt"][0]["text"].clone())
            .collect();
        let (status, events) = read_artifacts(dir.path());
        assert_eq!(
            (
                status.state,
                (status.turns, prompts.len()),
                parent_cards(events)
            ),
            (RunState::Ok, expected_turns, vec![delivery]),
            "refuse_steers: {refuse_steers}, hold_steers: {hold_steers}"
        );
        assert_eq!(
            prompts.last(),
            Some(&json!(frame_parent_message("course correction")))
        );
    }
}

/// A root state, listing the background commands `listed`.
fn state(running: bool, stop: Option<v2::StopReason>, listed: &[&str]) -> V2Step {
    let background = listed
        .iter()
        .map(|id| v2::BackgroundWork::Terminal(v2::BackgroundTerminal::new(id.to_string())))
        .collect::<Vec<_>>();
    let state = if running {
        v2::StateUpdate::Running(v2::RunningStateUpdate::new().background(background))
    } else {
        v2::StateUpdate::Idle(
            v2::IdleStateUpdate::new()
                .stop_reason(stop)
                .background(background),
        )
    };
    V2Step::Update {
        session: None,
        update: Box::new(v2::SessionUpdate::StateUpdate(state)),
    }
}

/// Tool call `id` of `session` (the root's when unset) at `status`.
fn tool_call(session: Option<&str>, id: &str, status: v2::ToolCallStatus) -> V2Step {
    V2Step::Update {
        session: session.map(str::to_owned),
        update: Box::new(v2::SessionUpdate::ToolCallUpdate(
            v2::ToolCallUpdate::new(id.to_owned()).status(status),
        )),
    }
}

fn wait(millis: u64) -> V2Step {
    V2Step::Wait { millis }
}

/// What a test does once the agent rests or waits mid-turn.
#[derive(Clone, Copy)]
enum Trigger {
    Nothing,
    Cancel,
    /// Send a parent message.
    Message,
}

/// Hears the replies a run hands its host as each later turn starts.
struct Replies(Arc<Mutex<Vec<String>>>);

impl crate::cli_runtime::status_sink::RunObserver for Replies {
    fn recorded(&mut self, _event: &AttachmentEvent) {}
    fn replied(&mut self, reply: &str) {
        self.0.lock().unwrap().push(reply.to_owned());
    }
    fn ended(&mut self, _reply: Option<&str>) {}
}

/// Runs `script`, doing `trigger` at the fake's first readiness signal:
/// the run's status, events, the replies its host heard, and the agent's
/// time it took, to a tenth of a second.
async fn keep_run(
    script: Script,
    trigger: Trigger,
    background_work: crate::cli_runtime::BackgroundWork,
) -> (
    crate::subagent::RunStatus,
    Vec<AttachmentEvent>,
    Vec<String>,
    u128,
) {
    let dir = tempfile::tempdir().unwrap();
    let (handle, inbox) = message_channel();
    let mut request = request(dir.path(), Some(inbox));
    let replies = Arc::new(Mutex::new(Vec::new()));
    request.overrides.observer = Some(Box::new(Replies(Arc::clone(&replies))));
    request.overrides.background_work = background_work;
    let cancellation = request.cancellation.clone();
    let (client, agent) = Channel::duplex();
    let (fake, _record, mut signals) = ScriptedAgent::new(script);
    let begun = tokio::time::Instant::now();
    tokio::time::timeout(std::time::Duration::from_secs(3_600), async {
        let trigger = async {
            let mut fired = false;
            while let Some(signal) = signals.recv().await {
                if fired || signal != super::scripted_agent::Signal::Waiting {
                    continue;
                }
                fired = true;
                match trigger {
                    Trigger::Nothing => {}
                    Trigger::Cancel => cancellation.cancel(),
                    Trigger::Message => handle.send("course correction".into()).unwrap(),
                }
            }
        };
        let run = async {
            let (client, _agent) = tokio::join!(
                run_on_channel(request, policy(dir.path(), None), client),
                fake.run(agent)
            );
            client.unwrap();
        };
        tokio::select! {
            () = run => {}
            () = trigger => unreachable!("the fake outlives its signals"),
        }
    })
    .await
    .expect("ACP runtime finished");
    let kept = begun.elapsed().as_millis() / 100;
    let (status, events) = read_artifacts(dir.path());
    let replies = replies.lock().unwrap().clone();
    (status, events, replies, kept)
}

// Covers: on v2 the run keeps the agent after its prompted turn while its
// background work may still report, so the run's answer is the turn the
// agent starts on its own to report it (the v1 bug kept the placeholder):
// - it waits 30 s for a report that does not come, and stops at the 10 min
//   budget with a notice, keeping the last whole reply if a turn is cut;
// - it does not wait when a call of the turn finished after the command
//   ended, which took it in, but a subagent's call is no step of the root;
// - a report turn that fails ends the run on the reply before it;
// - a parent message meanwhile goes as the next turn at once, and one
//   steered into a report turn that the agent takes late starts a turn of
//   its own, each turn's reply reaching the host once;
// - a cancel stops it, and a daemon turn (`Leave`) does not wait.
// Timings as claude-agent-acp 0.114.0 showed them (`running` 0.5-0.75 s
// after the list emptied), on tokio's paused clock.
// Owner: ACP v2 run boundary (background work).
#[tokio::test(start_paused = true)]
async fn v2_keeps_the_agent_while_its_background_work_may_report() {
    use crate::cli_runtime::BackgroundWork::{Await, Leave};
    let end = || Some(v2::StopReason::EndTurn);
    let started = |listed: &[&str]| {
        vec![
            state(true, None, listed),
            text("started"),
            state(false, end(), listed),
        ]
    };
    let report = |reply: &str| vec![state(true, None, &[]), text(reply), idle()];
    let one = |steps: Vec<Vec<V2Step>>| v2_script(vec![], vec![steps.concat()]);
    // The turn reads the output of a command that ended, by a call of
    // `session`, the root's when unset.
    let read = |session: Option<&str>| {
        one(vec![vec![
            state(true, None, &["toolu_1"]),
            tool_call(session, "toolu_2", v2::ToolCallStatus::Pending),
            state(true, None, &[]),
            tool_call(session, "toolu_2", v2::ToolCallStatus::Completed),
            text("read it"),
            state(false, end(), &[]),
            V2Step::Rest,
        ]])
    };
    let refused = V2Step::Idle {
        stop_reason: Some(v2::StopReason::Refusal),
    };
    let mut held = v2_script(
        vec![],
        vec![
            [
                started(&["toolu_1"]),
                vec![wait(1_000), state(false, None, &[]), wait(700)],
                vec![
                    state(true, None, &[]),
                    text("report"),
                    V2Step::AwaitSteer,
                    idle(),
                ],
            ]
            .concat(),
            vec![text("steered"), idle()],
        ],
    );
    held.v2.as_mut().unwrap().hold_steers = true;
    // (case, script, trigger, background work, expected (state, turns,
    // answer, notices, replies the host heard, seconds kept to a tenth))
    let cases = [
        (
            "a background command's report is the answer",
            one(vec![
                started(&["toolu_1"]),
                vec![wait(5_000), state(false, None, &[]), wait(700)],
                report("slept"),
            ]),
            Trigger::Nothing,
            Await,
            (RunState::Ok, 2, "slept", 0, vec!["started"], 57),
        ),
        (
            "a subagent that ended mid-turn reports",
            one(vec![
                vec![state(true, None, &["sub"]), state(true, None, &[])],
                started(&[]),
                vec![wait(700)],
                report("pong"),
            ]),
            Trigger::Nothing,
            Await,
            (RunState::Ok, 2, "pong", 0, vec!["started"], 7),
        ),
        (
            "no report comes: 30 s after the list empties",
            one(vec![
                started(&["toolu_1"]),
                vec![wait(1_000), state(false, None, &[]), V2Step::Rest],
            ]),
            Trigger::Nothing,
            Await,
            (RunState::Ok, 1, "started", 0, vec![], 310),
        ),
        (
            "a call that finished after the command ended took it in: no wait",
            read(None),
            Trigger::Nothing,
            Await,
            (RunState::Ok, 1, "read it", 0, vec![], 0),
        ),
        (
            "a subagent's call that finished is no step of the turn",
            read(Some("sub")),
            Trigger::Nothing,
            Await,
            (RunState::Ok, 1, "read it", 0, vec![], 300),
        ),
        (
            "work that never ends trips the 10 min budget",
            one(vec![started(&["toolu_1"]), vec![V2Step::Rest]]),
            Trigger::Nothing,
            Await,
            (RunState::Ok, 1, "started", 1, vec![], 6_000),
        ),
        (
            "the budget cuts a report turn: the whole reply before it stays",
            one(vec![
                started(&["toolu_1"]),
                vec![state(true, None, &["toolu_1"]), text("half"), V2Step::Rest],
            ]),
            Trigger::Nothing,
            Await,
            (RunState::Ok, 1, "started", 1, vec!["started"], 6_000),
        ),
        (
            "a report turn that fails ends the run on the reply before it",
            one(vec![
                started(&["toolu_1"]),
                vec![
                    wait(1_000),
                    state(false, None, &[]),
                    state(true, None, &[]),
                    text("no"),
                    refused,
                ],
            ]),
            Trigger::Nothing,
            Await,
            (RunState::Ok, 2, "started", 1, vec!["started"], 10),
        ),
        (
            "a parent message while the run waits goes as the next turn",
            v2_script(
                vec![],
                vec![
                    [started(&["toolu_1"]), vec![V2Step::Done]].concat(),
                    report("answered"),
                ],
            ),
            Trigger::Message,
            Await,
            // The list emptied with the turn: its report gets 30 s.
            (RunState::Ok, 2, "answered", 0, vec!["started"], 300),
        ),
        (
            "a steer a report turn takes late starts a turn of its own",
            held,
            Trigger::Message,
            Await,
            (RunState::Ok, 3, "steered", 0, vec!["started", "report"], 17),
        ),
        (
            "a cancel while the run waits stops it",
            // The second passes once the run took the idle, so it waits.
            one(vec![started(&["toolu_1"]), vec![wait(1_000), V2Step::Rest]]),
            Trigger::Cancel,
            Await,
            // The 200 ms cancel drain: no `idle` is owed.
            (RunState::Stopped, 1, "started", 0, vec![], 12),
        ),
        (
            "a daemon turn leaves its background work",
            one(vec![started(&["toolu_1"]), vec![V2Step::Rest]]),
            Trigger::Nothing,
            Leave,
            (RunState::Ok, 1, "started", 0, vec![], 0),
        ),
    ];
    for (case, script, trigger, background_work, expected) in cases {
        let (status, events, replies, kept) = keep_run(script, trigger, background_work).await;
        let notices = events
            .iter()
            .filter(|event| matches!(event, AttachmentEvent::Notice(_)))
            .count();
        assert_eq!(
            (
                status.state,
                status.turns,
                status.result.as_deref().unwrap_or_default(),
                notices,
                replies.iter().map(String::as_str).collect::<Vec<_>>(),
                kept
            ),
            (expected.0, expected.1, expected.2, expected.3, expected.4, expected.5),
            "{case}"
        );
    }
}