opencrabs 0.3.66

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
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
//! Tests for the processing-log flow renderers.
//!
//! Classic path: grouped tool calls render as native Telegram HTML using
//! `<blockquote expandable>` (Bot API 7.3+), never `<details>` — Telegram's
//! regular HTML parse mode does not support `<details>`, so that tag leaks
//! into the chat as literal text. Rich path (#420 path A): the rich API's
//! HTML INPUT mode is different — there `<details><summary>` is parsed
//! server-side into a native RichBlockDetails collapsible, so
//! `render_flow_details` emits exactly that wrapper.

use crate::channels::telegram::flow::{
    FlowEntry, FlowHeader, FlowOutcome, HeaderMarkup, extract_status_from_text, flow_header_text,
    humanize_duration, latest_activity_preview, pop_trailing_folded_texts,
    render_flow_details_with, render_flow_html_with,
};
use crate::channels::telegram::handler::{
    FlowLine, folded_duplicates_final, humanize_elapsed, render_flow_details, render_flow_html,
    render_flow_rich,
};

fn tline(label: &str, context: &str) -> FlowLine {
    FlowLine::Tool {
        label: label.to_string(),
        context: context.to_string(),
        raw_context: String::new(),
    }
}

/// Build a bash flow line the way production does (#488): `context` is the
/// decorated, middle-truncated display hint and `raw_context` is the untruncated
/// command. Status extraction must read `raw_context`, so tests that assert
/// `#`-comment status go through this, not `tline` (which passed the raw command
/// as `context` and so tested input the pipeline never produces).
fn bash_line(raw_command: &str) -> FlowLine {
    let input = serde_json::json!({ "command": raw_command });
    FlowLine::Tool {
        label: "⚙️ bash".to_string(),
        context: crate::utils::tool_context_hint("bash", &input),
        raw_context: crate::utils::tool_status_source("bash", &input),
    }
}

#[test]
fn empty_group_renders_nothing() {
    assert_eq!(render_flow_html(&[], None), "");
}

#[test]
fn single_tool_renders_plain_line_without_blockquote() {
    let out = render_flow_html(&[tline("✅ bash", "git status")], None);
    assert_eq!(out, "<b>✅ bash</b> <code>git status</code>");
    assert!(!out.contains("<blockquote"));
}

#[test]
fn single_tool_without_context_omits_trailing_space() {
    let out = render_flow_html(&[tline("⚙️ web_search", "")], None);
    assert_eq!(out, "<b>⚙️ web_search</b>");
}

#[test]
fn multiple_tools_render_expandable_blockquote() {
    let out = render_flow_html(
        &[
            tline("✅ bash", "cargo fmt"),
            tline("✅ read_file", "handler.rs"),
            tline("❌ grep", "pattern"),
        ],
        None,
    );
    // No narration, so the activity fallback is the most recent tool line; it
    // leads the header, then the count (#509).
    assert!(
        out.starts_with(
            "<blockquote expandable>⚙️ <b>❌ grep pattern</b> • <i>3 tool calls</i>\n\n"
        )
    );
    assert!(out.ends_with("</blockquote>"));
    assert!(out.contains("<b>✅ bash</b> <code>cargo fmt</code>"));
    assert!(out.contains("<b>✅ read_file</b> <code>handler.rs</code>"));
    assert!(out.contains("<b>❌ grep</b> <code>pattern</code>"));
}

#[test]
fn blocks_are_separated_by_blank_lines() {
    let out = render_flow_html(
        &[
            tline("✅ bash", "cargo fmt"),
            FlowLine::Text("Reformatted three files.".to_string()),
            tline("✅ read_file", "handler.rs"),
        ],
        None,
    );
    // The latest narration leads the header (#509); a blank line after it and
    // between every block keeps the log as separated entries, not a wall.
    assert!(out.starts_with(
        "<blockquote expandable>⚙️ <b>Reformatted three files.</b> • <i>2 tool calls</i>\n\n"
    ));
    assert!(out.contains("<b>✅ bash</b> <code>cargo fmt</code>\n\nReformatted three files."));
    assert!(
        out.contains("Reformatted three files.\n\n<b>✅ read_file</b> <code>handler.rs</code>")
    );
}

