rho-coding-agent 3.13.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
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
use std::{path::Path, sync::Arc};

use pretty_assertions::assert_eq;
use rho_protocol::{
    CardTone, CompactionCounts, CompactionId, CompactionStatus, ContentBlock, MessageId,
    MessageOrigin, PlanEntry, PlanStatus, RhoNotice, SessionEvent as WireEvent, SubagentRef,
    ToolCallId, ToolCallUpdate, ToolContent, ToolKind, ToolStatus,
};
use rho_sdk::{
    model::{self, AbortedAssistant, AssistantMessage, Message, ToolResult},
    tool::{ToolMetadata, ToolOutput},
    ContextEstimate, RunEvent, ToolCompletion, ToolExecution, UserInput,
};
use serde_json::json;

use super::{Boundary, SavedTranscript, SavedTurn, TurnEvents};
use crate::{
    agent::{AgentCapabilities, ToolCapability},
    app::{
        attach::TextView,
        session_events::{
            test_support::{
                canonical_messages, closed, finished, opened, origin, rendered, shell_call, text,
                updated, without_display, Placement,
            },
            CallIds, FeedEvent, LiveEvents, RESUME_NOTE,
        },
        session_runtime::{InsertedMessage, SessionEvent, SessionTools, TurnKeys},
    },
    config::Config,
    diagnostics::RuntimeDiagnostics,
    display_transcript::{DisplayRow, DisplayTranscript},
    session::tree::{DisplayMarks, ProjectedMessage, SubagentLink, TurnEnd},
    tools::{
        sdk_registry::{AppToolSet, ToolSetOptions},
        todo::{TodoItem, TodoList, TodoStatus},
    },
};

/// `messages` as display rows, each saved as its own row.
fn saved_rows(messages: &[Message]) -> Vec<ProjectedMessage> {
    messages
        .iter()
        .enumerate()
        .map(|(row, message)| ProjectedMessage {
            message_origin: None,
            origin: Some(origin(row)),
            message: message.clone(),
            saved_at: None,
            key: None,
            turn_end: None,
            subagent: None,
        })
        .collect()
}

/// The events a client that resets replays once `messages` saved as one
/// turn with the tools of `tool_set`.
fn replay_with(tool_set: &AppToolSet, messages: &[Message]) -> Vec<WireEvent> {
    let mut transcript = SavedTranscript::default();
    transcript.push(SavedTurn::capture(
        &saved_rows(messages),
        Path::new("/work"),
        SessionTools::of_tool_set_for_tests(tool_set),
        &mut CallIds::default(),
    ));
    transcript.events().map(|event| event.event).collect()
}

fn replay_messages(messages: &[Message]) -> Vec<WireEvent> {
    replay_with(&AppToolSet::disabled(), messages)
}

/// What a replay renders of `messages` saved as one turn, and what it
/// sends: before and after [`FinishedCalls`] joins each finished call's open
/// and result. Before, each open goes as its call opens, as live sends it.
fn replay_stages(messages: &[Message]) -> (Vec<FeedEvent>, Vec<FeedEvent>) {
    let tool_set = AppToolSet::disabled();
    let mut transcript = SavedTranscript::default();
    transcript.push(SavedTurn::capture(
        &saved_rows(messages),
        Path::new("/work"),
        SessionTools::of_tool_set_for_tests(&tool_set),
        &mut CallIds::default(),
    ));
    let joined: Vec<_> = transcript.events().collect();
    assert_eq!(joined.len(), transcript.len());
    (
        TurnEvents::new(Arc::clone(&transcript.turns[0])).collect(),
        joined,
    )
}

/// What a replay renders of `messages` saved as one turn, before
/// [`FinishedCalls`] joins each finished call's open and result.
fn rendered_rows(messages: &[Message]) -> Vec<FeedEvent> {
    replay_stages(messages).0
}

fn wire(events: Vec<FeedEvent>) -> Vec<WireEvent> {
    events.into_iter().map(|event| event.event).collect()
}

fn call_block(id: &str) -> model::ContentBlock {
    model::ContentBlock::ToolCall(shell_call(id, "ls"))
}

fn saved_id(row: usize, part: u32) -> MessageId {
    MessageId::new(format!("saved-node-{row}-{part}"))
}

fn user(message: MessageId, text: &str) -> WireEvent {
    WireEvent::UserMessage {
        message,
        content: vec![ContentBlock::Text { text: text.into() }],
        steer: None,
    }
}

fn saved_agent(message: MessageId, text: &str) -> WireEvent {
    WireEvent::AgentMessageChunk {
        message,
        text: text.into(),
    }
}

fn image() -> model::ImageContent {
    model::ImageContent {
        data: "YWJj".into(),
        mime_type: "image/png".into(),
    }
}

fn image_content() -> ToolContent {
    ToolContent::Image {
        mime_type: "image/png".into(),
        data: "YWJj".into(),
    }
}

fn background_transcript() -> DisplayTranscript {
    DisplayTranscript(vec![DisplayRow::Notice("Background done\nall good".into())])
}

/// The conversation both the replay and the agreement tests use, as saved.
fn saved_conversation() -> Vec<Message> {
    vec![
        Message::user_text("list files"),
        Message::Assistant(
            vec![
                model::ContentBlock::Text("Let me look.".into()),
                call_block("call-1"),
            ]
            .into(),
        ),
        Message::ToolResult(ToolResult::succeeded("call-1", "a.rs").into()),
        background_transcript().display_message(),
        Message::assistant_text("Found a.rs."),
    ]
}

// Covers: a saved conversation replays whole messages with ids from the
// rows they were saved in, a finished call with its provider id as one
// event at its result, and a background result's rows as cards, in saved
// order.
// Owner: session event replay
#[test]
fn a_saved_conversation_replays_messages_calls_and_cards() {
    assert_eq!(
        without_display(replay_messages(&saved_conversation())),
        vec![
            user(saved_id(0, 0), "list files"),
            saved_agent(saved_id(1, 0), "Let me look."),
            finished("call-1", "ls", ToolStatus::Completed, vec![text("a.rs")]),
            WireEvent::Card {
                title: "Background done".into(),
                markdown: "all good".into(),
                plain: "all good".into(),
                tone: CardTone::Neutral,
                display: None,
            },
            saved_agent(saved_id(4, 0), "Found a.rs."),
        ]
    );
}

