rho-coding-agent 3.12.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
use agent_client_protocol::v1::schema::{
    ContentChunk, Cost, ImageContent, PlanEntry, PlanEntryPriority, SessionInfoUpdate, ToolCall,
    ToolCallLocation, ToolCallStatus, ToolCallUpdate, ToolCallUpdateFields, ToolKind,
};
use pretty_assertions::assert_eq;
use rho_protocol::display::{Presentation, ToolBody, ToolCard, ToolFact, ToolFamily, ToolHeader};

use super::*;

fn attachment(event: AttachmentEvent) -> StreamEffect {
    StreamEffect::Attachment(event)
}

fn first_step(event: AttachmentEvent) -> Vec<StreamEffect> {
    vec![attachment(AttachmentEvent::StepStarted), attachment(event)]
}

fn read_call() -> ToolCall {
    ToolCall::new("read-1", "Read config")
        .kind(ToolKind::Read)
        .locations(vec![ToolCallLocation::new("/workspace/config.toml")])
}

fn read_card(status: ToolCardStatus) -> ToolCard {
    ToolCard::new(
        status,
        ToolFamily::FileCommand,
        ToolHeader::call("Read", Some("config.toml".into())),
    )
}

// Covers: ACP updates must not lose text, tool identity, diffs, or usage at the
// protocol/artifact seam. No existing CLI mapper exercises this typed schema.
// Owner: pure protocol-to-artifact translation.
#[test]
fn session_updates_render_as_artifacts() {
    struct Case {
        name: &'static str,
        updates: Vec<SessionUpdate>,
        expected: Vec<Vec<StreamEffect>>,
        result: &'static str,
    }
    let running = AttachmentEvent::ToolStarted {
        key: Some("read-1".into()),
        card: read_card(ToolCardStatus::Running),
    };
    let failed = read_card(ToolCardStatus::Error)
        .with_facts(vec![ToolFact::Error {
            text: "denied".into(),
        }])
        .with_body(ToolBody::Lines(vec!["denied".into()]));
    let step = |content: &str, status| PlanEntry::new(content, PlanEntryPriority::Medium, status);
    let recorded_step = |content: &str, status| rho_protocol::PlanEntry {
        content: content.into(),
        status,
    };
    let plan = Plan::new(vec![
        step("read", PlanEntryStatus::Completed),
        step("inspect", PlanEntryStatus::InProgress),
        step("fix", PlanEntryStatus::Pending),
    ]);
    let recorded_plan = AttachmentEvent::Plan(vec![
        recorded_step("read", rho_protocol::PlanStatus::Completed),
        recorded_step("inspect", rho_protocol::PlanStatus::InProgress),
        recorded_step("fix", rho_protocol::PlanStatus::Pending),
    ]);
    let long_plan = Plan::new(
        (0..=MAX_TOOL_BODY_LINES)
            .map(|index| step(&format!("step {index}"), PlanEntryStatus::Pending))
            .collect(),
    );
    let recorded_long_plan = AttachmentEvent::Plan(
        (0..MAX_TOOL_BODY_LINES)
            .map(|index| recorded_step(&format!("step {index}"), rho_protocol::PlanStatus::Pending))
            .collect(),
    );
    let cases = vec![
        Case {
            name: "assistant chunks accumulate without replay",
            updates: vec![
                SessionUpdate::AgentMessageChunk(ContentChunk::new("hel".into())),
                SessionUpdate::AgentMessageChunk(ContentChunk::new("lo".into())),
            ],
            expected: vec![
                vec![
                    attachment(AttachmentEvent::StepStarted),
                    attachment(AttachmentEvent::AssistantTextDelta("hel".into())),
                    StreamEffect::Status(StatusPatch {
                        last_activity: Some("assistant text".into()),
                        append_text: Some("hel".into()),
                        ..StatusPatch::default()
                    }),
                ],
                vec![
                    attachment(AttachmentEvent::AssistantTextDelta("lo".into())),
                    StreamEffect::Status(StatusPatch {
                        last_activity: Some("assistant text".into()),
                        append_text: Some("lo".into()),
                        ..StatusPatch::default()
                    }),
                ],
            ],
            result: "hello",
        },
        Case {
            name: "thoughts do not become final result text",
            updates: vec![SessionUpdate::AgentThoughtChunk(ContentChunk::new(
                "consider".into(),
            ))],
            expected: vec![vec![
                attachment(AttachmentEvent::StepStarted),
                attachment(AttachmentEvent::ReasoningDelta("consider".into())),
                StreamEffect::Status(StatusPatch {
                    last_activity: Some("reasoning".into()),
                    ..StatusPatch::default()
                }),
            ]],
            result: "",
        },
        Case {
            name: "opaque content becomes a notice, not encoded text",
            updates: vec![SessionUpdate::AgentMessageChunk(ContentChunk::new(
                ContentBlock::Image(ImageContent::new("base64-data", "image/png")),
            ))],
            expected: vec![vec![attachment(AttachmentEvent::Notice("[image]".into()))]],
            result: "",
        },
        Case {
            name: "pending tools start running cards",
            updates: vec![SessionUpdate::ToolCall(read_call())],
            expected: vec![first_step(running.clone())],
            result: "",
        },
        Case {
            name: "a tool finishes under the key it started with, failures as errors",
            updates: vec![
                SessionUpdate::ToolCall(read_call()),
                SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                    "read-1",
                    ToolCallUpdateFields::new()
                        .status(ToolCallStatus::Failed)
                        .content(vec!["denied".into()]),
                )),
            ],
            expected: vec![
                first_step(running.clone()),
                vec![attachment(AttachmentEvent::ToolFinished {
                    key: Some("read-1".into()),
                    presentation: failed.into(),
                })],
            ],
            result: "",
        },
        Case {
            name: "unknown tool id still renders and retains later partial updates",
            updates: vec![
                SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                    "unknown",
                    ToolCallUpdateFields::new()
                        .title("Inspect")
                        .kind(ToolKind::Read),
                )),
                SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                    "unknown",
                    ToolCallUpdateFields::new().status(ToolCallStatus::Completed),
                )),
            ],
            expected: vec![
                first_step(AttachmentEvent::ToolUpdated {
                    key: Some("unknown".into()),
                    card: ToolCard::new(
                        ToolCardStatus::Running,
                        ToolFamily::FileCommand,
                        ToolHeader::call("Read", Some("Inspect".into())),
                    ),
                }),
                vec![attachment(AttachmentEvent::ToolFinished {
                    key: Some("unknown".into()),
                    presentation: ToolCard::new(
                        ToolCardStatus::Ok,
                        ToolFamily::FileCommand,
                        ToolHeader::call("Read", Some("Inspect".into())),
                    )
                    .into(),
                })],
            ],
            result: "",
        },
        Case {
            name: "each plan snapshot records the whole plan",
            updates: vec![SessionUpdate::Plan(plan.clone()), SessionUpdate::Plan(plan)],
            expected: vec![
                first_step(recorded_plan.clone()),
                vec![attachment(recorded_plan)],
            ],
            result: "",
        },
        Case {
            name: "a plan past the journal's bound records its first steps and says so",
            updates: vec![SessionUpdate::Plan(long_plan)],
            expected: vec![vec![
                attachment(AttachmentEvent::StepStarted),
                attachment(AttachmentEvent::Notice(format!(
                    "acp: the agent's plan has 51 steps; recorded the first 50 \
                     ({MAX_TOOL_BODY_LINES} at most, {MAX_TOOL_PAYLOAD_CHARS} characters in all)"
                ))),
                attachment(recorded_long_plan),
            ]],
            result: "",
        },
        Case {
            name: "context and USD cost retain their distinct semantics",
            updates: vec![SessionUpdate::UsageUpdate(
                UsageUpdate::new(42, 100).cost(Cost::new(0.25, "USD")),
            )],
            expected: vec![vec![
                attachment(AttachmentEvent::ContextUsage(
                    ContextUsage::provider_reported(42, Some(100)),
                )),
                StreamEffect::Status(StatusPatch {
                    total_cost_usd: Some(0.25),
                    ..StatusPatch::default()
                }),
            ]],
            result: "",
        },
        Case {
            // The pinned schema has no constructible unknown SessionUpdate;
            // this is its known-unhandled path, not an unsafe fake enum variant.
            name: "user echoes and unsupported metadata do not duplicate output",
            updates: vec![
                SessionUpdate::UserMessageChunk(ContentChunk::new("echo".into())),
                SessionUpdate::SessionInfoUpdate(SessionInfoUpdate::new()),
            ],
            expected: vec![vec![], vec![]],
            result: "",
        },
    ];
    for case in cases {
        let mut renderer = EventRenderer::new("/workspace".into());
        let effects = case
            .updates
            .into_iter()
            .map(|update| renderer.render(AgentEvent::from(update)))
            .collect::<Vec<_>>();
        assert_eq!(
            (effects, renderer.result_text()),
            (case.expected, case.result),
            "{}",
            case.name
        );
    }
}