#[test]
fn tool_context_renders_as_monospace() {
    // Paths / commands / queries read as code, not prose, in the expanded block.
    let out = render_flow_html(
        &[
            tline("✅ read", "src/channels/telegram/handler.rs"),
            tline("✅ bash", "cargo clippy --all-features"),
        ],
        None,
    );
    assert!(out.contains("<b>✅ read</b> <code>src/channels/telegram/handler.rs</code>"));
    assert!(out.contains("<b>✅ bash</b> <code>cargo clippy --all-features</code>"));
}

#[test]
fn intermediate_text_renders_inline_markdown() {
    // Narration folded into the block gets the same inline markdown as the final
    // completion below it: `code` spans, **bold**, *italic* render, not raw.
    let out = render_flow_html(
        &[
            tline("✅ bash", "grep foo"),
            FlowLine::Text("Calling `analyze_image` then **committing** the *fix*.".to_string()),
        ],
        None,
    );
    assert!(out.contains("<code>analyze_image</code>"));
    assert!(out.contains("<b>committing</b>"));
    assert!(out.contains("<i>fix</i>"));
    // No raw markdown markers survive — the body renders them and the
    // latest-activity preview strips them (#405).
    assert!(!out.contains("`analyze_image`"));
    assert!(!out.contains("**committing**"));
}

#[test]
fn never_emits_details_tags() {
    let out = render_flow_html(&[tline("✅ a", "x"), tline("✅ b", "y")], None);
    assert!(!out.contains("<details>"));
    assert!(!out.contains("<summary>"));
}

#[test]
fn escapes_html_in_labels_and_context() {
    let out = render_flow_html(
        &[
            tline("✅ bash", "grep '<details>' & \"stuff\""),
            tline("✅ edit_file", "a < b > c"),
        ],
        None,
    );
    assert!(out.contains("grep '&lt;details&gt;' &amp; \"stuff\""));
    assert!(out.contains("a &lt; b &gt; c"));
    // No raw angle brackets from content survive outside our own tags
    assert!(!out.contains("'<details>'"));
}

// ── latest_activity_preview: whole human-readable text, JSON/code skip (#481) ──

#[test]
fn preview_uses_whole_human_readable_text_untruncated() {
    // Amendment: the whole intermediary text is the status source — every
    // paragraph, newlines preserved, no 96-char cap.
    let long = "First paragraph of the plan.\nSecond line with more detail.\nThird line that pushes well past the old ninety-six character truncation limit so the whole thing survives.";
    let out = latest_activity_preview(&[
        tline("✅ bash", "cargo test"),
        FlowLine::Text(long.to_string()),
    ]);
    assert_eq!(out.as_deref(), Some(long));
}

#[test]
fn preview_skips_json_last_entry_back_to_narration() {
    // A raw-JSON last entry is not human-readable; the preview walks back to the
    // prior narration instead of showing `{"model": ...}`.
    let out = latest_activity_preview(&[
        FlowLine::Text("Checking the model roster.".to_string()),
        FlowLine::Text("{\"model\": \"deepseek-v4-flash\", \"ok\": true}".to_string()),
    ]);
    assert_eq!(out.as_deref(), Some("Checking the model roster."));
}

#[test]
fn preview_skips_code_block_last_entry() {
    let out = latest_activity_preview(&[
        FlowLine::Text("Here is the fix.".to_string()),
        FlowLine::Text("```rust\nfn main() {}\n```".to_string()),
    ]);
    assert_eq!(out.as_deref(), Some("Here is the fix."));
}

#[test]
fn preview_strips_inline_markdown_markers() {
    let out = latest_activity_preview(&[FlowLine::Text(
        "Calling `grep` then **committing** the *fix*.".to_string(),
    )]);
    assert_eq!(
        out.as_deref(),
        Some("Calling grep then committing the fix.")
    );
}

#[test]
fn preview_keeps_one_word_sentence_but_skips_bare_path() {
    // "Done." is narration (keeps letters); a bare path is raw output, skipped.
    assert_eq!(
        latest_activity_preview(&[FlowLine::Text("Done.".to_string())]).as_deref(),
        Some("Done.")
    );
    let out = latest_activity_preview(&[
        tline("✅ read_file", "handler.rs"),
        FlowLine::Text("src/channels/telegram/flow.rs".to_string()),
    ]);
    assert_eq!(out.as_deref(), Some("✅ read_file handler.rs"));
}