// Covers: a transcript's boundaries fall after each saved row, but not a
// row whose call open waits for its result row, which goes out later, and
// the turn's last row's falls at the turn's end; a resume starts at its
// entry's boundary, and a row with none resumes nothing. A boundary placed
// before a row's events all went out would make a resumed client skip them.
// Owner: session event replay
#[test]
fn a_transcript_marks_where_its_replay_passes_each_saved_row() {
    let tool_set = AppToolSet::disabled();
    let mut transcript = SavedTranscript::default();
    for _ in 0..2 {
        transcript.push(SavedTurn::capture(
            &saved_rows(&saved_conversation()),
            Path::new("/work"),
            SessionTools::of_tool_set_for_tests(&tool_set),
            &mut CallIds::default(),
        ));
    }
    let boundary = |index, row: usize| Boundary {
        index,
        entry: rho_protocol::EntryId::new(format!("node/{row}")),
    };

    // Each turn sends the user message, the agent's text, the call once
    // its result came, the card, and the agent's answer. Both turns save
    // the same rows, so the same entries; only their boundaries move.
    let turn = [
        boundary(1, 0),
        boundary(3, 2),
        boundary(4, 3),
        boundary(5, 4),
    ];
    let expected: Vec<_> = turn
        .iter()
        .cloned()
        .chain(turn.iter().map(|b| Boundary {
            index: b.index + 5,
            entry: b.entry.clone(),
        }))
        .collect();
    assert_eq!(transcript.boundaries(), expected);
    assert_eq!(transcript.final_entry(), Some(expected[7].entry.clone()));
    let all: Vec<_> = transcript.events().map(|event| event.event).collect();
    let from_second_turn_card: Vec<_> =
        transcript.events_from(8).map(|event| event.event).collect();
    assert_eq!(from_second_turn_card, all[8..]);
    assert_eq!(
        transcript.start_of(&boundary(0, 1).entry),
        None,
        "the row whose call waited"
    );

    // A load that finds no result for the call adds an interrupted one,
    // which no row saved: the call's row ends where that settles it.
    let mut rows = saved_rows(&saved_conversation());
    rows[2].origin = None;
    rows[2].message = Message::ToolResult(ToolResult::interrupted("call-1").into());
    let mut reloaded = SavedTranscript::default();
    reloaded.push(SavedTurn::capture(
        &rows,
        Path::new("/work"),
        SessionTools::of_tool_set_for_tests(&tool_set),
        &mut CallIds::default(),
    ));
    assert_eq!(
        reloaded.boundaries(),
        [
            boundary(1, 0),
            boundary(3, 1),
            boundary(4, 3),
            boundary(5, 4)
        ]
    );
}

// Covers: a compaction replays where its row sits as the completed
// compaction event a live one ends with, carrying its counts, under an id
// from its row that stays the same on every load, rather than as agent text
// a markdown client runs together into one line.
// Owner: session event replay
#[test]
fn a_saved_compaction_replays_as_a_completed_compaction() {
    let counts = CompactionCounts {
        previous_messages: 263,
        current_messages: 65,
        previous_tokens: 247_276,
        current_tokens: 54_798,
        cost_usd_micros: Some(12_345),
    };
    assert_eq!(
        replay_messages(&[
            Message::user_text("long talk"),
            DisplayTranscript(vec![DisplayRow::Compaction(counts)]).display_message(),
            Message::user_text("after"),
        ]),
        vec![
            user(saved_id(0, 0), "long talk"),
            WireEvent::Compaction {
                id: CompactionId::new("saved-compaction-node-1"),
                status: CompactionStatus::Completed { counts },
            },
            user(saved_id(2, 0), "after"),
        ]
    );
}

// Covers: a client sees the same conversation live and replayed: the same
// messages (the user message under the same id), the same cards and the
// same calls, drawn with the same TUI cards, apart from how live text was
// chunked, the usage only live steps report, and the finished calls a
// replay joins (`held_opens_show_as_the_opens_and_results_did`).
// Owner: session event live and replay mapping
#[test]
fn live_and_replayed_turns_agree() {
    let tool_set = AppToolSet::disabled();
    let mut live = LiveEvents::new(
        Path::new("/work"),
        SessionTools::of_tool_set_for_tests(&tool_set),
        /*configured_window*/ None,
    );
    live.prompt(&UserInput::text("list files"), /*origin*/ None);
    let step = || {
        SessionEvent::Run(RunEvent::StepStarted {
            step: 0,
            context_estimate: ContextEstimate::from_estimated_tokens(10),
        })
    };
    let delta = |text: &str| SessionEvent::Run(RunEvent::AssistantTextDelta { text: text.into() });
    let call_id = rho_sdk::ToolCallId::from_string("call-1").unwrap();
    let events = [
        SessionEvent::MessageInserted(InsertedMessage::Saved(origin(0))),
        SessionEvent::RunStarted {
            keys: TurnKeys::for_tests("turn"),
        },
        step(),
        delta("Let me "),
        delta("look."),
        SessionEvent::Run(RunEvent::ToolProposed {
            call: shell_call("call-1", "ls"),
        }),
        SessionEvent::Run(RunEvent::ToolStarted {
            call_id: call_id.clone(),
            name: "bash".into(),
            metadata: ToolMetadata::new(),
            execution: ToolExecution::Attached,
        }),
        SessionEvent::Run(RunEvent::ToolFinished {
            call_id,
            result: ToolCompletion::Completed(ToolOutput::text("a.rs")),
        }),
        SessionEvent::BoundaryApplied {
            transcript: background_transcript(),
        },
        step(),
        delta("Found "),
        delta("a.rs."),
        SessionEvent::RunClosed,
        SessionEvent::RunFinished {
            context: ContextEstimate::from_estimated_tokens(10),
        },
    ];
    let live_events: Vec<_> = events
        .iter()
        .flat_map(|event| live.map(event))
        .map(|event| event.event)
        .collect();
    let replayed = wire(rendered_rows(&saved_conversation()));

    let users = |events: &[WireEvent]| -> Vec<WireEvent> {
        events
            .iter()
            .filter(|event| matches!(event, WireEvent::UserMessage { .. }))
            .cloned()
            .collect()
    };
    assert_eq!(users(&live_events), users(&replayed));
    let live_conversation = live_events
        .into_iter()
        .filter(|event| !matches!(event, WireEvent::Usage { .. } | WireEvent::ProviderRequest))
        .collect();
    assert_eq!(
        canonical_messages(merged_chunks(live_conversation)),
        canonical_messages(replayed)
    );
}

