agentty 0.10.5

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
use std::collections::HashMap;

use ratatui::Frame;
use ratatui::layout::{Alignment, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::Span;
use ratatui::widgets::{Block, BorderType, Borders, Clear, Padding};

use crate::app::Tab;
use crate::domain::agent::ReasoningLevel;
use crate::domain::session::{Session, SessionId};
use crate::infra::review_comment_cache::ReviewCommentCache;
use crate::ui::router::{ListBackgroundRenderContext, render_list_background};
use crate::ui::state::app_mode::{AppMode, ConfirmationViewMode, DiffRightPanel, HelpContext};
use crate::ui::style::palette;
use crate::ui::{Component, Page, component, markdown, page};

const OVERLAY_HORIZONTAL_PADDING: u16 = 2;
const OVERLAY_VERTICAL_PADDING: u16 = 1;

/// Borrowed parameters for rendering the sync-blocked popup overlay.
#[derive(Clone, Copy)]
pub(crate) struct SyncBlockedPopupRenderContext<'a> {
    /// Default branch shown in the popup detail, when available.
    pub(crate) default_branch: Option<&'a str>,
    /// Whether the popup should render its loading indicator.
    pub(crate) is_loading: bool,
    /// Main popup detail message.
    pub(crate) message: &'a str,
    /// Active project name shown in the popup detail, when available.
    pub(crate) project_name: Option<&'a str>,
    /// Popup title.
    pub(crate) title: &'a str,
}

/// Borrowed parameters for rendering a session-view info popup overlay.
#[derive(Clone, Copy)]
pub(crate) struct ViewInfoPopupRenderContext<'a> {
    /// Whether the restored session background can open its worktree.
    pub(crate) can_open_worktree: bool,
    /// Active project-scoped default reasoning level.
    pub(crate) default_reasoning_level: ReasoningLevel,
    /// Shared markdown cache reused by the restored session background.
    pub(crate) markdown_render_cache: &'a markdown::MarkdownRenderCache,
    /// Shared output-layout cache reused by the restored session background.
    pub(crate) output_layout_cache: &'a component::session_output::SessionOutputLayoutCache,
    /// Whether the popup should render its loading indicator.
    pub(crate) is_loading: bool,
    /// Loading indicator label.
    pub(crate) loading_label: &'a str,
    /// Popup detail message.
    pub(crate) message: &'a str,
    /// Restored session view rendered behind the popup.
    pub(crate) restore_view: &'a ConfirmationViewMode,
    /// Session progress messages keyed by session id.
    pub(crate) session_progress_messages: &'a HashMap<SessionId, String>,
    /// Latest observable update versions keyed by session id.
    pub(crate) session_update_versions: &'a HashMap<SessionId, u64>,
    /// Session rows available for restored background rendering.
    pub(crate) sessions: &'a [Session],
    /// Popup title.
    pub(crate) title: &'a str,
    /// Render-time clock used for deterministic timers.
    pub(crate) wall_clock_unix_seconds: i64,
}

/// Borrowed parameters for rendering the help overlay and its background page.
pub(crate) struct HelpOverlayRenderContext<'a> {
    /// Help overlay content and the background page to restore behind it.
    pub(crate) help_context: &'a HelpContext,
    /// Shared tab-list state rendered behind list-backed help overlays.
    pub(crate) list_background: ListBackgroundRenderContext<'a>,
    /// Shared diff-layout cache reused by restored diff backgrounds.
    pub(crate) diff_layout_cache: &'a page::diff::DiffLayoutCache,
    /// Shared markdown cache reused by restored background pages.
    pub(crate) markdown_render_cache: &'a markdown::MarkdownRenderCache,
    /// Shared output-layout cache reused by restored session backgrounds.
    pub(crate) output_layout_cache: &'a component::session_output::SessionOutputLayoutCache,
    /// Shared review-comment cache used to restore the review-comments page
    /// behind help overlays opened from that page.
    pub(crate) review_comment_cache: &'a ReviewCommentCache,
    /// Help overlay vertical scroll position.
    pub(crate) scroll_offset: u16,
    /// Session progress messages keyed by session id.
    pub(crate) session_progress_messages: &'a HashMap<SessionId, String>,
    /// Latest observable update versions keyed by session id.
    pub(crate) session_update_versions: &'a HashMap<SessionId, u64>,
    /// Render-time clock used for deterministic timers.
    pub(crate) wall_clock_unix_seconds: i64,
}