#[test]
fn preview_falls_back_to_tool_when_no_human_readable_text() {
    let out = latest_activity_preview(&[
        tline("✅ read_file", "handler.rs"),
        FlowLine::Text("[1,2,3]".to_string()),
    ]);
    assert_eq!(out.as_deref(), Some("✅ read_file handler.rs"));
}

#[test]
fn preview_is_none_when_empty() {
    assert_eq!(latest_activity_preview(&[]), None);
}

// ── extract_status_from_text: bash line-start # comments (#482) ──

#[test]
fn bash_comment_single_strips_decoration() {
    assert_eq!(
        extract_status_from_text("# --- Setup environment ---\nexport FOO=bar").as_deref(),
        Some("Setup environment")
    );
}

#[test]
fn bash_comment_multiple_join_with_newlines() {
    let cmd = "# Step one\napt-get update\n# Step two\napt-get install foo";
    assert_eq!(
        extract_status_from_text(cmd).as_deref(),
        Some("Step one\nStep two")
    );
}

#[test]
fn bash_comment_ignores_inline_hash_and_shebang() {
    // A shebang and an inline (not line-start) `#` are not status comments.
    let cmd = "#!/bin/bash\ncurl https://x.com/a#frag\necho ok";
    assert_eq!(extract_status_from_text(cmd), None);
}

#[test]
fn bash_comment_none_when_no_comments() {
    assert_eq!(extract_status_from_text("cargo build --release"), None);
}

#[test]
fn preview_uses_bash_comments_when_no_narration() {
    // No human-readable text → priority 2 pulls the bash command's comments.
    // bash_line (not tline) so the pipeline is realistic: context is decorated,
    // raw_context holds the raw command that extraction must read (#488).
    let out = latest_activity_preview(&[bash_line("# --- Installing deps ---\nnpm install")]);
    assert_eq!(out.as_deref(), Some("Installing deps"));
}

#[test]
fn preview_bash_comment_on_first_line_survives_decoration() {
    // The #488 regression: the display hint wraps the command as `` (`…`) ``, so
    // a comment on the command's FIRST line no longer starts with `#` after
    // decoration and was dropped. Reading raw_context restores it.
    let out = latest_activity_preview(&[bash_line("# --- Setup environment ---\nexport FOO=bar")]);
    assert_eq!(out.as_deref(), Some("Setup environment"));
}

#[test]
fn preview_bash_comment_survives_long_command_no_truncation() {
    // The display hint middle-truncates to 80 bytes, which elided comments in a
    // long command (#488). raw_context is untruncated, so a trailing comment
    // past the 80-byte budget still surfaces.
    let long = format!(
        "# Build step\n{}\n# Deploy step\nmake deploy",
        "echo padding-".repeat(12)
    );
    assert!(long.len() > 80);
    let out = latest_activity_preview(&[bash_line(&long)]);
    assert_eq!(out.as_deref(), Some("Build step\nDeploy step"));
}

#[test]
fn preview_narration_beats_bash_comments() {
    // Priority 1 (narration) wins over priority 2 (bash comments).
    let out = latest_activity_preview(&[
        bash_line("# --- Installing deps ---\nnpm install"),
        FlowLine::Text("Wiring up the new module.".to_string()),
    ]);
    assert_eq!(out.as_deref(), Some("Wiring up the new module."));
}

// ── Mixed processing-log flow (tool calls + intermediate text) — #300 ──

#[test]
fn tool_plus_text_folds_into_one_blockquote() {
    let out = render_flow_html(
        &[
            tline("✅ bash", "git status"),
            FlowLine::Text("Checked the tree, all clean.".to_string()),
            tline("✅ read_file", "handler.rs"),
        ],
        None,
    );
    assert!(out.starts_with(
        "<blockquote expandable>⚙️ <b>Checked the tree, all clean.</b> • <i>2 tool calls</i>\n\n"
    ));
    assert!(out.ends_with("</blockquote>"));
    assert!(out.contains("<b>✅ bash</b> <code>git status</code>"));
    assert!(out.contains("Checked the tree, all clean."));
    assert!(out.contains("<b>✅ read_file</b> <code>handler.rs</code>"));
    assert!(!out.contains("<details>"));
}