/// What `rho attach` prints of `events`.
fn attach_text(events: &[WireEvent]) -> String {
    let mut out = Vec::new();
    let mut view = TextView::new(&mut out, std::io::sink());
    for event in events {
        view.show(event).unwrap();
    }
    drop(view);
    String::from_utf8(out).unwrap()
}

// Covers: a finished call replays as one event, and every client shows the
// replay as it showed the one that sent each open as its call opened:
// wherever it places a call (its first event, where it closes), and in
// `rho attach`'s text, which prints a title line at the first and a
// failure line at the close.
// Owner: session event replay
#[test]
fn held_opens_show_as_the_opens_and_results_did() {
    let ok = |id: &str| Message::ToolResult(ToolResult::succeeded(id, format!("{id}.rs")).into());
    let failed = |id: &str| Message::ToolResult(ToolResult::failed(id, "denied").into());
    let assistant = |blocks: Vec<model::ContentBlock>| Message::Assistant(blocks.into());
    let said = |text: &str| model::ContentBlock::Text(text.into());
    let reasoned = Message::assistant(AssistantMessage {
        reasoning_summary: Some("why".into()),
        ..AssistantMessage::from_content(vec![said("before"), call_block("a"), said("after")])
    });
    // Each conversation, and how many of its calls go as one event.
    let cases = [
        (
            vec![
                Message::user_text("look"),
                assistant(vec![said("Both."), call_block("a"), call_block("b")]),
                ok("a"),
                failed("b"),
                assistant(vec![call_block("c"), model::ContentBlock::Image(image())]),
                ok("c"),
            ],
            3,
        ),
        // A failure line printed before the next call's title would pass it.
        (
            vec![
                assistant(vec![call_block("a"), call_block("b")]),
                failed("a"),
                ok("b"),
            ],
            0,
        ),
        // A call placed where it closes would pass the call opened before it.
        (
            vec![
                assistant(vec![call_block("a"), call_block("b")]),
                ok("b"),
                ok("a"),
            ],
            0,
        ),
        (
            vec![
                assistant(vec![call_block("a"), said("between"), call_block("b")]),
                failed("b"),
                ok("a"),
            ],
            1,
        ),
        (vec![reasoned, ok("a")], 0),
        (
            vec![
                assistant(vec![call_block("reused")]),
                assistant(vec![call_block("reused")]),
                failed("reused"),
                assistant(vec![call_block("left")]),
                ok("orphan"),
            ],
            1,
        ),
    ];
    for (messages, merged) in cases {
        let (before, joined) = replay_stages(&messages);
        let sent = wire(before);
        let held = wire(joined);
        for placement in [Placement::FirstEvent, Placement::Close] {
            assert_eq!(
                rendered(held.clone(), placement),
                rendered(sent.clone(), placement),
                "{placement:?} {messages:?}"
            );
        }
        assert_eq!(attach_text(&held), attach_text(&sent), "{messages:?}");
        assert_eq!(sent.len() - held.len(), merged, "{messages:?}");
    }
}

