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
//! Session header, footer, and transcript display formatting.

use ag_protocol::AgentResponseSummary;
use ag_tui_text::text_util;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Borders;

use crate::domain::agent::ReasoningLevel;
use crate::domain::review;
use crate::domain::session::{COMMITTING_PROGRESS_LABEL, Session, Status};
use crate::presentation::help_action::{self, ViewHelpState};
use crate::ui::icon::Icon;
use crate::ui::{markdown, style};

const REVIEW_PROJECT_IMPACT_HEADER: &str = "### Project Impact";
const REVIEW_SUGGESTIONS_HEADER: &str = "### Suggestions";
const REVIEW_SUGGESTIONS_HEADER_WITH_HINT: &str =
    "### Suggestions (type \"/apply\" to verify and apply)";
const SESSION_OUTPUT_DEFAULT_SUMMARY_TEXT: &str = "No changes";

/// Formats the session title and metadata lines rendered above the output
/// panel.
///
/// When a linked review-request URL is available, the URL shares the metadata
/// row when the full row fits and otherwise wraps to the row directly above
/// the transcript border.
pub fn session_header_lines(
    session: &Session,
    header_width: u16,
    default_reasoning_level: ReasoningLevel,
    wall_clock_unix_seconds: i64,
) -> Vec<Line<'static>> {
    let title_width = usize::from(header_width);
    let title_text = text_util::inline_text(session.display_title());
    let base_style = Style::default()
        .fg(style::status_color(session.status))
        .add_modifier(Modifier::BOLD);
    let title_spans = markdown::parse_inline_spans(&title_text, base_style);
    let title_spans = text_util::truncate_spans_with_ellipsis(title_spans, title_width);
    let metadata_lines = session_header_metadata_lines(
        session,
        header_width,
        default_reasoning_level,
        wall_clock_unix_seconds,
    );

    let mut lines = Vec::with_capacity(1 + metadata_lines.len());
    lines.push(Line::from(title_spans));

    for metadata_text in metadata_lines {
        lines.push(Line::from(Span::styled(
            metadata_text,
            Style::default().fg(style::palette::text_muted()),
        )));
    }

    lines
}

/// Formats the size, timer, token usage, model, and reasoning row shown in
/// single-line metadata contexts without any chat-header-only URL suffix.
pub fn session_metadata_text(
    session: &Session,
    header_width: u16,
    default_reasoning_level: ReasoningLevel,
    wall_clock_unix_seconds: i64,
) -> String {
    let metadata =
        session_metadata_base_text(session, default_reasoning_level, wall_clock_unix_seconds);

    text_util::truncate_with_ellipsis(&metadata, usize::from(header_width))
}

/// Formats the chat header metadata rows, including the linked review-request
/// URL when one is available.
///
/// When a PR/MR URL is available, it is placed on the same row as the
/// left-side metadata when space allows; otherwise it is moved to the next
/// metadata row.
fn session_header_metadata_lines(
    session: &Session,
    header_width: u16,
    default_reasoning_level: ReasoningLevel,
    wall_clock_unix_seconds: i64,
) -> Vec<String> {
    let metadata =
        session_metadata_base_text(session, default_reasoning_level, wall_clock_unix_seconds);
    let available_width = usize::from(header_width);

    let review_request_url = session
        .review_request
        .as_ref()
        .map(|request| request.summary.web_url.as_str())
        .filter(|url| !url.is_empty())
        .map(str::trim)
        .filter(|url| !url.is_empty());

    let Some(review_request_url) = review_request_url else {
        return vec![text_util::truncate_with_ellipsis(
            &metadata,
            available_width,
        )];
    };

    let metadata_width = metadata.chars().count();
    let url_width = review_request_url.chars().count();
    let separator_width = 2;
    let total_required_width = metadata_width
        .saturating_add(separator_width)
        .saturating_add(url_width);
    let mut metadata_lines = Vec::with_capacity(2);

    if total_required_width <= available_width {
        let separator = " ".repeat(
            available_width
                .saturating_sub(metadata_width)
                .saturating_sub(url_width),
        );
        metadata_lines.push(format!("{metadata}{separator}{review_request_url}"));

        return metadata_lines;
    }

    metadata_lines.push(text_util::truncate_with_ellipsis(
        &metadata,
        available_width,
    ));
    metadata_lines.push(text_util::truncate_with_ellipsis(
        review_request_url,
        available_width,
    ));

    metadata_lines
}

