codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
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
//! Drive `parse_sse_chunk` (the in-place SSE event extractor) over canned
//! chunk sequences. The full `handle_chat_completion_stream` path needs a
//! live `reqwest::Response` so it isn't unit-testable without a mock HTTP
//! harness (issue #69 tracks that). For #103 we exercise the chunk decoder
//! directly to verify each "class of stream failure" the engine relies on.
use super::*;
use crate::models::{ContentBlockStart, Delta, StreamEvent};

/// Decode a raw SSE-data JSON chunk into our internal events, mirroring
/// the per-event call shape used by `handle_chat_completion_stream`.
fn decode_chunk(json_text: &str) -> Vec<StreamEvent> {
    decode_chunk_with_reasoning(json_text, true)
}

fn decode_chunk_with_reasoning(json_text: &str, is_reasoning_model: bool) -> Vec<StreamEvent> {
    let chunk: Value = serde_json::from_str(json_text).expect("valid SSE JSON");
    let mut content_index = 0u32;
    let mut text_started = false;
    let mut thinking_started = false;
    let mut tool_indices = std::collections::HashMap::new();
    let mut reasoning_detail_buffers = std::collections::HashMap::new();
    parse_sse_chunk(
        &chunk,
        &mut content_index,
        &mut text_started,
        &mut thinking_started,
        &mut tool_indices,
        &mut reasoning_detail_buffers,
        is_reasoning_model,
    )
}

fn decode_chunks_with_style(
    chunks: &[&str],
    reasoning_stream_style: ReasoningStreamStyle,
) -> Vec<StreamEvent> {
    let mut content_index = 0u32;
    let mut text_started = false;
    let mut thinking_started = false;
    let mut tool_indices = std::collections::HashMap::new();
    let mut reasoning_detail_buffers = std::collections::HashMap::new();
    let mut inline_reasoning_tags = InlineReasoningTagState::default();
    let mut events = Vec::new();

    for chunk in chunks {
        let value: Value = serde_json::from_str(chunk).expect("valid SSE JSON");
        events.extend(parse_sse_chunk_with_reasoning_style(
            &value,
            &mut content_index,
            &mut text_started,
            &mut thinking_started,
            &mut tool_indices,
            &mut reasoning_detail_buffers,
            &mut inline_reasoning_tags,
            reasoning_stream_style,
        ));
    }
    events
}

fn text_delta_text(events: &[StreamEvent]) -> String {
    events
        .iter()
        .filter_map(|event| match event {
            StreamEvent::ContentBlockDelta {
                delta: Delta::TextDelta { text },
                ..
            } => Some(text.as_str()),
            _ => None,
        })
        .collect()
}

fn thinking_delta_text(events: &[StreamEvent]) -> String {
    events
        .iter()
        .filter_map(|event| match event {
            StreamEvent::ContentBlockDelta {
                delta: Delta::ThinkingDelta { thinking },
                ..
            } => Some(thinking.as_str()),
            _ => None,
        })
        .collect()
}

