agentty 0.13.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
use ratatui::Frame;
use ratatui::layout::{Alignment, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Paragraph, Wrap};
use unicode_width::UnicodeWidthStr;

use crate::ui::component::tachyon_loader::TachyonLoaderEffect;
use crate::ui::icon::Icon;
use crate::ui::markdown::render_markdown;
use crate::ui::style::palette;
use crate::ui::{Component, overlay};

const MIN_OVERLAY_HEIGHT: u16 = 9;
const MIN_OVERLAY_WIDTH: u16 = 44;
const OVERLAY_HORIZONTAL_CHROME: u16 = 6;
const OVERLAY_HEIGHT_PERCENT: u16 = 26;
const OVERLAY_MAX_WIDTH_PERCENT: u16 = 96;
const OVERLAY_WIDTH_PERCENT: u16 = 52;

/// Centered informational popup used for non-destructive workflow guidance.
pub struct InfoOverlay<'a> {
    is_loading: bool,
    loading_label: &'a str,
    message: &'a str,
    title: &'a str,
}

impl<'a> InfoOverlay<'a> {
    /// Creates an informational popup with title and body message.
    pub fn new(title: &'a str, message: &'a str) -> Self {
        Self {
            is_loading: false,
            loading_label: "Sync in progress...",
            message,
            title,
        }
    }

    /// Sets whether the overlay should display a loading indicator.
    #[must_use]
    pub fn is_loading(mut self, loading: bool) -> Self {
        self.is_loading = loading;
        self
    }

    /// Sets the spinner label shown while the overlay is loading.
    #[must_use]
    pub fn loading_label(mut self, loading_label: &'a str) -> Self {
        self.loading_label = loading_label;
        self
    }

    /// Renders the body message as markdown with inline highlight styles and
    /// explicit line breaks.
    fn message_lines(&self, message_width: usize) -> Vec<Line<'static>> {
        let normalized_message = Self::markdown_message_with_block_headers(self.message);
        let mut message_lines = render_markdown(&normalized_message, message_width);

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