#[test]
fn text_only_flow_uses_processing_log_header() {
    let out = render_flow_html(&[FlowLine::Text("Switching provider…".to_string())], None);
    // Text-only: the narration leads, the count slot reads "Processing log" (#509).
    assert!(out.starts_with(
        "<blockquote expandable>⚙️ <b>Switching provider…</b> • <i>Processing log</i>\n\n"
    ));
    assert!(out.contains("Switching provider…"));
    assert!(!out.contains("tool calls"));
}

#[test]
fn intermediate_text_is_html_escaped_in_flow() {
    let out = render_flow_html(
        &[
            tline("✅ bash", "echo hi"),
            FlowLine::Text("result: <b>bold</b> & <script>alert(1)</script>".to_string()),
        ],
        None,
    );
    assert!(out.contains("&lt;b&gt;bold&lt;/b&gt; &amp; &lt;script&gt;"));
    // The injected tags must never survive as live HTML.
    assert!(!out.contains("<script>"));
}

#[test]
fn blank_text_entries_are_dropped() {
    let out = render_flow_html(
        &[tline("✅ bash", "x"), FlowLine::Text("   ".to_string())],
        None,
    );
    // A lone tool with only blank text collapses to the one-liner.
    assert_eq!(out, "<b>✅ bash</b> <code>x</code>");
}

#[test]
fn empty_flow_renders_nothing() {
    assert_eq!(render_flow_html(&[], None), "");
}

// ── folded_duplicates_final: block dedup against the final answer ──
// A streamed copy of the final answer can land folded in the collapsed block.
// On API providers the answer also comes back in response.content, so it must
// be dropped from the block or it renders twice (once folded, once as the
// completion). Streaming often folds only a truncated head, so the check must
// catch a PREFIX, not just an exact match.

#[test]
fn folded_dup_matches_exact_final() {
    let answer = "The rebuild finished and the binary is swapped in.";
    assert!(folded_duplicates_final(answer, answer));
}

#[test]
fn folded_dup_matches_truncated_prefix() {
    // The block captured only the streamed head, cut off mid-sentence.
    let folded = "Yes, Adolfo. After you told me to search for the tool, I";
    let final_text =
        "Yes, Adolfo. After you told me to search for the tool, I found it and used it.";
    assert!(folded_duplicates_final(folded, final_text));
}

#[test]
fn folded_dup_ignores_whitespace_differences() {
    let folded = "line one\n\n  line two three four five";
    let final_text = "line one line two three four five and the rest of the answer here";
    assert!(folded_duplicates_final(folded, final_text));
}

#[test]
fn folded_dup_rejects_distinct_narration() {
    // A genuine mid-turn narration line that isn't the final answer.
    let folded = "Let me trace the delivery path first.";
    let final_text = "The root cause is an exact-equality dedup that misses a truncated prefix.";
    assert!(!folded_duplicates_final(folded, final_text));
}

#[test]
fn folded_dup_rejects_short_shared_opening() {
    // Too short an overlap to be sure it's the answer, not a coincidental start.
    let folded = "Done.";
    let final_text = "Done. Here is the full breakdown of everything that changed this turn.";
    assert!(!folded_duplicates_final(folded, final_text));
}

#[test]
fn folded_dup_exact_short_answer_matches() {
    // #316: a short final answer folded verbatim used to slip under the
    // 20-char prefix guard and render twice (in the block AND as the
    // completion). Exact equality is a duplicate at any length.
    assert!(folded_duplicates_final("Dropped it.", "Dropped it."));
}

#[test]
fn folded_dup_exact_short_with_whitespace_matches() {
    assert!(folded_duplicates_final("  Dropped   it.\n", "Dropped it."));
}

#[test]
fn folded_dup_empty_sides_never_match() {
    assert!(!folded_duplicates_final("", ""));
    assert!(!folded_duplicates_final("", "Dropped it."));
    assert!(!folded_duplicates_final("Dropped it.", ""));
}

// ── Live status in the block header — single progress surface (#360) ──
// While the turn runs, the open block's header carries the rolling status
// ("N tool calls • read_file • 45s") so no standalone ticker message exists
// alongside the block. When the final response lands the status is cleared
// and the header settles back to the plain count.

