agentty 0.12.9

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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
//! Session lifecycle orchestration for creation, refresh, prompt handling,
//! history management, merge, and cleanup.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use ag_git as git;
use tokio::task::{JoinHandle, JoinSet};

use super::workflow::merge::SessionMergeService;
pub(crate) use super::workflow::merge::{SyncMainOutcome, SyncSessionStartError};
pub(crate) use super::workflow::task::{
    RunAgentAssistTaskInput, SessionTaskService, StatusTransition,
};
use super::workflow::worker::SessionWorkerService;
use crate::app::session_state::SessionGitStatus;
use crate::app::{AppServices, SessionState, setting};
use crate::domain::agent::{AgentModel, ReasoningLevel};
use crate::domain::file_entry::FileEntry;
use crate::domain::question::QuestionItem;
use crate::domain::session::{
    DailyActivity, FollowUpTaskAction, PublishedBranchSyncStatus, ReviewRequest, Session,
    SessionFollowUpTask, SessionId, SessionStats,
};

/// Low-frequency fallback interval for metadata-based session refresh.
pub(crate) const SESSION_REFRESH_INTERVAL: Duration = Duration::from_secs(5);
/// Cache duration for `@`-mention filesystem index snapshots.
pub(crate) const AT_MENTION_INDEX_TTL: Duration = Duration::from_secs(30);

/// Defaults used when creating new sessions from the UI.
#[derive(Clone, Copy)]
pub(crate) struct SessionDefaults {
    /// Default model selected for newly created sessions.
    pub(crate) model: AgentModel,
}

/// Borrowed session state required to draw one UI frame.
pub(crate) struct SessionRenderParts<'a> {
    /// Exact prompt transcript blocks keyed by session id for active turns.
    pub(crate) active_prompt_outputs: &'a HashMap<SessionId, String>,
    /// Detected session worktree branch names keyed by session id.
    pub(crate) session_branch_names: &'a HashMap<SessionId, String>,
    /// Latest session-branch ahead/behind snapshots keyed by session id.
    pub(crate) session_git_statuses: &'a HashMap<SessionId, SessionGitStatus>,
    /// Cached session list positions keyed by stable session id.
    pub(crate) session_index_by_id: &'a HashMap<SessionId, usize>,
    /// Whether each rendered session currently has a materialized worktree on
    /// disk, keyed by session id.
    pub(crate) session_worktree_availability: &'a HashMap<SessionId, bool>,
    /// Session rows available for rendering.
    pub(crate) sessions: &'a [Session],
    /// Daily session activity series used by dashboard activity summaries.
    pub(crate) stats_activity: &'a [DailyActivity],
    /// Selected session row index.
    pub(crate) selected_index: Option<usize>,
}

/// Reducer-facing snapshot derived from one persisted turn result.
///
/// The worker computes this projection immediately after writing canonical turn
/// metadata so the reducer can apply the same summary, clarification-question,
/// follow-up-task, and token-usage updates without waiting for a full reload.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct TurnAppliedState {
    /// Persisted follow-up tasks for the latest completed turn.
    pub(crate) follow_up_tasks: Vec<SessionFollowUpTask>,
    /// Persisted clarification questions for the latest completed turn.
    pub(crate) questions: Vec<QuestionItem>,
    /// Raw persisted summary payload, if the turn produced one.
    pub(crate) summary: Option<String>,
    /// Token-usage delta reported for the completed turn.
    pub(crate) token_usage_delta: SessionStats,
}