// Covers: a message keeps its id live and replayed: the reasoning, each
// stretch of a reply's text (every chunk of one under one id, text after a
// call a new message, whether or not the call showed yet), a steer whether
// its record or its application reaches the daemon first, and the next
// step's reply, once saved under the keys the turn's saves give them.
// Owner: session event live and replay mapping
#[test]
fn a_message_keeps_its_live_id_when_replayed() {
    let turn = TurnKeys::for_tests("turn");
    let step = |step| {
        SessionEvent::Run(RunEvent::StepStarted {
            step,
            context_estimate: ContextEstimate::from_estimated_tokens(10),
        })
    };
    let delta = |text: &str| SessionEvent::Run(RunEvent::AssistantTextDelta { text: text.into() });
    let steer = rho_sdk::SteeringId::new();
    let applied = SessionEvent::Run(RunEvent::SteeringApplied {
        ids: vec![steer.clone()],
    });
    let call_id = rho_sdk::ToolCallId::from_string("call-1").unwrap();
    let first_step = |call_arguments: &str| {
        [
            SessionEvent::MessageInserted(InsertedMessage::Saved(origin(0))),
            SessionEvent::RunStarted { keys: turn.clone() },
            step(1),
            SessionEvent::Run(RunEvent::ReasoningDelta { text: "why".into() }),
            delta("Let me "),
            delta("look."),
            SessionEvent::Run(RunEvent::ToolCallUpdated {
                index: 0,
                id: Some("call-1".into()),
                name: Some("bash".into()),
                arguments_delta: call_arguments.into(),
            }),
            delta(" Then "),
            delta("this."),
            SessionEvent::Run(RunEvent::ToolProposed {
                call: shell_call("call-1", "ls"),
            }),
            SessionEvent::Run(RunEvent::ToolStarted {
                call_id: call_id.clone(),
                name: "bash".into(),
                metadata: ToolMetadata::new(),
                execution: ToolExecution::Attached,
            }),
            SessionEvent::Run(RunEvent::ToolFinished {
                call_id: call_id.clone(),
                result: ToolCompletion::Completed(ToolOutput::text("a.rs")),
            }),
        ]
    };
    let next_step = [
        step(2),
        delta("Found "),
        delta("a.rs."),
        SessionEvent::RunClosed,
        SessionEvent::RunFinished {
            context: ContextEstimate::from_estimated_tokens(10),
        },
    ];
    let reply = AssistantMessage {
        reasoning_summary: Some("why".into()),
        ..AssistantMessage::from_content(vec![
            model::ContentBlock::Text("Let me look.".into()),
            call_block("call-1"),
            model::ContentBlock::Text(" Then this.".into()),
        ])
    };
    let mut saved = saved_rows(&[
        Message::user_text("list files"),
        Message::assistant(reply),
        Message::ToolResult(ToolResult::succeeded("call-1", "a.rs").into()),
        Message::user_text("use tabs"),
        Message::assistant(AssistantMessage::from_content(vec![
            model::ContentBlock::Text("Found a.rs.".into()),
        ])),
    ]);
    saved[1].key = Some(turn.reply(1));
    saved[3].key = Some(turn.steer(1));
    saved[4].key = Some(turn.reply(2));
    let tool_set = AppToolSet::disabled();
    let tools = || SessionTools::of_tool_set_for_tests(&tool_set);
    let mut transcript = SavedTranscript::default();
    transcript.push(SavedTurn::capture(
        &saved,
        Path::new("/work"),
        tools(),
        &mut CallIds::default(),
    ));
    let replayed = messages(transcript.events().map(|event| event.event).collect());

    for (name, call_arguments, recorded_first) in [
        (
            "a call shown as it streams; a steer recorded before it applies",
            r#"{"command":"ls"}"#,
            true,
        ),
        (
            "a call not shown until it starts; a steer applied before the daemon records it",
            "",
            false,
        ),
    ] {
        let mut live =
            LiveEvents::new(Path::new("/work"), tools(), /*configured_window*/ None);
        live.prompt(&UserInput::text("list files"), /*origin*/ None);
        let mut events: Vec<_> = first_step(call_arguments)
            .iter()
            .flat_map(|event| live.map(event))
            .map(|event| event.event)
            .collect();
        if recorded_first {
            live.steered(
                steer.clone(),
                &UserInput::text("use tabs"),
                /*origin*/ None,
            );
            events.extend(live.map(&applied).into_iter().map(|event| event.event));
        } else {
            events.extend(live.map(&applied).into_iter().map(|event| event.event));
            live.steered(
                steer.clone(),
                &UserInput::text("use tabs"),
                /*origin*/ None,
            );
        }
        events.extend(
            next_step
                .iter()
                .flat_map(|event| live.map(event))
                .map(|event| event.event),
        );
        assert_eq!(messages(events), replayed, "{name}");
    }
}

/// The messages of `events`: each one's kind, id and whole text, its
/// chunks joined.
fn messages(events: Vec<WireEvent>) -> Vec<(&'static str, MessageId, String)> {
    merged_chunks(events)
        .into_iter()
        .filter_map(|event| match event {
            WireEvent::UserMessage {
                message, content, ..
            } => {
                let text = content
                    .into_iter()
                    .map(|block| match block {
                        ContentBlock::Text { text } => text,
                        other => panic!("unexpected block {other:?}"),
                    })
                    .collect();
                Some(("user", message, text))
            }
            WireEvent::AgentMessageChunk { message, text } => Some(("agent", message, text)),
            WireEvent::ThoughtChunk { message, text } => Some(("thought", message, text)),
            _ => None,
        })
        .collect()
}

/// `events` with consecutive chunks of one message joined into one.
fn merged_chunks(events: Vec<WireEvent>) -> Vec<WireEvent> {
    let mut merged: Vec<WireEvent> = Vec::new();
    for event in events {
        let extends_last = match (merged.last_mut(), &event) {
            (
                Some(WireEvent::AgentMessageChunk { message, text }),
                WireEvent::AgentMessageChunk {
                    message: next,
                    text: more,
                },
            )
            | (
                Some(WireEvent::ThoughtChunk { message, text }),
                WireEvent::ThoughtChunk {
                    message: next,
                    text: more,
                },
            ) if message == next => {
                text.push_str(more);
                true
            }
            _ => false,
        };
        if !extends_last {
            merged.push(event);
        }
    }
    merged
}

// Covers: parallel calls keep their ids and order, a result lands on its own
// call whatever order results arrive in, and its images follow its output.
// Owner: session event replay
#[test]
fn replay_pairs_out_of_order_results_with_their_images() {
    for (result, status) in [
        (ToolResult::succeeded("b", "output"), ToolStatus::Completed),
        (ToolResult::failed("b", "output"), ToolStatus::Failed),
    ] {
        let messages = vec![
            Message::user_text("read images"),
            Message::Assistant(
                vec![
                    call_block("a"),
                    model::ContentBlock::Text("between".into()),
                    call_block("b"),
                ]
                .into(),
            ),
            Message::ToolResult(result.with_images(vec![image()]).into()),
            Message::ToolResult(ToolResult::succeeded("a", String::new()).into()),
        ];
        assert_eq!(
            without_display(replay_messages(&messages)),
            vec![
                user(saved_id(0, 0), "read images"),
                opened("a", "ls"),
                saved_agent(saved_id(1, 0), "between"),
                finished("b", "ls", status, vec![text("output"), image_content()]),
                updated("a", ToolStatus::Completed, Vec::new()),
            ]
        );
    }
}