#[test]
fn decoder_emits_text_delta_for_content_chunk() {
    // The "happy" first chunk: a normal content delta. The engine treats
    // this as `any_content_received = true` and would NOT transparently
    // retry on a subsequent error.
    let events = decode_chunk(r#"{"choices":[{"delta":{"content":"hello"}}]}"#);
    assert!(
        matches!(
            events.first(),
            Some(StreamEvent::ContentBlockStart {
                content_block: ContentBlockStart::Text { .. },
                ..
            })
        ),
        "first event should open a text block; got {events:?}"
    );
    assert!(
        events
            .iter()
            .any(|e| matches!(e, StreamEvent::ContentBlockDelta {
                    delta: Delta::TextDelta { text },
                    ..
                } if text == "hello")),
        "should yield a TextDelta carrying 'hello'; got {events:?}"
    );
}

#[test]
fn decoder_emits_thinking_delta_for_reasoning_chunk() {
    // V4 thinking models surface reasoning_content first — the engine
    // also counts these as content received (so a subsequent stream error
    // surfaces rather than retrying transparently).
    let events = decode_chunk(r#"{"choices":[{"delta":{"reasoning_content":"plan..."}}]}"#);
    assert!(
        matches!(
            events.first(),
            Some(StreamEvent::ContentBlockStart {
                content_block: ContentBlockStart::Thinking { .. },
                ..
            })
        ),
        "first event should open a thinking block; got {events:?}"
    );
    assert!(
        events
            .iter()
            .any(|e| matches!(e, StreamEvent::ContentBlockDelta {
                    delta: Delta::ThinkingDelta { thinking },
                    ..
                } if thinking == "plan...")),
        "should yield a ThinkingDelta carrying 'plan...'; got {events:?}"
    );
}

#[test]
fn decoder_streams_moonshot_multi_chunk_reasoning_as_thinking() {
    // #3016: recorded shape from Moonshot's native endpoint — kimi-k2.6
    // streams `reasoning_content` deltas before the answer text. The
    // thinking deltas must accumulate into ONE thinking block and the
    // answer must arrive as text, not be glued into the trace.
    let chunks = [
        r#"{"id":"cmpl-kimi","model":"kimi-k2.6","choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":"Let me check"}}]}"#,
        r#"{"id":"cmpl-kimi","model":"kimi-k2.6","choices":[{"index":0,"delta":{"reasoning_content":" the config."}}]}"#,
        r#"{"id":"cmpl-kimi","model":"kimi-k2.6","choices":[{"index":0,"delta":{"content":"The answer is 42."}}]}"#,
    ];

    let is_reasoning =
        is_reasoning_model_for_stream(crate::config::ApiProvider::Moonshot, "kimi-k2.6");
    let mut content_index = 0u32;
    let mut text_started = false;
    let mut thinking_started = false;
    let mut tool_indices = std::collections::HashMap::new();
    let mut reasoning_detail_buffers = std::collections::HashMap::new();
    let mut events = Vec::new();
    for chunk in chunks {
        let value: Value = serde_json::from_str(chunk).expect("valid SSE JSON");
        events.extend(parse_sse_chunk(
            &value,
            &mut content_index,
            &mut text_started,
            &mut thinking_started,
            &mut tool_indices,
            &mut reasoning_detail_buffers,
            is_reasoning,
        ));
    }

    let thinking: String = events
        .iter()
        .filter_map(|event| match event {
            StreamEvent::ContentBlockDelta {
                delta: Delta::ThinkingDelta { thinking },
                ..
            } => Some(thinking.as_str()),
            _ => None,
        })
        .collect();
    assert_eq!(thinking, "Let me check the config.");

    let thinking_starts = events
        .iter()
        .filter(|event| {
            matches!(
                event,
                StreamEvent::ContentBlockStart {
                    content_block: ContentBlockStart::Thinking { .. },
                    ..
                }
            )
        })
        .count();
    assert_eq!(thinking_starts, 1, "one thinking block: {events:?}");

    let text: String = events
        .iter()
        .filter_map(|event| match event {
            StreamEvent::ContentBlockDelta {
                delta: Delta::TextDelta { text },
                ..
            } => Some(text.as_str()),
            _ => None,
        })
        .collect();
    assert_eq!(text, "The answer is 42.");
}

#[test]
fn decoder_accepts_openrouter_reasoning_delta_with_extra_fields() {
    let events = decode_chunk(
        r#"{"id":"or-1","choices":[{"delta":{"reasoning":"openrouter thought","reasoning_details":[{"type":"summary","text":"extra"}],"native_finish_reason":null}}],"usage":{"completion_tokens_details":{"reasoning_tokens":3}}}"#,
    );

    assert!(
        events.iter().any(|e| matches!(
            e,
            StreamEvent::ContentBlockDelta {
                delta: Delta::ThinkingDelta { thinking },
                ..
            } if thinking == "openrouter thought"
        )),
        "OpenRouter-style reasoning deltas with extra fields should not crash decoding; got {events:?}"
    );
}

#[test]
fn decoder_streams_minimax_reasoning_details_as_incremental_thinking() {
    // MiniMax's reasoning_split stream reports reasoning_details text as
    // a cumulative buffer. Emit only the suffix so the Thinking cell does
    // not duplicate earlier reasoning chunks.
    let chunks = [
        r#"{"id":"minimax-1","choices":[{"index":0,"delta":{"reasoning_details":[{"type":"text","text":"Inspect"}]}}]}"#,
        r#"{"id":"minimax-1","choices":[{"index":0,"delta":{"reasoning_details":[{"type":"text","text":"Inspect config"}]}}]}"#,
        r#"{"id":"minimax-1","choices":[{"index":0,"delta":{"content":"Done."}}]}"#,
    ];

    let is_reasoning = is_reasoning_model_for_stream(ApiProvider::Minimax, "MiniMax-M3");
    let mut content_index = 0u32;
    let mut text_started = false;
    let mut thinking_started = false;
    let mut tool_indices = std::collections::HashMap::new();
    let mut reasoning_detail_buffers = std::collections::HashMap::new();
    let mut events = Vec::new();
    for chunk in chunks {
        let value: Value = serde_json::from_str(chunk).expect("valid SSE JSON");
        events.extend(parse_sse_chunk(
            &value,
            &mut content_index,
            &mut text_started,
            &mut thinking_started,
            &mut tool_indices,
            &mut reasoning_detail_buffers,
            is_reasoning,
        ));
    }

    let thinking: String = events
        .iter()
        .filter_map(|event| match event {
            StreamEvent::ContentBlockDelta {
                delta: Delta::ThinkingDelta { thinking },
                ..
            } => Some(thinking.as_str()),
            _ => None,
        })
        .collect();
    assert_eq!(thinking, "Inspect config");

    assert!(!events.iter().any(|event| matches!(
        event,
        StreamEvent::ContentBlockDelta {
            delta: Delta::TextDelta { text },
            ..
        } if text == "Inspect" || text == "Inspect config"
    )));
}

#[test]
fn modelstudio_streams_reasoning_content_as_thinking() {
    // Recorded-style DashScope OpenAI-compatible frames (shape lifted from
    // Model Studio's deep-thinking docs): reasoning streams in
    // `delta.reasoning_content`, the answer in `delta.content`, and a
    // trailing usage-only chunk closes the stream.
    let chunks = [
        r#"{"choices":[{"delta":{"content":null,"role":"assistant","reasoning_content":""},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"model":"qwen3.8-max","id":"chatcmpl-ms-1"}"#,
        r#"{"choices":[{"delta":{"reasoning_content":"Let me think"},"index":0}],"object":"chat.completion.chunk","model":"qwen3.8-max","id":"chatcmpl-ms-1"}"#,
        r#"{"choices":[{"delta":{"reasoning_content":" about this."},"index":0}],"object":"chat.completion.chunk","model":"qwen3.8-max","id":"chatcmpl-ms-1"}"#,
        r#"{"choices":[{"delta":{"content":"The answer."},"index":0}],"object":"chat.completion.chunk","model":"qwen3.8-max","id":"chatcmpl-ms-1"}"#,
        r#"{"choices":[{"finish_reason":"stop","delta":{"content":"","reasoning_content":null},"index":0}],"object":"chat.completion.chunk","model":"qwen3.8-max","id":"chatcmpl-ms-1"}"#,
        r#"{"choices":[],"object":"chat.completion.chunk","usage":{"prompt_tokens":10,"completion_tokens":30,"total_tokens":40,"completion_tokens_details":{"reasoning_tokens":20}},"model":"qwen3.8-max","id":"chatcmpl-ms-1"}"#,
    ];

    // Both OpenAI-dialect plans classify their reasoning catalog.
    for (provider, base_url, model) in [
        (
            ApiProvider::ModelstudioTokenPlan,
            crate::config::DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL,
            "qwen3.8-max",
        ),
        (
            ApiProvider::ModelstudioCodingPlan,
            crate::config::DEFAULT_MODELSTUDIO_CODING_PLAN_BASE_URL,
            "qwen3.7-plus",
        ),
    ] {
        let style = reasoning_stream_style_for_route(provider, base_url, model, None);
        assert_eq!(style, ReasoningStreamStyle::SeparateField, "{provider:?}");

        let mut content_index = 0u32;
        let mut text_started = false;
        let mut thinking_started = false;
        let mut tool_indices = std::collections::HashMap::new();
        let mut reasoning_detail_buffers = std::collections::HashMap::new();
        let mut inline_reasoning_tags = InlineReasoningTagState::default();
        let mut events = Vec::new();
        for chunk in chunks {
            let value: Value = serde_json::from_str(chunk).expect("valid SSE JSON");
            events.extend(parse_sse_chunk_with_reasoning_style(
                &value,
                &mut content_index,
                &mut text_started,
                &mut thinking_started,
                &mut tool_indices,
                &mut reasoning_detail_buffers,
                &mut inline_reasoning_tags,
                style,
            ));
        }

        let thinking: String = events
            .iter()
            .filter_map(|event| match event {
                StreamEvent::ContentBlockDelta {
                    delta: Delta::ThinkingDelta { thinking },
                    ..
                } => Some(thinking.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(thinking, "Let me think about this.", "{provider:?}");

        let text: String = events
            .iter()
            .filter_map(|event| match event {
                StreamEvent::ContentBlockDelta {
                    delta: Delta::TextDelta { text },
                    ..
                } => Some(text.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(text, "The answer.", "{provider:?}");

        // The trailing usage chunk still surfaces token accounting.
        assert!(
            events.iter().any(|event| matches!(
                event,
                StreamEvent::MessageDelta { usage: Some(usage), .. }
                    if usage.output_tokens == 30
            )),
            "{provider:?}: {events:?}"
        );
    }

    // A non-reasoning model id on the same route keeps the old
    // pass-through semantics (no fabricated Thinking surface).
    let style = reasoning_stream_style_for_route(
        ApiProvider::ModelstudioTokenPlan,
        crate::config::DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL,
        "qwen3.8-max-lite-unknown",
        None,
    );
    assert_eq!(style, ReasoningStreamStyle::None);
}

#[test]
fn decoder_does_not_render_reasoning_as_text_for_known_provider_models() {
    let mut content_index = 0u32;
    let mut text_started = false;
    let mut thinking_started = false;
    let mut tool_indices = std::collections::HashMap::new();
    let mut reasoning_detail_buffers = std::collections::HashMap::new();
    let is_reasoning_model =
        is_reasoning_model_for_stream(ApiProvider::XiaomiMimo, "mimo-v2.5-pro");
    let events = parse_sse_chunk(
        &serde_json::json!({
            "choices": [{
                "delta": {
                    "reasoning_content": "private plan"
                }
            }]
        }),
        &mut content_index,
        &mut text_started,
        &mut thinking_started,
        &mut tool_indices,
        &mut reasoning_detail_buffers,
        is_reasoning_model,
    );

    assert!(events.iter().any(|event| matches!(
        event,
        StreamEvent::ContentBlockDelta {
            delta: Delta::ThinkingDelta { thinking },
            ..
        } if thinking == "private plan"
    )));
    assert!(!events.iter().any(|event| matches!(
        event,
        StreamEvent::ContentBlockDelta {
            delta: Delta::TextDelta { text },
            ..
        } if text == "private plan"
    )));
}

#[test]
fn decoder_treats_reasoning_content_as_text_when_provider_does_not_support_reasoning() {
    let events = decode_chunk_with_reasoning(
        r#"{"choices":[{"delta":{"reasoning_content":"hello"}}]}"#,
        false,
    );

    assert!(
        matches!(
            events.first(),
            Some(StreamEvent::ContentBlockStart {
                content_block: ContentBlockStart::Text { .. },
                ..
            })
        ),
        "first event should open a text block; got {events:?}"
    );
    assert!(
        events.iter().any(|e| matches!(
            e,
            StreamEvent::ContentBlockDelta {
                delta: Delta::TextDelta { text },
                ..
            } if text == "hello"
        )),
        "should yield a TextDelta carrying 'hello'; got {events:?}"
    );
    assert!(
        !events.iter().any(|e| matches!(
            e,
            StreamEvent::ContentBlockDelta {
                delta: Delta::ThinkingDelta { .. },
                ..
            }
        )),
        "should not emit thinking deltas for generic providers; got {events:?}"
    );
}

#[test]
fn reasoning_style_separate_field_routes_reasoning_to_thinking() {
    let events = decode_chunks_with_style(
        &[
            r#"{"choices":[{"delta":{"reasoning_content":"private plan"}}]}"#,
            r#"{"choices":[{"delta":{"content":"Public answer."}}]}"#,
        ],
        ReasoningStreamStyle::SeparateField,
    );

    assert_eq!(thinking_delta_text(&events), "private plan");
    assert_eq!(text_delta_text(&events), "Public answer.");
}

#[test]
fn exact_kimi_code_k3_streams_reasoning_content_as_thinking() {
    let style = reasoning_stream_style_for_route(
        ApiProvider::Moonshot,
        crate::config::DEFAULT_KIMI_CODE_BASE_URL,
        crate::config::KIMI_CODE_K3_MODEL,
        None,
    );
    assert_eq!(style, ReasoningStreamStyle::SeparateField);

    let events = decode_chunks_with_style(
        &[r#"{"choices":[{"delta":{"reasoning_content":"private K3 plan"}}]}"#],
        style,
    );
    assert_eq!(thinking_delta_text(&events), "private K3 plan");
    assert_eq!(text_delta_text(&events), "");

    let generic_style = reasoning_stream_style_for_route(
        ApiProvider::Moonshot,
        crate::config::DEFAULT_MOONSHOT_BASE_URL,
        crate::config::KIMI_CODE_K3_MODEL,
        None,
    );
    assert_eq!(generic_style, ReasoningStreamStyle::None);
}

#[test]
fn reasoning_style_inline_tags_routes_think_blocks_to_thinking() {
    let events = decode_chunks_with_style(
        &[
            r#"{"choices":[{"delta":{"content":"Before <thi"}}]}"#,
            r#"{"choices":[{"delta":{"content":"nk>private plan</thi"}}]}"#,
            r#"{"choices":[{"delta":{"content":"nk> after."}}]}"#,
        ],
        ReasoningStreamStyle::InlineTags,
    );

    assert_eq!(thinking_delta_text(&events), "private plan");
    assert_eq!(text_delta_text(&events), "Before  after.");
    assert!(
        !text_delta_text(&events).contains("<think>"),
        "inline reasoning tags must not leak into visible text: {events:?}"
    );
}

#[test]
fn reasoning_style_inline_tags_flushes_unclosed_think_at_stream_end() {
    let events = decode_chunks_with_style(
        &[
            r#"{"choices":[{"delta":{"content":"Before <think>partial reasoning"}}]}"#,
            r#"{"choices":[{"finish_reason":"stop"}]}"#,
        ],
        ReasoningStreamStyle::InlineTags,
    );

    assert_eq!(thinking_delta_text(&events), "partial reasoning");
    assert_eq!(text_delta_text(&events), "Before ");
}

#[test]
fn reasoning_style_inline_tags_ignores_separate_reasoning_field() {
    let events = decode_chunks_with_style(
        &[
            r#"{"choices":[{"delta":{"reasoning_content":"metadata","content":"<think>tagged</think> answer"}}]}"#,
        ],
        ReasoningStreamStyle::InlineTags,
    );

    assert_eq!(thinking_delta_text(&events), "tagged");
    assert_eq!(text_delta_text(&events), " answer");
}

#[test]
fn reasoning_style_none_keeps_inline_tags_visible_text() {
    let events = decode_chunks_with_style(
        &[r#"{"choices":[{"delta":{"content":"<think>visible</think> answer"}}]}"#],
        ReasoningStreamStyle::None,
    );

    assert_eq!(thinking_delta_text(&events), "");
    assert_eq!(text_delta_text(&events), "<think>visible</think> answer");
}

#[test]
fn configured_reasoning_style_overrides_route_default() {
    assert_eq!(
        reasoning_stream_style_for_stream(ApiProvider::Openai, "custom-minimax", None),
        ReasoningStreamStyle::None
    );
    assert_eq!(
        reasoning_stream_style_for_stream(
            ApiProvider::Openai,
            "custom-minimax",
            Some("inline-tags")
        ),
        ReasoningStreamStyle::InlineTags
    );
    assert_eq!(
        reasoning_stream_style_for_stream(ApiProvider::XiaomiMimo, "mimo-v2.5-pro", None),
        ReasoningStreamStyle::SeparateField
    );
    assert_eq!(
        reasoning_stream_style_for_stream(ApiProvider::XiaomiMimo, "mimo-v2.5-pro", Some("none")),
        ReasoningStreamStyle::None
    );
}

#[test]
fn decoder_yields_no_events_for_keepalive_chunk() {
    // DeepSeek often sends `{"choices":[]}` keepalive chunks before
    // emitting real content. The engine MUST treat a stream error after
    // these as "no content received" and be eligible for transparent
    // retry — assert here that the decoder yields no payload events.
    let events = decode_chunk(r#"{"choices":[]}"#);
    assert!(
        events.is_empty(),
        "empty-choices chunk must produce no events; got {events:?}"
    );
}

#[test]
fn decoder_treats_done_frame_as_terminal() {
    let mut content_index = 0u32;
    let mut text_started = false;
    let mut thinking_started = false;
    let mut tool_indices = std::collections::HashMap::new();
    let mut reasoning_detail_buffers = std::collections::HashMap::new();
    let mut inline_reasoning_tags = InlineReasoningTagState::default();

    let outcome = parse_sse_data_frame(
        "  [DONE]  ",
        &mut content_index,
        &mut text_started,
        &mut thinking_started,
        &mut tool_indices,
        &mut reasoning_detail_buffers,
        &mut inline_reasoning_tags,
        ReasoningStreamStyle::SeparateField,
    );

    assert!(
        matches!(outcome, SseDataFrame::Done),
        "`data: [DONE]` must terminate the stream instead of waiting for the HTTP connection to close"
    );
    assert_eq!(content_index, 0);
    assert!(!text_started);
    assert!(!thinking_started);
    assert!(tool_indices.is_empty());
}

#[test]
fn decoder_emits_tool_use_block_for_tool_call_delta() {
    // Tool-call deltas are content too — once one arrives, transparent
    // retry must be off (the model has committed to a tool invocation
    // path that DeepSeek has billed for).
    let events = decode_chunk(
        r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"grep_files","arguments":"{\"pattern\":\"foo\"}"}}]}}]}"#,
    );
    assert!(
        events.iter().any(|e| matches!(
            e,
            StreamEvent::ContentBlockStart {
                content_block: ContentBlockStart::ToolUse { name, ..},
                ..
            } if name == "grep_files"
        )),
        "should open a ToolUse block for grep_files; got {events:?}"
    );
    assert!(
        events.iter().any(|e| matches!(
            e,
            StreamEvent::ContentBlockDelta {
                delta: Delta::InputJsonDelta { partial_json },
                ..
            } if partial_json.contains("\"pattern\"")
        )),
        "should yield InputJsonDelta carrying the tool args; got {events:?}"
    );
}

#[test]
fn decoder_uses_fallback_name_for_empty_streaming_tool_name() {
    let events = decode_chunk(
        r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_empty","function":{"name":"","arguments":"{}"}}]}}]}"#,
    );

    assert!(
        events.iter().any(|event| matches!(
            event,
            StreamEvent::ContentBlockStart {
                content_block: ContentBlockStart::ToolUse { name, ..},
                ..
            } if name == "unknown_tool"
        )),
        "empty upstream tool names should render as unknown_tool; got {events:?}"
    );
}

#[test]
fn non_streaming_response_uses_fallback_name_for_missing_tool_name() {
    let payload: Value = serde_json::from_str(
        r#"{
                "id": "chatcmpl_1",
                "model": "deepseek-v4-pro",
                "choices": [{
                    "message": {
                        "role": "assistant",
                        "tool_calls": [{
                            "id": "call_missing",
                            "function": { "arguments": "{}" }
                        }]
                    },
                    "finish_reason": "tool_calls"
                }]
            }"#,
    )
    .expect("valid response");

    let parsed = parse_chat_message(&payload).expect("message parses");
    let tool_name = parsed.content.iter().find_map(|block| match block {
        ContentBlock::ToolUse { name, .. } => Some(name.as_str()),
        _ => None,
    });

    assert_eq!(tool_name, Some("unknown_tool"));
}

/// Regression for the parallel-tool-calls-without-id collision (audit
/// Finding 8): when the upstream chunk omits the `id` field, the
/// fallback used to be the literal string `"tool_call"` for every
/// parallel call, so two tool calls in one delta ended up sharing an
/// id. Downstream routing then matched the first call's tool_result
/// twice and the second call hung. The fallback is now indexed by the
/// content-block position, keeping each call unique within the
/// response.
#[test]
fn decoder_assigns_unique_fallback_ids_to_parallel_tool_calls_missing_id() {
    let events = decode_chunk(
        r#"{"choices":[{"delta":{"tool_calls":[
                {"index":0,"function":{"name":"grep_files","arguments":"{\"pattern\":\"a\"}"}},
                {"index":1,"function":{"name":"read_file","arguments":"{\"path\":\"x\"}"}}
            ]}}]}"#,
    );

    let ids: Vec<&str> = events
        .iter()
        .filter_map(|e| match e {
            StreamEvent::ContentBlockStart {
                content_block: ContentBlockStart::ToolUse { id, .. },
                ..
            } => Some(id.as_str()),
            _ => None,
        })
        .collect();

    assert_eq!(
        ids.len(),
        2,
        "expected two tool-use blocks for parallel tool calls; got {events:?}"
    );
    assert_ne!(
        ids[0], ids[1],
        "parallel tool calls without upstream `id` must get distinct fallback ids; got {ids:?}"
    );
}

