agentty 0.11.1

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
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph};

use crate::ui::input_layout::{
    CHAT_INPUT_MAX_VISIBLE_LINES, calculate_input_viewport, compute_input_layout,
    input_cursor_position, placeholder_cursor_position, suggestion_dropdown_height,
};
use crate::ui::{Component, style};

/// One row rendered inside a prompt suggestion dropdown.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SuggestionItem {
    /// Optional compact badge rendered before the main label.
    pub badge: Option<String>,
    /// Optional explanatory text rendered after the label.
    pub detail: Option<String>,
    /// Primary row label used for selection and insertion.
    pub label: String,
    /// Optional trailing metadata rendered with subdued styling.
    pub metadata: Option<String>,
}

/// Suggestion dropdown rendered above or alongside the prompt input block.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SuggestionList {
    /// Dropdown rows in display order.
    pub items: Vec<SuggestionItem>,
    /// Highlighted row index in `items`.
    pub selected_index: usize,
    /// Dropdown title shown in the rounded border chrome.
    pub title: String,
}

/// Prompt input component with optional rich suggestion dropdown.
pub struct ChatInput<'a> {
    pub placeholder: &'a str,
    active: bool,
    clear_style: Option<Style>,
    cursor: usize,
    input: &'a str,
    suggestion_list: Option<&'a SuggestionList>,
    title: &'a str,
}

impl<'a> ChatInput<'a> {
    /// Creates a new prompt input component.
    pub fn new(title: &'a str, input: &'a str, cursor: usize) -> Self {
        Self {
            placeholder: "",
            active: true,
            clear_style: None,
            cursor,
            input,
            suggestion_list: None,
            title,
        }
    }

    /// Sets the input placeholder text.
    #[must_use]
    pub fn placeholder(mut self, placeholder: &'a str) -> Self {
        self.placeholder = placeholder;
        self
    }

    /// Marks the input as inactive (dimmed border, no cursor).
    ///
    /// When `false`, the border uses a muted color and the terminal cursor
    /// is not rendered. Defaults to `true`.
    #[must_use]
    pub fn active(mut self, active: bool) -> Self {
        self.active = active;
        self
    }

    /// Sets the suggestion dropdown shown next to the prompt input.
    #[must_use]
    pub fn suggestion_list(mut self, suggestion_list: &'a SuggestionList) -> Self {
        self.suggestion_list = Some(suggestion_list);
        self
    }

    /// Sets the style reapplied after clearing the input area.
    ///
    /// Overlay-hosted inputs use this to keep popup-local cells on the
    /// semantic overlay surface instead of terminal-default colors.
    #[must_use]
    pub fn clear_style(mut self, clear_style: Style) -> Self {
        self.clear_style = Some(clear_style);
        self
    }

