agentty 0.8.0

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
use std::fmt::Write as _;
use std::sync::Arc;

use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::text::Line;
use ratatui::widgets::{Block, Paragraph};

use crate::domain::session::{Session, Status};
use crate::ui::markdown::{self, render_markdown};
use crate::ui::state::app_mode::DoneSessionOutputMode;
use crate::ui::util::{bottom_pinned_scroll_offset, panel_inner_width};
use crate::ui::{Component, layout, text_util};

const DRAFT_PREVIEW_HEADER: &str = "## Draft Session";
const DRAFT_PREVIEW_EMPTY_NOTE: &str = "No draft messages staged yet. Use `Enter` to stage the \
                                        first draft locally, then press `s` in session view to \
                                        start the bundle.";
const DRAFT_PREVIEW_STAGED_NOTE: &str =
    "Draft messages stay local until you press `s` in session view to start the staged bundle.";
const TRANSCRIPT_FOOTER_PREFIXES: &[&str] = &["[Commit]", "[Commit Error]"];
const USER_PROMPT_PREFIX: &str = "";
const USER_PROMPT_CONTINUATION_PREFIX: &str = "   ";

/// Session chat output panel renderer.
pub struct SessionOutput<'a> {
    active_prompt_output: Option<&'a str>,
    active_progress: Option<&'a str>,
    /// Selected panel content for the session output panel.
    done_session_output_mode: DoneSessionOutputMode,
    /// Shared render cache that avoids re-parsing unchanged markdown each
    /// frame.
    markdown_render_cache: Option<&'a markdown::MarkdownRenderCache>,
    review_status_message: Option<&'a str>,
    review_text: Option<&'a str>,
    scroll_offset: Option<u16>,
    session: &'a Session,
}

/// Borrowed inputs that control how session output lines are derived from one
/// session snapshot.
#[derive(Clone, Copy)]
pub(crate) struct SessionOutputLineContext<'a> {
    /// Exact prompt transcript block for the currently active turn, when one
    /// has been submitted in this app process.
    pub(crate) active_prompt_output: Option<&'a str>,
    /// Transient progress text rendered in the active-status loader row.
    pub(crate) active_progress: Option<&'a str>,
    /// Completed-session panel mode currently selected by the user.
    pub(crate) done_session_output_mode: DoneSessionOutputMode,
    /// Review fallback text shown while review output is unavailable.
    pub(crate) review_status_message: Option<&'a str>,
    /// Review markdown generated by the agent, when available.
    pub(crate) review_text: Option<&'a str>,
}

impl<'a> SessionOutput<'a> {
    /// Creates a new session output component.
    pub fn new(session: &'a Session) -> Self {
        Self {
            active_prompt_output: None,
            active_progress: None,
            done_session_output_mode: DoneSessionOutputMode::Summary,
            markdown_render_cache: None,
            review_status_message: None,
            review_text: None,
            scroll_offset: None,
            session,
        }
    }

    /// Sets the exact prompt transcript block for the currently active turn.
    #[must_use]
    pub fn active_prompt_output(mut self, active_prompt_output: Option<&'a str>) -> Self {
        self.active_prompt_output = active_prompt_output;
        self
    }

    /// Sets transient progress text rendered in the loader row.
    #[must_use]
    pub fn active_progress(mut self, active_progress: &'a str) -> Self {
        self.active_progress = Some(active_progress);
        self
    }

    /// Sets the output display mode for completed sessions.
    #[must_use]
    pub fn done_session_output_mode(mut self, mode: DoneSessionOutputMode) -> Self {
        self.done_session_output_mode = mode;
        self
    }

    /// Sets the shared markdown render cache used to avoid re-parsing
    /// unchanged transcript content each frame.
    #[must_use]
    pub fn markdown_render_cache(mut self, cache: &'a markdown::MarkdownRenderCache) -> Self {
        self.markdown_render_cache = Some(cache);
        self
    }

    /// Sets the review status message rendered when review text is not
    /// available.
    #[must_use]
    pub fn review_status_message(mut self, status_message: Option<&'a str>) -> Self {
        self.review_status_message = status_message;
        self
    }

    /// Sets review text generated by an agent.
    #[must_use]
    pub fn review_text(mut self, review_text: Option<&'a str>) -> Self {
        self.review_text = review_text;
        self
    }