#[test]
fn decoder_preserves_upstream_tool_call_id_when_present() {
    // Counter-test to the fallback regression: when the upstream chunk
    // does include `id`, we forward it verbatim — we shouldn't quietly
    // rewrite ids the API gave us just because we have a fallback path.
    let events = decode_chunk(
        r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_xyz","function":{"name":"grep_files","arguments":"{}"}}]}}]}"#,
    );
    let id = events
        .iter()
        .find_map(|e| match e {
            StreamEvent::ContentBlockStart {
                content_block: ContentBlockStart::ToolUse { id, .. },
                ..
            } => Some(id.as_str()),
            _ => None,
        })
        .expect("tool-use block present");
    assert_eq!(id, "call_xyz");
}

#[test]
fn request_builder_preserves_internal_system_messages() {
    let messages = vec![Message {
        role: "system".to_string(),
        content: vec![ContentBlock::Text {
            text: "internal runtime event".to_string(),
            cache_control: None,
        }],
    }];

    let built = build_chat_messages(None, &messages, "deepseek-v4-flash");

    assert_eq!(built.len(), 1);
    assert_eq!(built[0]["role"], "system");
    assert_eq!(built[0]["content"], "internal runtime event");
}

fn tool_use_message(id: &str, name: &str, input: Value) -> Message {
    Message {
        role: "assistant".to_string(),
        content: vec![ContentBlock::ToolUse {
            id: id.to_string(),
            name: name.to_string(),
            input,
            caller: None,
            thought_signature: None,
        }],
    }
}