    /// Returns the shared block styling for the prompt input frame.
    ///
    /// Uses accent styling when active and muted styling when inactive.
    fn input_block(&self) -> Block<'a> {
        let title = format!(" {} ", self.title);
        let (border_style, title_style) = if self.active {
            (Self::focused_border_style(), Self::focused_title_style())
        } else {
            (Self::inactive_border_style(), Self::inactive_title_style())
        };

        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(border_style)
            .title(Span::styled(title, title_style))
    }

    /// Returns the border style used to keep the active prompt field visually
    /// prominent.
    fn focused_border_style() -> Style {
        Style::default()
            .fg(style::palette::accent())
            .add_modifier(Modifier::BOLD)
    }

    /// Returns the title style used by the focused prompt input frame.
    fn focused_title_style() -> Style {
        Style::default()
            .fg(style::palette::accent())
            .add_modifier(Modifier::BOLD)
    }

    /// Returns the border style for an inactive (dimmed) prompt input frame.
    fn inactive_border_style() -> Style {
        Style::default().fg(style::palette::border())
    }

    /// Returns the title style for an inactive (dimmed) prompt input frame.
    fn inactive_title_style() -> Style {
        Style::default().fg(style::palette::border())
    }

    /// Returns the shared block styling for prompt suggestion dropdowns.
    fn dropdown_block(title: &str) -> Block<'_> {
        let title = format!(" {title} ");

        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(style::palette::accent_soft()))
            .title(Span::styled(
                title,
                Style::default().fg(style::palette::accent_soft()),
            ))
    }

    /// Returns the default foreground style for typed prompt content.
    fn input_text_style() -> Style {
        Style::default().fg(style::palette::text())
    }

    /// Clears an input rectangle and optionally renders an empty styled block
    /// so overlay-hosted input cells keep semantic colors.
    fn clear_area(f: &mut Frame, area: Rect, clear_style: Option<Style>) {
        f.render_widget(Clear, area);

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

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

    /// Renders the suggestion dropdown using the shared chat input chrome.
    ///
    /// This method is also used by the question-mode panel to render the
    /// at-mention file dropdown as an overlay above the input area.
    pub(crate) fn render_suggestion_dropdown(
        f: &mut Frame,
        area: Rect,
        suggestion_list: &SuggestionList,
    ) {
        let rows = suggestion_list
            .items
            .iter()
            .enumerate()
            .map(|(index, item)| {
                let is_selected = index == suggestion_list.selected_index;
                let prefix = if is_selected { ">" } else { " " };
                let label_style = if is_selected {
                    Style::default()
                        .fg(style::palette::accent())
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(style::palette::text_muted())
                };
                let description_style = if is_selected {
                    Style::default().fg(style::palette::text_muted())
                } else {
                    Style::default().fg(style::palette::text_subtle())
                };

                let mut spans = Vec::new();
                spans.push(Span::styled(format!("{prefix} "), label_style));

                if let Some(badge) = &item.badge {
                    spans.push(Span::styled(format!("[{badge}] "), description_style));
                }

                spans.push(Span::styled(item.label.as_str(), label_style));

                if let Some(metadata) = &item.metadata {
                    spans.push(Span::styled(format!("  {metadata}"), description_style));
                }

                if let Some(detail) = &item.detail {
                    spans.push(Span::styled(format!("  {detail}"), description_style));
                }

                Line::from(spans)
            })
            .collect::<Vec<_>>();

        let dropdown = Paragraph::new(rows)
            .style(Self::input_text_style())
            .block(Self::dropdown_block(&suggestion_list.title));

        Self::clear_area(f, area, None);
        f.render_widget(dropdown, area);
    }

    /// Render the prompt input with an internally scrollable viewport.
    fn render_input(&self, f: &mut Frame, area: Rect) {
        let block = self.input_block();

        if self.input.is_empty() {
            let prefix_style = if self.active {
                Style::default()
                    .fg(style::palette::accent())
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(style::palette::border())
            };
            let prefix = "";
            let display_lines = vec![Line::from(vec![
                Span::styled(prefix, prefix_style),
                Span::raw("  "),
                Span::styled(
                    self.placeholder,
                    Style::default().fg(style::palette::text_subtle()),
                ),
            ])];

            let widget = Paragraph::new(display_lines)
                .style(Self::input_text_style())
                .block(block);
            Self::clear_area(f, area, self.clear_style);
            f.render_widget(widget, area);
            if self.active {
                f.set_cursor_position(placeholder_cursor_position(area));
            }

            return;
        }

        let (display_lines, cursor_x, cursor_y) =
            compute_input_layout(self.input, area.width, self.cursor);
        let viewport_height = area
            .height
            .saturating_sub(2)
            .min(CHAT_INPUT_MAX_VISIBLE_LINES);
        let total_line_count = Self::total_viewport_line_count(display_lines.len(), cursor_y);
        let (scroll_offset, cursor_row) =
            calculate_input_viewport(total_line_count, cursor_y, viewport_height);
        let widget = Paragraph::new(display_lines)
            .style(Self::input_text_style())
            .scroll((scroll_offset, 0))
            .block(block);

        Self::clear_area(f, area, self.clear_style);
        f.render_widget(widget, area);
        if self.active {
            f.set_cursor_position(input_cursor_position(area, cursor_x, cursor_row));
        }
    }

    /// Computes the total line count used by input viewport scrolling.
    ///
    /// The cursor can legally point to a trailing wrapped line that has no
    /// visible characters yet (exact line-fit case), so viewport calculations
    /// must account for whichever line index is greater.
    fn total_viewport_line_count(display_line_count: usize, cursor_y: u16) -> usize {
        display_line_count.max(usize::from(cursor_y).saturating_add(1))
    }
}