impl TurnAppliedState {
    /// Merges one newer reducer projection into this batched state.
    ///
    /// Latest-turn fields (`follow_up_tasks`, `questions`, `summary`) replace
    /// the previous projection, while `token_usage_delta` accumulates so
    /// multiple completed turns queued in one reducer tick do not undercount
    /// session usage.
    pub(crate) fn merge_newer(&mut self, newer_turn_applied_state: Self) {
        self.follow_up_tasks = newer_turn_applied_state.follow_up_tasks;
        self.questions = newer_turn_applied_state.questions;
        self.summary = newer_turn_applied_state.summary;
        self.token_usage_delta.input_tokens = self
            .token_usage_delta
            .input_tokens
            .saturating_add(newer_turn_applied_state.token_usage_delta.input_tokens);
        self.token_usage_delta.output_tokens = self
            .token_usage_delta
            .output_tokens
            .saturating_add(newer_turn_applied_state.token_usage_delta.output_tokens);
    }
}

pub(crate) use crate::infra::clock::Clock;

/// Session domain state and worker orchestration state.
pub struct SessionManager {
    pub(super) active_prompt_outputs: HashMap<SessionId, String>,
    at_mention_indexes: HashMap<PathBuf, AtMentionIndex>,
    pub(super) default_session_model: AgentModel,
    pub(super) git_client: Arc<dyn git::GitClient>,
    pub(super) merge_service: SessionMergeService,
    pub(super) pending_history_replay: HashSet<SessionId>,
    pub(super) published_branch_sync_operations: HashMap<SessionId, String>,
    pub(super) state: SessionState,
    pub(super) stats_activity: Vec<DailyActivity>,
    pub(super) title_generation_tasks: HashMap<SessionId, TitleGenerationTask>,
    pub(super) worker_service: SessionWorkerService,
}

/// Tracks one draft-title generation task plus the generation used to identify
/// stale completion events.
pub(crate) struct TitleGenerationTask {
    generation: u64,
    join_handle: JoinHandle<()>,
}

/// Cached `@`-mention file index snapshot for one lookup root.
#[derive(Debug)]
struct AtMentionIndex {
    created_at: Instant,
    entries: Vec<FileEntry>,
}

impl SessionManager {
    /// Creates a session manager from persisted snapshot state and defaults.
    ///
    /// Review sessions are marked for one-time transcript replay so the next
    /// reply can rehydrate provider context after app restart.
    pub(crate) fn new(
        defaults: SessionDefaults,
        git_client: Arc<dyn git::GitClient>,
        state: SessionState,
        stats_activity: Vec<DailyActivity>,
    ) -> Self {
        let pending_history_replay = Self::startup_history_replay_set(&state.sessions);

        Self {
            active_prompt_outputs: HashMap::new(),
            at_mention_indexes: HashMap::new(),
            default_session_model: defaults.model,
            git_client,
            merge_service: SessionMergeService,
            pending_history_replay,
            published_branch_sync_operations: HashMap::new(),
            state,
            stats_activity,
            title_generation_tasks: HashMap::new(),
            worker_service: SessionWorkerService::new(),
        }
    }

    /// Replaces any in-flight staged title-generation task for one session.
    ///
    /// The superseded task is aborted before the new task handle is stored so
    /// rapid draft staging does not fan out redundant provider requests.
    pub(crate) fn replace_title_generation_task(
        &mut self,
        session_id: &str,
        generation: u64,
        title_generation_task: JoinHandle<()>,
    ) {
        if let Some(existing_task) = self.title_generation_tasks.remove(session_id)
            && !existing_task.join_handle.is_finished()
        {
            existing_task.join_handle.abort();
        }

        self.title_generation_tasks.insert(
            SessionId::from(session_id),
            TitleGenerationTask {
                generation,
                join_handle: title_generation_task,
            },
        );
    }

    /// Aborts and forgets any tracked staged title-generation task for one
    /// session.
    pub(crate) fn abort_title_generation_task(&mut self, session_id: &str) {
        if let Some(existing_task) = self.title_generation_tasks.remove(session_id)
            && !existing_task.join_handle.is_finished()
        {
            existing_task.join_handle.abort();
        }
    }

    /// Returns the next tracked generation number for one session's draft
    /// title-generation task.
    pub(crate) fn next_title_generation_task_generation(&self, session_id: &str) -> u64 {
        self.title_generation_tasks
            .get(session_id)
            .map_or(1, |tracked_task| tracked_task.generation.saturating_add(1))
    }