/// Builds the untruncated left-side metadata text shared by session header and
/// single-line metadata renderers.
fn session_metadata_base_text(
    session: &Session,
    _default_reasoning_level: ReasoningLevel,
    wall_clock_unix_seconds: i64,
) -> String {
    let added_lines = session.stats.added_lines;
    let deleted_lines = session.stats.deleted_lines;
    let timer = text_util::format_duration_compact(
        session.in_progress_duration_seconds(wall_clock_unix_seconds),
    );
    let reasoning_level = session.effective_reasoning_level();
    let input_tokens = text_util::format_token_count(session.stats.input_tokens);
    let output_tokens = text_util::format_token_count(session.stats.output_tokens);
    format!(
        "Size: {}  Lines: +{added_lines} / -{deleted_lines}  Timer: {timer}  Agent: {}  Model: \
         {}  Reasoning: {}  Tokens: {input_tokens}/{output_tokens}",
        session.size,
        session.agent.kind(),
        session.agent.model().as_str(),
        reasoning_level.as_str(),
    )
}

/// Builds the session-view footer and exposes linked forge comments on `c`
/// when the current session has a review request.
pub(crate) fn session_view_footer_line_with_review_comments(
    view_help_state: ViewHelpState,
    can_view_review_comments: bool,
) -> Line<'static> {
    crate::ui::help_format::footer_line(&help_action::view_footer_actions_with_review_comments(
        view_help_state,
        can_view_review_comments,
    ))
}

/// Renders persisted summary payloads into display markdown.
///
/// Structured JSON summaries are expanded into `Current Turn` and `Session
/// Changes` sections with a blank line after the section headers. Plain text
/// falls back unchanged, and empty content uses the shared `No changes`
/// placeholder for both sections.
pub(crate) fn session_output_summary_markdown(summary_text: &str) -> String {
    let trimmed_summary = summary_text.trim();
    if let Ok(summary_payload) = serde_json::from_str::<AgentResponseSummary>(trimmed_summary) {
        return format!(
            "## Change Summary\n\n### Current Turn\n{}\n\n### Session Changes\n{}",
            summary_section_text(&summary_payload.turn),
            summary_section_text(&summary_payload.session)
        );
    }

    if !trimmed_summary.is_empty() {
        return trimmed_summary.to_string();
    }

    format!(
        "## Change Summary\n\n### Current Turn\n{SESSION_OUTPUT_DEFAULT_SUMMARY_TEXT}\n\n### \
         Session Changes\n{SESSION_OUTPUT_DEFAULT_SUMMARY_TEXT}"
    )
}

/// Formats focused-review section headings with compact spacing and adds the
/// verification-gated `/apply` hint when suggestions are actionable.
pub(crate) fn format_review_markdown(review_markdown: &str) -> String {
    let has_actionable_suggestions =
        review::has_actionable_review_suggestions(Some(review_markdown));
    let mut formatted_lines = Vec::with_capacity(review_markdown.lines().count());
    let mut skip_section_spacing = false;

    for line in review_markdown.lines() {
        if skip_section_spacing && line.trim().is_empty() {
            continue;
        }
        skip_section_spacing = false;

        let trimmed_line = line.trim_end();
        if trimmed_line == REVIEW_PROJECT_IMPACT_HEADER {
            formatted_lines.push(line.to_string());
            skip_section_spacing = true;
        } else if matches!(
            trimmed_line,
            REVIEW_SUGGESTIONS_HEADER | REVIEW_SUGGESTIONS_HEADER_WITH_HINT
        ) {
            if has_actionable_suggestions {
                formatted_lines.push(REVIEW_SUGGESTIONS_HEADER_WITH_HINT.to_string());
            } else {
                formatted_lines.push(line.to_string());
            }
            skip_section_spacing = true;
        } else {
            formatted_lines.push(line.to_string());
        }
    }

    formatted_lines.join("\n")
}