fn tool_result_message(id: &str, content: &str) -> Message {
    Message {
        role: "user".to_string(),
        content: vec![ContentBlock::ToolResult {
            tool_use_id: id.to_string(),
            content: content.to_string(),
            is_error: None,
            content_blocks: None,
        }],
    }
}

fn user_message_with_turn_meta(turn_meta: &str, task: &str) -> Message {
    Message {
        role: "user".to_string(),
        content: vec![
            ContentBlock::Text {
                text: turn_meta.to_string(),
                cache_control: None,
            },
            ContentBlock::Text {
                text: task.to_string(),
                cache_control: None,
            },
        ],
    }
}

fn user_message_with_tail_turn_meta(task: &str, turn_meta: &str) -> Message {
    Message {
        role: "user".to_string(),
        content: vec![
            ContentBlock::Text {
                text: task.to_string(),
                cache_control: None,
            },
            ContentBlock::Text {
                text: turn_meta.to_string(),
                cache_control: None,
            },
        ],
    }
}

fn tool_message_content(messages: &[Value], index: usize) -> &str {
    messages
        .iter()
        .filter(|message| message.get("role").and_then(Value::as_str) == Some("tool"))
        .nth(index)
        .and_then(|message| message.get("content").and_then(Value::as_str))
        .expect("tool message content")
}