    /// Sets the vertical scroll offset.
    #[must_use]
    pub fn scroll_offset(mut self, offset: u16) -> Self {
        self.scroll_offset = Some(offset);
        self
    }

    /// Returns the rendered output line count for chat content at a given
    /// width.
    ///
    /// This mirrors the exact wrapping and footer line rules used during
    /// rendering so scroll math can stay in sync with what users see.
    pub(crate) fn rendered_line_count(
        session: &Session,
        output_width: u16,
        context: SessionOutputLineContext<'_>,
    ) -> u16 {
        let output_area = Rect::new(0, 0, output_width, 0);
        let lines = Self::output_lines(session, output_area, context, None);

        u16::try_from(lines.len()).unwrap_or(u16::MAX)
    }

    /// Builds rendered markdown lines and contextual status/help rows for the
    /// current session state.
    ///
    /// `Status::Done` includes an inline `t` toggle hint that switches between
    /// summary and full output views. Active statuses append only the generic
    /// loader row so transcript text stays stable until the turn completes.
    /// Wrapping width follows the configured output panel borders so line
    /// metrics stay in sync with rendered content. Transcript-derived content
    /// always renders in chronological order: completed-turn transcript,
    /// trailing commit/footer lines, then the currently active prompt block.
    /// Synthetic summary sections render only after the transcript so
    /// generated metadata never jumps above the latest visible user input.
    /// Focused-review output is appended after transcript content so it reads
    /// like agent-produced session output instead of replacing the transcript
    /// panel, but it is suppressed once the session reaches `Done` because
    /// merged sessions should only show final summary or transcript content.
    fn output_lines(
        session: &Session,
        output_area: Rect,
        context: SessionOutputLineContext<'_>,
        markdown_render_cache: Option<&markdown::MarkdownRenderCache>,
    ) -> Vec<Line<'static>> {
        let SessionOutputLineContext {
            active_prompt_output,
            active_progress,
            done_session_output_mode,
            review_status_message,
            review_text,
        } = context;
        let status = session.status;
        let output_text = Self::output_text(session, done_session_output_mode);
        let (completed_turn_text, active_turn_text) =
            Self::transcript_sections(status, &output_text, active_prompt_output);
        let completed_turn_text =
            layout::session_output_text_with_spaced_user_input(completed_turn_text);
        let active_turn_text =
            active_turn_text.map(layout::session_output_text_with_spaced_user_input);
        let inner_width = panel_inner_width(output_area, layout::session_output_panel_borders());
        let (completed_turn_text, trailing_footer_text) =
            text_util::split_trailing_line_block(&completed_turn_text, TRANSCRIPT_FOOTER_PREFIXES);
        let mut lines = Vec::new();
        Self::append_markdown_lines(
            &mut lines,
            completed_turn_text,
            inner_width,
            markdown_render_cache,
        );
        Self::append_transcript_footer_lines(
            &mut lines,
            trailing_footer_text,
            inner_width,
            markdown_render_cache,
        );
        Self::append_active_turn_lines(
            &mut lines,
            active_turn_text.as_deref(),
            inner_width,
            markdown_render_cache,
        );
        if Self::shows_summary_block(session.status, done_session_output_mode) {
            Self::append_summary_lines(
                &mut lines,
                session.summary.as_deref(),
                inner_width,
                markdown_render_cache,
            );
        }
        if Self::shows_review_lines(session.status) {
            Self::append_review_lines(&mut lines, review_text, inner_width, markdown_render_cache);
        }
        Self::append_published_branch_sync_lines(&mut lines, session);

        if let Some(status_line) =
            layout::session_output_status_line(status, active_progress, review_status_message)
        {
            while lines.last().is_some_and(|line| line.width() == 0) {
                lines.pop();
            }

            lines.push(Line::from(""));
            lines.push(status_line);
        } else if status == Status::Done {
            lines.push(Line::from(""));
            lines.push(layout::session_output_done_toggle_line(
                done_session_output_mode,
            ));
            lines.push(Line::from(""));
        } else {
            lines.push(Line::from(""));
        }