// Covers: a turn end closes the presentation step, so the next turn's first
// event opens a new one instead of merging into the previous turn.
// Owner: pure protocol-to-artifact translation.
#[test]
fn turn_end_restarts_the_presentation_step() {
    let mut renderer = EventRenderer::new("/workspace".into());
    let running = AttachmentEvent::ToolStarted {
        key: Some("read-1".into()),
        card: read_card(ToolCardStatus::Running),
    };
    let effects = [
        AgentEvent::from(SessionUpdate::ToolCall(read_call())),
        AgentEvent::TurnEnded(Some(StopReason::MaxTokens)),
        AgentEvent::from(SessionUpdate::ToolCall(read_call())),
    ]
    .map(|event| renderer.render(event));
    assert_eq!(
        effects,
        [
            first_step(running.clone()),
            vec![StreamEffect::Status(StatusPatch {
                last_activity: Some("turn ended: max_tokens".into()),
                ..StatusPatch::default()
            })],
            first_step(running),
        ]
    );
}

// Covers: saturation cannot drop a completion or grow retained state/result
// without bound. Later updates must render even when their start was not retained.
// Owner: pure protocol-to-artifact translation.
#[test]
fn saturated_state_remains_bounded_and_unknown_completion_renders() {
    use crate::cli_runtime::stream_effect::MAX_RESULT_CHARS;

    let mut renderer = EventRenderer::new("/workspace".into());
    for index in 0..MAX_ACTIVE_TOOLS {
        renderer.render(AgentEvent::from(SessionUpdate::ToolCall(ToolCall::new(
            index.to_string(),
            "Tool",
        ))));
    }
    let effects = renderer.render(AgentEvent::from(SessionUpdate::ToolCall(ToolCall::new(
        "overflow", "Tool",
    ))));
    assert_eq!(
        (renderer.active_tools.len(), effects),
        (MAX_ACTIVE_TOOLS, vec![
            attachment(AttachmentEvent::ToolStarted {
                key: Some("overflow".into()),
                card: ToolCard::new(ToolCardStatus::Running, ToolFamily::Default, ToolHeader::call("Tool", /*primary*/ None)),
            }),
            attachment(AttachmentEvent::Notice(format!(
                "acp: active tool budget {MAX_ACTIVE_TOOLS}, requested {}; card renders without retained update state",
                MAX_ACTIVE_TOOLS + 1,
            ))),
        ]),
    );
    let completion = renderer.render(AgentEvent::from(SessionUpdate::ToolCallUpdate(
        ToolCallUpdate::new(
            "overflow",
            ToolCallUpdateFields::new().status(ToolCallStatus::Completed),
        ),
    )));
    assert_eq!(
        completion,
        vec![attachment(AttachmentEvent::ToolFinished {
            key: Some("overflow".into()),
            presentation: ToolCard::new(
                ToolCardStatus::Ok,
                ToolFamily::Default,
                ToolHeader::call("Tool", /*primary*/ None)
            )
            .into(),
        })]
    );
    for _ in 0..2 {
        renderer.render(AgentEvent::from(SessionUpdate::AgentMessageChunk(
            ContentChunk::new("界".repeat(MAX_RESULT_CHARS).into()),
        )));
    }
    assert_eq!(
        renderer.result_text(),
        format!("{}… [truncated result]", "界".repeat(MAX_RESULT_CHARS))
    );
}