fn user_message_content(messages: &[Value], index: usize) -> &str {
    messages
        .iter()
        .filter(|message| message.get("role").and_then(Value::as_str) == Some("user"))
        .nth(index)
        .and_then(|message| message.get("content").and_then(Value::as_str))
        .expect("user message content")
}

fn with_tool_result_sha_spillover_root<T>(f: impl FnOnce() -> T) -> T {
    let _guard = crate::tools::truncate::TEST_SPILLOVER_GUARD
        .lock()
        .unwrap_or_else(|err| err.into_inner());
    let tmp = tempfile::tempdir().expect("tempdir");
    let prior = crate::tools::truncate::set_test_spillover_root(Some(
        tmp.path().join(".deepseek").join("tool_outputs"),
    ));
    struct Restore(Option<std::path::PathBuf>);
    impl Drop for Restore {
        fn drop(&mut self) {
            crate::tools::truncate::set_test_spillover_root(self.0.take());
        }
    }
    let _restore = Restore(prior);
    f()
}

#[test]
fn request_builder_deduplicates_consecutive_identical_turn_meta_for_wire() {
    let turn_meta = "<turn_meta>\nCurrent local date: 2026-05-09\n</turn_meta>";
    let messages = vec![
        user_message_with_turn_meta(turn_meta, "first task"),
        Message {
            role: "assistant".to_string(),
            content: vec![ContentBlock::Text {
                text: "first answer".to_string(),
                cache_control: None,
            }],
        },
        user_message_with_turn_meta(turn_meta, "second task"),
    ];

    let built = build_chat_messages(None, &messages, "deepseek-v4-flash");
    let first = user_message_content(&built, 0);
    let second = user_message_content(&built, 1);
    let expected_ref = "<turn_meta_unchanged />";

    assert!(first.starts_with(turn_meta), "got: {first}");
    assert!(second.starts_with(expected_ref), "got: {second}");
    assert!(second.ends_with("second task"), "got: {second}");
    assert_eq!(
        second,
        format!("{expected_ref}\nsecond task"),
        "ref text must stay stable"
    );
}

