ag-ui 1.0.0

Rust SDK for AG-UI 1.0 with protocol types, SSE, a server runtime for hosting agents, and a client runtime for consuming them.
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
//! Chunk normalization, and the edge cases that make it fiddly.

#![cfg(feature = "client")]

use ag_ui::client::apply::Applier;
use ag_ui::client::{ChunkNormalizer, normalize_all, verify_all};
use ag_ui::{
    Event, EventType, MessageId, TextMessageChunkEvent, TextMessageRole, ToolCallChunkEvent,
    ToolCallId,
};

fn types(events: &[Event]) -> Vec<EventType> {
    events.iter().map(Event::event_type).collect()
}

fn text_chunk(id: Option<&str>, delta: Option<&str>) -> Event {
    Event::text_message_chunk(
        id.map(MessageId::new),
        delta.map(std::borrow::ToOwned::to_owned),
    )
}

fn tool_chunk(id: Option<&str>, name: Option<&str>, delta: Option<&str>) -> Event {
    Event::tool_call_chunk(
        id.map(ToolCallId::new),
        name.map(std::borrow::ToOwned::to_owned),
        delta.map(std::borrow::ToOwned::to_owned),
    )
}

#[test]
fn a_chunk_stream_that_never_terminates_is_closed_at_the_end_of_the_stream() {
    // The last message of a run has nothing after it to imply its end, so the
    // end of the transport stream is what closes it.
    let events = normalize_all([
        text_chunk(Some("msg-1"), Some("Hel")),
        text_chunk(None, Some("lo")),
        text_chunk(None, Some("!")),
    ])
    .expect("normalizes");

    assert_eq!(
        types(&events),
        [
            EventType::TextMessageStart,
            EventType::TextMessageContent,
            EventType::TextMessageContent,
            EventType::TextMessageContent,
            EventType::TextMessageEnd,
        ]
    );

    let mut applier = Applier::new();
    for event in &events {
        applier.apply(event).expect("applies");
    }
    assert_eq!(applier.text_of("msg-1"), Some("Hello!"));
}

#[test]
fn a_chunk_with_no_preceding_id_is_a_protocol_error() {
    let error = normalize_all([text_chunk(None, Some("orphan"))])
        .expect_err("there is no message to attach the text to");
    assert!(
        error.to_string().contains("no messageId"),
        "unexpected error: {error}"
    );

    let error = normalize_all([tool_chunk(None, None, Some("{}"))])
        .expect_err("there is no call to attach the arguments to");
    assert!(
        error.to_string().contains("no toolCallId"),
        "unexpected error: {error}"
    );
}

#[test]
fn a_tool_call_chunk_that_opens_a_call_must_name_the_tool() {
    // Without a name there is nothing to put in TOOL_CALL_START, and inventing
    // one would silently call the wrong tool.
    let error = normalize_all([tool_chunk(Some("call-1"), None, Some("{}"))])
        .expect_err("a call has to be named");
    assert!(
        error.to_string().contains("without a toolCallName"),
        "unexpected error: {error}"
    );
}

#[test]
fn interleaved_chunk_streams_close_each_other() {
    // Two messages, alternating. Each switch ends the message before it — that
    // is the only signal the format gives.
    let events = normalize_all([
        text_chunk(Some("msg-1"), Some("a1")),
        text_chunk(Some("msg-2"), Some("b1")),
        text_chunk(None, Some("b2")),
        text_chunk(Some("msg-1"), Some("a2")),
    ])
    .expect("normalizes");

    assert_eq!(
        types(&events),
        [
            EventType::TextMessageStart,   // msg-1
            EventType::TextMessageContent, // a1
            EventType::TextMessageEnd,     // msg-1
            EventType::TextMessageStart,   // msg-2
            EventType::TextMessageContent, // b1
            EventType::TextMessageContent, // b2 — bare chunk continues msg-2
            EventType::TextMessageEnd,     // msg-2
            EventType::TextMessageStart,   // msg-1 again
            EventType::TextMessageContent, // a2
            EventType::TextMessageEnd,     // msg-1
        ]
    );

    // Re-opening a known id appends rather than duplicating the message.
    let mut applier = Applier::new();
    for event in &events {
        applier.apply(event).expect("applies");
    }
    assert_eq!(applier.messages().len(), 2);
    assert_eq!(applier.text_of("msg-1"), Some("a1a2"));
    assert_eq!(applier.text_of("msg-2"), Some("b1b2"));
}

