agentty 0.10.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
use ag_forge::RequestedReview;
use ratatui::layout::Rect;

use super::help_action::{self, HelpAction, ViewHelpState, ViewSessionState};
use super::prompt::{
    PromptAtMentionState, PromptAttachmentState, PromptHistoryState, PromptSlashState,
};
use crate::domain::input::InputState;
use crate::domain::question::QuestionItem;
use crate::domain::session::{PublishBranchAction, SessionId};

/// Semantic intent for a `Confirmation` overlay interaction.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ConfirmationIntent {
    /// Confirms quitting the application.
    Quit,
    /// Confirms canceling a selected review session.
    CancelSession,
    /// Confirms creating a continuation draft from one terminal session.
    ContinueSession,
    /// Confirms queueing merge for the active view session.
    MergeSession,
    /// Confirms regenerating the focused review for the active view session.
    RegenerateReview,
}

/// Stored view-mode values used to restore session view after session-scoped
/// confirmations and overlays.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ConfirmationViewMode {
    pub review_status_message: Option<String>,
    pub review_text: Option<String>,
    pub scroll_offset: Option<u16>,
    pub session_id: SessionId,
}

impl ConfirmationViewMode {
    /// Restores this snapshot as `AppMode::View`.
    #[must_use]
    pub fn into_view_mode(self) -> AppMode {
        AppMode::View {
            review_status_message: self.review_status_message,
            review_text: self.review_text,
            session_id: self.session_id,
            scroll_offset: self.scroll_offset,
        }
    }
}

/// Cached scroll bounds for the current diff selection and content area.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DiffScrollCache {
    pub content_area: Rect,
    pub file_explorer_selected_index: usize,
    pub max_scroll_offset: u16,
}

/// Selects which content pane is shown on the right side of the diff page.
///
/// The diff page hosts two semantically related views:
///
/// - [`DiffRightPanel::Diff`] renders the raw git diff for the selected file.
/// - [`DiffRightPanel::Comments`] renders cached review-request comments for
///   the selected file, or the review-request-wide conversation comments when
///   the synthetic "General discussion" entry is selected.
///
/// Users toggle between panels with the `c` key while in the diff page.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum DiffRightPanel {
    /// Shows the git diff content for the current file selection.
    #[default]
    Diff,
    /// Shows cached review-request comments for the current file selection.
    Comments,
}

impl DiffRightPanel {
    /// Returns the opposite panel selection.
    #[must_use]
    pub const fn toggled(self) -> Self {
        match self {
            Self::Diff => Self::Comments,
            Self::Comments => Self::Diff,
        }
    }
}

/// Captured question-mode state for restoring after diff preview.
///
/// When the user opens diff preview from question mode (`d` key while chat
/// is focused), the full question state is snapshotted here so it can be
/// restored when leaving the diff view.
pub struct QuestionModeSnapshot {
    pub at_mention_state: Option<PromptAtMentionState>,
    pub current_index: usize,
    pub input: InputState,
    pub questions: Vec<QuestionItem>,
    pub review_status_message: Option<String>,
    pub review_text: Option<String>,
    pub responses: Vec<String>,
    pub scroll_offset: Option<u16>,
    pub selected_option_index: Option<usize>,
    pub session_id: SessionId,
}

impl QuestionModeSnapshot {
    /// Restores this snapshot as `AppMode::Question` with `Answer` focus.
    #[must_use]
    pub fn into_question_mode(self) -> AppMode {
        AppMode::Question {
            at_mention_state: self.at_mention_state,
            current_index: self.current_index,
            focus: QuestionFocus::Answer,
            input: self.input,
            questions: self.questions,
            review_status_message: self.review_status_message,
            review_text: self.review_text,
            responses: self.responses,
            scroll_offset: self.scroll_offset,
            selected_option_index: self.selected_option_index,
            session_id: self.session_id,
        }
    }
}

/// Tracks which panel has input focus during question-answer mode.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum QuestionFocus {
    /// Question panel is focused for option navigation or free-text input.
    #[default]
    Answer,
    /// Chat output area is focused for scrolling.
    Chat,
}