        message_lines
    }

    /// Adds markdown block headers for numbered sync sections and inserts blank
    /// lines between each section.
    fn markdown_message_with_block_headers(message: &str) -> String {
        let mut normalized_lines: Vec<String> = Vec::new();

        for raw_line in message.split('\n') {
            if let Some(formatted_line) = Self::format_sync_block_title(raw_line) {
                if let Some(previous_line) = normalized_lines.last()
                    && !previous_line.is_empty()
                {
                    normalized_lines.push(String::new());
                }

                normalized_lines.push(formatted_line);
                continue;
            }

            normalized_lines.push(raw_line.to_string());
        }

        normalized_lines.join("\n")
    }

    /// Converts known sync section title lines (e.g., `1. Pull`, `2. Push`) to
    /// markdown heading text.
    fn format_sync_block_title(raw_line: &str) -> Option<String> {
        let trimmed_line = raw_line.trim();
        if trimmed_line.is_empty() {
            return None;
        }

        let heading_content = trimmed_line.strip_prefix("## ").unwrap_or(trimmed_line);

        split_prefixed_title(heading_content)?;
        let normalized_title = heading_content.to_ascii_lowercase();
        if !normalized_title.contains("pull")
            && !normalized_title.contains("push")
            && !normalized_title.contains("conflict")
        {
            return None;
        }

        if trimmed_line.starts_with("## ") {
            return Some(trimmed_line.to_string());
        }

        Some(format!("## {heading_content}"))
    }

    /// Centers the first body line when it matches the sync context header
    /// format (`Project ...` or `Main branch ...`).
    fn center_sync_context_header(message_lines: &mut [Line<'static>]) {
        let Some(first_line) = message_lines.first_mut() else {
            return;
        };

        if !Self::is_sync_context_header(first_line) {
            return;
        }

        *first_line = first_line.clone().alignment(Alignment::Center);
    }

    /// Returns whether a message line is the generated sync context header.
    fn is_sync_context_header(line: &Line<'_>) -> bool {
        let line_text: String = line
            .spans
            .iter()
            .map(|span| span.content.as_ref())
            .collect();

        line_text.starts_with("Project ") || line_text.starts_with("Main branch ")
    }

    /// Builds the styled body lines including the action row at the bottom.
    fn body_lines(&self, message_width: usize) -> Vec<Line<'static>> {
        let mut lines = self.message_lines(message_width);

        if !self.is_loading {
            Self::center_sync_context_header(&mut lines);
        }

        lines.push(Line::from(""));
        lines.push(self.action_row());

        lines
    }

    /// Returns the bottom action row: a spinner during loading or an `OK`
    /// button when complete.
    fn action_row(&self) -> Line<'static> {
        if self.is_loading {
            let loading_text = format!("{} {}", Icon::current_spinner(), self.loading_label);

            Line::from(vec![Span::styled(loading_text, loading_indicator_style())])
                .alignment(Alignment::Center)
        } else {
            Line::from(vec![Span::styled(" OK ", ok_button_style())]).alignment(Alignment::Center)
        }
    }

    /// Returns the popup border color: cyan during loading, yellow when
    /// complete.
    fn border_color(&self) -> Color {
        if self.is_loading {
            palette::accent()
        } else {
            palette::warning()
        }
    }

    /// Returns the body text alignment: centered during loading, left-aligned
    /// when complete.
    fn body_alignment(&self) -> Alignment {
        if self.is_loading {
            Alignment::Center
        } else {
            Alignment::Left
        }
    }

    /// Returns popup width constrained by overlay defaults and frame bounds.
    fn popup_width(&self, area: Rect) -> u16 {
        let default_width = (area.width * OVERLAY_WIDTH_PERCENT / 100)
            .max(MIN_OVERLAY_WIDTH)
            .min(area.width);
        let max_width = (area.width * OVERLAY_MAX_WIDTH_PERCENT / 100)
            .max(MIN_OVERLAY_WIDTH)
            .min(area.width);
        let preferred_width = self.preferred_popup_width(max_width);

        default_width.max(preferred_width).min(max_width)
    }

    /// Returns the popup width preferred by the current message content.
    fn preferred_popup_width(&self, max_width: u16) -> u16 {
        let longest_line_width = self.longest_unwrapped_line_width();
        let preferred_content_width = u16::try_from(longest_line_width)
            .unwrap_or(u16::MAX)
            .saturating_add(1);

        preferred_content_width
            .saturating_add(OVERLAY_HORIZONTAL_CHROME)
            .min(max_width)
    }

    /// Returns the terminal display width of the longest unwrapped message or
    /// action row line before the paragraph widget applies wrapping.
    fn longest_unwrapped_line_width(&self) -> usize {
        let message = Self::markdown_message_with_block_headers(self.message);
        let message_width = message
            .lines()
            .map(UnicodeWidthStr::width)
            .max()
            .unwrap_or(0);
        let action_width = if self.is_loading {
            UnicodeWidthStr::width(
                format!("{} {}", Icon::current_spinner(), self.loading_label).as_str(),
            )
        } else {
            UnicodeWidthStr::width(" OK ")
        };

        message_width.max(action_width)
    }

    /// Returns popup height sized to keep wrapped body content and the action
    /// row visible.
    fn popup_height(&self, area: Rect, width: u16) -> u16 {
        let min_height = (area.height * OVERLAY_HEIGHT_PERCENT / 100)
            .max(MIN_OVERLAY_HEIGHT)
            .min(area.height);
        let message_width = overlay::overlay_content_width(width);
        let required_inner_lines = self.body_lines(message_width).len();
        let required_height =
            overlay::overlay_required_height(required_inner_lines).min(area.height);

        required_height.max(min_height)
    }

    /// Returns the default body foreground used by unhighlighted overlay text.
    fn body_text_style() -> Style {
        Style::default().fg(palette::text())
    }
}

