agentty 0.9.3

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 std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{LazyLock, Mutex};
use std::time::Duration;

use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tracing::warn;

use crate::app::AppEvent;
use crate::app::session::SessionManager;
use crate::domain::file_entry::FileEntry;
use crate::domain::input::InputState;
use crate::domain::session::SessionId;
use crate::infra::file_index;
use crate::ui::state::prompt::PromptAtMentionState;

/// Delay applied before a fresh `@`-mention filesystem walk starts.
const AT_MENTION_LOAD_DEBOUNCE: Duration = Duration::from_millis(75);
/// Monotonic counter used to distinguish stale and current load tasks.
static NEXT_AT_MENTION_REQUEST_ID: AtomicU64 = AtomicU64::new(1);
/// Per-session debounced file-index tasks keyed by session identifier.
static PENDING_AT_MENTION_LOADS: LazyLock<Mutex<HashMap<SessionId, PendingAtMentionLoad>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

/// Describes how one mode should update its visible `@`-mention state after an
/// input edit or cursor move.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum AtMentionSyncAction {
    /// Open the dropdown and start loading entries.
    Activate,
    /// Hide the dropdown because the cursor no longer sits inside an `@` token.
    Dismiss,
    /// Keep the dropdown open and reset its selected row.
    KeepOpen,
}

/// Text replacement derived from the currently highlighted `@`-mention row.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct AtMentionSelection {
    /// End character index of the active `@query`.
    pub cursor: usize,
    /// Replacement text inserted into the input.
    pub text: String,
    /// Start character index of the active `@query`.
    pub at_start: usize,
}

/// Tracks one debounced background file-index load for a session.
struct PendingAtMentionLoad {
    /// Background task that sleeps, walks, and publishes the latest entries.
    handle: JoinHandle<()>,
    /// Monotonic identifier used to ignore stale completions.
    request_id: u64,
}

/// Returns the next `@`-mention sync action for one input buffer and dropdown
/// state pair.
pub(crate) fn sync_action(
    input: &InputState,
    at_mention_state: Option<&PromptAtMentionState>,
) -> AtMentionSyncAction {
    match (
        input.at_mention_query().is_some(),
        at_mention_state.is_some(),
    ) {
        (true, true) => AtMentionSyncAction::KeepOpen,
        (true, false) => AtMentionSyncAction::Activate,
        (false, _) => AtMentionSyncAction::Dismiss,
    }
}

/// Starts asynchronous loading of `@`-mention entries for one composer root.
///
/// When a fresh cache entry already exists for `lookup_root`, this emits the
/// loaded event immediately and skips the debounced filesystem walk.
pub(crate) fn start_loading_entries(
    event_tx: mpsc::UnboundedSender<AppEvent>,
    lookup_root: PathBuf,
    session_id: SessionId,
    session_manager: &mut SessionManager,
) {
    if let Some(entries) = session_manager.at_mention_index_for_root(&lookup_root) {
        if event_tx
            .send(AppEvent::AtMentionEntriesLoaded {
                entries,
                session_id: session_id.clone(),
            })
            .is_err()
        {
            warn!(
                session_id = %session_id,
                "failed to publish cached at-mention entries because the app event receiver is closed"
            );
        }

        return;
    }

    let request_id = NEXT_AT_MENTION_REQUEST_ID.fetch_add(1, Ordering::Relaxed);
    let tracked_session_id = session_id.clone();
    let task_session_id = session_id.clone();
    let handle = tokio::spawn(async move {
        tokio::time::sleep(AT_MENTION_LOAD_DEBOUNCE).await;

        let entries =
            match tokio::task::spawn_blocking(move || file_index::list_files(&lookup_root)).await {
                Ok(entries) => entries,
                Err(error) => {
                    warn!(
                        session_id = %session_id,
                        error = %error,
                        "failed to join at-mention file index task"
                    );

                    Vec::new()
                }
            };

        if event_tx
            .send(AppEvent::AtMentionEntriesLoaded {
                entries,
                session_id: session_id.clone(),
            })
            .is_err()
        {
            warn!(
                session_id = %session_id,
                "failed to publish at-mention entries because the app event receiver is closed"
            );
        }

        finish_pending_load(&task_session_id, request_id);
    });

    track_pending_load(tracked_session_id, request_id, handle);
}