/// Borrowed parameters for rendering the background behind the help overlay.
struct HelpBackgroundRenderContext<'a> {
    /// Help overlay content and the background page to restore behind it.
    help_context: &'a HelpContext,
    /// Shared tab-list state rendered behind list-backed help overlays.
    list_background: ListBackgroundRenderContext<'a>,
    /// Shared diff-layout cache reused by restored diff backgrounds.
    diff_layout_cache: &'a page::diff::DiffLayoutCache,
    /// Shared markdown cache reused by restored background pages.
    markdown_render_cache: &'a markdown::MarkdownRenderCache,
    /// Shared output-layout cache reused by restored session backgrounds.
    output_layout_cache: &'a component::session_output::SessionOutputLayoutCache,
    /// Shared review-comment cache used to restore diff review comments behind
    /// help.
    review_comment_cache: &'a ReviewCommentCache,
    /// Session progress messages keyed by session id.
    session_progress_messages: &'a HashMap<SessionId, String>,
    /// Latest observable update versions keyed by session id.
    session_update_versions: &'a HashMap<SessionId, u64>,
    /// Render-time clock used for deterministic timers.
    wall_clock_unix_seconds: i64,
}

/// Renders the list background and generic confirmation overlay.
pub(crate) fn render_confirmation_overlay(
    f: &mut Frame,
    area: Rect,
    mode: &AppMode,
    list_background: ListBackgroundRenderContext<'_>,
    wall_clock_unix_seconds: i64,
) {
    render_list_background(f, area, list_background, wall_clock_unix_seconds);

    let AppMode::Confirmation {
        confirmation_message,
        confirmation_title,
        selected_confirmation_index,
        ..
    } = mode
    else {
        unreachable!("matched confirmation mode above");
    };

    component::confirmation_overlay::ConfirmationOverlay::new(
        confirmation_title,
        confirmation_message,
    )
    .selected_yes(*selected_confirmation_index == 0)
    .render(f, area);
}

/// Renders the list background and session creation selector overlay.
pub(crate) fn render_session_creation_overlay(
    f: &mut Frame,
    area: Rect,
    list_background: ListBackgroundRenderContext<'_>,
    selected_option_index: usize,
    wall_clock_unix_seconds: i64,
) {
    let can_create_stacked_session = list_background.current_tab == Tab::Sessions
        && list_background
            .table_state
            .selected()
            .and_then(|selected_index| list_background.sessions.get(selected_index))
            .is_some_and(Session::allows_stacked_child_creation);

    render_list_background(f, area, list_background, wall_clock_unix_seconds);

    component::session_creation_overlay::SessionCreationOverlay::new(
        selected_option_index,
        can_create_stacked_session,
    )
    .render(f, area);
}

/// Renders the list background and sync informational popup overlay.
pub(crate) fn render_sync_blocked_popup(
    f: &mut Frame,
    area: Rect,
    list_background: ListBackgroundRenderContext<'_>,
    wall_clock_unix_seconds: i64,
    context: SyncBlockedPopupRenderContext<'_>,
) {
    let SyncBlockedPopupRenderContext {
        default_branch,
        is_loading,
        message,
        project_name,
        title,
    } = context;

    render_list_background(f, area, list_background, wall_clock_unix_seconds);

    let popup_message = sync_popup_message(default_branch, message, project_name);

    component::info_overlay::InfoOverlay::new(title, &popup_message)
        .is_loading(is_loading)
        .loading_label("Sync in progress...")
        .render(f, area);
}

