agentty 0.13.2

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
use ag_forge::{AssignedIssue, IssueDetail, RequestedReview};

use super::help_action::{
    self, HelpAction, ViewActionAvailability, 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 forking a root review-ready session into a new session.
    ForkSession,
    /// 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 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 {
            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: ViewportRect,
    pub file_explorer_selected_index: usize,
    pub max_scroll_offset: u16,
}

/// Frontend-neutral rectangular viewport coordinates.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ViewportRect {
    pub height: u16,
    pub width: u16,
    pub x: u16,
    pub y: u16,
}

/// 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 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 `Input` 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: ChatFocus::Input,
            input: self.input,
            questions: self.questions,
            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 on the session chat page.
///
/// Both the prompt composer and the question panel share this focus model:
/// `Tab` moves focus to the transcript for scrolling and back to the bottom
/// input panel.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ChatFocus {
    /// Bottom input panel is focused for typing, option navigation, or
    /// submission.
    #[default]
    Input,
    /// Chat output area is focused for scrolling.
    Chat,
}

/// Represents the active UI mode for the application.
pub enum AppMode {
    List,
    /// Displays a selected assigned issue while its base details load and
    /// after the detail request completes.
    IssueDetail {
        /// Loaded base details, excluding comments.
        detail: Option<IssueDetail>,
        /// User-facing detail-load failure.
        error: Option<String>,
        /// Assigned-issue row opened from the top-level issue list.
        issue: AssignedIssue,
        /// Vertical offset applied to the rendered issue detail page.
        scroll_offset: u16,
    },
    /// Displays the selected forge review request title, description, comment
    /// loading state, loaded comments, and any comment-load failure.
    ReviewDetail {
        /// User-facing comment-load failure shown in the comments section.
        comment_error: Option<String>,
        /// Whether a background task is fetching the selected review's
        /// comment snapshot.
        is_loading_comments: bool,
        /// 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 an advisory before opening the session creation selector.
    PreCommitHookWarning {
        /// Full warning text, installation commands, and future-enforcement
        /// guidance.
        message: String,
    },
    /// Displays the MRU-ordered project switcher popup above the sessions
    /// list.
    ProjectSwitcher {
        /// Highlighted project row in most-recently-opened order.
        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 above the list for sync outcomes,
    /// including success and blocked/failed states, and for other list-level
    /// action failures such as a failed project switch.
    SyncBlockedPopup {
        /// Project name the reported action applies to, when the action was
        /// scoped to one project.
        project_name: Option<String>,
        /// Repository default branch used as sync target. Stays `None` for
        /// actions that have no branch target, such as a project switch.
        default_branch: Option<String>,
        /// Whether the reported action is still running in the background.
        is_loading: bool,
        /// Body text describing the current action state or final outcome.
        message: String,
        /// Popup title describing the reported action.
        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,
    },
    /// Launch-configuration selector overlay opened from session view when
    /// multiple entries are configured.
    LaunchConfigurationSelector {
        /// Available launch configurations in display/selection order.
        commands: Vec<String>,
        /// View state restored after launch-configuration selection or cancel.
        restore_view: ConfirmationViewMode,
        /// Highlighted launch-configuration 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,
        /// Panel that currently receives key input: the composer or the chat
        /// transcript above it.
        focus: ChatFocus,
        /// Prompt-history navigation state for `Up`/`Down`.
        history_state: PromptHistoryState,
        /// 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 {
        session_id: SessionId,
        scroll_offset: Option<u16>,
    },
    /// Focused diff view with file-tree navigation and independent scrolling.
    Diff {
        /// Raw git diff rendered in the right-hand panel.
        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>,
        /// 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 is 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>,
        /// 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: ChatFocus,
        /// 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_fork_session: bool,
        can_merge_session_branch: bool,
        can_mutate_session_branch: bool,
        can_open_worktree: bool,
        can_rebase_session_branch: bool,
        can_reply_to_session: bool,
        can_start_staged_session: bool,
        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>,
        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_fork_session,
                can_merge_session_branch,
                can_mutate_session_branch,
                can_open_worktree,
                can_rebase_session_branch,
                can_reply_to_session,
                can_start_staged_session,
                publish_pull_request_action,
                session_state,
                ..
            } => help_action::view_actions(ViewHelpState {
                can_fork_session: ViewActionAvailability::from_bool(*can_fork_session),
                can_merge_session_branch: ViewActionAvailability::from_bool(
                    *can_merge_session_branch,
                ),
                can_mutate_session_branch: ViewActionAvailability::from_bool(
                    *can_mutate_session_branch,
                ),
                can_open_worktree: ViewActionAvailability::from_bool(*can_open_worktree),
                can_rebase_session_branch: ViewActionAvailability::from_bool(
                    *can_rebase_session_branch,
                ),
                reply_to_session: ViewActionAvailability::from_bool(*can_reply_to_session),
                can_start_staged_session: ViewActionAvailability::from_bool(
                    *can_start_staged_session,
                ),
                publish_pull_request_action: *publish_pull_request_action,
                session_state: *session_state,
            }),
            HelpContext::List { keybindings } => keybindings.clone(),
            HelpContext::Diff { .. } => help_action::diff_actions(),
        }
    }

    /// Reconstructs the `AppMode` that was active before help was opened.
    pub fn restore_mode(self) -> AppMode {
        match self {
            HelpContext::List { .. } => AppMode::List,
            HelpContext::View {
                publish_pull_request_action: _,
                session_id,
                scroll_offset,
                ..
            } => AppMode::View {
                session_id,
                scroll_offset,
            },
            HelpContext::Diff {
                diff,
                file_explorer_selected_index,
                restore_question,
                session_id,
                scroll_offset,
            } => AppMode::Diff {
                diff,
                file_explorer_selected_index,
                restore_question,
                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::domain::session::PublishBranchAction;

    #[test]
    fn test_confirmation_view_mode_into_view_mode_restores_view_identity() {
        // Arrange
        let confirmation_view_mode = ConfirmationViewMode {
            scroll_offset: Some(7),
            session_id: "session-id".into(),
        };

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

        // Assert
        assert!(matches!(
            mode,
            AppMode::View {
                ref session_id,
                scroll_offset: Some(7),
            } if session_id == "session-id"
        ));
    }

    #[test]
    fn test_help_context_view_keybindings_for_in_progress_show_sync_and_hide_edit_actions() {
        // Arrange
        let context = HelpContext::View {
            can_fork_session: true,
            can_merge_session_branch: true,
            can_mutate_session_branch: true,
            can_open_worktree: true,
            can_rebase_session_branch: true,
            can_reply_to_session: true,
            can_start_staged_session: false,
            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 == "r"));
        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 == "S-Tab"));
    }

    #[test]
    fn test_help_context_restore_mode_ignores_help_only_view_fields() {
        // Arrange
        let context = HelpContext::View {
            can_fork_session: true,
            can_merge_session_branch: true,
            can_mutate_session_branch: true,
            can_open_worktree: true,
            can_rebase_session_branch: true,
            can_reply_to_session: true,
            can_start_staged_session: false,
            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,
                scroll_offset: Some(4),
                ..
            } if session_id == "session-id"
        ));
    }

    #[test]
    fn test_help_context_view_keybindings_include_publish_pull_request_action() {
        // Arrange
        let context = HelpContext::View {
            can_fork_session: true,
            can_merge_session_branch: true,
            can_mutate_session_branch: true,
            can_open_worktree: true,
            can_rebase_session_branch: true,
            can_reply_to_session: true,
            can_start_staged_session: false,
            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 == "?"));
    }
}