/// Aborts and removes any pending debounced load for one session.
pub(crate) fn clear_pending_load(session_id: &str) {
    if let Ok(mut pending_loads) = PENDING_AT_MENTION_LOADS.lock()
        && let Some(pending_load) = pending_loads.remove(session_id)
    {
        pending_load.handle.abort();
    }
}

/// Stores the latest pending load task for one session and aborts any stale
/// debounced predecessor.
fn track_pending_load(session_id: SessionId, request_id: u64, handle: JoinHandle<()>) {
    if let Ok(mut pending_loads) = PENDING_AT_MENTION_LOADS.lock()
        && let Some(previous_task) =
            pending_loads.insert(session_id, PendingAtMentionLoad { handle, request_id })
    {
        previous_task.handle.abort();
    }
}

/// Clears a pending task entry when the completing request is still current.
fn finish_pending_load(session_id: &str, request_id: u64) {
    if let Ok(mut pending_loads) = PENDING_AT_MENTION_LOADS.lock()
        && pending_loads
            .get(session_id)
            .is_some_and(|task| task.request_id == request_id)
    {
        pending_loads.remove(session_id);
    }
}

/// Returns the directory that should back one active `@`-mention lookup.
///
/// Materialized sessions index their worktree folder. Unstarted draft sessions
/// have no worktree yet, so the active project working directory is used until
/// the deferred worktree exists.
pub(crate) fn lookup_root(
    project_working_dir: PathBuf,
    session_folder: Option<PathBuf>,
    has_session_folder: bool,
) -> PathBuf {
    if has_session_folder && let Some(session_folder) = session_folder {
        return session_folder;
    }

    project_working_dir
}

/// Clears one visible `@`-mention dropdown state.
pub(crate) fn dismiss(at_mention_state: &mut Option<PromptAtMentionState>) {
    *at_mention_state = None;
}

/// Resets the highlighted `@`-mention row to the first visible entry.
pub(crate) fn reset_selection(at_mention_state: &mut PromptAtMentionState) {
    at_mention_state.selected_index = 0;
}

/// Moves the highlighted `@`-mention row up by one item.
pub(crate) fn move_selection_up(at_mention_state: &mut PromptAtMentionState) {
    at_mention_state.selected_index = at_mention_state.selected_index.saturating_sub(1);
}

/// Moves the highlighted `@`-mention row down by one filtered item.
pub(crate) fn move_selection_down(input: &InputState, at_mention_state: &mut PromptAtMentionState) {
    let filtered_count =
        filtered_entries(input, at_mention_state).map_or(0_usize, |entries| entries.len());
    let max_index = filtered_count.saturating_sub(1);

    at_mention_state.selected_index = (at_mention_state.selected_index + 1).min(max_index);
}

/// Returns the replacement text for the highlighted `@`-mention entry, if the
/// input still contains an active `@query`.
pub(crate) fn selected_replacement(
    input: &InputState,
    at_mention_state: &PromptAtMentionState,
) -> Option<AtMentionSelection> {
    let (at_start, query) = input.at_mention_query()?;
    let filtered = file_index::filter_entries(&at_mention_state.all_entries, &query);
    let clamped_index = at_mention_state
        .selected_index
        .min(filtered.len().saturating_sub(1));

    filtered.get(clamped_index).map(|entry| AtMentionSelection {
        at_start,
        cursor: input.cursor,
        text: format_mention_text(entry),
    })
}

/// Returns the filtered `@`-mention entries for the current input query.
fn filtered_entries<'a>(
    input: &InputState,
    at_mention_state: &'a PromptAtMentionState,
) -> Option<Vec<&'a FileEntry>> {
    let (_, query) = input.at_mention_query()?;

    Some(file_index::filter_entries(
        &at_mention_state.all_entries,
        &query,
    ))
}