// Covers: history a killed process left without results does not leave
// calls running, whichever kind of assistant message holds them, and a
// result without its call still opens a complete card.
// Owner: session event replay
#[test]
fn replay_closes_incomplete_calls_and_opens_orphan_results() {
    for message in [
        Message::Assistant(vec![call_block("a")].into()),
        Message::EnrichedAssistant(Arc::new(AssistantMessage::from_content(vec![call_block(
            "a",
        )]))),
        Message::AbortedAssistant(Arc::new(AbortedAssistant {
            content: vec![call_block("a")],
            ..Default::default()
        })),
    ] {
        assert_eq!(
            without_display(replay_messages(&[message])),
            vec![opened("a", "ls"), closed("a")]
        );
    }
    for (result, status) in [
        (
            ToolResult::succeeded("orphan", "output"),
            ToolStatus::Completed,
        ),
        (ToolResult::failed("orphan", "output"), ToolStatus::Failed),
    ] {
        assert_eq!(
            without_display(replay_messages(&[Message::ToolResult(result.into())])),
            vec![WireEvent::tool_call(ToolCallUpdate {
                id: ToolCallId::new("orphan"),
                title: Some("tool".into()),
                kind: Some(ToolKind::Other),
                status: Some(status),
                raw_input: None,
                content: Some(vec![text("output")]),
                locations: None,
                display: None,
            })]
        );
    }
}

// Covers: a saved result shows how its call ended live: one a cancelled
// turn interrupted `cancelled`, as live closed it; an interruption in a turn
// that failed, or one a load or an earlier rho saved, and a real failure in
// a cancelled turn, `failed`.
// Owner: session event replay
#[test]
fn a_saved_result_replays_how_its_call_ended() {
    let interrupted = ToolResult::interrupted("a");
    let denied = ToolResult::failed("a", "denied");
    let done = ToolResult::succeeded("a", "done");
    let cases = [
        (
            Some(TurnEnd::Cancelled),
            &interrupted,
            ToolStatus::Cancelled,
        ),
        (Some(TurnEnd::Failed), &interrupted, ToolStatus::Failed),
        (Some(TurnEnd::Unknown), &interrupted, ToolStatus::Failed),
        (None, &interrupted, ToolStatus::Failed),
        (Some(TurnEnd::Cancelled), &denied, ToolStatus::Failed),
        (Some(TurnEnd::Cancelled), &done, ToolStatus::Completed),
    ];
    for (turn_end, result, status) in cases {
        // A step's save holds the call; the turn's settling save, the result.
        let mut rows = saved_rows(&[
            Message::Assistant(vec![call_block("a")].into()),
            Message::ToolResult(result.clone().into()),
        ]);
        rows[1].turn_end = turn_end;
        let mut transcript = SavedTranscript::default();
        transcript.push(SavedTurn::capture(
            &rows,
            Path::new("/work"),
            SessionTools::of_tool_set_for_tests(&AppToolSet::disabled()),
            &mut CallIds::default(),
        ));
        // A cancelled call stays opened, then updated: rho-ui shows
        // `cancelled` only on a call it saw running.
        let sent = if status == ToolStatus::Cancelled {
            vec![
                opened("a", "ls"),
                updated("a", status, vec![text(&result.content)]),
            ]
        } else {
            vec![finished("a", "ls", status, vec![text(&result.content)])]
        };
        assert_eq!(
            without_display(transcript.events().map(|event| event.event).collect()),
            sent,
            "{turn_end:?} {result:?}"
        );
    }
}

// Covers: a replayed event carries when the row it shows was saved, and a
// call the replay closes itself, superseded or left open at the end,
// carries no time. A miss dates a closing the session never saved at the
// next row's time.
// Owner: session event replay
#[test]
fn replayed_events_carry_their_rows_time_and_closings_none() {
    let rows: Vec<_> = [
        (1_000, Message::Assistant(vec![call_block("reused")].into())),
        (2_000, Message::Assistant(vec![call_block("reused")].into())),
    ]
    .into_iter()
    .enumerate()
    .map(|(row, (saved_at, message))| ProjectedMessage {
        message_origin: None,
        origin: Some(origin(row)),
        message,
        saved_at: Some(saved_at),
        key: None,
        turn_end: None,
        subagent: None,
    })
    .collect();
    let mut transcript = SavedTranscript::default();
    transcript.push(SavedTurn::capture(
        &rows,
        Path::new("/work"),
        SessionTools::of_tool_set_for_tests(&AppToolSet::disabled()),
        &mut CallIds::default(),
    ));

    let (events, times): (Vec<_>, Vec<_>) = transcript
        .events()
        .map(|event| (event.event, event.at))
        .unzip();
    assert_eq!(
        (without_display(events), times),
        (
            vec![
                opened("reused", "ls"),
                closed("reused"),
                opened("reused#2", "ls"),
                closed("reused#2"),
            ],
            vec![Some(1_000), None, Some(2_000), None],
        )
    );
}

// Covers: a provider id reused across turns opens a new call rather than
// updating the earlier one, an unfinished occurrence it supersedes closes,
// and later results and end-of-history closing reach the newest call.
// Owner: session event replay
#[test]
fn replay_gives_reused_provider_ids_their_own_calls() {
    let messages = vec![
        Message::Assistant(vec![call_block("reused")].into()),
        Message::Assistant(vec![call_block("reused")].into()),
        Message::ToolResult(
            ToolResult::failed("reused", "second output")
                .with_images(vec![image()])
                .into(),
        ),
        Message::Assistant(vec![call_block("reused")].into()),
    ];
    assert_eq!(
        without_display(replay_messages(&messages)),
        vec![
            opened("reused", "ls"),
            closed("reused"),
            finished(
                "reused#2",
                "ls",
                ToolStatus::Failed,
                vec![text("second output"), image_content()]
            ),
            opened("reused#3", "ls"),
            closed("reused#3"),
        ]
    );
}