impl Component for InfoOverlay<'_> {
    fn render(&self, f: &mut Frame, area: Rect) {
        let width = self.popup_width(area);
        let message_width = overlay::overlay_content_width(width);
        let border_color = self.border_color();
        let paragraph = Paragraph::new(self.body_lines(message_width))
            .alignment(self.body_alignment())
            .style(Self::body_text_style())
            .wrap(Wrap { trim: true })
            .block(overlay::overlay_block(self.title, border_color));

        let height = self.popup_height(area, width);
        let popup_area = overlay::centered_popup_area(
            area,
            OVERLAY_WIDTH_PERCENT,
            OVERLAY_HEIGHT_PERCENT,
            width,
            height,
        );

        overlay::clear_popup_area(f, popup_area);
        f.render_widget(paragraph, popup_area);

        if self.is_loading {
            TachyonLoaderEffect::apply_to_last_glyph(
                f.buffer_mut(),
                popup_area,
                Icon::current_spinner_frame(),
            );
        }
    }
}

/// Style for the `OK` confirmation button.
fn ok_button_style() -> Style {
    Style::default()
        .fg(palette::surface_overlay())
        .bg(palette::accent())
        .add_modifier(Modifier::BOLD)
}

/// Style for the loading spinner text.
fn loading_indicator_style() -> Style {
    Style::default()
        .fg(palette::accent())
        .add_modifier(Modifier::BOLD)
}