#[test]
fn live_status_rides_in_blockquote_header() {
    // Live header order (#509): latest activity (bold) leads, then the count,
    // then the duration (italic), `•`-separated.
    let out = render_flow_html(
        &[
            tline("✅ bash", "cargo fmt"),
            FlowLine::Text("Reading the handler.".to_string()),
            tline("⚙️ read_file", "handler.rs"),
        ],
        Some("45s"),
    );
    assert!(out.starts_with(
        "<blockquote expandable>⚙️ <b>Reading the handler.</b> • <i>2 tool calls</i> • <i>45s</i>\n"
    ));
    assert!(out.ends_with("</blockquote>"));
}

#[test]
fn no_duration_still_leads_with_activity() {
    // No elapsed duration yet: the header still leads with the latest activity
    // (here the most-recent tool line fallback) and the count, with no trailing
    // duration segment (#509).
    let out = render_flow_html(
        &[
            tline("✅ bash", "cargo fmt"),
            tline("✅ read_file", "handler.rs"),
        ],
        None,
    );
    assert!(out.starts_with(
        "<blockquote expandable>⚙️ <b>✅ read_file handler.rs</b> • <i>2 tool calls</i>\n"
    ));
    assert!(!out.contains("45s"));
}

#[test]
fn live_status_on_text_only_flow_uses_processing_log_header() {
    let out = render_flow_html(
        &[FlowLine::Text("Looking into it.".to_string())],
        Some("15s"),
    );
    assert!(out.starts_with(
        "<blockquote expandable>⚙️ <b>Looking into it.</b> • <i>Processing log</i> • <i>15s</i>\n"
    ));
}

#[test]
fn live_status_appends_to_single_tool_line() {
    // A lone tool call renders as a plain line (no blockquote); the status
    // still rides on it so the single surface shows progress from call one.
    let out = render_flow_html(&[tline("⚙️ bash", "git status")], Some("bash • 5s"));
    assert_eq!(out, "<b>⚙️ bash</b> <code>git status</code> • bash • 5s");
    assert!(!out.contains("<blockquote"));
}

#[test]
fn humanize_elapsed_snaps_to_five_second_steps() {
    // 5s snapping keeps header edits at most one per ~5s, not one per tick.
    assert_eq!(humanize_elapsed(0), "0s");
    assert_eq!(humanize_elapsed(4), "0s");
    assert_eq!(humanize_elapsed(7), "5s");
    assert_eq!(humanize_elapsed(59), "55s");
    assert_eq!(humanize_elapsed(61), "1m 0s");
    assert_eq!(humanize_elapsed(93), "1m 30s");
    assert_eq!(humanize_elapsed(3601), "60m 0s");
}

// ── Header wall-clock duration + settled outcome states (#480) ──

#[test]
fn humanize_duration_precise_then_minutes() {
    // Precise wall-clock seconds under a minute, then "X min Ys" (#480).
    assert_eq!(humanize_duration(0), "0s");
    assert_eq!(humanize_duration(45), "45s");
    assert_eq!(humanize_duration(59), "59s");
    assert_eq!(humanize_duration(60), "1 min 0s");
    assert_eq!(humanize_duration(90), "1 min 30s");
    assert_eq!(humanize_duration(300), "5 min 0s");
    assert_eq!(humanize_duration(3661), "61 min 1s");
}

#[test]
fn flow_header_live_and_settled_formats() {
    // Live order (#509): gear + bold status message FIRST, then the italic
    // tool-call count, then the italic duration, `•`-separated.
    assert_eq!(
        flow_header_text(
            3,
            &FlowHeader::Live(Some("45s")),
            Some("Reading logs"),
            HeaderMarkup::Html
        ),
        "⚙️ <b>Reading logs</b> • <i>3 tool calls</i> • <i>45s</i>"
    );
    // No status message, duration present → count + duration (italic), no lead.
    assert_eq!(
        flow_header_text(3, &FlowHeader::Live(Some("45s")), None, HeaderMarkup::Html),
        "⚙️ <i>3 tool calls</i> • <i>45s</i>"
    );
    // Neither status nor duration (just started) → plain bold count / log.
    assert_eq!(
        flow_header_text(3, &FlowHeader::Live(None), None, HeaderMarkup::Html),
        "<b>3 tool calls</b>"
    );
    assert_eq!(
        flow_header_text(0, &FlowHeader::Live(None), None, HeaderMarkup::Html),
        "<b>Processing log</b>"
    );
    // Markdown dialect swaps the tags: `**`/`_` where HTML uses `<b>`/`<i>`.
    assert_eq!(
        flow_header_text(
            3,
            &FlowHeader::Live(Some("45s")),
            Some("Reading logs"),
            HeaderMarkup::Markdown
        ),
        "⚙️ **Reading logs** • _3 tool calls_ • _45s_"
    );
    // Settled: outcome verb, count-in-parens, duration, fully bold; count clause
    // dropped when no tools ran. The status-message arg is ignored when settled.
    assert_eq!(
        flow_header_text(
            12,
            &FlowHeader::Settled {
                icon: "",
                verb: "Finished",
                duration: "45s"
            },
            None,
            HeaderMarkup::Html
        ),
        "<b>✅ Finished (12 tool calls, 45s)</b>"
    );
    assert_eq!(
        flow_header_text(
            0,
            &FlowHeader::Settled {
                icon: "",
                verb: "Finished",
                duration: "45s"
            },
            None,
            HeaderMarkup::Html
        ),
        "<b>✅ Finished (45s)</b>"
    );
}