        lines
    }

    /// Appends one automatic published-branch sync status row when the latest
    /// completed turn started, finished, or failed an auto-push.
    fn append_published_branch_sync_lines(lines: &mut Vec<Line<'static>>, session: &Session) {
        let Some(sync_line) = layout::session_output_published_branch_sync_line(session) else {
            return;
        };

        while lines.last().is_some_and(|line| line.width() == 0) {
            lines.pop();
        }

        lines.push(Line::from(""));
        lines.push(sync_line);
    }

    /// Splits the transcript at the exact active-turn prompt block captured
    /// when the current turn was submitted.
    fn transcript_sections<'text>(
        status: Status,
        output_text: &'text str,
        active_prompt_output: Option<&str>,
    ) -> (&'text str, Option<&'text str>) {
        if !matches!(
            status,
            Status::InProgress | Status::Queued | Status::Rebasing | Status::Merging
        ) {
            return (output_text, None);
        }
        let Some(active_prompt_output) = active_prompt_output else {
            return (output_text, None);
        };
        let Some(active_prompt_start) = output_text.rfind(active_prompt_output) else {
            return (output_text, None);
        };
        if active_prompt_start == 0 {
            return (output_text, None);
        }

        (
            &output_text[..active_prompt_start],
            Some(&output_text[active_prompt_start..]),
        )
    }

    /// Returns the source text shown in the output panel for the current
    /// status and done-session display mode.
    ///
    /// Summary markdown is shown only for `Done` sessions after it has been
    /// persisted. New draft sessions render staged-draft guidance before
    /// their first live turn starts. Active and canceled sessions otherwise
    /// render transcript output only.
    fn output_text(session: &Session, done_session_output_mode: DoneSessionOutputMode) -> String {
        match session.status {
            Status::New if session.is_draft_session() => {
                return Self::render_draft_session_preview(session);
            }
            Status::Done if done_session_output_mode == DoneSessionOutputMode::Summary => {
                return layout::session_output_summary_markdown(Self::session_summary_text(
                    session,
                ));
            }
            Status::Canceled => {
                return session.output.clone();
            }
            Status::Review
            | Status::AgentReview
            | Status::Question
            | Status::New
            | Status::Done
            | Status::InProgress
            | Status::Queued
            | Status::Rebasing
            | Status::Merging => {}
        }

        session.output.clone()
    }

    /// Renders the staged-draft guidance shown while a draft session remains
    /// in `New`.
    fn render_draft_session_preview(session: &Session) -> String {
        let mut output = String::from(DRAFT_PREVIEW_HEADER);

        if session.has_staged_drafts() {
            let _ = write!(output, "\n\n{DRAFT_PREVIEW_STAGED_NOTE}\n\n");
            output.push_str(&Self::staged_draft_transcript_block(&session.prompt));
        } else {
            let _ = write!(output, "\n\n{DRAFT_PREVIEW_EMPTY_NOTE}\n");
        }

        output
    }

    /// Formats the staged draft-session prompt using the same transcript
    /// prompt markers used for persisted user-turn output.
    fn staged_draft_transcript_block(prompt_text: &str) -> String {
        let prompt_lines = prompt_text.split('\n').collect::<Vec<_>>();
        let mut formatted_lines = Vec::with_capacity(prompt_lines.len());

        for (index, prompt_line) in prompt_lines.into_iter().enumerate() {
            let prefix = if index == 0 {
                USER_PROMPT_PREFIX
            } else {
                USER_PROMPT_CONTINUATION_PREFIX
            };

            formatted_lines.push(format!("{prefix}{prompt_line}"));
        }

        format!("{}\n\n", formatted_lines.join("\n"))
    }

    /// Returns the persisted raw summary payload or plain-text fallback.
    fn session_summary_text(session: &Session) -> &str {
        session
            .summary
            .as_deref()
            .map(str::trim)
            .filter(|summary| !summary.is_empty())
            .unwrap_or("")
    }

    /// Returns whether the output panel should append the structured summary
    /// block outside the persisted transcript string.
    ///
    /// Canceled sessions keep the raw transcript visible so interrupted turns
    /// do not render synthetic summary content that was never finalized.
    fn shows_summary_block(
        status: Status,
        done_session_output_mode: DoneSessionOutputMode,
    ) -> bool {
        if status == Status::Canceled {
            return false;
        }

        !(status == Status::Done && done_session_output_mode == DoneSessionOutputMode::Summary)
    }

    /// Returns whether focused-review output belongs in the current session
    /// view.
    ///
    /// Merged sessions enter `Status::Done`, and at that point any cached
    /// review text is stale next to the final summary or transcript view.
    fn shows_review_lines(status: Status) -> bool {
        status != Status::Done
    }

    /// Appends focused-review output to the transcript when review text is
    /// available for the current session view.
    ///
    /// The `### Suggestions` header is annotated with a `(type "/apply" to
    /// apply)` hint at render time so users discover the apply shortcut
    /// without polluting the persisted review markdown consumed by
    /// suggestion extraction.
    fn append_review_lines(
        lines: &mut Vec<Line<'static>>,
        review_text: Option<&str>,
        inner_width: usize,
        markdown_render_cache: Option<&markdown::MarkdownRenderCache>,
    ) {
        let review_markdown = review_text
            .map(str::trim)
            .filter(|review_text| !review_text.is_empty())
            .map(layout::annotate_review_suggestions_header);

        let Some(review_markdown) = review_markdown else {
            return;
        };

        Self::append_markdown_lines(lines, &review_markdown, inner_width, markdown_render_cache);
    }

    /// Appends a rendered structured-summary section without mutating the
    /// persisted transcript string.
    fn append_summary_lines(
        lines: &mut Vec<Line<'static>>,
        summary_text: Option<&str>,
        inner_width: usize,
        markdown_render_cache: Option<&markdown::MarkdownRenderCache>,
    ) {
        let Some(summary_text) = summary_text else {
            return;
        };
        if summary_text.trim().is_empty() {
            return;
        }

        Self::append_markdown_lines(
            lines,
            &layout::session_output_summary_markdown(summary_text),
            inner_width,
            markdown_render_cache,
        );
    }

    /// Appends one trailing transcript footer immediately after completed-turn
    /// transcript content when a known footer block is present.
    fn append_transcript_footer_lines(
        lines: &mut Vec<Line<'static>>,
        trailing_footer_text: Option<&str>,
        inner_width: usize,
        markdown_render_cache: Option<&markdown::MarkdownRenderCache>,
    ) {
        let Some(trailing_footer_text) = trailing_footer_text else {
            return;
        };

        Self::append_markdown_lines(
            lines,
            trailing_footer_text,
            inner_width,
            markdown_render_cache,
        );
    }

    /// Appends the currently active prompt-led transcript block after earlier
    /// transcript content so the rendered transcript remains chronological.
    fn append_active_turn_lines(
        lines: &mut Vec<Line<'static>>,
        active_turn_text: Option<&str>,
        inner_width: usize,
        markdown_render_cache: Option<&markdown::MarkdownRenderCache>,
    ) {
        let Some(active_turn_text) = active_turn_text else {
            return;
        };
        if active_turn_text.trim().is_empty() {
            return;
        }

        Self::append_markdown_lines(lines, active_turn_text, inner_width, markdown_render_cache);
    }

    /// Appends rendered markdown with one blank separator while trimming any
    /// existing trailing blank lines from `lines`.
    ///
    /// When a shared render cache is available, every appended markdown block
    /// reuses it so transcript sections do not evict each other between
    /// frames.
    fn append_markdown_lines(
        lines: &mut Vec<Line<'static>>,
        markdown: &str,
        inner_width: usize,
        markdown_render_cache: Option<&markdown::MarkdownRenderCache>,
    ) {
        let rendered_lines =
            Self::rendered_markdown_lines(markdown, inner_width, markdown_render_cache);
        if rendered_lines.is_empty() {
            return;
        }

        while lines.last().is_some_and(|line| line.width() == 0) {
            lines.pop();
        }

        if !lines.is_empty() {
            lines.push(Line::from(""));
        }

        lines.extend(rendered_lines.iter().cloned());
    }

    /// Returns rendered markdown as a shared slice so cache hits avoid cloning
    /// the entire rendered block.
    fn rendered_markdown_lines(
        markdown: &str,
        inner_width: usize,
        markdown_render_cache: Option<&markdown::MarkdownRenderCache>,
    ) -> Arc<[Line<'static>]> {
        match markdown_render_cache {
            Some(cache) => cache.render(markdown, inner_width),
            None => Arc::from(render_markdown(markdown, inner_width)),
        }
    }
}