/// Formats one selected file or directory entry for insertion into the input.
fn format_mention_text(entry: &FileEntry) -> String {
    if entry.is_dir {
        return format!("@{}/ ", entry.path);
    }

    format!("@{} ", entry.path)
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::sync::Arc;

    use ratatui::widgets::TableState;
    use tempfile::TempDir;

    use super::*;
    use crate::app::SessionState;
    use crate::app::session::{RealClock, SessionDefaults};
    use crate::domain::agent::AgentModel;
    use crate::domain::session::{Session, SessionHandles, SessionSize, SessionStats, Status};
    use crate::infra::git;

    #[test]
    fn test_sync_action_requests_activation_for_new_query() {
        // Arrange
        let input = InputState::with_text("@src".to_string());

        // Act
        let action = sync_action(&input, None);

        // Assert
        assert_eq!(action, AtMentionSyncAction::Activate);
    }

    #[test]
    fn test_move_selection_down_clamps_to_last_filtered_entry() {
        // Arrange
        let input = InputState::with_text("@src".to_string());
        let mut at_mention_state = PromptAtMentionState::new(vec![
            FileEntry {
                is_dir: true,
                path: "src".to_string(),
            },
            FileEntry {
                is_dir: false,
                path: "src/lib.rs".to_string(),
            },
        ]);
        at_mention_state.selected_index = 99;

        // Act
        move_selection_down(&input, &mut at_mention_state);

        // Assert
        assert_eq!(at_mention_state.selected_index, 1);
    }

    #[test]
    fn test_selected_replacement_formats_directory_with_trailing_slash() {
        // Arrange
        let input = InputState::with_text("@src".to_string());
        let at_mention_state = PromptAtMentionState::new(vec![FileEntry {
            is_dir: true,
            path: "src".to_string(),
        }]);

        // Act
        let selection =
            selected_replacement(&input, &at_mention_state).expect("expected directory selection");

        // Assert
        assert_eq!(
            selection,
            AtMentionSelection {
                at_start: 0,
                cursor: 4,
                text: "@src/ ".to_string(),
            }
        );
    }

    #[test]
    fn test_lookup_root_prefers_materialized_session_folder() {
        // Arrange
        let project_working_dir = PathBuf::from("/project");
        let session_folder = PathBuf::from("/project/.agentty/session");

        // Act
        let lookup_root = lookup_root(project_working_dir, Some(session_folder.clone()), true);

        // Assert
        assert_eq!(lookup_root, session_folder);
    }

    #[test]
    fn test_lookup_root_falls_back_to_project_working_dir_without_session_folder() {
        // Arrange
        let project_working_dir = PathBuf::from("/project");
        let session_folder = PathBuf::from("/project/.agentty/session");

        // Act
        let lookup_root = lookup_root(project_working_dir.clone(), Some(session_folder), false);

        // Assert
        assert_eq!(lookup_root, project_working_dir);
    }

    #[tokio::test]
    async fn test_start_loading_entries_aborts_stale_debounced_loads() {
        // Arrange
        let temp_dir = TempDir::new().expect("create temp dir");
        let event_session_id = "session-1".to_string();
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        let mut initial_session_manager = test_session_manager(&event_session_id);
        std::fs::write(temp_dir.path().join("first.txt"), "").expect("write first file");

        start_loading_entries(
            event_tx.clone(),
            temp_dir.path().to_path_buf(),
            event_session_id.clone().into(),
            &mut initial_session_manager,
        );

        std::fs::write(temp_dir.path().join("second.txt"), "").expect("write second file");

        // Act
        let mut session_manager = test_session_manager(&event_session_id);

        start_loading_entries(
            event_tx,
            temp_dir.path().to_path_buf(),
            event_session_id.clone().into(),
            &mut session_manager,
        );
        let next_event = tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
            .await
            .expect("at-mention event should arrive")
            .expect("event channel should stay open");

        // Assert
        match next_event {
            AppEvent::AtMentionEntriesLoaded {
                entries,
                session_id,
            } => {
                assert_eq!(session_id, event_session_id);
                assert!(entries.iter().any(|entry| entry.path == "second.txt"));
            }
            _ => unreachable!("expected at-mention entries event"),
        }

        let extra_event = tokio::time::timeout(Duration::from_millis(250), event_rx.recv()).await;
        assert!(!matches!(
            extra_event,
            Ok(Some(AppEvent::AtMentionEntriesLoaded { .. }))
        ));
    }

    #[tokio::test]
    async fn test_clear_pending_load_aborts_pending_task_for_session() {
        // Arrange
        let temp_dir = TempDir::new().expect("create temp dir");
        let session_id = "session-1".to_string();
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();

        let mut session_manager = test_session_manager(&session_id);

        start_loading_entries(
            event_tx,
            temp_dir.path().to_path_buf(),
            session_id.clone().into(),
            &mut session_manager,
        );

        // Act
        clear_pending_load(&session_id);

        // Assert
        let next_event = tokio::time::timeout(Duration::from_millis(250), event_rx.recv()).await;
        assert!(!matches!(
            next_event,
            Ok(Some(AppEvent::AtMentionEntriesLoaded { .. }))
        ));
    }

    #[tokio::test]
    async fn test_start_loading_entries_uses_cached_index_without_debounced_walk() {
        // Arrange
        let temp_dir = TempDir::new().expect("create temp dir");
        let lookup_root = temp_dir.path().to_path_buf();
        let session_id = "session-1".to_string();
        let cached_entries = vec![FileEntry {
            is_dir: false,
            path: "src/main.rs".to_string(),
        }];
        let mut session_manager = test_session_manager(&session_id);
        session_manager.set_at_mention_index_for_root(lookup_root.clone(), cached_entries.clone());
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();

        // Act
        start_loading_entries(
            event_tx,
            lookup_root,
            session_id.clone().into(),
            &mut session_manager,
        );
        let next_event = tokio::time::timeout(Duration::from_millis(25), event_rx.recv())
            .await
            .expect("cached at-mention event should arrive immediately")
            .expect("event channel should stay open");

        // Assert
        assert_eq!(
            next_event,
            AppEvent::AtMentionEntriesLoaded {
                entries: cached_entries,
                session_id: session_id.into(),
            }
        );

        let extra_event = tokio::time::timeout(Duration::from_millis(125), event_rx.recv()).await;
        assert!(
            !matches!(
                extra_event,
                Ok(Some(AppEvent::AtMentionEntriesLoaded { .. }))
            ),
            "cache hits should not schedule a debounced filesystem walk"
        );
    }

    /// Builds a minimal `SessionManager` for cache tests.
    fn test_session_manager(session_id: &str) -> SessionManager {
        let mut handles = HashMap::new();
        handles.insert(
            session_id.to_string().into(),
            SessionHandles::new(String::new(), Status::Review),
        );

        let state = SessionState::new(
            handles,
            vec![Session {
                base_branch: "main".to_string(),
                created_at: 0,
                draft_attachments: Vec::new(),
                folder: PathBuf::from(format!("/tmp/{session_id}")),
                follow_up_tasks: Vec::new(),
                id: session_id.into(),
                in_progress_started_at: None,
                in_progress_total_seconds: 0,
                is_draft: false,
                model: AgentModel::Gpt54,
                output: String::new(),
                project_name: "project".to_string(),
                prompt: String::new(),
                queued_messages: Vec::new(),
                reasoning_level_override: None,
                published_upstream_ref: None,
                published_branch_sync_status:
                    crate::domain::session::PublishedBranchSyncStatus::Idle,
                questions: Vec::new(),
                review_request: None,
                size: SessionSize::Xs,
                stats: SessionStats::default(),
                status: Status::Review,
                summary: None,
                title: Some("Title".to_string()),
                updated_at: 0,
                workflow_notice: None,
            }],
            TableState::default(),
            Arc::new(RealClock),
            1,
            0,
        );

        SessionManager::new(
            SessionDefaults {
                model: AgentModel::Gpt54,
            },
            Arc::new(git::MockGitClient::new()),
            state,
            Vec::new(),
        )
    }
}