#[test]
fn flow_outcome_icons_and_verbs() {
    assert_eq!(FlowOutcome::Finished.icon_verb(), ("", "Finished"));
    assert_eq!(FlowOutcome::Failed.icon_verb(), ("", "Failed"));
    assert_eq!(FlowOutcome::TimedOut.icon_verb(), ("", "Timed out"));
}

#[test]
fn settled_outcome_renders_block_header_over_lone_tool() {
    // A settled outcome always renders the block header (not the live lone-tool
    // one-liner) so the ❌/✅/⏱ badge, count, and duration show (#480).
    let out = render_flow_html_with(
        &[tline("✅ bash", "cargo test")],
        &FlowHeader::Settled {
            icon: "",
            verb: "Failed",
            duration: "12s",
        },
    );
    assert!(
        out.starts_with("<blockquote expandable><b>❌ Failed (1 tool calls, 12s)</b>"),
        "settled header: {out}"
    );
}

#[test]
fn settled_block_carries_no_activity_preview_classic() {
    // #498: the latest-activity preview is live-only. Once the block settles,
    // the stale narration must NOT stick under the Finished header — the rollup
    // stands alone. The narration still lives in the collapsed body log; only
    // the header-attached `•` preview is suppressed.
    let out = render_flow_html_with(
        &[
            tline("✅ bash", "cargo test"),
            FlowLine::Text("Running the test suite".to_string()),
        ],
        &FlowHeader::Settled {
            icon: "",
            verb: "Finished",
            duration: "3 min 15s",
        },
    );
    assert!(out.starts_with("<blockquote expandable><b>✅ Finished (1 tool calls, 3 min 15s)</b>"));
    assert!(
        !out.contains("• <i>"),
        "settled block must not carry a preview: {out}"
    );
}

#[test]
fn settled_block_carries_no_activity_preview_rich() {
    // #498, rich <details> surface (the one Adolfo runs): settled summary is
    // the outcome header alone, no trailing `•` preview stuck to it.
    let out = render_flow_details_with(
        &[
            tline("✅ bash", "cargo test"),
            FlowLine::Text("Running the test suite".to_string()),
        ],
        &FlowHeader::Settled {
            icon: "",
            verb: "Finished",
            duration: "3 min 15s",
        },
    );
    let summary_end = out.find("</summary>").expect("summary");
    let summary = &out[..summary_end];
    assert!(summary.contains("✅ Finished (1 tool calls, 3 min 15s)"));
    assert!(
        !summary.contains(""),
        "settled summary must not carry a preview: {summary}"
    );
}

// ── Rich API flow rendering tests (#393) ─────────────────────────────────────

#[test]
fn rich_empty_group_renders_nothing() {
    assert_eq!(render_flow_rich(&[], None), "");
}

#[test]
fn rich_single_tool_renders_plain_line() {
    let out = render_flow_rich(&[tline("✅ bash", "git status")], None);
    assert_eq!(out, "**✅ bash** `git status`");
    // Single tool: no blockquote wrapping, just bold label + context
    assert!(!out.contains(">"));
}

#[test]
fn rich_multiple_tools_render_markdown_header() {
    let out = render_flow_rich(
        &[tline("✅ bash", "git status"), tline("✅ read", "file.rs")],
        None,
    );
    // No narration: the activity fallback (most recent tool line) leads the
    // header, bold, then the italic count (#509).
    assert!(out.starts_with("⚙️ **✅ read file.rs** • _2 tool calls_\n\n"));
    assert!(out.contains("**✅ bash** `git status`"));
    assert!(out.contains("**✅ read** `file.rs`"));
}