impl Component for SessionOutput<'_> {
    /// Renders bordered output content for the active session.
    ///
    /// Session status/title headers are rendered by the page layer so this
    /// component keeps the output border title-free.
    fn render(&self, f: &mut Frame, output_area: Rect) {
        let status = self.session.status;
        let lines = Self::output_lines(
            self.session,
            output_area,
            SessionOutputLineContext {
                active_prompt_output: self.active_prompt_output,
                active_progress: self.active_progress,
                done_session_output_mode: self.done_session_output_mode,
                review_status_message: self.review_status_message,
                review_text: self.review_text,
            },
            self.markdown_render_cache,
        );
        let final_scroll = bottom_pinned_scroll_offset(
            output_area,
            layout::session_output_panel_borders(),
            lines.len(),
            self.scroll_offset,
        );

        let paragraph = Paragraph::new(lines)
            .block(
                Block::default()
                    .borders(layout::session_output_panel_borders())
                    .border_style(layout::session_output_panel_border_style(status)),
            )
            .scroll((final_scroll, 0));

        f.render_widget(paragraph, output_area);
    }
}

#[cfg(test)]
mod tests {
    use serde_json;

    use super::*;
    use crate::infra::agent::protocol::AgentResponseSummary;

    /// Builds one output-line context with defaults suitable for tests.
    fn line_context<'a>(
        done_session_output_mode: DoneSessionOutputMode,
        review_status_message: Option<&'a str>,
        review_text: Option<&'a str>,
        active_progress: Option<&'a str>,
    ) -> SessionOutputLineContext<'a> {
        SessionOutputLineContext {
            active_prompt_output: None,
            active_progress,
            done_session_output_mode,
            review_status_message,
            review_text,
        }
    }

    fn summary_fixture() -> String {
        serde_json::to_string(&AgentResponseSummary {
            turn: "- Added the structured protocol summary.".to_string(),
            session: "- Session output now renders persisted summary markdown.".to_string(),
        })
        .expect("summary fixture should serialize")
    }

    fn session_fixture() -> Session {
        crate::domain::session::tests::SessionFixtureBuilder::new()
            .status(Status::New)
            .build()
    }

    #[test]
    fn test_rendered_line_count_counts_wrapped_content() {
        // Arrange
        let mut session = session_fixture();
        session.output = "word ".repeat(40);
        let raw_line_count = u16::try_from(session.output.lines().count()).unwrap_or(u16::MAX);

        // Act
        let rendered_line_count = SessionOutput::rendered_line_count(
            &session,
            20,
            line_context(DoneSessionOutputMode::Summary, None, None, None),
        );

        // Assert
        assert!(rendered_line_count > raw_line_count);
    }

    #[test]
    fn test_output_lines_uses_summary_for_done_session() {
        // Arrange
        let mut session = session_fixture();
        session.output = "streamed output".to_string();
        session.summary = Some(summary_fixture());
        session.status = Status::Done;

        // Act
        let lines = SessionOutput::output_lines(
            &session,
            Rect::new(0, 0, 80, 5),
            line_context(DoneSessionOutputMode::Summary, None, None, None),
            None,
        );
        let text = lines
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n");

        // Assert
        assert!(text.contains("Added the structured protocol summary."));
        assert!(text.contains("Session output now renders persisted summary markdown."));
        assert!(!text.contains("streamed output"));
    }

    #[test]
    fn test_output_lines_render_staged_draft_preview_for_new_session() {
        // Arrange
        let mut session = session_fixture();
        session.is_draft = true;
        session.prompt = "First draft\n\nSecond draft".to_string();

        // Act
        let lines = SessionOutput::output_lines(
            &session,
            Rect::new(0, 0, 80, 8),
            line_context(DoneSessionOutputMode::Summary, None, None, None),
            None,
        );
        let text = lines
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n");

        // Assert
        assert!(text.contains("Draft Session"));
        assert!(text.contains("Draft messages stay local until you press s in session view"));
        assert!(text.contains("First draft"));
        assert!(text.contains("Second draft"));
    }

    #[test]
    fn test_output_lines_render_empty_draft_preview_for_new_session() {
        // Arrange
        let mut session = session_fixture();
        session.is_draft = true;

        // Act
        let lines = SessionOutput::output_lines(
            &session,
            Rect::new(0, 0, 80, 8),
            line_context(DoneSessionOutputMode::Summary, None, None, None),
            None,
        );
        let text = lines
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n");

        // Assert
        assert!(text.contains("Draft Session"));
        assert!(text.contains("No draft messages staged yet."));
        assert!(text.contains("Use Enter to stage the first draft locally"));
    }

    #[test]
    fn test_output_lines_done_output_mode_appends_structured_summary() {
        // Arrange
        let mut session = session_fixture();
        session.output = "streamed output".to_string();
        session.summary = Some(summary_fixture());
        session.status = Status::Done;

        // Act
        let lines = SessionOutput::output_lines(
            &session,
            Rect::new(0, 0, 80, 5),
            line_context(DoneSessionOutputMode::Output, None, None, None),
            None,
        );
        let text = lines
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n");

        // Assert
        assert!(text.contains("streamed output"));
        assert!(text.contains("Added the structured protocol summary."));
        assert!(text.contains("Session output now renders persisted summary markdown."));
    }

    #[test]
    fn test_output_lines_review_session_appends_structured_summary() {
        // Arrange
        let mut session = session_fixture();
        session.output = "implemented the feature".to_string();
        session.summary = Some(summary_fixture());
        session.status = Status::Review;

        // Act
        let lines = SessionOutput::output_lines(
            &session,
            Rect::new(0, 0, 80, 5),
            line_context(DoneSessionOutputMode::Summary, None, None, None),
            None,
        );
        let text = lines
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n");

        // Assert
        assert!(text.contains("implemented the feature"));
        assert!(text.contains("Added the structured protocol summary."));
        assert!(text.contains("Session output now renders persisted summary markdown."));
    }

    #[test]
    fn test_output_lines_in_progress_session_keeps_active_prompt_before_summary() {
        // Arrange
        let mut session = session_fixture();
        session.output =
            " › hi\n\n[Commit] No changes to commit.\n\n › add hello world\n\n".to_string();
        session.summary = Some(summary_fixture());
        session.status = Status::InProgress;

        // Act
        let lines = SessionOutput::output_lines(
            &session,
            Rect::new(0, 0, 80, 8),
            SessionOutputLineContext {
                active_prompt_output: Some("\n › add hello world\n\n"),
                ..line_context(DoneSessionOutputMode::Summary, None, None, None)
            },
            None,
        );
        let text = lines
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n");
        let commit_index = text
            .find("[Commit] No changes to commit.")
            .expect("commit footer should be rendered");
        let summary_index = text
            .find("Change Summary")
            .expect("structured summary should be rendered");
        let prompt_index = text
            .find(" › add hello world")
            .expect("active prompt should be rendered");

        // Assert
        assert!(commit_index < prompt_index);
        assert!(prompt_index < summary_index);
    }

    #[test]
    fn test_output_lines_in_progress_single_prompt_keeps_summary_after_transcript() {
        // Arrange
        let mut session = session_fixture();
        session.output = " › add hello world\n\nI added the README change.\n".to_string();
        session.summary = Some(summary_fixture());
        session.status = Status::InProgress;

        // Act
        let lines = SessionOutput::output_lines(
            &session,
            Rect::new(0, 0, 80, 8),
            SessionOutputLineContext {
                active_prompt_output: Some(" › add hello world\n\n"),
                ..line_context(DoneSessionOutputMode::Summary, None, None, None)
            },
            None,
        );
        let text = lines
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n");
        let prompt_index = text
            .find(" › add hello world")
            .expect("prompt should be rendered");
        let summary_index = text
            .find("Change Summary")
            .expect("structured summary should be rendered");

        // Assert
        assert!(text.contains("I added the README change."));
        assert!(prompt_index < summary_index);
    }

    #[test]
    fn test_output_lines_in_progress_ignores_assistant_lines_that_look_like_prompts() {
        // Arrange
        let mut session = session_fixture();
        session.output = " › hi\n\nprevious answer\n\n › actual prompt\n\nstreaming answer\n\
                          quoted output\n"
            .to_string();
        session.summary = Some(summary_fixture());
        session.status = Status::InProgress;

        // Act
        let lines = SessionOutput::output_lines(
            &session,
            Rect::new(0, 0, 80, 8),
            SessionOutputLineContext {
                active_prompt_output: Some("\n › actual prompt\n\n"),
                ..line_context(DoneSessionOutputMode::Summary, None, None, None)
            },
            None,
        );
        let text = lines
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n");
        let summary_index = text
            .find("Change Summary")
            .expect("structured summary should be rendered");
        let prompt_index = text
            .find(" › actual prompt")
            .expect("active prompt should be rendered");

        // Assert
        assert!(text.contains(" › quoted output"));
        assert!(prompt_index < summary_index);
    }

    #[test]
    fn test_output_lines_review_session_without_summary_keeps_transcript_only() {
        // Arrange
        let mut session = session_fixture();
        session.output = "implemented the feature".to_string();
        session.status = Status::Review;

        // Act
        let lines = SessionOutput::output_lines(
            &session,
            Rect::new(0, 0, 80, 5),
            line_context(DoneSessionOutputMode::Summary, None, None, None),
            None,
        );
        let text = lines
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n");

        // Assert
        assert!(text.contains("implemented the feature"));
        assert!(!text.contains("No changes"));
        assert!(!text.contains("Current Turn"));
        assert!(!text.contains("Session Changes"));
    }

    /// Verifies the done-summary transition renders the rewritten summary
    /// payload exactly once in summary mode.
    #[test]
    fn test_output_lines_done_summary_transition_renders_rewritten_summary() {
        // Arrange
        let mut session = session_fixture();
        session.output = "streamed output".to_string();
        session.summary = Some(summary_fixture());
        session.status = Status::Review;
        let review_lines = SessionOutput::output_lines(
            &session,
            Rect::new(0, 0, 80, 8),
            line_context(DoneSessionOutputMode::Summary, None, None, None),
            None,
        );
        let review_text = review_lines
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n");
        session.summary = Some(
            "# Summary\n\nSession now greets users on startup.\n\n# Commit\n\nRefine session \
             summary"
                .to_string(),
        );
        session.status = Status::Done;

        // Act
        let done_output_text = SessionOutput::output_text(&session, DoneSessionOutputMode::Summary);
        let done_lines = SessionOutput::output_lines(
            &session,
            Rect::new(0, 0, 80, 8),
            line_context(DoneSessionOutputMode::Summary, None, None, None),
            None,
        );
        let done_text = done_lines
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n");

        // Assert
        assert!(review_text.contains("Change Summary"));
        assert!(review_text.contains("Added the structured protocol summary."));
        assert_eq!(
            done_output_text,
            "# Summary\n\nSession now greets users on startup.\n\n# Commit\n\nRefine session \
             summary"
        );
        assert!(done_text.contains("Summary"));
        assert!(done_text.contains("Session now greets users on startup."));
        assert!(done_text.contains("Commit"));
        assert!(done_text.contains("Refine session summary"));
        assert!(!done_text.contains("Change Summary"));
        assert!(!done_text.contains("streamed output"));
    }

    #[test]
    fn test_output_lines_agent_review_mode_shows_assisted_text() {
        // Arrange
        let mut session = session_fixture();
        session.status = Status::AgentReview;
        let assisted_text = "## Review\n\n- Focused finding";

        // Act
        let lines = SessionOutput::output_lines(
            &session,
            Rect::new(0, 0, 80, 5),
            line_context(
                DoneSessionOutputMode::Review,
                Some("Reviewing changes with gpt-5.4"),
                Some(assisted_text),
                None,
            ),
            None,
        );
        let text = lines
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n");

        // Assert
        assert!(text.contains("Focused finding"));
        assert!(!text.contains("Review is not available."));
    }

    #[test]
    fn test_output_lines_uses_transcript_for_canceled_session() {
        // Arrange
        let mut session = session_fixture();
        session.output = "streamed output".to_string();
        session.summary = Some(summary_fixture());
        session.status = Status::Canceled;

        // Act
        let lines = SessionOutput::output_lines(
            &session,
            Rect::new(0, 0, 80, 5),
            line_context(DoneSessionOutputMode::Summary, None, None, None),
            None,
        );
        let text = lines
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n");

        // Assert
        assert!(!text.contains("Added the structured protocol summary."));
        assert!(text.contains("streamed output"));
    }

    #[test]
    fn test_output_lines_use_generic_in_progress_loader() {
        // Arrange
        let mut session = session_fixture();
        session.output = "some output".to_string();
        session.status = Status::InProgress;

        // Act
        let lines = SessionOutput::output_lines(
            &session,
            Rect::new(0, 0, 80, 5),
            line_context(DoneSessionOutputMode::Summary, None, None, None),
            None,
        );
        let text = lines
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n");

        // Assert
        assert!(text.contains("Working..."));
    }
}