/// Renders an informational popup above the restored session-view background.
pub(crate) fn render_view_info_popup(
    f: &mut Frame,
    area: Rect,
    context: ViewInfoPopupRenderContext<'_>,
) {
    let ViewInfoPopupRenderContext {
        can_open_worktree,
        default_reasoning_level,
        markdown_render_cache,
        output_layout_cache,
        is_loading,
        loading_label,
        message,
        restore_view,
        session_progress_messages,
        session_update_versions,
        sessions,
        title,
        wall_clock_unix_seconds,
    } = context;
    let background_mode = restore_view.clone().into_view_mode();

    if let Some(session_index) = sessions
        .iter()
        .position(|session| session.id == restore_view.session_id)
    {
        let active_progress = session_progress_messages
            .get(&restore_view.session_id)
            .map(std::string::String::as_str);
        let session_update_version = session_update_versions
            .get(&restore_view.session_id)
            .copied()
            .unwrap_or_default();
        page::session_chat::SessionChatPage::new(page::session_chat::SessionChatPageInput {
            active_prompt_output: None,
            active_progress,
            default_reasoning_level,
            markdown_render_cache,
            mode: &background_mode,
            output_layout_cache,
            scroll_offset: restore_view.scroll_offset,
            session_index,
            session_update_version,
            sessions,
            wall_clock_unix_seconds,
        })
        .can_open_worktree(can_open_worktree)
        .render(f, area);
    }

    component::info_overlay::InfoOverlay::new(title, message)
        .is_loading(is_loading)
        .loading_label(loading_label)
        .render(f, area);
}

/// Composes sync popup body with optional project and branch context.
pub(crate) fn sync_popup_message(
    default_branch: Option<&str>,
    detail_message: &str,
    project_name: Option<&str>,
) -> String {
    match (project_name, default_branch) {
        (Some(project_name), Some(default_branch)) => format!(
            "Project `{project_name}` on main branch `{default_branch}`.\n\n{detail_message}"
        ),
        (Some(project_name), None) => format!("Project `{project_name}`.\n\n{detail_message}"),
        (None, Some(default_branch)) => {
            format!("Main branch `{default_branch}`.\n\n{detail_message}")
        }
        (None, None) => detail_message.to_string(),
    }
}

/// Renders help overlay above the context-specific background page.
pub(crate) fn render_help(f: &mut Frame, area: Rect, context: HelpOverlayRenderContext<'_>) {
    let HelpOverlayRenderContext {
        diff_layout_cache,
        help_context,
        list_background,
        markdown_render_cache,
        output_layout_cache,
        review_comment_cache,
        scroll_offset,
        session_progress_messages,
        session_update_versions,
        wall_clock_unix_seconds,
    } = context;

    render_help_background(
        f,
        area,
        HelpBackgroundRenderContext {
            help_context,
            list_background,
            diff_layout_cache,
            markdown_render_cache,
            output_layout_cache,
            review_comment_cache,
            session_progress_messages,
            session_update_versions,
            wall_clock_unix_seconds,
        },
    );
    component::help_overlay::HelpOverlay::new(help_context)
        .scroll_offset(scroll_offset)
        .render(f, area);
}

/// Clears popup-local cells and immediately reapplies the overlay surface
/// style so modal content never falls back to terminal-default colors.
pub(crate) fn clear_popup_area(f: &mut Frame, area: Rect) {
    let popup_style = Style::default()
        .fg(palette::text())
        .bg(palette::surface_overlay());

    f.render_widget(Clear, area);
    f.render_widget(Block::default().style(popup_style), area);
}

/// Returns a centered popup rectangle constrained by bounds and minimum size.
pub(crate) fn centered_popup_area(
    area: Rect,
    width_percent: u16,
    height_percent: u16,
    min_width: u16,
    min_height: u16,
) -> Rect {
    let popup_width = (area.width * width_percent / 100)
        .max(min_width)
        .min(area.width);
    let popup_height = (area.height * height_percent / 100)
        .max(min_height)
        .min(area.height);

    Rect::new(
        area.x + (area.width.saturating_sub(popup_width)) / 2,
        area.y + (area.height.saturating_sub(popup_height)) / 2,
        popup_width,
        popup_height,
    )
}