#[test]
fn a_tool_call_chunk_closes_an_open_text_chunk_stream() {
    let events = normalize_all([
        text_chunk(Some("msg-1"), Some("Checking")),
        tool_chunk(Some("call-1"), Some("get_weather"), Some(r#"{"city":"#)),
        tool_chunk(None, None, Some(r#""Seoul"}"#)),
    ])
    .expect("normalizes");

    assert_eq!(
        types(&events),
        [
            EventType::TextMessageStart,
            EventType::TextMessageContent,
            EventType::TextMessageEnd,
            EventType::ToolCallStart,
            EventType::ToolCallArgs,
            EventType::ToolCallArgs,
            EventType::ToolCallEnd,
        ]
    );

    // And what comes out is a stream the verifier accepts.
    let mut run = vec![Event::run_started("thread-1", "run-1")];
    run.extend(events);
    run.push(Event::run_finished_success("thread-1", "run-1"));
    verify_all(&run).expect("normalized chunks should be a valid stream");
}

#[test]
fn the_run_ending_closes_an_open_chunk_stream_before_it() {
    let events = normalize_all([
        Event::run_started("thread-1", "run-1"),
        text_chunk(Some("msg-1"), Some("Done.")),
        Event::run_finished_success("thread-1", "run-1"),
    ])
    .expect("normalizes");

    assert_eq!(
        types(&events),
        [
            EventType::RunStarted,
            EventType::TextMessageStart,
            EventType::TextMessageContent,
            EventType::TextMessageEnd,
            EventType::RunFinished,
        ]
    );
}

#[test]
fn an_explicit_event_ends_the_chunk_stream_it_names_rather_than_joining_it() {
    // AG-UI 1.0, "The chunked form": the two spellings do not mix within one
    // item. An explicit event carrying the id a chunk stream is assembling
    // ends the shorthand, and is then judged by the rules of the explicit
    // form. The local streams `explicit-content-after-chunk-fatal` and
    // `chunk-after-explicit-start-fatal` hold the same on every lane.
    for (explicit, said) in [
        (
            Event::text_message_end("msg-1"),
            r#"TEXT_MESSAGE_END for message "msg-1", which is not open"#,
        ),
        (
            Event::text_message_content("msg-1", "!"),
            r#"TEXT_MESSAGE_CONTENT for message "msg-1", which is not open"#,
        ),
    ] {
        let kind = explicit.event_type();
        let events = normalize_all([
            Event::run_started("t", "r"),
            text_chunk(Some("msg-1"), Some("Hi")),
            explicit,
        ])
        .expect("normalizes");

        // The end the chunk stream is owed comes first, and is the only one
        // the normalizer adds.
        assert_eq!(
            types(&events),
            [
                EventType::RunStarted,
                EventType::TextMessageStart,
                EventType::TextMessageContent,
                EventType::TextMessageEnd,
                kind,
            ]
        );
        let error = verify_all(&events).expect_err("the message closed with its chunk stream");
        assert!(error.to_string().contains(said), "{error}");
    }

    // An explicit start is the one explicit event that may follow: the
    // message has closed, and a closed message may be reopened.
    let events = normalize_all([
        Event::run_started("t", "r"),
        text_chunk(Some("msg-1"), Some("Hel")),
        Event::text_message_start("msg-1", TextMessageRole::Assistant),
        Event::text_message_content("msg-1", "lo"),
        Event::text_message_end("msg-1"),
        Event::run_finished_success("t", "r"),
    ])
    .expect("normalizes");
    verify_all(&events).expect("a reopened message is a valid stream");
    let mut applier = Applier::new();
    for event in &events {
        applier.apply(event).expect("applies");
    }
    assert_eq!(applier.text_of("msg-1"), Some("Hello"));
}

#[test]
fn an_explicitly_opened_message_is_not_a_stream_a_chunk_can_continue() {
    // "An item opened by a `*_START` is continued and closed explicitly." A
    // chunk that names no id continues a chunk stream, and an explicit start
    // does not open one. The reference client rejects this stream the same
    // way; alpha.3 appended the chunk to the open message.
    let error = normalize_all([
        Event::text_message_start("msg-1", TextMessageRole::Assistant),
        Event::text_message_content("msg-1", "Hel"),
        text_chunk(None, Some("lo")),
        Event::text_message_end("msg-1"),
    ])
    .expect_err("no chunk opened anything for it to continue");
    assert!(
        error
            .to_string()
            .contains("carries no messageId and no message is open as a chunk stream"),
        "{error}"
    );

    // One that names the open message's id is the first chunk of a new item
    // under that id, which the verifier refuses as a second start.
    let events = normalize_all([
        Event::run_started("t", "r"),
        Event::text_message_start("msg-1", TextMessageRole::Assistant),
        text_chunk(Some("msg-1"), Some("lo")),
    ])
    .expect("normalizes");
    let error = verify_all(&events).expect_err("msg-1 is already open");
    assert!(
        error
            .to_string()
            .contains(r#"TEXT_MESSAGE_START for message "msg-1", which is already open"#),
        "{error}"
    );
}

#[test]
fn an_event_in_the_lane_ends_the_chunk_stream() {
    // AG-UI 1.0, "Closing a chunk stream": a message, tool-call, step, state,
    // custom or reasoning event in the stream's lane ends it. A fragment that
    // names no id afterwards has nothing to continue.
    for between in [
        Event::state_snapshot(serde_json::json!({ "progress": 0.5 })),
        Event::state_delta(Vec::<ag_ui::PatchOperation>::new()),
        Event::custom("note", serde_json::json!(1)),
        Event::step_started("plan"),
        Event::step_finished("plan"),
        Event::reasoning_start("span-1"),
        Event::reasoning_end("span-1"),
        Event::messages_snapshot(Vec::<ag_ui::Message>::new()),
        Event::run_started("thread-1", "run-1"),
    ] {
        let kind = between.event_type();
        let mut normalizer = ChunkNormalizer::new();
        let mut out = Vec::new();
        normalizer
            .normalize(text_chunk(Some("msg-1"), Some("Hel")), &mut out)
            .expect("opens");
        normalizer.normalize(between, &mut out).expect("passes");
        assert_eq!(
            types(&out),
            [
                EventType::TextMessageStart,
                EventType::TextMessageContent,
                EventType::TextMessageEnd,
                kind,
            ],
            "{kind} must end the open chunk stream before it is delivered"
        );
        let error = normalizer
            .normalize(text_chunk(None, Some("lo")), &mut out)
            .expect_err("nothing is open to continue");
        assert!(error.to_string().contains("no message is open"), "{error}");
    }
}

#[test]
fn events_that_stand_aside_do_not_end_the_chunk_stream() {
    // RAW, ACTIVITY_SNAPSHOT, ACTIVITY_DELTA, REASONING_ENCRYPTED_VALUE and
    // SUBAGENT_STARTED take no part in assembly.
    for aside in [
        Event::raw(serde_json::json!({ "provider": "heartbeat" })),
        Event::activity_snapshot("act-1", "search", ag_ui::JsonObject::new()),
        Event::activity_delta("act-1", "search", Vec::<ag_ui::PatchOperation>::new()),
        Event::reasoning_encrypted_value(
            ag_ui::ReasoningEncryptedValueSubtype::Message,
            "msg-1",
            "b3BhcXVl",
        ),
        Event::subagent_started("sub-1", "researcher"),
    ] {
        let kind = aside.event_type();
        let events = normalize_all([
            text_chunk(Some("msg-1"), Some("Hel")),
            aside,
            text_chunk(None, Some("lo")),
        ])
        .unwrap_or_else(|error| panic!("{kind} must not end the stream: {error}"));
        assert_eq!(
            types(&events),
            [
                EventType::TextMessageStart,
                EventType::TextMessageContent,
                kind,
                EventType::TextMessageContent,
                EventType::TextMessageEnd,
            ]
        );
    }
}

#[test]
fn an_event_in_another_lane_leaves_the_chunk_stream_open() {
    // A lane is the parent agent's or one subagent's, and each is closed by
    // its own events only.
    let tagged = |event: Event| event.with_subagent_run_id("sub-1");
    let events = normalize_all([
        text_chunk(Some("msg-1"), Some("Hel")),
        tagged(Event::custom("note", serde_json::json!(1))),
        text_chunk(None, Some("lo")),
    ])
    .expect("the parent's stream is untouched by a subagent's event");
    assert_eq!(
        types(&events),
        [
            EventType::TextMessageStart,
            EventType::TextMessageContent,
            EventType::Custom,
            EventType::TextMessageContent,
            EventType::TextMessageEnd,
        ]
    );
}

#[test]
fn a_subagent_terminal_ends_the_chunk_stream_in_its_lane() {
    // "A chunk stream MUST NOT outlive its owner": the synthesized end comes
    // before the terminal, and only that subagent's stream is ended.
    for terminal in [
        Event::subagent_finished("sub-1"),
        Event::subagent_error("sub-1", "failed"),
    ] {
        let kind = terminal.event_type();
        let events = normalize_all([
            text_chunk(Some("parent-msg"), Some("still ")),
            text_chunk(Some("sub-msg"), Some("delegated")).with_subagent_run_id("sub-1"),
            terminal,
            text_chunk(None, Some("streaming")),
        ])
        .expect("normalizes");
        assert_eq!(
            types(&events),
            [
                EventType::TextMessageStart,
                EventType::TextMessageContent,
                EventType::TextMessageStart,
                EventType::TextMessageContent,
                EventType::TextMessageEnd,
                kind,
                EventType::TextMessageContent,
                EventType::TextMessageEnd,
            ]
        );
        let Event::TextMessageEnd(first_end) = &events[4] else {
            unreachable!()
        };
        assert_eq!(first_end.message_id, "sub-msg");
        assert_eq!(first_end.subagent_run_id.as_deref(), Some("sub-1"));
    }
}

#[test]
fn a_continuation_chunk_may_repeat_what_its_opener_said_but_not_contradict_it() {
    let role = |role| {
        Event::TextMessageChunk(TextMessageChunkEvent {
            message_id: Some("msg-1".into()),
            role,
            delta: Some("x".into()),
            ..Default::default()
        })
    };
    let named = |name: Option<&str>| {
        Event::TextMessageChunk(TextMessageChunkEvent {
            message_id: Some("msg-1".into()),
            name: name.map(str::to_owned),
            ..Default::default()
        })
    };
    let user = Some(TextMessageRole::User);
    let assistant = Some(TextMessageRole::Assistant);

    // The same value again, or none, continues the stream.
    assert!(normalize_all([role(user), role(user), role(None)]).is_ok());
    assert!(normalize_all([named(Some("ada")), named(Some("ada")), named(None)]).is_ok());

    let error = normalize_all([role(user), role(assistant)]).expect_err("two roles");
    assert!(
        error.to_string().contains(
            r#"repeats role "assistant", which does not match the open stream's role "user""#
        ),
        "{error}"
    );
    // An opener that names no role opened an assistant message.
    assert!(normalize_all([role(None), role(assistant)]).is_ok());
    let error = normalize_all([role(None), role(user)]).expect_err("user after the default");
    assert!(
        error
            .to_string()
            .contains(r#"the open stream's role "assistant""#),
        "{error}"
    );
    let error = normalize_all([named(None), named(Some("ada"))]).expect_err("a late name");
    assert!(
        error
            .to_string()
            .contains("the open stream's name (absent)"),
        "{error}"
    );

    let tool = |name: Option<&str>, parent: Option<&str>| {
        Event::ToolCallChunk(ToolCallChunkEvent {
            tool_call_id: Some("call-1".into()),
            tool_call_name: name.map(str::to_owned),
            parent_message_id: parent.map(MessageId::new),
            delta: Some("{}".into()),
            ..Default::default()
        })
    };
    assert!(
        normalize_all([
            tool(Some("search"), Some("m")),
            tool(Some("search"), Some("m")),
            tool(None, None)
        ])
        .is_ok()
    );
    let error = normalize_all([tool(Some("search"), None), tool(Some("delete"), None)])
        .expect_err("a renamed call");
    assert!(
        error.to_string().contains(
            r#"repeats toolCallName "delete", which does not match the open stream's toolCallName "search""#
        ),
        "{error}"
    );
    let error = normalize_all([tool(Some("search"), Some("m")), tool(None, Some("other"))])
        .expect_err("a moved call");
    assert!(
        error
            .to_string()
            .contains(r#"the open stream's parentMessageId "m""#),
        "{error}"
    );

    // Only a chunk's own opener is repeated. A message a TEXT_MESSAGE_START
    // opened is not a chunk stream, so a chunk naming it has nothing to
    // contradict: it opens the id a second time, which is the verifier's to
    // refuse.
    let events = normalize_all([
        Event::run_started("t", "r"),
        Event::text_message_start("msg-1", TextMessageRole::User),
        role(assistant),
    ])
    .expect("the chunk opens a stream of its own");
    let error = verify_all(&events).expect_err("msg-1 is already open");
    assert!(error.to_string().contains("already open"), "{error}");
}

#[test]
fn splitting_a_message_on_an_intervening_event_assembles_the_same_text() {
    // An intervening event ends the stream, and a fragment that names the id
    // again re-opens the message. Written out by hand, and through the
    // normalizer: both have to assemble the same text.
    let upstream = [
        Event::text_message_start("msg-1", TextMessageRole::Assistant),
        Event::text_message_content("msg-1", "Hel"),
        Event::text_message_end("msg-1"),
        Event::state_snapshot(serde_json::json!({ "progress": 0.5 })),
        Event::text_message_start("msg-1", TextMessageRole::Assistant),
        Event::text_message_content("msg-1", "lo"),
        Event::text_message_end("msg-1"),
    ];
    let ours = normalize_all([
        text_chunk(Some("msg-1"), Some("Hel")),
        Event::state_snapshot(serde_json::json!({ "progress": 0.5 })),
        text_chunk(Some("msg-1"), Some("lo")),
    ])
    .expect("normalizes");

    let assemble = |events: &[Event]| {
        let mut applier = Applier::new();
        for event in events {
            applier.apply(event).expect("applies");
        }
        (
            applier.messages().len(),
            applier.text_of("msg-1").map(str::to_owned),
        )
    };

    assert_eq!(assemble(&upstream), (1, Some("Hello".to_owned())));
    assert_eq!(assemble(&ours), assemble(&upstream));
}

#[test]
fn two_messages_and_two_calls_interleaved_expand_exactly_as_upstream_does() {
    // The fixture from upstream's `chunks/__tests__/transform.test.ts`,
    // "should handle interleaved chunks with different message and tool call
    // IDs", down to its counts: re-opening an id the stream has already closed
    // is a *new* bracket, not a continuation, so six starts, six ends, six
    // payloads and the terminal event — nineteen events.
    let events = normalize_all([
        // Upstream's fixture starts at the first chunk; a real stream has to
        // open, and the verification below needs it to.
        Event::run_started("thread-1", "run-1"),
        text_chunk(Some("msg-1"), Some("First message part 1")),
        tool_chunk(Some("tool-1"), Some("firstTool"), Some(r#"{"arg1":"#)),
        text_chunk(Some("msg-1"), Some("First message part 2")),
        text_chunk(Some("msg-2"), Some("Second message")),
        tool_chunk(Some("tool-2"), Some("secondTool"), Some(r#"{"arg2":"#)),
        tool_chunk(Some("tool-1"), Some("firstTool"), Some(r#""more"}"#)),
        Event::run_finished_success("thread-1", "run-1"),
    ])
    .expect("normalizes");

    let count = |kind: EventType| types(&events).iter().filter(|t| **t == kind).count();
    assert_eq!(count(EventType::TextMessageStart), 3);
    assert_eq!(count(EventType::TextMessageEnd), 3);
    assert_eq!(count(EventType::TextMessageContent), 3);
    assert_eq!(count(EventType::ToolCallStart), 3);
    assert_eq!(count(EventType::ToolCallEnd), 3);
    assert_eq!(count(EventType::ToolCallArgs), 3);
    assert_eq!(count(EventType::RunFinished), 1);
    assert_eq!(events.len(), 20, "upstream's nineteen, plus RUN_STARTED");

    // The terminator for the last call goes out *before* RUN_FINISHED, so the
    // stream a verifier sees never has a call open at the end.
    assert_eq!(
        types(&events)[18..],
        [EventType::ToolCallEnd, EventType::RunFinished]
    );
    verify_all(&events).expect("the expansion should be a valid stream");
}

#[test]
fn events_outside_the_protocols_ordering_never_close_a_chunk_stream() {
    // Upstream returns `[event]` for exactly RAW, ACTIVITY_SNAPSHOT,
    // ACTIVITY_DELTA and REASONING_ENCRYPTED_VALUE — the only four that skip
    // `closePendingEvent()`. Ours must not close on them either.
    let events = normalize_all([
        text_chunk(Some("msg-1"), Some("Hel")),
        Event::raw(serde_json::json!({ "provider": "anything" })),
        Event::activity_snapshot("act-1", "web_search", serde_json::Map::new()),
        text_chunk(Some("msg-1"), Some("lo")),
    ])
    .expect("normalizes");

    assert_eq!(
        types(&events),
        [
            EventType::TextMessageStart,
            EventType::TextMessageContent,
            EventType::Raw,
            EventType::ActivitySnapshot,
            EventType::TextMessageContent,
            EventType::TextMessageEnd,
        ]
    );
}

#[test]
fn a_chunk_carries_its_role_and_name_onto_the_synthesized_start() {
    let chunk = Event::TextMessageChunk(TextMessageChunkEvent {
        message_id: Some(MessageId::new("msg-1")),
        role: Some(TextMessageRole::User),
        delta: Some("typed by a human".into()),
        name: Some("ada".into()),
        ..TextMessageChunkEvent::default()
    });

    let events = normalize_all([chunk]).expect("normalizes");
    let Event::TextMessageStart(start) = &events[0] else {
        panic!("expected a start event");
    };
    assert_eq!(start.role, TextMessageRole::User);
    assert_eq!(start.name.as_deref(), Some("ada"));

    let mut applier = Applier::new();
    for event in &events {
        applier.apply(event).expect("applies");
    }
    assert_eq!(applier.messages()[0].role(), ag_ui::Role::User);
}

#[test]
fn a_tool_chunk_carries_its_parent_message_onto_the_synthesized_start() {
    let chunk = Event::ToolCallChunk(ToolCallChunkEvent {
        tool_call_id: Some(ToolCallId::new("call-1")),
        tool_call_name: Some("get_weather".into()),
        parent_message_id: Some(MessageId::new("msg-1")),
        delta: Some("{}".into()),
        ..ToolCallChunkEvent::default()
    });

    let events = normalize_all([chunk]).expect("normalizes");
    let Event::ToolCallStart(start) = &events[0] else {
        panic!("expected a tool call start");
    };
    assert_eq!(
        start.parent_message_id.as_ref().map(|id| id.as_str()),
        Some("msg-1")
    );
}

#[test]
fn reasoning_chunks_normalize_the_same_way() {
    let events = normalize_all([
        Event::reasoning_message_chunk(Some(MessageId::new("r-1")), Some("Think".into())),
        Event::reasoning_message_chunk(None, Some("ing".into())),
    ])
    .expect("normalizes");

    assert_eq!(
        types(&events),
        [
            EventType::ReasoningMessageStart,
            EventType::ReasoningMessageContent,
            EventType::ReasoningMessageContent,
            EventType::ReasoningMessageEnd,
        ]
    );

    let mut applier = Applier::new();
    for event in &events {
        applier.apply(event).expect("applies");
    }
    assert_eq!(applier.reasoning_text(&"r-1".into()), Some("Thinking"));
}

#[test]
fn a_chunk_with_no_delta_still_opens_its_message() {
    let events = normalize_all([text_chunk(Some("msg-1"), None)]).expect("normalizes");
    assert_eq!(
        types(&events),
        [EventType::TextMessageStart, EventType::TextMessageEnd]
    );
}

#[test]
fn the_normalizer_reports_whether_a_stream_is_open() {
    let mut normalizer = ChunkNormalizer::new();
    let mut out = Vec::new();

    assert!(!normalizer.is_open());
    normalizer
        .normalize(text_chunk(Some("msg-1"), Some("Hi")), &mut out)
        .expect("normalizes");
    assert!(normalizer.is_open());

    normalizer.finish(&mut out);
    assert!(!normalizer.is_open());
    assert_eq!(
        out.last().map(Event::event_type),
        Some(EventType::TextMessageEnd)
    );
}

#[test]
#[allow(deprecated)]
fn the_applier_leaves_a_retired_thinking_event_to_the_compatibility_boundary() {
    // The boundary translates THINKING_* to REASONING_* on both transport
    // forms, so the applier has no translation of its own to disagree with.
    let mut applier = Applier::new();
    for retired in [
        Event::thinking_start(None),
        Event::thinking_text_message_start(),
        Event::thinking_text_message_content("hmm"),
        Event::thinking_text_message_end(),
        Event::thinking_end(),
    ] {
        let error = applier.apply(&retired).expect_err("a retired event");
        assert!(
            matches!(error, ag_ui::client::Error::Unsupported(_)),
            "{error:?}"
        );
        assert!(error.to_string().contains("REASONING_*"), "{error}");
    }
    assert!(applier.messages().is_empty());
}

#[test]
fn the_applier_takes_a_chunk_only_in_its_expanded_form() {
    // What a chunk continues is decided in one place, the normalizer. An
    // applier handed a raw chunk says so rather than dropping the payload or
    // assembling it by rules of its own.
    let mut applier = Applier::new();
    for chunk in [
        text_chunk(Some("msg-1"), Some("Hel")),
        tool_chunk(Some("call-1"), Some("t"), Some("{}")),
        Event::reasoning_message_chunk(Some(MessageId::new("r-1")), Some("Think".into())),
    ] {
        let error = applier.apply(&chunk).expect_err("not the explicit form");
        assert!(
            matches!(error, ag_ui::client::Error::Unsupported(_)),
            "{error:?}"
        );
        assert!(error.to_string().contains("ChunkNormalizer"), "{error}");
    }
    assert!(applier.messages().is_empty());

    // Through the normalizer, the same events assemble.
    let events = normalize_all([
        text_chunk(Some("msg-1"), Some("Hel")),
        text_chunk(None, Some("lo")),
        tool_chunk(Some("call-1"), Some("t"), Some("{}")),
    ])
    .expect("normalizes");
    for event in &events {
        applier.apply(event).expect("applies");
    }
    assert_eq!(applier.text_of("msg-1"), Some("Hello"));
    let ag_ui::Message::Assistant(assistant) = &applier.messages()[1] else {
        panic!("expected the tool call's message");
    };
    assert_eq!(
        assistant.tool_calls.as_ref().expect("calls")[0]
            .function
            .arguments,
        "{}"
    );
}

#[test]
fn a_tool_result_closes_the_chunk_streamed_call_it_answers() {
    // A chunk-streamed call has no `TOOL_CALL_END` of its own, so the result
    // is the first event that says the call is over. Until this was handled the
    // synthesized end came out *after* the result — a stream both verifiers
    // reject, and whose `TOOL_CALL_RESULT` a `Thread` then discards.
    let events = normalize_all([
        Event::run_started("t", "r"),
        tool_chunk(Some("call-1"), Some("search"), Some("{}")),
        Event::tool_call_result("msg-1", "call-1", "sunny"),
        Event::run_finished_success("t", "r"),
    ])
    .expect("normalizes");

    assert_eq!(
        types(&events),
        [
            EventType::RunStarted,
            EventType::ToolCallStart,
            EventType::ToolCallArgs,
            EventType::ToolCallEnd,
            EventType::ToolCallResult,
            EventType::RunFinished,
        ]
    );
    verify_all(&events).expect("the normalized stream should verify");
}

#[test]
fn parallel_chunk_streamed_calls_each_close_before_their_own_result() {
    // What a provider adapter actually emits when the model asks for three
    // tools at once: the calls stream one after another, and the results come
    // back in whatever order the tools finished — here, not the order asked.
    // Every call must be closed before the first result, and each `TOOL_CALL_END`
    // must precede the result that answers it.
    let events = normalize_all([
        Event::run_started("t", "r"),
        tool_chunk(Some("call-1"), Some("search"), Some(r#"{"q":"#)),
        tool_chunk(None, None, Some(r#""seoul"}"#)),
        tool_chunk(Some("call-2"), Some("lookup"), Some("{}")),
        Event::tool_call_result("msg-1", "call-1", "sunny"),
        tool_chunk(Some("call-3"), Some("geocode"), Some("{}")),
        Event::tool_call_result("msg-2", "call-3", "37.5"),
        Event::tool_call_result("msg-3", "call-2", "found"),
        Event::run_finished_success("t", "r"),
    ])
    .expect("normalizes");

    assert_eq!(
        types(&events),
        [
            EventType::RunStarted,
            EventType::ToolCallStart,  // call-1
            EventType::ToolCallArgs,   // {"q":
            EventType::ToolCallArgs,   // "seoul"}
            EventType::ToolCallEnd,    // call-1, closed by call-2 opening
            EventType::ToolCallStart,  // call-2
            EventType::ToolCallArgs,   // {}
            EventType::ToolCallEnd,    // call-2, closed by call-1's result
            EventType::ToolCallResult, // call-1
            EventType::ToolCallStart,  // call-3
            EventType::ToolCallArgs,   // {}
            EventType::ToolCallEnd,    // call-3, closed by its own result
            EventType::ToolCallResult, // call-3
            EventType::ToolCallResult, // call-2
            EventType::RunFinished,
        ]
    );
    verify_all(&events).expect("the normalized stream should verify");

    // The ordering, per call, spelled out: an assertion on the type sequence
    // alone would still pass if the ends came out against the wrong ids.
    for id in ["call-1", "call-2", "call-3"] {
        let end = events
            .iter()
            .position(|event| matches!(event, Event::ToolCallEnd(e) if e.tool_call_id == id))
            .unwrap_or_else(|| panic!("{id} was never closed"));
        let result = events
            .iter()
            .position(|event| matches!(event, Event::ToolCallResult(e) if e.tool_call_id == id))
            .unwrap_or_else(|| panic!("{id} got no result"));
        assert!(
            end < result,
            "{id} was closed at {end}, after its result at {result}"
        );
    }

    // And the arguments survived being split across two chunks.
    let mut applier = Applier::new();
    for event in &events {
        applier.apply(event).expect("applies");
    }
    let ag_ui::Message::Assistant(assistant) = &applier.messages()[0] else {
        panic!("expected the first call's message");
    };
    assert_eq!(
        assistant.tool_calls.as_ref().expect("calls")[0]
            .function
            .arguments,
        r#"{"q":"seoul"}"#
    );
}

#[test]
fn a_tool_result_closes_a_chunk_streamed_message_too() {
    // The other stream a result can arrive underneath: it may not interleave
    // with an open message either.
    let events = normalize_all([
        Event::run_started("t", "r"),
        Event::tool_call_start("call-1", "search"),
        Event::tool_call_end("call-1"),
        text_chunk(Some("msg-1"), Some("looking")),
        Event::tool_call_result("msg-2", "call-1", "sunny"),
        Event::run_finished_success("t", "r"),
    ])
    .expect("normalizes");

    assert_eq!(
        types(&events),
        [
            EventType::RunStarted,
            EventType::ToolCallStart,
            EventType::ToolCallEnd,
            EventType::TextMessageStart,
            EventType::TextMessageContent,
            EventType::TextMessageEnd,
            EventType::ToolCallResult,
            EventType::RunFinished,
        ]
    );
    verify_all(&events).expect("the normalized stream should verify");
}

#[test]
fn a_tool_result_for_an_explicitly_ended_call_adds_no_terminator() {
    // Nothing is owed when the producer closed the call itself, so the result
    // must not grow a second `TOOL_CALL_END`.
    let events = normalize_all([
        Event::run_started("t", "r"),
        Event::tool_call_start("call-1", "search"),
        Event::tool_call_args("call-1", "{}"),
        Event::tool_call_end("call-1"),
        Event::tool_call_result("msg-1", "call-1", "sunny"),
        Event::run_finished_success("t", "r"),
    ])
    .expect("normalizes");

    assert_eq!(
        types(&events),
        [
            EventType::RunStarted,
            EventType::ToolCallStart,
            EventType::ToolCallArgs,
            EventType::ToolCallEnd,
            EventType::ToolCallResult,
            EventType::RunFinished,
        ]
    );
    verify_all(&events).expect("the normalized stream should verify");
}

// ---- subagents ------------------------------------------------------------

#[test]
fn concurrent_subagents_chunk_streams_resolve_within_their_own_stream() {
    let tagged = |event: Event, id: &str| event.with_subagent_run_id(id);
    let events = normalize_all([
        Event::run_started("t", "r"),
        Event::subagent_started("s1", "researcher"),
        Event::subagent_started("s2", "researcher"),
        tagged(text_chunk(Some("m1"), Some("A ")), "s1"),
        tagged(text_chunk(Some("m2"), Some("B ")), "s2"),
        tagged(text_chunk(None, Some("one")), "s1"),
        tagged(text_chunk(None, Some("two")), "s2"),
        Event::subagent_finished_success("s1"),
        Event::subagent_finished_success("s2"),
        Event::run_finished_success("t", "r"),
    ])
    .expect("normalizes");

    // Each stream's start and end carry its owner, and neither closed the other.
    let starts: Vec<_> = events
        .iter()
        .filter(|e| e.event_type() == EventType::TextMessageStart)
        .map(|e| e.subagent_run_id().map(|id| id.as_str()))
        .collect();
    assert_eq!(starts, [Some("s1"), Some("s2")]);
    let ends: Vec<_> = events
        .iter()
        .filter(|e| e.event_type() == EventType::TextMessageEnd)
        .map(|e| e.subagent_run_id().map(|id| id.as_str()))
        .collect();
    assert_eq!(ends.len(), 2);
    assert!(ends.contains(&Some("s1")) && ends.contains(&Some("s2")));
    verify_all(&events).expect("the normalized stream should verify");

    let mut applier = Applier::new();
    for event in &events {
        applier.apply(event).expect("applies");
    }
    assert_eq!(applier.text_of("m1"), Some("A one"));
    assert_eq!(applier.text_of("m2"), Some("B two"));
}

#[test]
fn an_untagged_chunk_continues_the_parents_stream_or_the_only_one() {
    let tagged = |event: Event, id: &str| event.with_subagent_run_id(id);

    // The sole open stream belongs to a subagent: an untagged chunk continues it.
    let events = normalize_all([
        tagged(text_chunk(Some("m1"), Some("Hel")), "s1"),
        text_chunk(None, Some("lo")),
    ])
    .expect("normalizes");
    let mut applier = Applier::new();
    for event in &events {
        applier.apply(event).expect("applies");
    }
    assert_eq!(applier.text_of("m1"), Some("Hello"));

    // The parent's stream wins over a subagent's when both are open.
    let events = normalize_all([
        tagged(text_chunk(Some("m1"), Some("theirs ")), "s1"),
        text_chunk(Some("m2"), Some("mine ")),
        text_chunk(None, Some("too")),
    ])
    .expect("normalizes");
    let mut applier = Applier::new();
    for event in &events {
        applier.apply(event).expect("applies");
    }
    assert_eq!(applier.text_of("m2"), Some("mine too"));
    assert_eq!(applier.text_of("m1"), Some("theirs "));
}

#[test]
fn an_untagged_chunk_with_several_subagent_streams_open_is_refused() {
    let tagged = |event: Event, id: &str| event.with_subagent_run_id(id);
    let error = normalize_all([
        tagged(text_chunk(Some("m1"), Some("A")), "s1"),
        tagged(text_chunk(Some("m2"), Some("B")), "s2"),
        text_chunk(None, Some("?")),
    ])
    .expect_err("nothing to resolve the chunk against");
    assert!(error.to_string().contains("several subagents"), "{error}");

    let error = normalize_all([
        tagged(text_chunk(Some("m1"), Some("A")), "s1"),
        tagged(text_chunk(None, Some("?")), "s3"),
    ])
    .expect_err("s3 has nothing open");
    assert!(
        error.to_string().contains("\"s3\" has no message open"),
        "{error}"
    );
}

#[test]
fn a_subagents_tool_result_closes_only_its_own_stream() {
    let tagged = |event: Event, id: &str| event.with_subagent_run_id(id);
    let events = normalize_all([
        Event::run_started("t", "r"),
        text_chunk(Some("m1"), Some("parent narrating")),
        tagged(tool_chunk(Some("call-1"), Some("search"), Some("{}")), "s1"),
        tagged(Event::tool_call_result("m2", "call-1", "hit"), "s1"),
        text_chunk(None, Some(" still")),
        Event::run_finished_success("t", "r"),
    ])
    .expect("normalizes");
    let mut applier = Applier::new();
    for event in &events {
        applier.apply(event).expect("applies");
    }
    assert_eq!(
        applier.text_of("m1"),
        Some("parent narrating still"),
        "the subagent's result did not end the parent's message"
    );
    verify_all(&events).expect("the normalized stream should verify");
}

#[test]
fn a_tagged_chunk_naming_another_owners_open_stream_is_a_verifier_complaint_not_a_crossed_message()
{
    let tagged = |event: Event, id: &str| event.with_subagent_run_id(id);
    // s2 continues m1, which s1 opened by chunk and never closed.
    let events = normalize_all([
        Event::run_started("t", "r"),
        tagged(text_chunk(Some("m1"), Some("A")), "s1"),
        tagged(text_chunk(Some("m1"), Some("B")), "s2"),
        Event::run_finished_success("t", "r"),
    ])
    .expect("normalization does not judge ownership");

    // The normalizer took the tag at its word — a second start for m1 under
    // s2 — and the verifier is where that is a complaint.
    let error = verify_all(&events).expect_err("m1 belongs to s1");
    assert!(error.to_string().contains("m1"), "{error}");

    // An untagged result for a subagent's call closes that call's stream and
    // the parent's open message — the result is the parent's — but not the
    // subagent's other stream.
    let events = normalize_all([
        Event::run_started("t", "r"),
        tagged(tool_chunk(Some("c1"), Some("search"), Some("{}")), "s1"),
        // One stream per owner: s1's text closes its call.
        tagged(text_chunk(Some("m1"), Some("child says")), "s1"),
        text_chunk(Some("m2"), Some("parent says")),
        Event::tool_call_result("m3", "c1", "hit"),
        tagged(text_chunk(None, Some(" more")), "s1"),
        Event::run_finished_success("t", "r"),
    ])
    .expect("normalizes");
    let mut applier = Applier::new();
    for event in &events {
        applier.apply(event).expect("applies");
    }
    assert_eq!(applier.text_of("m1"), Some("child says more"));
    assert_eq!(applier.text_of("m2"), Some("parent says"));
    verify_all(&events).expect("the normalized stream should verify");
}