    /// Clears one tracked draft-title generation task when the completion event
    /// matches the currently tracked generation.
    pub(crate) fn clear_title_generation_task_if_matches(
        &mut self,
        session_id: &str,
        generation: u64,
    ) {
        let should_clear = self
            .title_generation_tasks
            .get(session_id)
            .is_some_and(|tracked_task| tracked_task.generation == generation);

        if should_clear {
            self.title_generation_tasks.remove(session_id);
        }
    }

    /// Returns the internal merge orchestration service.
    pub(crate) fn merge_service(&self) -> &SessionMergeService {
        &self.merge_service
    }

    /// Returns the configured session git client used by orchestration flows.
    pub(crate) fn git_client(&self) -> Arc<dyn git::GitClient> {
        Arc::clone(&self.git_client)
    }

    /// Returns mutable access to worker orchestration state.
    pub(crate) fn worker_service_mut(&mut self) -> &mut SessionWorkerService {
        &mut self.worker_service
    }

    /// Returns the default smart model used for session-scoped agent
    /// workflows.
    pub(crate) fn default_session_model(&self) -> AgentModel {
        self.default_session_model
    }

    /// Replaces the default smart model used for newly created sessions.
    pub(crate) fn set_default_session_model(&mut self, session_model: AgentModel) {
        self.default_session_model = session_model;
    }

    /// Loads the default smart model persisted for new sessions.
    pub(crate) async fn load_default_session_model(
        services: &AppServices,
        project_id: Option<i64>,
        fallback_model: AgentModel,
    ) -> AgentModel {
        setting::load_default_smart_model_setting(services, project_id, fallback_model).await
    }