// Covers: result.json must carry the final answer, not pre-tool narration or an
// earlier turn's reply (a head-truncated whole-session log could drop it).
// Owner: renderer result accounting.
#[test]
fn result_text_is_the_last_assistant_segment() {
    let text = |t: &str| {
        AgentEvent::from(SessionUpdate::AgentMessageChunk(ContentChunk::new(
            t.into(),
        )))
    };
    let cases: Vec<(&str, Vec<AgentEvent>, &str)> = vec![
        (
            "narration before a tool call is replaced by the answer after it",
            vec![
                text("I'll read the config."),
                AgentEvent::from(SessionUpdate::ToolCall(read_call())),
                text("DONE"),
            ],
            "DONE",
        ),
        (
            "a tool call with no later text keeps the earlier segment",
            vec![
                text("partial"),
                AgentEvent::from(SessionUpdate::ToolCall(read_call())),
            ],
            "partial",
        ),
        (
            "a follow-up turn's reply replaces the previous turn's reply",
            vec![
                text("first"),
                AgentEvent::TurnEnded(Some(StopReason::EndTurn)),
                text("second"),
            ],
            "second",
        ),
    ];
    for (name, events, expected) in cases {
        let mut renderer = EventRenderer::new(PathBuf::from("/workspace"));
        for event in events {
            renderer.render(event);
        }
        assert_eq!(renderer.result_text(), expected, "{name}");
    }
}