/// Represents the active UI mode for the application.
pub enum AppMode {
    List,
    /// Displays the selected forge review request title and description.
    ReviewDetail {
        /// Requested review snapshot opened from the top-level review list.
        review: RequestedReview,
        /// Vertical offset applied to the rendered review description page.
        scroll_offset: u16,
    },
    /// Displays the session creation selector above the sessions list.
    SessionCreation {
        /// Highlighted session creation option.
        selected_option_index: usize,
    },
    /// Displays a generic confirmation overlay with `Yes` and `No` options.
    Confirmation {
        /// Semantic action to execute when users choose `Yes`.
        confirmation_intent: ConfirmationIntent,
        confirmation_message: String,
        confirmation_title: String,
        /// View state to restore when dismissing a session-scoped
        /// confirmation.
        restore_view: Option<ConfirmationViewMode>,
        session_id: Option<SessionId>,
        selected_confirmation_index: usize,
    },
    /// Informational popup displayed for sync outcomes, including success and
    /// blocked/failed states.
    SyncBlockedPopup {
        /// Selected project name for which sync was requested.
        project_name: Option<String>,
        /// Repository default branch used as sync target.
        default_branch: Option<String>,
        /// Whether sync is still running in the background.
        is_loading: bool,
        /// Body text describing current sync state or final outcome.
        message: String,
        /// Popup title describing sync state.
        title: String,
    },
    /// Informational popup rendered above session view for review-request
    /// workflows.
    ViewInfoPopup {
        /// Whether the background review-request workflow is still running.
        is_loading: bool,
        /// Spinner label rendered while the popup remains in the loading
        /// state.
        loading_label: String,
        /// Body text describing the current review-request outcome.
        message: String,
        /// View state restored after the popup is dismissed.
        restore_view: ConfirmationViewMode,
        /// Popup title describing the current review-request phase.
        title: String,
    },
    /// Command selector overlay opened from session view when multiple open
    /// commands are configured.
    OpenCommandSelector {
        /// Available open commands in display/selection order.
        commands: Vec<String>,
        /// View state restored after command selection or cancel.
        restore_view: ConfirmationViewMode,
        /// Highlighted command index in `commands`.
        selected_command_index: usize,
    },
    /// Session-view popup that collects an optional remote branch name before
    /// publishing or refreshing the current forge review request.
    PublishBranchInput {
        /// Default remote branch name used when users leave the field blank.
        default_branch_name: String,
        /// Editable remote branch name. An empty value keeps the default push
        /// target for the session branch before review-request publication.
        input: InputState,
        /// Existing upstream reference, when the session branch already tracks
        /// one remote branch and the input must stay locked.
        locked_upstream_ref: Option<String>,
        /// Publish action that will run when users confirm the popup.
        publish_branch_action: PublishBranchAction,
        /// View state restored after publish or cancel.
        restore_view: ConfirmationViewMode,
    },
    /// Session chat composer for the first prompt or a follow-up reply.
    Prompt {
        /// Active `@`-mention dropdown state for file and directory lookup.
        at_mention_state: Option<PromptAtMentionState>,
        /// Ordered local image attachments referenced by inline placeholders in
        /// `input`.
        attachment_state: PromptAttachmentState,
        /// Prompt-history navigation state for `Up`/`Down`.
        history_state: PromptHistoryState,
        /// Focused-review status text preserved while the composer is open so
        /// canceling the prompt restores the same session output view.
        review_status_message: Option<String>,
        /// Focused-review output preserved while the composer is open so the
        /// session transcript remains stable until a new prompt is submitted.
        review_text: Option<String>,
        /// Slash-command selection state for the current prompt input.
        slash_state: PromptSlashState,
        /// Session whose prompt composer is currently active.
        session_id: SessionId,
        /// Editable prompt text, including inline attachment placeholders.
        input: InputState,
        /// Scroll position applied to the session transcript above the
        /// composer.
        scroll_offset: Option<u16>,
    },
    View {
        /// Optional status line shown while review text is loading or
        /// unavailable.
        review_status_message: Option<String>,
        /// Agent-assisted review text for the active session.
        review_text: Option<String>,
        session_id: SessionId,
        scroll_offset: Option<u16>,
    },
    /// Focused diff view with file-tree navigation and independent scrolling.
    ///
    /// The right-hand panel shows either the raw git diff or cached
    /// review-request comments, selected by `right_panel`. Users toggle
    /// between the panels with the `c` key while the mode is active.
    Diff {
        /// Raw git diff rendered in the right-hand panel when `right_panel` is
        /// [`DiffRightPanel::Diff`].
        diff: String,
        /// Selected file or folder in the left explorer tree.
        file_explorer_selected_index: usize,
        /// Captured question state restored when leaving diff, if the diff was
        /// opened from question mode. `None` restores to `View` mode.
        restore_question: Option<QuestionModeSnapshot>,
        /// Active right-hand panel selection.
        right_panel: DiffRightPanel,
        /// Cached max scroll bound for the current content-area and selection.
        scroll_cache: Option<DiffScrollCache>,
        /// Vertical offset inside the rendered right panel.
        scroll_offset: u16,
        /// Session whose diff and review-comments are currently visible.
        session_id: SessionId,
    },