    /// Returns session snapshots, render caches, and semantic selection
    /// required for one frame.
    ///
    /// The render parts borrow disjoint manager fields directly so
    /// [`crate::ui::render_app`] can avoid cloning session maps or active
    /// prompt output blocks while runtime retains the concrete table viewport.
    pub(crate) fn render_parts(&self) -> SessionRenderParts<'_> {
        SessionRenderParts {
            active_prompt_outputs: &self.active_prompt_outputs,
            session_branch_names: &self.state.session_branch_names,
            session_git_statuses: &self.state.session_git_statuses,
            session_index_by_id: &self.state.session_index_by_id,
            session_worktree_availability: &self.state.session_worktree_availability,
            sessions: &self.state.sessions,
            stats_activity: &self.stats_activity,
            selected_index: self.state.table_state.selected(),
        }
    }

    /// Returns all loaded session snapshots in current list order.
    pub(crate) fn sessions(&self) -> &[Session] {
        &self.state.sessions
    }

    /// Returns mutable access to all loaded session snapshots for focused
    /// reducers and tests that need to stage state directly.
    pub(crate) fn sessions_mut(&mut self) -> &mut [Session] {
        &mut self.state.sessions
    }

    /// Appends one loaded session snapshot and updates stable id lookups.
    #[cfg(test)]
    pub(crate) fn push_session(&mut self, session: Session) {
        self.state.push_session(session);
    }

    /// Removes one loaded session snapshot by list index.
    pub(crate) fn remove_session_at(&mut self, session_index: usize) -> Option<Session> {
        self.state.remove_session_at(session_index)
    }

    /// Returns the selected session-list index.
    pub(crate) fn selected_session_index(&self) -> Option<usize> {
        self.state.table_state.selected()
    }

    /// Replaces the selected session-list index.
    pub(crate) fn select_session_index(&mut self, session_index: Option<usize>) {
        self.state.table_state.select(session_index);
    }

    /// Returns one mutable session snapshot by current list index.
    pub(crate) fn session_at_mut(&mut self, session_index: usize) -> Option<&mut Session> {
        self.state.sessions.get_mut(session_index)
    }

    /// Returns one immutable session snapshot by stable identifier.
    pub(crate) fn session_for_id(&self, session_id: &str) -> Option<&Session> {
        self.state.session_for_id(session_id)
    }

    /// Synchronizes all loaded session snapshots from live runtime handles.
    #[cfg(test)]
    pub(crate) fn sync_from_handles(&mut self) {
        self.state.sync_from_handles();
    }

    /// Synchronizes one loaded session snapshot from its live runtime handle.
    pub(crate) fn sync_session_from_handle(&mut self, session_id: &str) {
        self.state.sync_session_from_handle(session_id);
    }

    /// Applies a recomputed diff-size snapshot to one loaded session.
    pub(crate) fn apply_session_size_updated(
        &mut self,
        session_id: &str,
        added_lines: u64,
        deleted_lines: u64,
        session_size: crate::domain::session::SessionSize,
    ) {
        self.state
            .apply_session_size_updated(session_id, added_lines, deleted_lines, session_size);
    }

    /// Returns runtime handles keyed by stable session id.
    pub(crate) fn session_handles(
        &self,
    ) -> &HashMap<SessionId, crate::domain::session::SessionHandles> {
        &self.state.handles
    }

    /// Returns mutable runtime handles keyed by stable session id.
    #[cfg(test)]
    pub(crate) fn session_handles_mut(
        &mut self,
    ) -> &mut HashMap<SessionId, crate::domain::session::SessionHandles> {
        &mut self.state.handles
    }

    /// Returns the active prompt transcript block cached for sessions that are
    /// currently running a turn.
    pub(crate) fn active_prompt_outputs(&self) -> &HashMap<SessionId, String> {
        &self.active_prompt_outputs
    }

    /// Returns shared immutable access to session render and refresh state.
    pub(crate) fn state(&self) -> &SessionState {
        &self.state
    }

    /// Returns shared mutable access to session render and refresh state for
    /// reducers that still operate on [`SessionState`] directly.
    pub(crate) fn state_mut(&mut self) -> &mut SessionState {
        &mut self.state
    }

    /// Applies reducer updates after session agent/model changes are
    /// persisted.
    ///
    /// This updates only the target session snapshot. Global default-model
    /// selection is managed by settings persistence and loaded when creating
    /// new sessions.
    pub(crate) fn apply_session_model_updated(
        &mut self,
        session_id: &str,
        session_agent: crate::domain::agent::AgentSelection,
    ) {
        if let Some(session) = self
            .state
            .sessions
            .iter_mut()
            .find(|session| session.id == session_id)
        {
            session.agent = session_agent;
        }
    }

    /// Applies one persisted reasoning-level update to the matching
    /// in-memory session snapshot.
    pub(crate) fn apply_session_reasoning_level_updated(
        &mut self,
        session_id: &str,
        reasoning_level: ReasoningLevel,
    ) {
        if let Some(session) = self
            .state
            .sessions
            .iter_mut()
            .find(|session| session.id == session_id)
        {
            session.reasoning_level_override = Some(reasoning_level);
        }
    }

    /// Applies one persisted published-upstream reference to the matching
    /// in-memory session snapshot.
    pub(crate) fn apply_published_upstream_ref(
        &mut self,
        session_id: &str,
        published_upstream_ref: String,
    ) {
        if let Some(session) = self
            .state
            .sessions
            .iter_mut()
            .find(|session| session.id == session_id)
        {
            session.published_upstream_ref = Some(published_upstream_ref);
        }
    }

    /// Applies one persisted review-request snapshot to the matching in-memory
    /// session row.
    pub(crate) fn apply_review_request(&mut self, session_id: &str, review_request: ReviewRequest) {
        if let Some(session) = self
            .state
            .sessions
            .iter_mut()
            .find(|session| session.id == session_id)
        {
            session.review_request = Some(review_request);
        }
    }

    /// Marks one session branch as currently auto-syncing to its published
    /// upstream reference.
    pub(crate) fn start_published_branch_sync(
        &mut self,
        session_id: &str,
        sync_operation_id: String,
    ) {
        self.published_branch_sync_operations
            .insert(SessionId::from(session_id), sync_operation_id);

        if let Some(session) = self
            .state
            .sessions
            .iter_mut()
            .find(|session| session.id == session_id)
        {
            session.published_branch_sync_status = PublishedBranchSyncStatus::InProgress;
        }
    }

    /// Applies one terminal auto-push state when it matches the latest tracked
    /// sync operation for the session.
    pub(crate) fn finish_published_branch_sync(
        &mut self,
        session_id: &str,
        sync_operation_id: &str,
        sync_status: PublishedBranchSyncStatus,
    ) {
        let Some(current_operation_id) = self.published_branch_sync_operations.get(session_id)
        else {
            return;
        };
        if current_operation_id != sync_operation_id {
            return;
        }

        self.published_branch_sync_operations.remove(session_id);

        if let Some(session) = self
            .state
            .sessions
            .iter_mut()
            .find(|session| session.id == session_id)
        {
            session.published_branch_sync_status = sync_status;
        }
    }

    /// Appends one transient workflow notice shown for one session.
    pub(crate) fn append_workflow_notice(&mut self, session_id: &str, notice: String) {
        if let Some(session) = self
            .state
            .sessions
            .iter_mut()
            .find(|session| session.id == session_id)
        {
            if let Some(workflow_notice) = &mut session.workflow_notice {
                workflow_notice.push_str("\n\n");
                workflow_notice.push_str(&notice);
            } else {
                session.workflow_notice = Some(notice);
            }
        }
    }

    /// Applies one completed-turn projection to the matching in-memory
    /// session snapshot.
    pub(crate) fn apply_turn_applied_state(
        &mut self,
        session_id: &str,
        turn_applied_state: &TurnAppliedState,
    ) {
        let Some(session) = self
            .state
            .sessions
            .iter_mut()
            .find(|session| session.id == session_id)
        else {
            return;
        };

        session
            .follow_up_tasks
            .clone_from(&turn_applied_state.follow_up_tasks);
        session.questions.clone_from(&turn_applied_state.questions);
        session.summary.clone_from(&turn_applied_state.summary);
        session.stats.input_tokens = session
            .stats
            .input_tokens
            .saturating_add(turn_applied_state.token_usage_delta.input_tokens);
        session.stats.output_tokens = session
            .stats
            .output_tokens
            .saturating_add(turn_applied_state.token_usage_delta.output_tokens);
        self.active_prompt_outputs.remove(session_id);
    }

    /// Caches one exact prompt transcript block for an active session turn so
    /// rendering can anchor synthetic metadata to the correct boundary without
    /// reparsing generic transcript markers.
    pub(crate) fn set_active_prompt_output(&mut self, session_id: &str, prompt_output: String) {
        self.active_prompt_outputs
            .insert(SessionId::from(session_id), prompt_output);
    }

    /// Returns cached `@`-mention entries for one lookup root when the cache
    /// entry is still within its TTL window.
    pub(crate) fn at_mention_index_for_root(
        &mut self,
        lookup_root: &Path,
    ) -> Option<Vec<FileEntry>> {
        let cached_index = self.at_mention_indexes.get(lookup_root)?;

        if self
            .state
            .clock
            .now_instant()
            .saturating_duration_since(cached_index.created_at)
            > AT_MENTION_INDEX_TTL
        {
            self.at_mention_indexes.remove(lookup_root);

            return None;
        }

        Some(cached_index.entries.clone())
    }

    /// Replaces the cached `@`-mention index for one lookup root.
    pub(crate) fn set_at_mention_index_for_root(
        &mut self,
        lookup_root: PathBuf,
        entries: Vec<FileEntry>,
    ) {
        self.at_mention_indexes.insert(
            lookup_root,
            AtMentionIndex {
                created_at: self.state.clock.now_instant(),
                entries,
            },
        );
    }

    /// Drops the cached `@`-mention index for one lookup root.
    pub(crate) fn remove_at_mention_index_for_root(&mut self, lookup_root: &Path) {
        self.at_mention_indexes.remove(lookup_root);
    }

    /// Drops cached prompt transcript blocks for sessions that are no longer
    /// actively running a turn and prunes expired `@`-mention indexes.
    pub(crate) fn retain_active_prompt_outputs(&mut self) {
        self.active_prompt_outputs.retain(|session_id, _| {
            self.state
                .sessions
                .iter()
                .find(|session| session.id == *session_id)
                .is_some_and(|session| {
                    matches!(
                        session.status,
                        crate::domain::session::Status::InProgress
                            | crate::domain::session::Status::Queued
                            | crate::domain::session::Status::Rebasing
                            | crate::domain::session::Status::Merging
                    )
                })
        });
        self.prune_expired_at_mention_indexes();
    }

    /// Replaces cached session git-status snapshots from the latest
    /// background poll.
    pub(crate) fn replace_session_git_statuses(
        &mut self,
        session_git_statuses: HashMap<SessionId, SessionGitStatus>,
    ) {
        self.state
            .replace_session_git_statuses(session_git_statuses);
    }

    /// Removes expired `@`-mention indexes so unused lookup roots do not
    /// accumulate indefinitely in memory.
    fn prune_expired_at_mention_indexes(&mut self) {
        let now = self.state.clock.now_instant();

        self.at_mention_indexes.retain(|_, cached_index| {
            now.saturating_duration_since(cached_index.created_at) <= AT_MENTION_INDEX_TTL
        });
    }

    /// Replaces cached worktree-availability snapshots from the latest
    /// session reload.
    pub(crate) fn replace_session_worktree_availability(
        &mut self,
        session_worktree_availability: HashMap<SessionId, bool>,
    ) {
        self.state
            .replace_session_worktree_availability(session_worktree_availability);
    }

    /// Returns cached worktree availability keyed by session id.
    pub(crate) fn session_worktree_availability(&self) -> &HashMap<SessionId, bool> {
        &self.state.session_worktree_availability
    }

    /// Replaces cached detected session branch names from the latest reload.
    pub(crate) fn replace_session_branch_names(
        &mut self,
        session_branch_names: HashMap<SessionId, String>,
    ) {
        self.state
            .replace_session_branch_names(session_branch_names);
    }

    /// Returns the cached or derived branch name for one session.
    pub(crate) fn session_branch_name(&self, session_id: &str) -> Option<&str> {
        self.state
            .session_branch_names
            .get(session_id)
            .map(String::as_str)
    }

    /// Updates cached worktree availability for one session after its
    /// lifecycle materializes or removes the worktree.
    pub(crate) fn set_session_worktree_available(&mut self, session_id: &str, is_available: bool) {
        self.state
            .set_session_worktree_available(session_id, is_available);
    }

    /// Drops cached worktree availability for one removed session.
    pub(crate) fn remove_session_worktree_availability(&mut self, session_id: &str) {
        self.state.remove_session_worktree_availability(session_id);
    }

    /// Refreshes cached branch names for all currently loaded sessions by
    /// detecting each worktree `HEAD` and falling back to the derived default
    /// session branch when detection is unavailable.
    ///
    /// Branch detection runs concurrently so startup and session refresh do
    /// not pay one subprocess round trip per session in series.
    pub(crate) async fn refresh_session_branch_names(&mut self) {
        let session_inputs = self
            .state
            .sessions
            .iter()
            .map(|session| {
                let session_id = session.id.clone();
                let default_branch_name = session_branch(&session_id);

                (session_id, session.folder.clone(), default_branch_name)
            })
            .collect::<Vec<_>>();
        let mut session_branch_names = session_inputs
            .iter()
            .map(|(session_id, _, default_branch_name)| {
                (session_id.clone(), default_branch_name.clone())
            })
            .collect::<HashMap<_, _>>();
        let mut branch_detection_tasks = JoinSet::new();

        for (session_id, session_folder, default_branch_name) in session_inputs {
            let git_client = Arc::clone(&self.git_client);
            branch_detection_tasks.spawn(async move {
                let branch_name = git_client
                    .detect_git_info(session_folder)
                    .await
                    .unwrap_or(default_branch_name);

                (session_id, branch_name)
            });
        }

        while let Some(branch_detection_result) = branch_detection_tasks.join_next().await {
            let Ok((session_id, branch_name)) = branch_detection_result else {
                continue;
            };

            session_branch_names.insert(session_id, branch_name);
        }

        self.replace_session_branch_names(session_branch_names);
    }

    /// Returns the selected follow-up task position for one session.
    pub(crate) fn selected_follow_up_task_position(&self, session_id: &str) -> Option<usize> {
        self.state.selected_follow_up_task_position(session_id)
    }

    /// Returns the action currently available for the selected follow-up task
    /// in one session.
    pub(crate) fn selected_follow_up_task_action(
        &self,
        session_id: &str,
    ) -> Option<FollowUpTaskAction> {
        let position = self.selected_follow_up_task_position(session_id)?;
        let session = self
            .state
            .sessions
            .iter()
            .find(|session| session.id == session_id)?;

        session
            .follow_up_task(position)
            .map(crate::domain::session::SessionFollowUpTask::action)
    }

    /// Returns whether one session has more than one follow-up task.
    pub(crate) fn has_multiple_follow_up_tasks(&self, session_id: &str) -> bool {
        self.state
            .sessions
            .iter()
            .find(|session| session.id == session_id)
            .is_some_and(|session| session.follow_up_tasks.len() > 1)
    }

    /// Advances the selected follow-up task to the next item for one session.
    pub(crate) fn select_next_follow_up_task(&mut self, session_id: &str) {
        self.state.select_next_follow_up_task(session_id);
    }

    /// Moves the selected follow-up task to the previous item for one
    /// session.
    pub(crate) fn select_previous_follow_up_task(&mut self, session_id: &str) {
        self.state.select_previous_follow_up_task(session_id);
    }

    /// Sets the launched sibling-session link for the matching cached
    /// follow-up task.
    pub(crate) fn set_follow_up_task_launched_session_id(
        &mut self,
        session_id: &str,
        position: usize,
        launched_session_id: Option<SessionId>,
    ) {
        self.state.set_follow_up_task_launched_session_id(
            session_id,
            position,
            launched_session_id,
        );
    }
}