#[test]
fn request_builder_keeps_tail_turn_meta_after_user_text_for_wire() {
    let turn_meta = "<turn_meta>\nCurrent local date: 2026-05-09\n</turn_meta>";
    let messages = vec![
        user_message_with_tail_turn_meta("first task", turn_meta),
        Message {
            role: "assistant".to_string(),
            content: vec![ContentBlock::Text {
                text: "first answer".to_string(),
                cache_control: None,
            }],
        },
        user_message_with_tail_turn_meta("second task", turn_meta),
    ];

    let built = build_chat_messages(None, &messages, "deepseek-v4-flash");
    let first = user_message_content(&built, 0);
    let second = user_message_content(&built, 1);
    let expected_ref = "<turn_meta_unchanged />";

    assert_eq!(first, format!("first task\n{turn_meta}"));
    assert_eq!(second, format!("second task\n{expected_ref}"));
}

#[test]
fn request_builder_keeps_changed_turn_meta_full_and_updates_recent_hash() {
    let first_meta = "<turn_meta>\nCurrent local date: 2026-05-09\n</turn_meta>";
    let second_meta =
        "<turn_meta>\nCurrent local date: 2026-05-09\nWorking set: src/lib.rs\n</turn_meta>";
    let messages = vec![
        user_message_with_turn_meta(first_meta, "first task"),
        user_message_with_turn_meta(second_meta, "second task"),
    ];

    let built = build_chat_messages(None, &messages, "deepseek-v4-flash");
    let first = user_message_content(&built, 0);
    let second = user_message_content(&built, 1);

    assert!(first.starts_with(first_meta), "got: {first}");
    assert!(second.starts_with(second_meta), "got: {second}");
    assert!(!second.contains("<TURN_META_REF"), "got: {second}");
}

#[test]
fn turn_meta_dedup_is_wire_only_and_does_not_mutate_session_message() {
    let turn_meta = "<turn_meta>\nCurrent local date: 2026-05-09\n</turn_meta>";
    let messages = vec![
        user_message_with_turn_meta(turn_meta, "first task"),
        user_message_with_turn_meta(turn_meta, "second task"),
    ];

    let built = build_chat_messages(None, &messages, "deepseek-v4-flash");
    assert!(
        user_message_content(&built, 1).starts_with("<turn_meta_unchanged />"),
        "got: {}",
        user_message_content(&built, 1)
    );

    match &messages[1].content[0] {
        ContentBlock::Text { text, .. } => assert_eq!(text, turn_meta),
        other => panic!("expected text block, got {other:?}"),
    }
}

#[test]
fn cache_inspect_reports_turn_meta_dedup_metadata() {
    let turn_meta = format!(
        "<turn_meta>\nCurrent local date: 2026-05-09\n{}\n</turn_meta>",
        "Working set: src/lib.rs\n".repeat(20)
    );
    let request = MessageRequest {
        model: "deepseek-v4-flash".to_string(),
        messages: vec![
            user_message_with_turn_meta(&turn_meta, "first task"),
            user_message_with_turn_meta(&turn_meta, "second task"),
        ],
        max_tokens: 0,
        system: None,
        tools: None,
        tool_choice: None,
        metadata: None,
        thinking: None,
        reasoning_effort: None,
        stream: None,
        temperature: None,
        top_p: None,
    };

    let inspection = inspect_prompt_for_request(&request);
    let turn_meta_layers: Vec<_> = inspection
        .layers
        .iter()
        .filter_map(|layer| layer.turn_meta.as_ref())
        .collect();

    assert_eq!(turn_meta_layers.len(), 2);
    assert_eq!(
        turn_meta_layers[0].original_chars,
        turn_meta.chars().count()
    );
    assert_eq!(turn_meta_layers[0].sent_chars, turn_meta.chars().count());
    assert!(!turn_meta_layers[0].deduplicated);
    assert_eq!(turn_meta_layers[0].sha256, sha256_hex(turn_meta.as_bytes()));
    assert_eq!(
        turn_meta_layers[1].original_chars,
        turn_meta.chars().count()
    );
    assert!(turn_meta_layers[1].sent_chars < turn_meta_layers[1].original_chars);
    assert!(turn_meta_layers[1].deduplicated);
    assert_eq!(turn_meta_layers[1].sha256, turn_meta_layers[0].sha256);
}

#[test]
fn request_builder_truncates_large_tool_result_for_wire() {
    let long_output = format!("{}{}", "A".repeat(7_000), "Z".repeat(7_000));
    let messages = vec![
        tool_use_message(
            "tool-long",
            "shell_command",
            json!({"command": "cargo test"}),
        ),
        tool_result_message("tool-long", &long_output),
    ];

    let built = build_chat_messages(None, &messages, "deepseek-v4-flash");
    let sent = tool_message_content(&built, 0);

    assert!(sent.contains("[TOOL_RESULT_TRUNCATED]"), "got: {sent}");
    assert!(sent.contains("tool_name: shell_command"), "got: {sent}");
    assert!(sent.contains("command_or_query: cargo test"), "got: {sent}");
    assert!(sent.contains("original_chars: 14000"), "got: {sent}");
    assert!(sent.contains("sha256:"), "got: {sent}");
    assert!(
        sent.contains("exact_detail: unavailable; no session-owned artifact was recorded"),
        "got: {sent}"
    );
    assert!(!sent.contains("retrieve_tool_result"), "got: {sent}");
    assert!(sent.contains(&"A".repeat(4_000)), "got: {sent}");
    assert!(sent.contains(&"Z".repeat(4_000)), "got: {sent}");
    assert!(
        sent.contains("truncated 6000 chars from middle"),
        "got: {sent}"
    );
    assert_ne!(sent, long_output);
}