/// Returns the inner text width for overlay content based on shared frame
/// chrome.
pub(crate) fn overlay_content_width(popup_width: u16) -> usize {
    let horizontal_chrome = 2 + (OVERLAY_HORIZONTAL_PADDING * 2);

    usize::from(popup_width.saturating_sub(horizontal_chrome).max(1))
}

/// Returns the total popup height required to render a given number of body
/// lines inside the shared overlay frame.
pub(crate) fn overlay_required_height(inner_line_count: usize) -> u16 {
    let vertical_chrome = 2 + (OVERLAY_VERTICAL_PADDING * 2);

    u16::try_from(inner_line_count.saturating_add(usize::from(vertical_chrome))).unwrap_or(u16::MAX)
}

/// Builds a shared rounded overlay frame block with centered styled title and
/// default body padding.
pub(crate) fn overlay_block(title: &str, border_color: Color) -> Block<'static> {
    let title_text = format!(" {title} ");

    Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(border_color))
        .padding(Padding::new(
            OVERLAY_HORIZONTAL_PADDING,
            OVERLAY_HORIZONTAL_PADDING,
            OVERLAY_VERTICAL_PADDING,
            OVERLAY_VERTICAL_PADDING,
        ))
        .title(Span::styled(title_text, overlay_title_style(border_color)))
        .title_alignment(Alignment::Center)
}

/// Returns the shared title text style for overlay frame headers.
fn overlay_title_style(border_color: Color) -> Style {
    Style::default()
        .fg(border_color)
        .add_modifier(Modifier::BOLD)
}

/// Describes which background page should be restored behind the help overlay.
enum ResolvedHelpBackground<'a> {
    List,
    View {
        review_status_message: &'a Option<String>,
        review_text: &'a Option<String>,
        scroll_offset: Option<u16>,
        session_id: &'a str,
        session_index: usize,
    },
    Diff {
        diff: &'a str,
        file_explorer_selected_index: usize,
        right_panel: DiffRightPanel,
        scroll_offset: u16,
        session: &'a Session,
        snapshot: Option<crate::infra::review_comment_cache::CachedReviewCommentSnapshot>,
    },
}

/// Resolves the page state that should be rendered behind the help overlay.
fn resolve_help_background<'a>(
    help_context: &'a HelpContext,
    sessions: &'a [Session],
    review_comment_cache: &ReviewCommentCache,
) -> Option<ResolvedHelpBackground<'a>> {
    match help_context {
        HelpContext::List { .. } => Some(ResolvedHelpBackground::List),
        HelpContext::View {
            review_status_message,
            review_text,
            session_id,
            scroll_offset,
            ..
        } => sessions
            .iter()
            .position(|session| session.id == *session_id)
            .map(|session_index| ResolvedHelpBackground::View {
                review_status_message,
                review_text,
                scroll_offset: *scroll_offset,
                session_id,
                session_index,
            }),
        HelpContext::Diff {
            diff,
            file_explorer_selected_index,
            right_panel,
            scroll_offset,
            session_id,
            ..
        } => sessions
            .iter()
            .find(|session| session.id == *session_id)
            .map(|session| ResolvedHelpBackground::Diff {
                diff,
                file_explorer_selected_index: *file_explorer_selected_index,
                right_panel: *right_panel,
                scroll_offset: *scroll_offset,
                session,
                snapshot: review_comment_cache.snapshot(session_id),
            }),
    }
}