// Covers: a call of a served tool shows the served call's cards alone,
// under the agent's tool call id, whichever of the agent's announcement and
// the served call's first card renders first, with nothing of the agent's
// card, which would show over it; and one the agent ends before a served
// call drew it, as a call refused or cancelled before it ran, still shows,
// closed, as a call of no served tool shows, and stays closed when the
// served call draws after all, as it may when a cancel races the call; one
// the agent never ended nor ran by the turn's end shows interrupted.
// Owner: pure protocol-to-artifact translation (served calls).
#[test]
fn served_calls_show_their_own_cards_in_place_of_the_agents() {
    const ID: &str = "toolu_ui";
    let announced = || ToolCall::new(ID, "mcp__rho__ui");
    let update = |status| {
        AgentEvent::from(SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
            ID,
            ToolCallUpdateFields::new()
                .status(status)
                .content(vec!["the agent's result".into()]),
        )))
    };
    let card = |status| {
        ToolCard::new(
            status,
            ToolFamily::Form,
            ToolHeader::call("UI", /*primary*/ None),
        )
    };
    let surface = || rho_protocol::ToolContent::Surface {
        surface: "merge".into(),
        messages: Vec::new(),
    };
    let served = |card| AgentEvent::Served {
        call: ToolCallId::new(ID),
        card,
    };
    let started = || served(ServedCard::Started(card(ToolCardStatus::Running)));
    let progressed = || {
        served(ServedCard::Updated {
            card: card(ToolCardStatus::Running),
            content: vec![surface()],
        })
    };
    let finished = || {
        served(ServedCard::Finished {
            presentation: Presentation::Card(card(ToolCardStatus::Ok)),
            content: Vec::new(),
        })
    };
    let drawn = || {
        vec![
            attachment(AttachmentEvent::StepStarted),
            attachment(AttachmentEvent::ToolStarted {
                key: Some(ID.into()),
                card: card(ToolCardStatus::Running),
            }),
            attachment(AttachmentEvent::ToolUpdated {
                key: Some(ID.into()),
                card: card(ToolCardStatus::Running),
            }),
            attachment(AttachmentEvent::ToolContent {
                key: ID.into(),
                content: vec![surface()],
            }),
            attachment(AttachmentEvent::ToolFinished {
                key: Some(ID.into()),
                presentation: Presentation::Card(card(ToolCardStatus::Ok)),
            }),
        ]
    };
    // What the agent's card shows of a call of no served tool.
    let unserved = |events: Vec<AgentEvent>| {
        let mut renderer = EventRenderer::new("/workspace".into());
        events
            .into_iter()
            .flat_map(|event| renderer.render(event))
            .collect::<Vec<_>>()
    };
    let cases = [
        (
            "announced first",
            vec![
                AgentEvent::ServedToolCall(Box::new(announced())),
                update(ToolCallStatus::InProgress),
                started(),
                progressed(),
                finished(),
                update(ToolCallStatus::Completed),
            ],
            drawn(),
        ),
        (
            "drawn first",
            vec![
                started(),
                AgentEvent::ServedToolCall(Box::new(announced())),
                progressed(),
                update(ToolCallStatus::InProgress),
                finished(),
                update(ToolCallStatus::Completed),
            ],
            drawn(),
        ),
        (
            "ended before it ran",
            vec![
                AgentEvent::ServedToolCall(Box::new(announced())),
                update(ToolCallStatus::Failed),
            ],
            unserved(vec![
                AgentEvent::from(SessionUpdate::ToolCall(announced())),
                update(ToolCallStatus::Failed),
            ]),
        ),
        (
            "ended before it ran, then drawn",
            vec![
                AgentEvent::ServedToolCall(Box::new(announced())),
                update(ToolCallStatus::Failed),
                started(),
                progressed(),
                finished(),
            ],
            unserved(vec![
                AgentEvent::from(SessionUpdate::ToolCall(announced())),
                update(ToolCallStatus::Failed),
            ]),
        ),
        (
            "never ran by the turn's end",
            vec![
                AgentEvent::ServedToolCall(Box::new(announced())),
                AgentEvent::TurnEnded(Some(StopReason::Cancelled)),
            ],
            vec![
                attachment(AttachmentEvent::StepStarted),
                attachment(AttachmentEvent::ToolStarted {
                    key: Some(ID.into()),
                    card: ToolCard::new(
                        ToolCardStatus::Interrupted,
                        ToolFamily::Default,
                        ToolHeader::call("mcp__rho__ui", /*primary*/ None),
                    ),
                }),
                StreamEffect::Status(StatusPatch {
                    last_activity: Some("turn ended: cancelled".into()),
                    ..StatusPatch::default()
                }),
            ],
        ),
    ];
    for (name, events, expected) in cases {
        let mut renderer = EventRenderer::new("/workspace".into());
        let effects = events
            .into_iter()
            .flat_map(|event| renderer.render(event))
            .collect::<Vec<_>>();

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

// Covers: the agent's call of a served tool that shows on another call's
// card (an `await` of the stdio bridge) draws nothing, whichever of its
// announcement and the hiding renders first, and whatever the agent ends
// it with; one the agent ended before the hiding keeps the closed card it
// showed, and one already shown as the agent's keeps its card to its end;
// past the budget of calls in flight, the hiding says so and the agent's
// card shows. Kills: the held arm left as it was (the agent's end releases
// the await's card), the arm for a call not yet announced tracking nothing
// (its announcement is held, then released by its end), that arm's check
// for the agent's card shown already dropped (the card shown never
// closes), the budget check dropped (a call tracked past
// `MAX_ACTIVE_TOOLS`, silently).
// Owner: pure protocol-to-artifact translation (served calls).
#[test]
fn a_hidden_served_call_draws_nothing_of_its_own() {
    const ID: &str = "agy-await";
    let announced = || ToolCall::new(ID, "mcp_rho_await").status(ToolCallStatus::InProgress);
    let announce = || AgentEvent::ServedToolCall(Box::new(announced()));
    let hidden = || AgentEvent::ServedHidden(ToolCallId::new(ID));
    let ended = |status| {
        AgentEvent::from(SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
            ID,
            ToolCallUpdateFields::new().status(status),
        )))
    };
    let turn_ended = || {
        StreamEffect::Status(StatusPatch {
            last_activity: Some("turn ended: end_turn".into()),
            ..StatusPatch::default()
        })
    };
    let budget = || {
        attachment(AttachmentEvent::Notice(format!(
            "acp: active tool budget {MAX_ACTIVE_TOOLS}, requested {}; card renders without retained update state",
            MAX_ACTIVE_TOOLS + 1
        )))
    };
    // What the agent's card shows of a call of no served tool it ends with
    // `status`.
    let shown_by_agent = |status| {
        let mut unserved = EventRenderer::new("/workspace".into());
        [
            AgentEvent::from(SessionUpdate::ToolCall(announced())),
            ended(status),
        ]
        .into_iter()
        .flat_map(|event| unserved.render(event))
        .collect::<Vec<_>>()
    };
    let cases = [
        (
            "hidden before it is announced",
            /*busy*/ 0,
            vec![hidden(), announce(), ended(ToolCallStatus::Completed)],
            vec![turn_ended()],
        ),
        (
            "announced, then hidden",
            0,
            vec![announce(), hidden(), ended(ToolCallStatus::Completed)],
            vec![turn_ended()],
        ),
        (
            "hidden again once drawn",
            0,
            vec![
                hidden(),
                announce(),
                hidden(),
                ended(ToolCallStatus::Completed),
            ],
            vec![turn_ended()],
        ),
        (
            "ended by the agent before it is hidden",
            0,
            vec![announce(), ended(ToolCallStatus::Failed), hidden()],
            [shown_by_agent(ToolCallStatus::Failed), vec![turn_ended()]].concat(),
        ),
        (
            "shown as the agent's before it is hidden",
            0,
            vec![
                AgentEvent::from(SessionUpdate::ToolCall(announced())),
                hidden(),
                ended(ToolCallStatus::Completed),
            ],
            [
                shown_by_agent(ToolCallStatus::Completed),
                vec![turn_ended()],
            ]
            .concat(),
        ),
        (
            "hidden past the budget",
            MAX_ACTIVE_TOOLS,
            vec![hidden(), announce()],
            vec![
                budget(),
                attachment(AttachmentEvent::ToolStarted {
                    key: Some(ID.into()),
                    card: ToolCard::new(
                        ToolCardStatus::Running,
                        ToolFamily::Default,
                        ToolHeader::call("mcp_rho_await", /*primary*/ None),
                    ),
                }),
                budget(),
                turn_ended(),
            ],
        ),
    ];
    for (name, busy, events, expected) in cases {
        let mut renderer = EventRenderer::new("/workspace".into());
        // Other calls in flight, rendered before the case's own.
        for other in 0..busy {
            let call = ToolCall::new(format!("busy-{other}"), "Busy");
            renderer.render(AgentEvent::from(SessionUpdate::ToolCall(call)));
        }
        let effects = events
            .into_iter()
            .chain([AgentEvent::TurnEnded(Some(StopReason::EndTurn))])
            .flat_map(|event| renderer.render(event))
            .collect::<Vec<_>>();

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

// Covers: a served call's card that outlives the agent's end of its call,
// as a call the stdio bridge parked, stays the served call's: its later
// cards update and end it, and its end frees the call's slot of the budget
// of calls in flight; one still open as the run ends ends interrupted, as
// it last showed, since the run's end stops the call and its own end comes
// after the run stopped rendering; a card the call ended before stays as
// it ended. Kills: the agent's end forgetting a call whose served card is
// still open (`agent_ended` always forgetting: the served end re-tracks it
// and its slot leaks, `in_flight` 1), the served end of such a call not
// forgetting it (the same leak), the agent's end keeping a call whose card
// already ended (`agent_ended` never forgetting), the run's end leaving
// served cards open (the journal's end closes them as completed), a
// finished card not forgotten (closed a second time, as interrupted).
// Owner: pure protocol-to-artifact translation (served calls).
#[test]
fn a_parked_served_card_ends_by_its_own_end_or_the_runs() {
    const ID: &str = "agy-slow";
    let card = |status, primary: Option<&str>| {
        ToolCard::new(
            status,
            ToolFamily::Default,
            ToolHeader::call("Slow", primary.map(str::to_owned)),
        )
    };
    let served = |card| AgentEvent::Served {
        call: ToolCallId::new(ID),
        card,
    };
    let started = || served(ServedCard::Started(card(ToolCardStatus::Running, None)));
    let updated = || {
        served(ServedCard::Updated {
            card: card(ToolCardStatus::Running, Some("halfway")),
            content: Vec::new(),
        })
    };
    let finished = || {
        served(ServedCard::Finished {
            presentation: Presentation::Card(card(ToolCardStatus::Ok, None)),
            content: Vec::new(),
        })
    };
    let announce = || {
        AgentEvent::ServedToolCall(Box::new(
            ToolCall::new(ID, "mcp_rho_slow").status(ToolCallStatus::InProgress),
        ))
    };
    // The agent ends its call once the bridge answered it, parked or done.
    let agent_ended = || {
        AgentEvent::from(SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
            ID,
            ToolCallUpdateFields::new().status(ToolCallStatus::Completed),
        )))
    };
    let drew_started = || {
        vec![
            attachment(AttachmentEvent::StepStarted),
            attachment(AttachmentEvent::ToolStarted {
                key: Some(ID.into()),
                card: card(ToolCardStatus::Running, None),
            }),
        ]
    };
    let drew_updated = || {
        attachment(AttachmentEvent::ToolUpdated {
            key: Some(ID.into()),
            card: card(ToolCardStatus::Running, Some("halfway")),
        })
    };
    let drew_finished = || {
        attachment(AttachmentEvent::ToolFinished {
            key: Some(ID.into()),
            presentation: Presentation::Card(card(ToolCardStatus::Ok, None)),
        })
    };
    let interrupted = |primary| {
        vec![attachment(AttachmentEvent::ToolFinished {
            key: Some(ID.into()),
            presentation: Presentation::Card(card(ToolCardStatus::Interrupted, primary)),
        })]
    };
    // Its name, the events, then what they drew, the calls left in flight,
    // and what the run's end draws.
    let cases = [
        (
            "parked as the run ends",
            vec![announce(), started(), agent_ended()],
            drew_started(),
            1,
            interrupted(None),
        ),
        (
            "ended before the run",
            vec![announce(), started(), finished(), agent_ended()],
            [drew_started(), vec![drew_finished()]].concat(),
            0,
            Vec::new(),
        ),
        (
            "parked, then finished",
            vec![announce(), started(), agent_ended(), finished()],
            [drew_started(), vec![drew_finished()]].concat(),
            0,
            Vec::new(),
        ),
        (
            "parked, then updated",
            vec![announce(), started(), agent_ended(), updated()],
            [drew_started(), vec![drew_updated()]].concat(),
            1,
            interrupted(Some("halfway")),
        ),
        (
            "parked, updated, then finished",
            vec![announce(), started(), agent_ended(), updated(), finished()],
            [drew_started(), vec![drew_updated(), drew_finished()]].concat(),
            0,
            Vec::new(),
        ),
    ];
    for (name, events, drew, in_flight, run_end) in cases {
        let mut renderer = EventRenderer::new("/workspace".into());
        let effects: Vec<_> = events
            .into_iter()
            .flat_map(|event| renderer.render(event))
            .collect();
        let left = renderer.in_flight();

        assert_eq!(
            (effects, left, renderer.run_ended()),
            (drew, in_flight, run_end),
            "{name}"
        );
    }
}