#[test]
fn rich_live_status_in_header() {
    // Status-first order (#509): narration (bold) leads, then the count and the
    // duration (italic).
    let out = render_flow_rich(
        &[
            tline("✅ bash", "x"),
            FlowLine::Text("Searching.".to_string()),
            tline("⚙️ grep", "pattern"),
        ],
        Some("10s"),
    );
    assert!(out.starts_with("⚙️ **Searching.** • _2 tool calls_ • _10s_\n\n"));
}

#[test]
fn rich_single_tool_live_status_appends() {
    let out = render_flow_rich(&[tline("⚙️ bash", "git status")], Some("bash • 5s"));
    assert_eq!(out, "**⚙️ bash** `git status` • bash • 5s");
}

// ── Rich-API details flow rendering (#420 path A) ──

#[test]
fn details_empty_group_renders_nothing() {
    assert_eq!(render_flow_details(&[], None), "");
}

#[test]
fn details_single_tool_renders_plain_line() {
    // Lone tool line stays plain (mirrors #296), same as the HTML renderer.
    let out = render_flow_details(&[tline("✅ bash", "git status")], None);
    assert_eq!(out, "<b>✅ bash</b> <code>git status</code>");
    assert!(!out.contains("<details"));
}

#[test]
fn details_multiple_tools_wrap_in_collapsed_details() {
    let out = render_flow_details(
        &[tline("✅ bash", "git status"), tline("✅ read", "file.rs")],
        None,
    );
    // Collapsed by default: plain <details>, never <details open>. The summary
    // carries the latest-activity preview so the collapsed block shows progress
    // even with the body hidden (#405); with no narration it falls back to the
    // most recent tool line.
    assert!(out.starts_with(
        "<details><summary><sub>⚙️ <b>✅ read file.rs</b> • <i>2 tool calls</i></sub></summary>"
    ));
    assert!(out.ends_with("</details>"));
    assert!(!out.contains("<details open"));
    // Each entry is its own <p>: the rich HTML parser ignores raw newlines,
    // so without block-level wrapping the log runs together as one wall.
    assert!(out.contains("<p><b>✅ bash</b> <code>git status</code></p>"));
    assert!(out.contains("<p><b>✅ read</b> <code>file.rs</code></p>"));
}

#[test]
fn details_summary_carries_live_status() {
    let out = render_flow_details(
        &[
            tline("✅ bash", "x"),
            FlowLine::Text("Grepping.".to_string()),
            tline("⚙️ grep", "pattern"),
        ],
        Some("10s"),
    );
    let summary_end = out.find("</summary>").expect("summary");
    let summary = &out[..summary_end];
    // Status-first order (#509): narration (bold) leads, then count, then duration.
    assert!(summary.contains("⚙️ <b>Grepping.</b> • <i>2 tool calls</i> • <i>10s</i>"));
    // Summary is wrapped in <sub> for visual de-emphasis (#436).
    assert!(summary.contains("<sub>⚙️ <b>Grepping.</b>"));
    // Latest-activity preview rides in the summary (#405): the rich <details>
    // collapses to the summary ALONE, hiding the body, so without the preview
    // the collapsed block shows no progress at all.
    assert!(summary.contains("• <i>"));
}

#[test]
fn details_collapsed_summary_shows_intermediate_narration() {
    // Regression (#405): the COLLAPSED rich block must surface the latest
    // narration in its summary — the body is hidden by default, so the summary
    // is the only place a user sees mid-turn progress. Narration wins over the
    // trailing tool line as the preview source (#481).
    let out = render_flow_details(
        &[
            FlowLine::Text("Running the test suite".to_string()),
            tline("⚙️ bash", "cargo test"),
        ],
        Some("45s"),
    );
    let summary_end = out.find("</summary>").expect("summary");
    let summary = &out[..summary_end];
    // Narration leads the summary, bold (#509).
    assert!(summary.contains("⚙️ <b>Running the test suite</b>"));
}

#[test]
fn details_escapes_html_in_tool_context() {
    let out = render_flow_details(&[tline("✅ bash", "a < b"), tline("✅ read", "x.rs")], None);
    assert!(out.contains("<code>a &lt; b</code>"));
}