#[test]
fn request_builder_keeps_unowned_extreme_tool_output_bounded_without_false_hint() {
    with_tool_result_sha_spillover_root(|| {
        let huge_output = format!(
            "{}{}{}",
            "DIFF_HEAD\n".repeat(10_000),
            "MIDDLE_POISON\n".repeat(10_000),
            "DIFF_TAIL\n".repeat(10_000)
        );
        let sha = sha256_hex(huge_output.as_bytes());
        let messages = vec![
            tool_use_message("tool-huge", "exec_shell", json!({"command": "git diff"})),
            tool_result_message("tool-huge", &huge_output),
        ];

        let built = build_chat_messages(None, &messages, "deepseek-v4-flash");
        let sent = tool_message_content(&built, 0);

        assert!(sent.contains("[TOOL_RESULT_TRUNCATED]"), "got: {sent}");
        assert!(sent.contains("tool_name: exec_shell"), "got: {sent}");
        assert!(sent.contains("command_or_query: git diff"), "got: {sent}");
        assert!(sent.contains(&format!("sha256: {sha}")), "got: {sent}");
        assert!(sent.contains("exact_detail: unavailable"), "got: {sent}");
        assert!(!sent.contains("retrieve_tool_result"), "got: {sent}");
        assert!(
            sent.chars().count() <= TOOL_RESULT_SENT_CHAR_BUDGET,
            "truncated result should stay bounded, sent {} chars",
            sent.chars().count()
        );
        assert!(
            !sent.contains("MIDDLE_POISON"),
            "omitted middle should not be sent to the next model turn"
        );
        assert_ne!(sent, huge_output);
    });
}

#[test]
fn request_builder_does_not_dedup_short_tool_results_for_wire() {
    let output = "same tool output";
    let messages = vec![
        tool_use_message("tool-1", "read_file", json!({"path": "README.md"})),
        tool_result_message("tool-1", output),
        tool_use_message("tool-2", "read_file", json!({"path": "README.md"})),
        tool_result_message("tool-2", output),
    ];

    let built = build_chat_messages(None, &messages, "deepseek-v4-flash");
    let first = tool_message_content(&built, 0);
    let second = tool_message_content(&built, 1);

    assert_eq!(first, output);
    assert_eq!(second, output);
    assert!(!second.contains("<TOOL_RESULT_REF"), "got: {second}");
}

#[test]
fn request_builder_deduplicates_medium_identical_tool_results_to_earlier_message() {
    with_tool_result_sha_spillover_root(|| {
        // 2,000 chars is intentionally above TOOL_RESULT_DEDUP_MIN_CHARS
        // (1,024) but below TOOL_RESULT_SENT_CHAR_BUDGET (12,000). This
        // verifies the cache-saving path for repeated medium outputs that
        // do not otherwise need truncation.
        let output = "A".repeat(2_000);
        let messages = vec![
            tool_use_message("tool-1", "read_file", json!({"path": "README.md"})),
            tool_result_message("tool-1", &output),
            tool_use_message("tool-2", "read_file", json!({"path": "README.md"})),
            tool_result_message("tool-2", &output),
        ];

        let built = build_chat_messages(None, &messages, "deepseek-v4-flash");
        let first = tool_message_content(&built, 0);
        let second = tool_message_content(&built, 1);

        assert_eq!(first, output);
        assert!(!first.contains("[TOOL_RESULT_TRUNCATED]"), "got: {first}");
        assert!(
            second.starts_with("<TOOL_RESULT_REF sha=\""),
            "got: {second}"
        );
        assert!(
            second.contains("original_message=\"Message #1\""),
            "got: {second}"
        );
        assert!(second.contains("chars=\"2000\""), "got: {second}");
        assert!(
            second.contains("source: full content appears in Message #1 earlier in this request"),
            "got: {second}"
        );
        assert!(!second.contains("retrieve_tool_result"), "got: {second}");
    });
}

#[test]
fn request_builder_never_dedups_large_identical_write_file_confirmations() {
    with_tool_result_sha_spillover_root(|| {
        // A `write_file` result embeds the unified diff + summary; it is a
        // confirmation, not retrievable data. Two identical >1024-char
        // write_file results must BOTH stay inline — collapsing the second
        // to a SHA ref makes the model lose write-success context and
        // report the file as missing (#1695).
        let output = "A".repeat(2_000);
        let messages = vec![
            tool_use_message("tool-1", "write_file", json!({"path": "big.txt"})),
            tool_result_message("tool-1", &output),
            tool_use_message("tool-2", "write_file", json!({"path": "big.txt"})),
            tool_result_message("tool-2", &output),
        ];

        let built = build_chat_messages(None, &messages, "deepseek-v4-flash");
        let first = tool_message_content(&built, 0);
        let second = tool_message_content(&built, 1);

        assert_eq!(first, output);
        assert_eq!(second, output);
        assert!(!second.contains("<TOOL_RESULT_REF"), "got: {second}");

        // Non-mutation tools still dedup: an identical medium read_file
        // result points back to the first full message in this request.
        let read_messages = vec![
            tool_use_message("read-1", "read_file", json!({"path": "README.md"})),
            tool_result_message("read-1", &output),
            tool_use_message("read-2", "read_file", json!({"path": "README.md"})),
            tool_result_message("read-2", &output),
        ];
        let read_built = build_chat_messages(None, &read_messages, "deepseek-v4-flash");
        let read_first = tool_message_content(&read_built, 0);
        let read_second = tool_message_content(&read_built, 1);
        assert_eq!(read_first, output);
        assert!(
            read_second.starts_with("<TOOL_RESULT_REF sha=\""),
            "got: {read_second}"
        );
        assert!(read_second.contains("source: full content appears in Message #1"));
        assert!(!read_second.contains("retrieve_tool_result"));
    });
}