/// Prefix used for default session worktree branches.
const SESSION_BRANCH_PREFIX: &str = "wt/";

/// Returns the folder path for a session under the given base directory.
pub(crate) fn session_folder(base: &Path, session_id: &str) -> PathBuf {
    let len = session_id.len().min(8);
    base.join(&session_id[..len])
}

/// Returns the default worktree branch name for a session.
pub(crate) fn session_branch(session_id: &str) -> String {
    let len = session_id.len().min(8);
    format!("{SESSION_BRANCH_PREFIX}{}", &session_id[..len])
}

/// Extracts the remote branch portion from one upstream reference.
///
/// For example, `origin/wt/abc12345` returns `wt/abc12345`. When the
/// reference contains no `/` separator, the full input is returned as-is.
pub(crate) fn remote_branch_name_from_upstream_ref(upstream_ref: &str) -> String {
    upstream_ref.split_once('/').map_or_else(
        || upstream_ref.to_string(),
        |(_, branch_name)| branch_name.to_string(),
    )
}

/// Converts one wall-clock timestamp into Unix seconds.
pub(crate) fn unix_timestamp_from_system_time(system_time: SystemTime) -> i64 {
    system_time
        .duration_since(UNIX_EPOCH)
        .map_or(0, |duration| i64::try_from(duration.as_secs()).unwrap_or(0))
}

#[cfg(test)]
#[path = "core_test.rs"]
mod tests;