// Covers: replayed messages split where live ones do (text after a tool
// call, a reasoning summary), come in live order (the summary before the
// text it led to), and take ids from their saved row, so equal text saved
// twice is two messages.
// Owner: session event replay
#[test]
fn replayed_messages_split_where_live_ones_do() {
    let assistant = AssistantMessage {
        reasoning_summary: Some("why".into()),
        ..AssistantMessage::from_content(vec![
            model::ContentBlock::Text("before".into()),
            call_block("a"),
            model::ContentBlock::Text("after".into()),
            model::ContentBlock::Text(" more".into()),
        ])
    };
    let messages = vec![
        Message::user_text("continue"),
        Message::assistant(assistant),
        Message::ToolResult(ToolResult::succeeded("a", String::new()).into()),
        Message::user_text("continue"),
    ];
    assert_eq!(
        without_display(replay_messages(&messages)),
        vec![
            user(saved_id(0, 0), "continue"),
            WireEvent::ThoughtChunk {
                message: saved_id(1, 0),
                text: "why".into(),
            },
            saved_agent(saved_id(1, 1), "before"),
            opened("a", "ls"),
            saved_agent(saved_id(1, 2), "after more"),
            updated("a", ToolStatus::Completed, Vec::new()),
            user(saved_id(3, 0), "continue"),
        ]
    );
}

// Covers: a replayed call of a registered tool gets the kind its tool
// reports at start, as a live call does, including a tool that builds its
// metadata while preparing (`sessions`); an unknown tool stays `other`.
// Owner: session event replay; saved history keeps no tool metadata.
#[test]
fn replayed_calls_take_their_kind_from_the_session_tools() {
    let config = Config::default();
    let tool_set = AppToolSet::new(
        &config,
        RuntimeDiagnostics::new(&config),
        ToolSetOptions::new(AgentCapabilities::new(
            [
                ToolCapability::ReadFile,
                ToolCapability::Grep,
                ToolCapability::Sessions,
            ]
            .into(),
        )),
    );
    let call = |id: &str, name: &str, arguments| {
        model::ContentBlock::ToolCall(model::ToolCall::new(id.into(), name.into(), arguments))
    };
    let messages = [Message::assistant(AssistantMessage::from_content(vec![
        call("a", "read_file", json!({"path": "src/lib.rs"})),
        call("b", "grep", json!({"pattern": "fn main"})),
        call("s", "sessions", json!({"action": "search", "query": "x"})),
        call("c", "not_a_tool", json!({})),
    ]))];
    let kinds: Vec<_> = replay_with(&tool_set, &messages)
        .into_iter()
        .filter_map(|event| match event {
            WireEvent::ToolCall(update) => update.kind,
            _ => None,
        })
        .collect();
    assert_eq!(
        kinds,
        vec![
            ToolKind::Read,
            ToolKind::Search,
            ToolKind::Read,
            ToolKind::Other
        ]
    );
}

// Covers: a sessions call's title names its action and target without the
// card header's tense verb: a new session by its quoted first prompt and
// the agent it runs as, though its card's header leads with the agent.
// Owner: session event titles, through the registered sessions tool.
#[test]
fn sessions_calls_are_titled_by_action_and_target() {
    let config = Config::default();
    let tool_set = AppToolSet::new(
        &config,
        RuntimeDiagnostics::new(&config),
        ToolSetOptions::new(AgentCapabilities::new([ToolCapability::Sessions].into())),
    );
    let call = |id: &str, arguments| {
        model::ContentBlock::ToolCall(model::ToolCall::new(
            id.into(),
            "sessions".into(),
            arguments,
        ))
    };
    let messages = [Message::assistant(AssistantMessage::from_content(vec![
        call(
            "a",
            json!({"action": "new", "workspace": "/w", "prompt": "Fix it\nthen test"}),
        ),
        call(
            "b",
            json!({"action": "new", "workspace": "/w", "prompt": "Port it", "agent": "worker"}),
        ),
        call(
            "c",
            json!({"action": "wait", "session": "1a2b3c4d-0000-4000-8000-000000000000"}),
        ),
    ]))];
    let titles: Vec<_> = replay_with(&tool_set, &messages)
        .into_iter()
        .filter_map(|event| match event {
            WireEvent::ToolCall(update) => update.title,
            _ => None,
        })
        .collect();
    assert_eq!(
        titles,
        [
            "new \"Fix it\"",
            "new \"Port it\" (worker)",
            "wait 1a2b3c4d"
        ]
    );
}

// Covers: a process call's title says what it runs, as a shell call's does:
// a start is titled by its bare command, which Zed shows as an execute
// card's command, and a poll or stop names the process it acts on. Replay
// and live calls share the title, from the metadata the real tool reports.
// Owner: session event replay titles, through the registered process tool
#[test]
fn process_call_titles_name_what_they_run() {
    let config = Config::default();
    let tool_set = AppToolSet::new(
        &config,
        RuntimeDiagnostics::new(&config),
        ToolSetOptions::new(AgentCapabilities::new([ToolCapability::Process].into())),
    );
    let call = |id: &str, arguments| {
        model::ContentBlock::ToolCall(model::ToolCall::new(id.into(), "process".into(), arguments))
    };
    let command = "cd /work/app && .venv/bin/python -m unittest tests.test_app";
    let messages = [Message::assistant(AssistantMessage::from_content(vec![
        call("a", json!({"action": "start", "command": command})),
        call("b", json!({"action": "poll", "process_id": "process-1"})),
        call("c", json!({"action": "stop", "process_id": "process-1"})),
    ]))];
    let titles: Vec<_> = replay_with(&tool_set, &messages)
        .into_iter()
        .filter_map(|event| match event {
            // Only a call's opening carries its title; replay then closes
            // these result-less calls with status-only updates.
            WireEvent::ToolCall(update) => update.title.map(|title| (update.kind, title)),
            _ => None,
        })
        .collect();
    assert_eq!(
        titles,
        vec![
            (Some(ToolKind::Execute), command.to_owned()),
            (
                Some(ToolKind::Execute),
                "process(poll process-1)".to_owned()
            ),
            (
                Some(ToolKind::Execute),
                "process(stop process-1)".to_owned()
            ),
        ]
    );
}