// ── Latest-activity preview in the collapsed block (#405) ──

#[test]
fn collapsed_preview_prefers_narration_over_tool_line() {
    // #481: the status source is the most recent human-readable narration — the
    // latest thing the agent SAID — even when a tool line follows it (that
    // narration usually describes the tool now running), which reads better
    // than a bare "⚙️ read_file src/agent.rs".
    let out = render_flow_html(
        &[
            FlowLine::Text("Checking how the scheduler resolves the next run".to_string()),
            tline("✅ bash", "grep flow"),
            tline("⚙️ read_file", "src/agent.rs"),
        ],
        None,
    );
    // Narration now LEADS the header, bold (#509), instead of a line below it.
    let header_line = out.lines().next().expect("header line");
    assert!(
        header_line.contains("<b>Checking how the scheduler resolves the next run</b>"),
        "header must lead with the narration: {header_line}"
    );
    // Full chronological log still follows for the expanded view.
    assert!(out.contains("<b>⚙️ read_file</b> <code>src/agent.rs</code>"));
}

#[test]
fn preview_keeps_long_text_whole_and_strips_markdown() {
    // #481 amendment: no truncation. Inline markers still stripped so the
    // preview never shows raw ** source.
    let long = format!("**{}**", "x".repeat(200));
    let out = render_flow_html(&[tline("✅ bash", "a"), FlowLine::Text(long)], None);
    // The narration leads the header (#509); it stays whole and markdown markers
    // are stripped before the header bolds it with `<b>`.
    let header_line = out.lines().next().unwrap();
    assert!(!header_line.contains(''), "not truncated: {header_line}");
    assert!(
        header_line.contains(&"x".repeat(200)),
        "whole text kept: {header_line}"
    );
    assert!(
        !header_line.contains("**"),
        "markers stripped: {header_line}"
    );
}

// ── trailing folded-answer reclaim (#478) ───────────────────────────

#[test]
fn trailing_text_run_pops_joined_in_order() {
    // The incident shape: tool rounds, then TWO trailing answer texts
    // (the second folded after a queued follow-up). Both must come out,
    // in order, so neither stays imprisoned in the block.
    let mut entries = vec![
        FlowEntry::Tool(0),
        FlowEntry::Text("first part of the answer".into()),
        FlowEntry::Text("Already factored in. Standing by.".into()),
    ];
    let reclaimed = pop_trailing_folded_texts(&mut entries).expect("reclaims");
    assert_eq!(
        reclaimed,
        "first part of the answer\n\nAlready factored in. Standing by."
    );
    assert_eq!(entries.len(), 1, "tool entry stays");
    assert!(matches!(entries[0], FlowEntry::Tool(0)));
}

#[test]
fn text_only_flow_pops_everything() {
    let mut entries = vec![
        FlowEntry::Text("the whole answer".into()),
        FlowEntry::Text("plus a follow-up".into()),
    ];
    let reclaimed = pop_trailing_folded_texts(&mut entries).expect("reclaims");
    assert!(reclaimed.starts_with("the whole answer"));
    assert!(entries.is_empty());
}

#[test]
fn tool_last_flow_reclaims_nothing() {
    // Trailing tool call = the answer is in response.content, not folded.
    let mut entries = vec![FlowEntry::Text("narration".into()), FlowEntry::Tool(0)];
    assert!(pop_trailing_folded_texts(&mut entries).is_none());
    assert_eq!(entries.len(), 2, "nothing consumed");
}

// ── folded narration cap keeps the block compact (#489) ─────────────

#[test]
fn long_folded_narration_is_capped_in_the_block() {
    // A verbose CLI narration entry (over the 300-char cap) renders
    // truncated with an ellipsis, so the collapsed block stays small and
    // more tool rounds fit before the 30K rich size freeze.
    let long = "x".repeat(1200);
    let out = render_flow_html(
        &[
            tline("✅ bash", "cargo test"),
            FlowLine::Text(long.clone()),
            FlowLine::Text("all done here now".into()),
            tline("✅ read", "flow.rs"),
        ],
        None,
    );
    assert!(out.contains(''), "capped body entry ends with an ellipsis");
    // A LATER human text is the latest-activity preview (#487, shown whole),
    // so the long entry is body-only and its full run must NOT appear.
    assert!(!out.contains(&long), "body narration must be truncated");
}