/// Splits numbered section titles like `1. Pull` or `2) Push`.
fn split_prefixed_title(line: &str) -> Option<&str> {
    if let Some(dot_index) = line.find('.') {
        if dot_index == 0 {
            return None;
        }

        if !line[..dot_index]
            .chars()
            .all(|character| character.is_ascii_digit())
        {
            return None;
        }

        return Some(line[dot_index + 1..].trim());
    }

    let parenthesis_index = line.find(')')?;
    if parenthesis_index == 0 {
        return None;
    }

    if !line[..parenthesis_index]
        .chars()
        .all(|character| character.is_ascii_digit())
    {
        return None;
    }

    Some(line[parenthesis_index + 1..].trim())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::theme::ColorTheme;
    use crate::test_support;
    use crate::ui::style;

    #[test]
    fn test_info_overlay_new_stores_fields() {
        // Arrange
        let message = "Sync is blocked";
        let title = "Sync blocked";

        // Act
        let overlay = InfoOverlay::new(title, message);

        // Assert
        assert!(!overlay.is_loading);
        assert_eq!(overlay.message, message);
        assert_eq!(overlay.title, title);
    }

    #[test]
    fn test_info_overlay_render_includes_ok_indicator() {
        // Arrange
        let backend = ratatui::backend::TestBackend::new(100, 20);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");
        let overlay = InfoOverlay::new("Sync blocked", "Main has uncommitted changes");

        // Act
        terminal
            .draw(|f| {
                let area = f.area();
                Component::render(&overlay, f, area);
            })
            .expect("failed to draw");

        // Assert
        let buffer = terminal.backend().buffer();
        let content = buffer.content();
        let text: String = content.iter().map(ratatui::buffer::Cell::symbol).collect();
        assert!(text.contains("OK"));
        assert!(text.contains("Main has uncommitted changes"));
    }

    #[test]
    fn test_info_overlay_render_includes_loading_indicator_when_loading() {
        // Arrange
        let backend = ratatui::backend::TestBackend::new(100, 20);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");
        let overlay = InfoOverlay::new("Sync in progress", "Synchronizing branch").is_loading(true);

        // Act
        terminal
            .draw(|f| {
                let area = f.area();
                Component::render(&overlay, f, area);
            })
            .expect("failed to draw");

        // Assert
        let buffer = terminal.backend().buffer();
        let content = buffer.content();
        let text: String = content.iter().map(ratatui::buffer::Cell::symbol).collect();
        assert!(text.contains("Sync in progress..."));
        assert!(!text.contains("Please wait."));
        assert!(!text.contains("OK"));
    }

    #[test]
    fn test_info_overlay_green_theme_uses_session_list_text_color_for_body_text() {
        // Arrange
        let _theme_scope = style::scoped_active_theme(ColorTheme::Green);
        let backend = ratatui::backend::TestBackend::new(100, 20);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");
        let overlay = InfoOverlay::new("Sync blocked", "Use the session list text color.");

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                Component::render(&overlay, frame, area);
            })
            .expect("failed to draw");

        // Assert
        let body_cell = test_support::rendered_text_start_cell(
            terminal.backend().buffer(),
            "Use the session list text color.",
        )
        .expect("body text should render");
        assert_eq!(body_cell.fg, palette::text());
    }

    #[test]
    fn test_info_overlay_render_keeps_ok_indicator_for_multiline_message() {
        // Arrange
        let backend = ratatui::backend::TestBackend::new(100, 20);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");
        let overlay = InfoOverlay::new(
            "Sync failed",
            "Project `agentty` on main branch `main`.\n\nGit push requires authentication for \
             this repository.\nAuthorize git access, then run sync again.\nRun `gh auth login`, \
             or configure credentials with a PAT/SSH key.",
        );

        // Act
        terminal
            .draw(|f| {
                let area = f.area();
                Component::render(&overlay, f, area);
            })
            .expect("failed to draw");

        // Assert
        let buffer = terminal.backend().buffer();
        let content = buffer.content();
        let text: String = content.iter().map(ratatui::buffer::Cell::symbol).collect();
        assert!(text.contains("OK"));
    }

    #[test]
    fn test_message_lines_keeps_each_sentence_on_its_own_line() {
        // Arrange
        let overlay = InfoOverlay::new(
            "Sync blocked",
            "Sync cannot run on this branch.\nCommit or stash, then retry.",
        );

        // Act
        let message_lines = overlay.message_lines(80);

        // Assert
        assert_eq!(message_lines.len(), 2);
        assert_eq!(
            rendered_line_text(&message_lines[0]),
            "Sync cannot run on this branch."
        );
        assert_eq!(
            rendered_line_text(&message_lines[1]),
            "Commit or stash, then retry."
        );
    }

    #[test]
    fn test_message_lines_highlight_inline_code_segments() {
        // Arrange
        let overlay = InfoOverlay::new("Sync blocked", "Run `gh auth login` then retry.");

        // Act
        let message_lines = overlay.message_lines(80);

        // Assert
        assert_eq!(message_lines.len(), 1);
        assert_eq!(
            rendered_line_text(&message_lines[0]),
            "Run gh auth login then retry."
        );
        assert!(
            message_lines[0]
                .spans
                .iter()
                .any(|span| span.style.fg == Some(palette::warning()))
        );
    }

    #[test]
    fn test_markdown_message_with_block_headers_formats_sync_sections() {
        // Arrange
        let message = "1. Pull\n2 commits pulled\n\n2. Push\n1 commit pushed\n\n3. \
                       Conflicts\nconflicts fixed: src/lib.rs";

        // Act
        let formatted_message = InfoOverlay::markdown_message_with_block_headers(message);

        // Assert
        assert_eq!(
            formatted_message,
            concat!(
                "## 1. Pull\n",
                "2 commits pulled\n",
                "\n",
                "## 2. Push\n",
                "1 commit pushed\n",
                "\n",
                "## 3. Conflicts\n",
                "conflicts fixed: src/lib.rs",
            )
        );
    }

    #[test]
    fn test_markdown_message_with_block_headers_inserts_missing_section_spacing() {
        // Arrange
        let message = concat!(
            "## 1. 2 commits pulled\n",
            "2 commits pulled\n",
            "## 2. 1 commit pushed\n",
            "1 commit pushed\n",
            "## 3. conflicts fixed: src/lib.rs\n",
            "conflicts fixed: src/lib.rs",
        );

        // Act
        let formatted_message = InfoOverlay::markdown_message_with_block_headers(message);

        // Assert
        assert!(formatted_message.contains("2 commits pulled\n\n## 2. 1 commit pushed"));
        assert!(
            formatted_message.contains("1 commit pushed\n\n## 3. conflicts fixed: src/lib.rs",)
        );
    }

    #[test]
    fn test_result_state_centers_branch_header_like_loading_state() {
        // Arrange
        let message =
            "Project `agentty` on main branch `main`.\n\nSynchronizing with its upstream.";
        let loading_overlay = InfoOverlay::new("Sync in progress", message).is_loading(true);
        let blocked_overlay = InfoOverlay::new("Sync blocked", message);
        let loading_lines = render_overlay_lines(&loading_overlay);
        let blocked_lines = render_overlay_lines(&blocked_overlay);
        let header_text = "Project";
        let detail_text = "Synchronizing with its upstream.";
        let loader_text = "Sync in progress...";

        // Act
        let loading_header_column =
            line_start_column(&loading_lines, header_text).expect("missing loading header");
        let blocked_header_column =
            line_start_column(&blocked_lines, header_text).expect("missing blocked header");
        let blocked_detail_column =
            line_start_column(&blocked_lines, detail_text).expect("missing blocked detail");
        let loading_loader_column =
            line_start_column(&loading_lines, loader_text).expect("missing loader text");

        // Assert
        assert_eq!(loading_header_column, blocked_header_column);
        assert!(blocked_header_column > blocked_detail_column);
        assert!(loading_loader_column > blocked_header_column);
    }

    #[test]
    fn test_popup_width_expands_for_long_link_lines() {
        // Arrange
        let review_request_url = "https://github.com/minev-development/agentty/compare/main...feature%2Fvery-long-review-branch?expand=1";
        let message = format!("Open this link to create the pull request:\n{review_request_url}");
        let overlay = InfoOverlay::new("Branch pushed", &message);
        let area = Rect::new(0, 0, 160, 20);

        // Act
        let popup_width = overlay.popup_width(area);
        let content_width = overlay::overlay_content_width(popup_width);

        // Assert
        assert!(popup_width > (area.width * OVERLAY_WIDTH_PERCENT / 100));
        assert!(content_width >= review_request_url.len());
    }

    #[test]
    fn test_longest_unwrapped_line_width_uses_terminal_display_width() {
        // Arrange
        let overlay = InfoOverlay::new("Branch pushed", "PR表");

        // Act
        let longest_line_width = overlay.longest_unwrapped_line_width();

        // Assert
        assert_eq!(longest_line_width, UnicodeWidthStr::width("PR表"));
        assert_eq!(longest_line_width, 4);
    }

    #[test]
    fn test_info_overlay_render_keeps_long_link_on_one_row_when_terminal_is_wide_enough() {
        // Arrange
        let backend = ratatui::backend::TestBackend::new(160, 20);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");
        let review_request_url = "https://github.com/minev-development/agentty/compare/main...feature%2Fvery-long-review-branch?expand=1";
        let message = format!("Open this link to create the pull request:\n{review_request_url}");
        let overlay = InfoOverlay::new("Branch pushed", &message);

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                Component::render(&overlay, frame, area);
            })
            .expect("failed to draw");

        let buffer = terminal.backend().buffer();
        let rows: Vec<String> = buffer
            .content()
            .chunks(160)
            .map(|row| row.iter().map(ratatui::buffer::Cell::symbol).collect())
            .collect();

        // Assert
        assert!(rows.iter().any(|row| row.contains(review_request_url)));
    }

    /// Renders one overlay and returns text rows for column-position
    /// assertions.
    fn render_overlay_lines(overlay: &InfoOverlay<'_>) -> Vec<String> {
        let backend = ratatui::backend::TestBackend::new(100, 20);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");

        terminal
            .draw(|frame| {
                let area = frame.area();
                Component::render(overlay, frame, area);
            })
            .expect("failed to draw");

        let text_cells = terminal.backend().buffer().content();

        text_cells
            .chunks(100)
            .map(|row| row.iter().map(ratatui::buffer::Cell::symbol).collect())
            .collect()
    }

    /// Returns the left-most column index for `needle` within rendered rows.
    fn line_start_column(lines: &[String], needle: &str) -> Option<usize> {
        lines.iter().find_map(|line| line.find(needle))
    }

    /// Returns the concatenated plain text for one rendered `Line`.
    fn rendered_line_text(line: &Line<'_>) -> String {
        line.spans
            .iter()
            .map(|span| span.content.as_ref())
            .collect()
    }
}