// Covers: a replay ends with the session's checklist, so a client that
// attaches sees the plan the live mapper counts as sent.
// Owner: session event replay
#[test]
fn replay_ends_with_the_current_plan() {
    let tool_set = AppToolSet::disabled();
    tool_set.todo_state().replace(Some(TodoList {
        todos: vec![TodoItem {
            content: "read".into(),
            status: TodoStatus::InProgress,
        }],
    }));
    assert_eq!(
        replay_with(&tool_set, &[Message::user_text("go")]),
        vec![
            user(saved_id(0, 0), "go"),
            WireEvent::Plan {
                entries: vec![PlanEntry {
                    content: "read".into(),
                    status: PlanStatus::InProgress,
                }],
            },
        ]
    );
}

// Covers: replaying the saved rows again after a turn that saved nothing
// yields nothing, so the daemon keeps that turn's live events in resets
// instead of cutting them for an empty save.
// Owner: session event live and replay mapping
#[test]
fn a_replay_with_no_new_rows_reports_nothing_saved() {
    let tool_set = AppToolSet::disabled();
    let tools = || SessionTools::of_tool_set_for_tests(&tool_set);
    let rows = saved_rows(&[Message::Assistant(vec![call_block("call")].into())]);
    let mut live = LiveEvents::new(Path::new("/work"), tools(), /*configured_window*/ None);
    assert!(live.replay(&rows, Path::new("/work"), tools()).is_some());
    assert!(live.replay(&rows, Path::new("/work"), tools()).is_none());
}

// Covers: a provider id the saved transcript already used is numbered live
// as replay numbers it, so the live call opens its own card rather than
// updating the saved one, and a client reset after the turn saves sees the
// same id and the same TUI cards.
// Owner: session event live and replay mapping
#[test]
fn live_calls_continue_the_numbering_of_the_saved_transcript() {
    let tool_set = AppToolSet::disabled();
    let tools = || SessionTools::of_tool_set_for_tests(&tool_set);
    let saved = vec![
        Message::Assistant(vec![call_block("reused")].into()),
        Message::ToolResult(ToolResult::succeeded("reused", "a.rs").into()),
    ];
    let mut live = LiveEvents::new(Path::new("/work"), tools(), /*configured_window*/ None);
    live.replay(&saved_rows(&saved), Path::new("/work"), tools());
    live.prompt(&UserInput::text("again"), /*origin*/ None);
    let call_id = rho_sdk::ToolCallId::from_string("reused").unwrap();
    let live_calls: Vec<_> = [
        SessionEvent::Run(RunEvent::ToolProposed {
            call: shell_call("reused", "ls"),
        }),
        SessionEvent::Run(RunEvent::ToolStarted {
            call_id: call_id.clone(),
            name: "bash".into(),
            metadata: ToolMetadata::new(),
            execution: ToolExecution::Attached,
        }),
        SessionEvent::Run(RunEvent::ToolFinished {
            call_id,
            result: ToolCompletion::Completed(ToolOutput::text("b.rs")),
        }),
    ]
    .iter()
    .flat_map(|event| live.map(event))
    .map(|event| event.event)
    .collect();

    let mut whole = saved;
    whole.extend([
        Message::Assistant(vec![call_block("reused")].into()),
        Message::ToolResult(ToolResult::succeeded("reused", "b.rs").into()),
    ]);
    let replayed_tail = wire(rendered_rows(&whole)).split_off(2);
    assert_eq!(
        without_display(live_calls.clone()),
        vec![
            opened("reused#2", "ls"),
            updated("reused#2", ToolStatus::Completed, vec![text("b.rs")]),
        ]
    );
    assert_eq!(live_calls, replayed_tail);
}

// Covers: a saved transcript built a save at a time numbers a call id the
// provider reused in a later save as its own call, as a replay of every row
// at once does, and replays the same events each time a client resets. The
// daemon renders a reset from the saved rows again for each client, so a
// numbering that restarted per save would update the earlier call's card.
// Owner: session event replay
#[test]
fn a_transcript_saved_turn_by_turn_replays_as_one_and_the_same_each_time() {
    let tool_set = AppToolSet::disabled();
    let tools = || SessionTools::of_tool_set_for_tests(&tool_set);
    let first = vec![
        Message::Assistant(vec![call_block("reused")].into()),
        Message::ToolResult(ToolResult::succeeded("reused", "a.rs").into()),
    ];
    let mut whole = first.clone();
    whole.extend([
        Message::Assistant(vec![call_block("reused")].into()),
        Message::ToolResult(ToolResult::succeeded("reused", "b.rs").into()),
    ]);
    let mut live = LiveEvents::new(Path::new("/work"), tools(), /*configured_window*/ None);
    let mut transcript = SavedTranscript::default();
    for saved in [&first, &whole] {
        let turn = live.replay(&saved_rows(saved), Path::new("/work"), tools());
        transcript.push(turn.expect("each save adds rows"));
    }

    let rendered: Vec<_> = transcript.events().map(|event| event.event).collect();
    let ids: Vec<_> = rendered
        .iter()
        .filter_map(|event| match event {
            WireEvent::ToolCall(update) => Some(update.id.as_str().to_owned()),
            _ => None,
        })
        .collect();
    assert_eq!(ids, ["reused", "reused#2"]);
    assert_eq!(rendered, replay_messages(&whole));
    assert_eq!(
        rendered,
        transcript
            .events()
            .map(|event| event.event)
            .collect::<Vec<_>>()
    );
    assert_eq!(rendered.len(), transcript.len());
}