    /// Interactive clarification flow that asks agent questions one-by-one.
    Question {
        /// File/directory mention dropdown state for the free-text input.
        at_mention_state: Option<PromptAtMentionState>,
        /// Focused-review status text kept visible above the clarification
        /// panel while a review is still loading or has failed.
        review_status_message: Option<String>,
        /// Focused-review output kept visible above the clarification panel so
        /// question mode does not hide the latest assisted review block.
        review_text: Option<String>,
        /// Session receiving the follow-up clarification reply.
        session_id: SessionId,
        /// Ordered clarification prompts emitted by the model.
        questions: Vec<QuestionItem>,
        /// Collected user responses aligned to `questions`.
        responses: Vec<String>,
        /// Active question index inside `questions`.
        current_index: usize,
        /// Which panel currently owns keyboard focus.
        focus: QuestionFocus,
        /// Editable response input for the active question.
        input: InputState,
        /// Scroll position applied to the session transcript above the
        /// question panel.
        scroll_offset: Option<u16>,
        /// Highlighted option index when the current question has predefined
        /// options. `None` means free-text input is active.
        selected_option_index: Option<usize>,
    },

    Help {
        context: HelpContext,
        scroll_offset: u16,
    },
}

/// Captures which page opened the help overlay so it can be restored on close.
pub enum HelpContext {
    /// Generic list-mode help context with precomputed keybindings.
    List { keybindings: Vec<HelpAction> },
    View {
        can_open_worktree: bool,
        review_status_message: Option<String>,
        review_text: Option<String>,
        publish_pull_request_action: Option<PublishBranchAction>,
        session_id: SessionId,
        session_state: ViewSessionState,
        scroll_offset: Option<u16>,
    },
    Diff {
        diff: String,
        file_explorer_selected_index: usize,
        /// Preserved question-mode snapshot so the help→diff→exit path can
        /// still return to question mode when the diff was opened from there.
        restore_question: Option<QuestionModeSnapshot>,
        /// Right-hand panel selection preserved across help entry/exit so the
        /// comments/diff toggle survives the help overlay.
        right_panel: DiffRightPanel,
        session_id: SessionId,
        scroll_offset: u16,
    },
}

impl HelpContext {
    /// Returns projected keybinding entries for the originating page.
    pub fn keybindings(&self) -> Vec<HelpAction> {
        match self {
            HelpContext::View {
                can_open_worktree,
                publish_pull_request_action,
                session_state,
                ..
            } => help_action::view_actions(ViewHelpState {
                can_open_worktree: *can_open_worktree,
                publish_pull_request_action: *publish_pull_request_action,
                session_state: *session_state,
            }),
            HelpContext::List { keybindings } => keybindings.clone(),
            HelpContext::Diff { right_panel, .. } => help_action::diff_actions(*right_panel),
        }
    }

    /// Reconstructs the `AppMode` that was active before help was opened.
    pub fn restore_mode(self) -> AppMode {
        match self {
            HelpContext::List { .. } => AppMode::List,
            HelpContext::View {
                review_status_message,
                review_text,
                publish_pull_request_action: _,
                session_id,
                scroll_offset,
                ..
            } => AppMode::View {
                review_status_message,
                review_text,
                session_id,
                scroll_offset,
            },
            HelpContext::Diff {
                diff,
                file_explorer_selected_index,
                restore_question,
                right_panel,
                session_id,
                scroll_offset,
            } => AppMode::Diff {
                diff,
                file_explorer_selected_index,
                restore_question,
                right_panel,
                scroll_cache: None,
                session_id,
                scroll_offset,
            },
        }
    }