/// Returns borders used for the session output panel.
///
/// Vertical borders stay hidden so terminal copy/select flows do not pick up
/// extra gutter characters.
pub fn session_output_panel_borders() -> Borders {
    Borders::TOP | Borders::BOTTOM
}

/// Returns the border style used for the session output panel.
pub fn session_output_panel_border_style(status: Status) -> Style {
    Style::default().fg(style::status_color(status))
}

/// Returns whether the session-output status row receives a Tachyon loader
/// effect.
pub(crate) fn session_output_uses_tachyon_loader(status: Status) -> bool {
    matches!(
        status,
        Status::InProgress
            | Status::AgentReview
            | Status::Rebasing
            | Status::Merging
            | Status::Merged
    )
}

/// Builds the inline shortcut hint for continuing a completed session.
pub fn session_output_done_line() -> Line<'static> {
    Line::from(vec![Span::styled(
        "Press 'C' to continue in a new session.",
        Style::default().fg(style::palette::text_subtle()),
    )])
}

/// Builds the active-status line shown at the end of an in-flight session
/// transcript.
///
/// The leading glyph is stable text because the session output component
/// applies the Tachyonfx loader animation directly to those buffer cells after
/// the paragraph is rendered.
pub fn session_output_status_line(
    status: Status,
    active_progress: Option<&str>,
    review_status_message: Option<&str>,
) -> Option<Line<'static>> {
    if !matches!(
        status,
        Status::InProgress
            | Status::AgentReview
            | Status::Queued
            | Status::Rebasing
            | Status::Merging
            | Status::Merged
    ) {
        return None;
    }

    let status_message =
        session_output_status_message(status, active_progress, review_status_message);

    Some(Line::from(vec![Span::styled(
        format!("{} {status_message}", session_output_status_icon(status)),
        Style::default().fg(style::status_color(status)),
    )]))
}

/// Builds one animated loading row for an explicit transient workflow slot.
pub(crate) fn session_output_transient_loading_line(message: &str) -> Line<'static> {
    Line::from(vec![Span::styled(
        format!("{} {}", Icon::Spinner, message.trim()),
        Style::default().fg(style::palette::warning()),
    )])
}

/// Returns one rendered summary section or the shared empty placeholder.
fn summary_section_text(summary_text: &str) -> &str {
    let trimmed_summary = summary_text.trim();
    if trimmed_summary.is_empty() {
        return SESSION_OUTPUT_DEFAULT_SUMMARY_TEXT;
    }

    trimmed_summary
}

/// Returns the loader label for active session states.
///
/// Most in-progress details are agent thinking snippets appended to the
/// generic working label. Post-turn auto-commit sends a complete loader label
/// so commit-message generation and git commit work render as committing.
fn session_output_status_message(
    status: Status,
    active_progress: Option<&str>,
    review_status_message: Option<&str>,
) -> String {
    match status {
        Status::InProgress => active_progress
            .map(str::trim)
            .filter(|progress| !progress.is_empty())
            .map_or_else(
                || "Working...".to_string(),
                |progress| {
                    if progress == COMMITTING_PROGRESS_LABEL {
                        progress.to_string()
                    } else {
                        format!("Working... {progress}")
                    }
                },
            ),
        Status::AgentReview => review_status_message
            .map(str::trim)
            .filter(|status_message| !status_message.is_empty())
            .unwrap_or("Reviewing changes...")
            .to_string(),
        Status::Queued => "Waiting in merge queue...".to_string(),
        Status::Rebasing => "Rebasing...".to_string(),
        Status::Merging => "Merging...".to_string(),
        Status::Merged => "Waiting for manual local target sync...".to_string(),
        Status::Draft | Status::Review | Status::Question | Status::Done | Status::Canceled => {
            String::new()
        }
    }
}