#[test]
fn large_unowned_results_stay_bounded_without_false_retrieval_handles() {
    // The adaptive router normally replaces a large result with a
    // session-owned artifact receipt before this provider-wire fallback.
    // If legacy/raw history reaches here, it may be excerpted but must not
    // advertise the process-wide SHA store as retrievable.
    let big_diff = "D".repeat(20_000);
    let sha = sha256_hex(big_diff.as_bytes());

    let messages = vec![
        tool_use_message("w-1", "write_file", json!({"path": "huge.rs"})),
        tool_result_message("w-1", &big_diff),
        tool_use_message("w-2", "write_file", json!({"path": "huge.rs"})),
        tool_result_message("w-2", &big_diff),
    ];
    let built = build_chat_messages(None, &messages, "deepseek-v4-flash");
    let first = tool_message_content(&built, 0);
    let second = tool_message_content(&built, 1);

    // Mutation confirmations are independently excerpted, never deduped.
    assert!(
        first.contains("[TOOL_RESULT_TRUNCATED]"),
        "first should be truncated, got: {first}"
    );
    assert!(
        !first.contains("<TOOL_RESULT_REF"),
        "first must not be a dedup ref, got: {first}"
    );
    assert!(
        !second.contains("<TOOL_RESULT_REF"),
        "second identical write_file must stay inline (#1695), got: {second}"
    );
    assert!(
        second.contains("[TOOL_RESULT_TRUNCATED]"),
        "second should also be inline-truncated, got: {second}"
    );
    assert!(
        first.contains(&format!("sha256: {sha}")),
        "truncation block should retain an integrity digest, got: {first}"
    );
    assert!(first.contains("exact_detail: unavailable"));
    assert!(!first.contains("retrieve_tool_result"));

    // A huge non-mutation result cannot refer to an earlier *full* message,
    // because both wire messages are excerpts. It therefore stays a
    // truthful bounded excerpt too.
    let read_messages = vec![
        tool_use_message("r-1", "read_file", json!({"path": "huge.rs"})),
        tool_result_message("r-1", &big_diff),
        tool_use_message("r-2", "read_file", json!({"path": "huge.rs"})),
        tool_result_message("r-2", &big_diff),
    ];
    let read_built = build_chat_messages(None, &read_messages, "deepseek-v4-flash");
    let read_second = tool_message_content(&read_built, 1);
    assert!(read_second.contains("[TOOL_RESULT_TRUNCATED]"));
    assert!(!read_second.contains("<TOOL_RESULT_REF"));
    assert!(!read_second.contains("retrieve_tool_result"));
}

#[test]
fn tool_result_budget_is_wire_only_and_does_not_mutate_session_message() {
    let long_output = format!("{}{}", "A".repeat(7_000), "Z".repeat(7_000));
    let messages = vec![
        tool_use_message(
            "tool-long",
            "shell_command",
            json!({"command": "cargo test"}),
        ),
        tool_result_message("tool-long", &long_output),
    ];

    let built = build_chat_messages(None, &messages, "deepseek-v4-flash");
    let sent = tool_message_content(&built, 0);
    assert_ne!(sent, long_output);

    match &messages[1].content[0] {
        ContentBlock::ToolResult { content, .. } => assert_eq!(content, &long_output),
        other => panic!("expected tool result, got {other:?}"),
    }
}

#[test]
fn cache_inspect_reports_bounded_unowned_tool_result_metadata() {
    let long_output = format!("{}{}", "A".repeat(7_000), "Z".repeat(7_000));
    let request = MessageRequest {
        model: "deepseek-v4-flash".to_string(),
        messages: vec![
            tool_use_message("tool-1", "shell_command", json!({"command": "cargo test"})),
            tool_result_message("tool-1", &long_output),
            tool_use_message("tool-2", "shell_command", json!({"command": "cargo test"})),
            tool_result_message("tool-2", &long_output),
        ],
        max_tokens: 0,
        system: None,
        tools: None,
        tool_choice: None,
        metadata: None,
        thinking: None,
        reasoning_effort: None,
        stream: None,
        temperature: None,
        top_p: None,
    };

    let inspection = inspect_prompt_for_request(&request);
    let tool_layers: Vec<_> = inspection
        .layers
        .iter()
        .filter_map(|layer| layer.tool_result.as_ref())
        .collect();

    assert_eq!(tool_layers.len(), 2);
    for layer in tool_layers {
        assert_eq!(layer.original_chars, 14_000);
        assert!(layer.sent_chars < layer.original_chars);
        assert!(layer.truncated);
        assert!(!layer.deduplicated);
    }
}

#[test]
fn mistral_stream_blocks_are_decoded_only_by_the_mistral_style() {
    let chunk = r#"{
            "choices": [{
                "index": 0,
                "delta": {"content": [
                    {"type": "thinking", "thinking": [
                        {"type": "text", "text": "private trace"}
                    ], "closed": true},
                    {"type": "text", "text": "public answer"}
                ]},
                "finish_reason": null
            }]
        }"#;

    let mistral = decode_chunks_with_style(&[chunk], ReasoningStreamStyle::MistralBlocks);
    assert!(mistral.iter().any(|event| matches!(
        event,
        StreamEvent::ContentBlockDelta {
            delta: Delta::ThinkingDelta { thinking },
            ..
        } if thinking == "private trace"
    )));
    assert!(mistral.iter().any(|event| matches!(
        event,
        StreamEvent::ContentBlockDelta {
            delta: Delta::TextDelta { text },
            ..
        } if text == "public answer"
    )));

    let generic = decode_chunks_with_style(&[chunk], ReasoningStreamStyle::None);
    assert!(!generic.iter().any(|event| matches!(
        event,
        StreamEvent::ContentBlockDelta {
            delta: Delta::ThinkingDelta { .. },
            ..
        }
    )));
    assert!(!generic.iter().any(|event| matches!(
        event,
        StreamEvent::ContentBlockDelta {
            delta: Delta::TextDelta { .. },
            ..
        }
    )));
}