impl Component for ChatInput<'_> {
    fn render(&self, f: &mut Frame, area: Rect) {
        if let Some(suggestion_list) = &self.suggestion_list {
            let dropdown_height = suggestion_dropdown_height(suggestion_list.items.len());
            let sections = Layout::default()
                .constraints([Constraint::Length(dropdown_height), Constraint::Min(0)])
                .split(area);

            Self::render_suggestion_dropdown(f, sections[0], suggestion_list);
            self.render_input(f, sections[1]);

            return;
        }

        self.render_input(f, area);
    }
}

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

    /// Returns the rendered symbols for one buffer row.
    fn buffer_row_text(buffer: &ratatui::buffer::Buffer, row: u16, width: u16) -> String {
        let start = usize::from(row) * usize::from(width);
        let end = start + usize::from(width);

        buffer.content()[start..end]
            .iter()
            .map(ratatui::buffer::Cell::symbol)
            .collect()
    }

    #[test]
    fn test_builder_methods() {
        // Arrange
        let title = "Chat";
        let input = "Hello";
        let cursor = 5;
        let placeholder = "Start typing...";
        let suggestion_list = SuggestionList {
            items: vec![],
            selected_index: 0,
            title: "Menu".to_string(),
        };

        // Act
        let chat_input = ChatInput::new(title, input, cursor)
            .placeholder(placeholder)
            .suggestion_list(&suggestion_list);

        // Assert
        assert_eq!(chat_input.title, title);
        assert_eq!(chat_input.input, input);
        assert_eq!(chat_input.cursor, cursor);
        assert_eq!(chat_input.placeholder, placeholder);
        assert!(chat_input.suggestion_list.is_some());
        assert_eq!(
            chat_input
                .suggestion_list
                .expect("suggestion list should be set")
                .title,
            "Menu"
        );
    }

    #[test]
    fn test_total_viewport_line_count_uses_cursor_row_when_cursor_is_below_last_display_line() {
        // Arrange
        let display_line_count = 1;
        let cursor_y = 1;

        // Act
        let total_line_count = ChatInput::total_viewport_line_count(display_line_count, cursor_y);

        // Assert
        assert_eq!(total_line_count, 2);
    }

    #[test]
    fn test_render_uses_rounded_focused_frame_for_prompt_input() {
        // Arrange
        let width = 32;
        let backend = ratatui::backend::TestBackend::new(width, 5);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");
        let chat_input = ChatInput::new("Prompt", "", 0).placeholder("Type your message");

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                chat_input.render(frame, area);
            })
            .expect("failed to draw prompt input");

        // Assert
        let top_row = buffer_row_text(terminal.backend().buffer(), 0, width);
        assert!(top_row.starts_with(""));
        assert!(top_row.contains(" Prompt "));
        assert!(top_row.contains(""));
    }

    #[test]
    fn test_render_inactive_uses_dimmed_border_style() {
        // Arrange
        let width = 32;
        let backend = ratatui::backend::TestBackend::new(width, 5);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");
        let chat_input = ChatInput::new("Prompt", "", 0)
            .placeholder("Type your message")
            .active(false);

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                chat_input.render(frame, area);
            })
            .expect("failed to draw inactive prompt input");

        // Assert — border is rendered with the muted BORDER color, not ACCENT.
        let buffer = terminal.backend().buffer();
        let top_left_cell = &buffer.content()[0];
        assert_eq!(top_left_cell.fg, style::palette::border());
    }

    #[test]
    fn test_render_inactive_with_text_uses_dimmed_border() {
        // Arrange — inactive input with text still uses the muted border.
        let width = 32;
        let backend = ratatui::backend::TestBackend::new(width, 5);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");
        let chat_input = ChatInput::new("Prompt", "hello", 5).active(false);

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                chat_input.render(frame, area);
            })
            .expect("failed to draw inactive prompt input with text");

        // Assert — border still uses muted BORDER color.
        let buffer = terminal.backend().buffer();
        let top_left_cell = &buffer.content()[0];
        assert_eq!(top_left_cell.fg, style::palette::border());
    }

    #[test]
    fn test_render_hacker_theme_uses_session_list_text_color_for_input_text() {
        // Arrange
        let _theme_scope = style::scoped_active_theme(ColorTheme::Hacker);
        let width = 48;
        let backend = ratatui::backend::TestBackend::new(width, 5);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");
        let chat_input = ChatInput::new("Prompt", "typed-green", "typed-green".chars().count());

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                chat_input.render(frame, area);
            })
            .expect("failed to draw prompt input");

        // Assert
        let typed_cell =
            test_support::rendered_text_start_cell(terminal.backend().buffer(), "typed-green")
                .expect("typed input should render");
        assert_eq!(typed_cell.fg, style::palette::text());
    }

    #[test]
    fn test_render_reapplies_configured_clear_style() {
        // Arrange
        let width = 48;
        let backend = ratatui::backend::TestBackend::new(width, 5);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");
        let clear_style = Style::default()
            .fg(style::palette::text())
            .bg(style::palette::surface_overlay());
        let chat_input = ChatInput::new("Prompt", "typed", 5).clear_style(clear_style);

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                chat_input.render(frame, area);
            })
            .expect("failed to draw prompt input");

        // Assert
        let buffer = terminal.backend().buffer();
        let blank_cell = &buffer[(1, 2)];
        assert_eq!(blank_cell.fg, style::palette::text());
        assert_eq!(blank_cell.bg, style::palette::surface_overlay());
    }

    #[test]
    fn test_render_uses_matching_rounded_dropdown_frame() {
        // Arrange
        let width = 40;
        let backend = ratatui::backend::TestBackend::new(width, 8);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");
        let suggestion_list = SuggestionList {
            items: vec![SuggestionItem {
                badge: Some("cmd".to_string()),
                detail: Some("Choose a model".to_string()),
                label: "/model".to_string(),
                metadata: Some("Enter".to_string()),
            }],
            selected_index: 0,
            title: "Prompt Suggestion".to_string(),
        };
        let chat_input = ChatInput::new("Prompt", "/", 1).suggestion_list(&suggestion_list);

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                chat_input.render(frame, area);
            })
            .expect("failed to draw prompt input with dropdown");

        // Assert
        let top_row = buffer_row_text(terminal.backend().buffer(), 0, width);
        assert!(top_row.starts_with(""));
        assert!(top_row.contains(" Prompt Suggestion "));
        assert!(top_row.contains(""));
    }

    #[test]
    fn test_render_keeps_raw_at_lookup_text_visible_in_input() {
        // Arrange
        let width = 48;
        let backend = ratatui::backend::TestBackend::new(width, 5);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");
        let chat_input = ChatInput::new("Prompt", "@src/main.rs", "@src/main.rs".chars().count());

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                chat_input.render(frame, area);
            })
            .expect("failed to draw prompt input with at-lookup");

        // Assert
        let visible_text = (0..5)
            .map(|row| buffer_row_text(terminal.backend().buffer(), row, width))
            .collect::<Vec<_>>()
            .join("\n");
        assert!(visible_text.contains("@src/main.rs"));
    }
}