/// Returns the status indicator icon used for inline session-output messages.
fn session_output_status_icon(status: Status) -> Icon {
    match status {
        Status::InProgress
        | Status::AgentReview
        | Status::Rebasing
        | Status::Merging
        | Status::Merged => Icon::TachyonLoader,
        Status::Queued
        | Status::Draft
        | Status::Review
        | Status::Question
        | Status::Done
        | Status::Canceled => Icon::Pending,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::agent::AgentModel;
    use crate::domain::session::{
        ForgeKind, ReviewRequest, ReviewRequestState, ReviewRequestSummary,
    };
    use crate::test_support::SessionFixtureBuilder;

    fn session_with_review_request(url: &str) -> Session {
        let mut session = SessionFixtureBuilder::new().build();
        session.review_request = Some(ReviewRequest {
            last_refreshed_at: 1,
            summary: ReviewRequestSummary {
                display_id: "#42".to_string(),
                forge_kind: ForgeKind::GitHub,
                source_branch: "main".to_string(),
                state: ReviewRequestState::Open,
                status_summary: None,
                target_branch: "main".to_string(),
                title: "Update workflow".to_string(),
                web_url: url.to_string(),
            },
        });

        session
    }

    #[test]
    fn test_session_header_lines_keeps_review_request_url_on_same_line_if_it_fits() {
        // Arrange
        let session = session_with_review_request("https://github.com/agentty-xyz/agentty/pull/42");
        let header_width = 180;

        // Act
        let header_lines =
            session_header_lines(&session, header_width, ReasoningLevel::default(), 0);
        let metadata_line = header_lines[1].to_string();

        // Assert
        assert_eq!(header_lines.len(), 2);
        assert_eq!(metadata_line.chars().count(), usize::from(header_width));
        assert!(metadata_line.contains("Tokens: 0/0"));
        assert!(metadata_line.ends_with("https://github.com/agentty-xyz/agentty/pull/42"));
    }

    #[test]
    fn test_session_header_lines_wraps_review_request_url_to_second_line_when_too_narrow() {
        // Arrange
        let session = session_with_review_request("https://example.test/pull/42");

        // Act
        let header_lines = session_header_lines(&session, 60, ReasoningLevel::default(), 0);
        let metadata_line = header_lines[1].to_string();
        let review_url_line = header_lines[2].to_string();

        // Assert
        assert_eq!(header_lines.len(), 3);
        assert!(metadata_line.contains("Size: XS"));
        assert!(review_url_line.starts_with("https://"));
        assert!(review_url_line.ends_with("https://example.test/pull/42"));
    }

    #[test]
    fn test_session_metadata_text_omits_review_request_url() {
        // Arrange
        let session = session_with_review_request("https://example.test/pull/42");

        // Act
        let metadata_text = session_metadata_text(&session, 160, ReasoningLevel::default(), 0);

        // Assert
        assert!(metadata_text.contains("Tokens: 0/0"));
        assert!(!metadata_text.contains("https://example.test/pull/42"));
    }

    #[test]
    fn test_session_metadata_text_prints_agent_before_model() {
        // Arrange
        let mut session = SessionFixtureBuilder::new().build();
        session.agent = crate::domain::agent::AgentSelection::new(
            crate::domain::agent::AgentKind::Codex,
            AgentModel::Gpt55,
        );

        // Act
        let metadata_text = session_metadata_text(&session, 160, ReasoningLevel::default(), 0);

        // Assert
        assert!(metadata_text.contains("Agent: codex  Model: gpt-5.5"));
    }

    #[test]
    fn test_session_output_uses_tachyon_loader_for_animated_statuses() {
        // Arrange
        let animated_statuses = [
            Status::InProgress,
            Status::AgentReview,
            Status::Rebasing,
            Status::Merging,
            Status::Merged,
        ];
        let static_statuses = [
            Status::Draft,
            Status::Review,
            Status::Question,
            Status::Queued,
            Status::Done,
            Status::Canceled,
        ];

        // Act
        let animated_results = animated_statuses.map(session_output_uses_tachyon_loader);
        let static_results = static_statuses.map(session_output_uses_tachyon_loader);

        // Assert
        assert!(animated_results.into_iter().all(|uses_loader| uses_loader));
        assert!(static_results.into_iter().all(|uses_loader| !uses_loader));
    }

    #[test]
    fn merged_session_output_explains_manual_sync_wait() {
        // Arrange
        let status = Status::Merged;

        // Act
        let message = session_output_status_message(status, None, None);
        let icon = session_output_status_icon(status);

        // Assert
        assert_eq!(message, "Waiting for manual local target sync...");
        assert!(matches!(icon, Icon::TachyonLoader));
    }
}