    /// Display title for the help overlay header.
    pub fn title(&self) -> &'static str {
        "Keybindings"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::review_loading_message;
    use crate::domain::agent::AgentModel;
    use crate::domain::session::PublishBranchAction;

    #[test]
    fn test_confirmation_view_mode_into_view_mode_restores_snapshot_values() {
        // Arrange
        let confirmation_view_mode = ConfirmationViewMode {
            review_status_message: Some(review_loading_message(AgentModel::Gpt55)),
            review_text: Some("Critical finding".to_string()),
            scroll_offset: Some(7),
            session_id: "session-id".into(),
        };

        // Act
        let mode = confirmation_view_mode.into_view_mode();

        // Assert
        assert!(matches!(
            mode,
            AppMode::View {
                review_status_message: Some(ref review_status_message),
                review_text: Some(ref review_text),
                ref session_id,
                scroll_offset: Some(7),
            } if session_id == "session-id"
                && review_status_message == &review_loading_message(AgentModel::Gpt55)
                && review_text == "Critical finding"
        ));
    }

    #[test]
    fn test_help_context_view_keybindings_for_in_progress_hide_edit_actions() {
        // Arrange
        let context = HelpContext::View {
            can_open_worktree: true,
            review_status_message: None,
            review_text: None,
            publish_pull_request_action: None,
            session_id: "session-id".into(),
            session_state: ViewSessionState::InProgress,
            scroll_offset: Some(2),
        };

        // Act
        let bindings = context.keybindings();

        // Assert
        assert!(bindings.iter().any(|binding| binding.key == "q"));
        assert!(bindings.iter().any(|binding| binding.key == "j/k"));
        assert!(bindings.iter().any(|binding| binding.key == "?"));
        assert!(bindings.iter().any(|binding| binding.key == "Ctrl+c"));
        assert!(!bindings.iter().any(|binding| binding.key == "Enter"));
        assert!(!bindings.iter().any(|binding| binding.key == "d"));
        assert!(!bindings.iter().any(|binding| binding.key == "m"));
        assert!(!bindings.iter().any(|binding| binding.key == "r"));
        assert!(!bindings.iter().any(|binding| binding.key == "S-Tab"));
    }

    #[test]
    fn test_help_context_restore_mode_ignores_help_only_view_fields() {
        // Arrange
        let context = HelpContext::View {
            can_open_worktree: true,
            review_status_message: Some(review_loading_message(AgentModel::Gpt55)),
            review_text: Some("Ready".to_string()),
            publish_pull_request_action: Some(PublishBranchAction::PublishPullRequest),
            session_id: "session-id".into(),
            session_state: ViewSessionState::InProgress,
            scroll_offset: Some(4),
        };

        // Act
        let mode = context.restore_mode();

        // Assert
        assert!(matches!(
            mode,
            AppMode::View {
                ref session_id,
                review_status_message: Some(ref review_status_message),
                review_text: Some(ref review_text),
                scroll_offset: Some(4),
                ..
            } if session_id == "session-id"
                && review_status_message == &review_loading_message(AgentModel::Gpt55)
                && review_text == "Ready"
        ));
    }

    #[test]
    fn test_help_context_view_keybindings_include_publish_pull_request_action() {
        // Arrange
        let context = HelpContext::View {
            can_open_worktree: true,
            review_status_message: None,
            review_text: None,
            publish_pull_request_action: Some(PublishBranchAction::PublishPullRequest),
            session_id: "session-id".into(),
            session_state: ViewSessionState::Interactive,
            scroll_offset: None,
        };

        // Act
        let bindings = context.keybindings();

        // Assert
        assert!(bindings.iter().any(|binding| binding.key == "p"));
    }

    #[test]
    fn test_help_context_list_keybindings_return_stored_actions() {
        // Arrange
        let keybindings = vec![
            HelpAction::new("quit", "q", "Quit"),
            HelpAction::new("help", "?", "Help"),
        ];
        let context = HelpContext::List { keybindings };

        // Act
        let bindings = context.keybindings();

        // Assert
        assert_eq!(bindings.len(), 2);
        assert!(bindings.iter().any(|binding| binding.key == "q"));
        assert!(bindings.iter().any(|binding| binding.key == "?"));
    }
}