/// Renders background content behind help based on the source `HelpContext`.
fn render_help_background(f: &mut Frame, area: Rect, context: HelpBackgroundRenderContext<'_>) {
    let HelpBackgroundRenderContext {
        diff_layout_cache,
        help_context,
        list_background,
        markdown_render_cache,
        output_layout_cache,
        review_comment_cache,
        session_progress_messages,
        session_update_versions,
        wall_clock_unix_seconds,
    } = context;
    let sessions = list_background.sessions;

    match resolve_help_background(help_context, sessions, review_comment_cache) {
        Some(ResolvedHelpBackground::List) => {
            render_list_background(f, area, list_background, wall_clock_unix_seconds);
        }
        Some(ResolvedHelpBackground::View {
            review_status_message,
            review_text,
            session_id,
            session_index,
            scroll_offset,
        }) => {
            let bg_mode = AppMode::View {
                review_status_message: review_status_message.clone(),
                review_text: review_text.clone(),
                session_id: session_id.into(),
                scroll_offset,
            };
            let active_progress = session_progress_messages
                .get(session_id)
                .map(std::string::String::as_str);
            let session_update_version = session_update_versions
                .get(session_id)
                .copied()
                .unwrap_or_default();
            page::session_chat::SessionChatPage::new(page::session_chat::SessionChatPageInput {
                active_prompt_output: None,
                active_progress,
                default_reasoning_level: list_background.settings.reasoning_level,
                markdown_render_cache,
                mode: &bg_mode,
                output_layout_cache,
                scroll_offset,
                session_index,
                session_update_version,
                sessions,
                wall_clock_unix_seconds,
            })
            .render(f, area);
        }
        Some(ResolvedHelpBackground::Diff {
            diff,
            file_explorer_selected_index,
            right_panel,
            session,
            snapshot,
            scroll_offset,
        }) => page::diff::DiffPage::new(page::diff::DiffPageInput {
            diff,
            diff_layout_cache,
            file_explorer_selected_index,
            markdown_render_cache,
            review_comment_snapshot: snapshot.as_ref(),
            right_panel,
            scroll_offset,
            session,
        })
        .render(f, area),
        None => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ui::style::palette;

    #[test]
    fn test_sync_popup_message_with_project_and_branch() {
        // Arrange
        let default_branch = Some("develop");
        let detail_message = "Synchronizing with its upstream.";
        let project_name = Some("agentty");

        // Act
        let message = sync_popup_message(default_branch, detail_message, project_name);

        // Assert
        assert_eq!(
            message,
            "Project `agentty` on main branch `develop`.\n\nSynchronizing with its upstream."
        );
    }

    #[test]
    fn test_sync_popup_message_with_project_only() {
        // Arrange
        let default_branch = None;
        let detail_message = "Synchronization is blocked.";
        let project_name = Some("agentty");

        // Act
        let message = sync_popup_message(default_branch, detail_message, project_name);

        // Assert
        assert_eq!(message, "Project `agentty`.\n\nSynchronization is blocked.");
    }

    #[test]
    fn test_sync_popup_message_with_branch_only() {
        // Arrange
        let default_branch = Some("main");
        let detail_message = "Synchronization is blocked.";
        let project_name = None;

        // Act
        let message = sync_popup_message(default_branch, detail_message, project_name);

        // Assert
        assert_eq!(
            message,
            "Main branch `main`.\n\nSynchronization is blocked."
        );
    }

    #[test]
    fn test_sync_popup_message_without_project_or_branch() {
        // Arrange
        let default_branch = None;
        let detail_message = "Synchronization is blocked.";
        let project_name = None;

        // Act
        let message = sync_popup_message(default_branch, detail_message, project_name);

        // Assert
        assert_eq!(message, "Synchronization is blocked.");
    }

    #[test]
    fn test_centered_popup_area_centers_within_bounds() {
        // Arrange
        let area = Rect::new(0, 0, 100, 50);

        // Act
        let popup_area = centered_popup_area(area, 40, 20, 30, 7);

        // Assert
        assert_eq!(popup_area.width, 40);
        assert_eq!(popup_area.height, 10);
        assert_eq!(popup_area.x, 30);
        assert_eq!(popup_area.y, 20);
    }

    #[test]
    fn test_centered_popup_area_clamps_to_small_terminal() {
        // Arrange
        let area = Rect::new(0, 0, 20, 6);

        // Act
        let popup_area = centered_popup_area(area, 50, 50, 30, 10);

        // Assert
        assert_eq!(popup_area.width, 20);
        assert_eq!(popup_area.height, 6);
        assert_eq!(popup_area.x, 0);
        assert_eq!(popup_area.y, 0);
    }

    #[test]
    fn test_centered_popup_area_respects_minimum_size_before_centering() {
        // Arrange
        let area = Rect::new(10, 5, 80, 40);

        // Act
        let popup_area = centered_popup_area(area, 10, 10, 30, 12);

        // Assert
        assert_eq!(popup_area.width, 30);
        assert_eq!(popup_area.height, 12);
        assert_eq!(popup_area.x, 35);
        assert_eq!(popup_area.y, 19);
    }

    #[test]
    fn test_overlay_content_width_subtracts_shared_frame_chrome() {
        // Arrange
        let popup_width = 40;

        // Act
        let content_width = overlay_content_width(popup_width);

        // Assert
        assert_eq!(content_width, 34);
    }

    #[test]
    fn test_overlay_content_width_keeps_minimum_width_for_tiny_popup() {
        // Arrange
        let popup_width = 1;

        // Act
        let content_width = overlay_content_width(popup_width);

        // Assert
        assert_eq!(content_width, 1);
    }

    #[test]
    fn test_overlay_required_height_adds_shared_frame_chrome() {
        // Arrange
        let inner_line_count = 8;

        // Act
        let total_height = overlay_required_height(inner_line_count);

        // Assert
        assert_eq!(total_height, 12);
    }

    #[test]
    fn test_overlay_required_height_saturates_at_u16_max() {
        // Arrange
        let inner_line_count = usize::MAX;

        // Act
        let total_height = overlay_required_height(inner_line_count);

        // Assert
        assert_eq!(total_height, u16::MAX);
    }

    #[test]
    fn test_resolve_help_background_returns_list_variant_for_list_context() {
        // Arrange
        let help_context = HelpContext::List {
            keybindings: vec![],
        };

        // Act
        let resolved = resolve_help_background(&help_context, &[], &ReviewCommentCache::default());

        // Assert
        assert!(matches!(resolved, Some(ResolvedHelpBackground::List)));
    }

    #[test]
    fn test_resolve_help_background_returns_none_for_missing_view_session() {
        // Arrange
        let help_context = HelpContext::View {
            can_mutate_session_branch: true,
            can_open_worktree: true,
            can_start_staged_session: false,
            review_status_message: None,
            review_text: None,
            publish_pull_request_action: None,
            session_id: "missing-session".into(),
            session_state: crate::ui::state::help_action::ViewSessionState::Done,
            scroll_offset: Some(0),
        };

        // Act
        let resolved = resolve_help_background(&help_context, &[], &ReviewCommentCache::default());

        // Assert
        assert!(resolved.is_none());
    }

    #[test]
    fn test_resolve_help_background_returns_none_for_missing_diff_session() {
        // Arrange
        let help_context = HelpContext::Diff {
            session_id: "missing-session".into(),
            diff: "diff --git a/file b/file".to_string(),
            restore_question: None,
            right_panel: DiffRightPanel::Diff,
            scroll_offset: 0,
            file_explorer_selected_index: 0,
        };

        // Act
        let resolved = resolve_help_background(&help_context, &[], &ReviewCommentCache::default());

        // Assert
        assert!(resolved.is_none());
    }

    #[test]
    fn test_clear_popup_area_uses_overlay_surface_style() {
        // Arrange
        let backend = ratatui::backend::TestBackend::new(8, 4);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");
        let initial_style = Style::default()
            .fg(palette::warning())
            .bg(palette::surface());

        // Act
        terminal
            .draw(|frame| {
                let area = Rect::new(2, 1, 3, 2);
                frame.render_widget(Block::default().style(initial_style), frame.area());
                clear_popup_area(frame, area);
            })
            .expect("failed to draw");

        // Assert
        let buffer = terminal.backend().buffer();
        for y in 1..3 {
            for x in 2..5 {
                let cell = &buffer[(x, y)];
                assert_eq!(cell.symbol(), " ");
                assert_eq!(cell.fg, palette::text());
                assert_eq!(cell.bg, palette::surface_overlay());
            }
        }
    }
}