// Covers: an `agent` call's replay links the subagent its save wrote with
// its result, titled as live showed it, read back from the session file by
// a replay whose session knows no subagents, as after a daemon restart.
// Owner: session event replay of saved calls
#[test]
fn an_agent_call_replays_the_subagent_saved_with_it() {
    let root = tempfile::tempdir().unwrap();
    let session = crate::session::Session::create_in_root(root.path(), root.path()).unwrap();
    let rows = [
        Message::user_text("delegate"),
        Message::Assistant(
            vec![model::ContentBlock::ToolCall(model::ToolCall::new(
                "call-1".into(),
                "agent".into(),
                json!({"prompt": "Fix the parser"}),
            ))]
            .into(),
        ),
        Message::ToolResult(ToolResult::succeeded("call-1", "started run-1").into()),
    ];
    let snapshot = rho_sdk::SessionSnapshot::new(
        rho_sdk::SessionId::from_string(session.id().to_owned()).unwrap(),
        rho_sdk::Revision::from_u64(1),
        rows.to_vec(),
        model::ModelIdentity::new("provider", "api", "model"),
        rho_sdk::CompactionState::default(),
    );
    let marks = DisplayMarks {
        subagents: vec![(
            2,
            SubagentLink {
                run: "run-1".into(),
                session: Some("child-1".into()),
                title: Some("Fix the parser".into()),
            },
        )],
        ..DisplayMarks::default()
    };
    session
        .save_settled_turn(&snapshot, &rows, marks, TurnEnd::Completed)
        .unwrap();

    let tool_set = AppToolSet::disabled();
    let mut transcript = SavedTranscript::default();
    transcript.push(SavedTurn::capture(
        &session.active_display_history().unwrap(),
        Path::new("/work"),
        SessionTools::of_tool_set_for_tests(&tool_set),
        &mut CallIds::default(),
    ));
    let content = transcript
        .events()
        .filter_map(|event| match event.event {
            WireEvent::ToolCall(update) => update.content,
            _ => None,
        })
        .last();
    assert_eq!(
        content,
        Some(vec![
            text("started run-1"),
            ToolContent::Subagent(
                SubagentRef::new("run-1", Some(rho_protocol::SessionId::new("child-1")))
                    .titled("Fix the parser")
            ),
        ])
    );
}

// Covers: a replay of a whole session at once, as after a daemon restart,
// links each `agent` call to the subagent saved with its own result, though
// a provider reused the call's id: for a call a cancel cut off before its
// result, for another `agent` call, and for a later call of another tool,
// which links none.
// Owner: session event replay of saved calls
#[test]
fn a_saved_subagent_survives_calls_reusing_its_id() {
    let call = |name: &str| {
        vec![model::ContentBlock::ToolCall(model::ToolCall::new(
            "x".into(),
            name.into(),
            json!({}),
        ))]
    };
    let link = |run: &str, title: &str| SubagentLink {
        run: run.into(),
        session: None,
        title: Some(title.into()),
    };
    let mut rows = saved_rows(&[
        Message::user_text("look"),
        Message::AbortedAssistant(Arc::new(AbortedAssistant {
            content: call("read_file"),
            ..Default::default()
        })),
        Message::user_text("delegate"),
        Message::Assistant(call("agent").into()),
        Message::ToolResult(ToolResult::succeeded("x", "started run-1").into()),
        Message::Assistant(call("agent").into()),
        Message::ToolResult(ToolResult::succeeded("x", "started run-2").into()),
        Message::assistant_text("delegated"),
        Message::user_text("read it"),
        Message::Assistant(call("read_file").into()),
        Message::ToolResult(ToolResult::succeeded("x", "file").into()),
    ]);
    rows[4].subagent = Some(link("run-1", "Fix the parser"));
    rows[6].subagent = Some(link("run-2", "Test the parser"));

    let tool_set = AppToolSet::disabled();
    let mut transcript = SavedTranscript::default();
    transcript.push(SavedTurn::capture(
        &rows,
        Path::new("/work"),
        SessionTools::of_tool_set_for_tests(&tool_set),
        &mut CallIds::default(),
    ));
    let contents: Vec<_> = transcript
        .events()
        .filter_map(|event| match event.event {
            WireEvent::ToolCall(update) => update.content,
            _ => None,
        })
        .collect();
    let subagent =
        |run: &str, title: &str| ToolContent::Subagent(SubagentRef::new(run, None).titled(title));
    assert_eq!(
        contents,
        vec![
            vec![text("started run-1"), subagent("run-1", "Fix the parser")],
            vec![text("started run-2"), subagent("run-2", "Test the parser")],
            vec![text("file")],
        ]
    );
}

// Covers: a replayed user row is marked with the origin saved with it, and,
// saved before origins were, a background input as rho's notification and
// the exact restart note as rho's restart; any other row, a hand-labelled
// one too, stays the person's.
// Owner: session event replay
#[test]
fn replayed_user_rows_carry_who_wrote_them() {
    let sender = MessageOrigin::session(
        rho_protocol::SessionId::new("loader"),
        Some("loader".into()),
    );
    let rho = MessageOrigin::rho;
    let background = Message::BoundaryInput(Arc::from([model::ContentBlock::Text(
        "[session notification] done".into(),
    )]));
    let cases = [
        (
            Message::user_text("ship it"),
            Some(sender.clone()),
            Some(sender),
        ),
        (
            Message::user_text(RESUME_NOTE),
            None,
            Some(rho(RhoNotice::Restart)),
        ),
        (background, None, Some(rho(RhoNotice::Notification))),
        (
            Message::user_text("[ARCTIC worker 1f64ce0c] PR 1 is ready"),
            None,
            None,
        ),
        (
            Message::user_text(format!("{RESUME_NOTE} Also lint.")),
            None,
            None,
        ),
    ];
    for (message, saved, expected) in cases {
        let rows = vec![ProjectedMessage {
            message_origin: saved,
            ..saved_rows(std::slice::from_ref(&message)).remove(0)
        }];
        let mut transcript = SavedTranscript::default();
        transcript.push(SavedTurn::capture(
            &rows,
            Path::new("/work"),
            SessionTools::of_tool_set_for_tests(&AppToolSet::disabled()),
            &mut CallIds::default(),
        ));
        let origins: Vec<_> = transcript.events().map(|event| event.origin).collect();
        assert_eq!(origins, vec![expected], "{message:?}");
    }
}