agentty 0.9.5

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
//! Event types and reducer helpers for the app core module.

use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;

use app::branch_publish::{
    BranchPublishActionUpdate, BranchPublishTaskResult, BranchPublishTaskSuccess,
    branch_publish_loading_label as branch_publish_loading_label_text,
    branch_publish_loading_message as branch_publish_loading_message_text,
    branch_publish_loading_title as branch_publish_loading_title_text,
    branch_publish_success_title as branch_publish_success_title_text,
    detected_forge_kind_from_git_push_error, git_push_authentication_message,
    is_git_push_authentication_error,
    pull_request_publish_success_message as pull_request_publish_success_message_text,
};
use app::reducer::AppEventReducer;
use app::review::{
    FocusedReviewPersistence, ReviewUpdate, apply_review_updates, auto_start_reviews,
};

use super::state::{App, SyncPopupContext, SyncReviewRequestTaskResult, UpdateStatus};
use crate::app;
use crate::app::session::{
    SessionTaskService, SyncMainOutcome, SyncSessionStartError, TurnAppliedState,
};
use crate::app::session_state::SessionGitStatus;
use crate::domain::file_entry::FileEntry;
use crate::domain::input::InputState;
use crate::domain::session::{
    PublishBranchAction, PublishedBranchSyncStatus, SessionId, SessionSize, Status,
};
use crate::domain::transcript_notice::TranscriptNotice;
use crate::runtime::mode::{at_mention, question, sync_blocked};
use crate::ui::state::app_mode::{AppMode, ConfirmationViewMode, QuestionFocus};
use crate::ui::state::prompt::PromptAtMentionState;

/// Internal app events emitted by background workers and workflows.
///
/// Producers should emit events only; state mutation is centralized in
/// [`App::apply_app_events`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum AppEvent {
    /// Indicates background-loaded prompt at-mention entries for one session.
    AtMentionEntriesLoaded {
        entries: Vec<FileEntry>,
        session_id: SessionId,
    },
    /// Indicates the latest project-branch and session-branch ahead/behind
    /// information from the git status worker.
    GitStatusUpdated {
        session_statuses: HashMap<SessionId, SessionGitStatus>,
        status: Option<(u32, u32)>,
    },
    /// Indicates whether a newer stable `agentty` release is available.
    VersionAvailabilityUpdated {
        latest_available_version: Option<String>,
    },
    /// Indicates progress of the background auto-update.
    UpdateStatusChanged { update_status: UpdateStatus },
    /// Indicates a session model selection has been persisted.
    SessionModelUpdated {
        session_id: SessionId,
        session_model: crate::domain::agent::AgentModel,
    },
    /// Indicates a session reasoning override selection has been persisted.
    SessionReasoningLevelUpdated {
        reasoning_level_override: Option<crate::domain::agent::ReasoningLevel>,
        session_id: SessionId,
    },
    /// Requests a full session list refresh.
    RefreshSessions,
    /// Requests an immediate git-status refresh outside the periodic poll
    /// cadence.
    RefreshGitStatus,
    /// Indicates completion of one requested-review list refresh.
    RequestedReviewsLoaded {
        /// Refresh generation assigned when the task was spawned.
        generation: u64,
        /// Project id whose requested reviews were loaded.
        project_id: i64,
        /// Forge result from the background requested-review task.
        result: Result<Vec<ag_forge::RequestedReview>, String>,
    },
    /// Indicates compact live thinking text for an in-progress session.
    SessionProgressUpdated {
        progress_message: Option<String>,
        session_id: SessionId,
    },
    /// Indicates completion of a list-mode sync workflow.
    SyncMainCompleted {
        result: Result<SyncMainOutcome, SyncSessionStartError>,
    },
    /// Indicates recomputed diff-derived size and line-count totals for one
    /// session.
    SessionSizeUpdated {
        added_lines: u64,
        deleted_lines: u64,
        session_id: SessionId,
        session_size: SessionSize,
    },
    /// Indicates one tracked draft-title generation task reached a terminal
    /// outcome and can be pruned from in-memory task tracking.
    SessionTitleGenerationFinished {
        generation: u64,
        session_id: SessionId,
    },
    /// Indicates completion of a session-view branch-publish action.
    BranchPublishActionCompleted {
        restore_view: ConfirmationViewMode,
        result: Box<BranchPublishTaskResult>,
        session_id: SessionId,
    },
    /// Indicates review assist output became available for a session.
    ReviewPrepared {
        diff_hash: u64,
        review_text: String,
        session_id: SessionId,
    },
    /// Indicates review assist failed for a session.
    ReviewPreparationFailed {
        diff_hash: u64,
        error: String,
        session_id: SessionId,
    },
    /// Indicates that a session handle snapshot changed in-memory and carries
    /// the latest observable handle version for redraw deduplication.
    SessionUpdated { session_id: SessionId, version: u64 },
    /// Indicates that an agent turn completed and persisted one reducer-ready
    /// projection.
    AgentResponseReceived {
        session_id: SessionId,
        turn_applied_state: TurnAppliedState,
    },
    /// Indicates a transient workflow notice changed for one session.
    SessionWorkflowNoticeUpdated {
        notice: String,
        session_id: SessionId,
    },
    /// Indicates that one published session branch started or finished a
    /// background auto-push after a completed turn.
    PublishedBranchSyncUpdated {
        session_id: SessionId,
        sync_operation_id: String,
        sync_status: PublishedBranchSyncStatus,
    },
    /// Indicates completion of one background review-request status refresh.
    ReviewRequestStatusUpdated {
        result: Result<SyncReviewRequestTaskResult, String>,
        session_id: SessionId,
    },
    /// Indicates that the inline review-comment cache for one session now
    /// exposes updated thread content.
    ///
    /// Emitted only when the background sync task observes a content change
    /// (see `ReviewCommentCache::record_snapshot`) so the UI can redraw without
    /// being woken on every 60-second tick.
    ReviewCommentsUpdated { session_id: SessionId },
}

/// Reduced representation of all app events currently queued for one tick.
#[derive(Default)]
pub(super) struct AppEventBatch {
    pub(super) applied_turns: HashMap<SessionId, TurnAppliedState>,
    pub(super) at_mention_entries_updates: HashMap<SessionId, Vec<FileEntry>>,
    pub(super) branch_publish_action_update: Option<BranchPublishActionUpdate>,
    pub(super) git_status_update: Option<GitStatusBatchUpdate>,
    pub(super) latest_available_version_update: Option<LatestAvailableVersionUpdate>,
    pub(super) published_branch_sync_updates: Vec<(SessionId, PublishedBranchSyncUpdate)>,
    pub(super) review_updates: HashMap<SessionId, ReviewUpdate>,
    pub(super) session_git_status_updates: HashMap<SessionId, SessionGitStatus>,
    pub(super) session_ids: HashSet<SessionId>,
    pub(super) session_update_versions: HashMap<SessionId, u64>,
    pub(super) session_model_updates: HashMap<SessionId, crate::domain::agent::AgentModel>,
    pub(super) session_reasoning_level_updates:
        HashMap<SessionId, Option<crate::domain::agent::ReasoningLevel>>,
    pub(super) session_progress_updates: HashMap<SessionId, Option<String>>,
    pub(super) session_size_updates: HashMap<SessionId, (u64, u64, SessionSize)>,
    pub(super) session_title_generation_finished: HashMap<SessionId, u64>,
    pub(super) session_workflow_notice_updates: HashMap<SessionId, Vec<String>>,
    pub(super) should_refresh_git_status: bool,
    pub(super) should_force_reload: bool,
    pub(super) review_request_status_updates: Vec<ReviewRequestStatusUpdate>,
    pub(super) review_comment_session_ids: HashSet<SessionId>,
    /// Latest requested-review task result collected for this reducer batch,
    /// including its generation for stale-result rejection.
    pub(super) requested_reviews:
        Option<(u64, i64, Result<Vec<ag_forge::RequestedReview>, String>)>,
    pub(super) sync_main_result: Option<Result<SyncMainOutcome, SyncSessionStartError>>,
    pub(super) update_status: Option<UpdateStatus>,
}

/// Optional aggregate git status payload from the latest status event in one
/// reducer batch.
pub(super) struct GitStatusBatchUpdate {
    /// Main worktree added/deleted line counts, when available.
    status: Option<(u32, u32)>,
}

/// Optional version-availability payload from the latest updater event in one
/// reducer batch.
pub(super) struct LatestAvailableVersionUpdate {
    /// Latest available version string, or `None` when no update is available.
    latest_available_version: Option<String>,
}

/// One ordered published-branch sync update queued for one session.
pub(super) struct PublishedBranchSyncUpdate {
    /// Operation identifier used to ignore stale terminal auto-push updates.
    sync_operation_id: String,
    /// Auto-push state carried by this update.
    sync_status: PublishedBranchSyncStatus,
}

/// Completed review-request status refresh payload ready for reducer
/// application.
pub(super) struct ReviewRequestStatusUpdate {
    pub(super) result: Result<SyncReviewRequestTaskResult, String>,
    pub(super) session_id: SessionId,
}

impl AppEventBatch {
    /// Collects one app event into the coalesced batch state.
    ///
    /// Most per-session projections use latest-wins semantics, but queued
    /// `AgentResponseReceived` events merge token-usage deltas so one reducer
    /// tick preserves cumulative usage from multiple completed turns.
    pub(super) fn collect_event(&mut self, event: AppEvent) {
        match event {
            AppEvent::AtMentionEntriesLoaded {
                entries,
                session_id,
            } => self.collect_at_mention_entries_loaded(session_id, entries),
            AppEvent::GitStatusUpdated {
                session_statuses,
                status,
            } => self.collect_git_status_updated(session_statuses, status),
            AppEvent::VersionAvailabilityUpdated {
                latest_available_version,
            } => self.collect_version_availability_updated(latest_available_version),
            AppEvent::UpdateStatusChanged { update_status } => {
                self.collect_update_status_changed(update_status);
            }
            AppEvent::SessionModelUpdated {
                session_id,
                session_model,
            } => self.collect_session_model_updated(session_id, session_model),
            AppEvent::SessionReasoningLevelUpdated {
                reasoning_level_override,
                session_id,
            } => self.collect_session_reasoning_level_updated(session_id, reasoning_level_override),
            AppEvent::RefreshSessions => self.collect_refresh_sessions(),
            AppEvent::RefreshGitStatus => self.collect_refresh_git_status(),
            AppEvent::RequestedReviewsLoaded {
                generation,
                project_id,
                result,
            } => self.collect_requested_reviews_loaded(generation, project_id, result),
            AppEvent::SessionProgressUpdated {
                progress_message,
                session_id,
            } => {
                self.session_progress_updates
                    .insert(session_id, progress_message);
            }
            AppEvent::SyncMainCompleted { result } => self.collect_sync_main_completed(result),
            AppEvent::SessionSizeUpdated {
                added_lines,
                deleted_lines,
                session_id,
                session_size,
            } => {
                self.session_size_updates
                    .insert(session_id, (added_lines, deleted_lines, session_size));
            }
            AppEvent::SessionTitleGenerationFinished {
                generation,
                session_id,
            } => {
                self.session_title_generation_finished
                    .insert(session_id, generation);
            }
            AppEvent::BranchPublishActionCompleted {
                restore_view,
                result,
                session_id,
            } => self.collect_branch_publish_action_completed(restore_view, *result, session_id),
            AppEvent::ReviewPrepared {
                diff_hash,
                review_text,
                session_id,
            } => self.collect_review_prepared(diff_hash, review_text, session_id),
            AppEvent::ReviewPreparationFailed {
                diff_hash,
                error,
                session_id,
            } => self.collect_review_preparation_failed(diff_hash, error, session_id),
            AppEvent::SessionUpdated {
                session_id,
                version,
            } => self.collect_session_updated(session_id, version),
            AppEvent::AgentResponseReceived {
                session_id,
                turn_applied_state,
            } => self.collect_agent_response_received(session_id, turn_applied_state),
            AppEvent::SessionWorkflowNoticeUpdated { notice, session_id } => {
                self.collect_session_workflow_notice_updated(session_id, notice);
            }
            AppEvent::PublishedBranchSyncUpdated {
                session_id,
                sync_operation_id,
                sync_status,
            } => self.collect_published_branch_sync_updated(
                session_id,
                sync_operation_id,
                sync_status,
            ),
            AppEvent::ReviewRequestStatusUpdated { result, session_id } => {
                self.collect_review_request_status_updated(result, session_id);
            }
            AppEvent::ReviewCommentsUpdated { session_id } => {
                self.collect_review_comments_updated(session_id);
            }
        }
    }

    /// Keeps the freshest requested-review result when multiple refreshes
    /// complete during one drained event batch.
    fn collect_requested_reviews_loaded(
        &mut self,
        generation: u64,
        project_id: i64,
        result: Result<Vec<ag_forge::RequestedReview>, String>,
    ) {
        if self
            .requested_reviews
            .as_ref()
            .is_none_or(|(batched_generation, _, _)| generation >= *batched_generation)
        {
            self.requested_reviews = Some((generation, project_id, result));
        }
    }

    /// Stores a session model update for reducer application.
    fn collect_session_model_updated(
        &mut self,
        session_id: SessionId,
        session_model: crate::domain::agent::AgentModel,
    ) {
        self.session_model_updates.insert(session_id, session_model);
    }

    /// Stores a session reasoning-level update for reducer application.
    fn collect_session_reasoning_level_updated(
        &mut self,
        session_id: SessionId,
        reasoning_level_override: Option<crate::domain::agent::ReasoningLevel>,
    ) {
        self.session_reasoning_level_updates
            .insert(session_id, reasoning_level_override);
    }

    /// Stores a workflow notice update and marks its session as touched.
    fn collect_session_workflow_notice_updated(&mut self, session_id: SessionId, notice: String) {
        self.session_ids.insert(session_id.clone());
        self.session_workflow_notice_updates
            .entry(session_id)
            .or_default()
            .push(notice);
    }

    /// Tracks one review-comment cache update so the reducer redraws and
    /// clears stale diff scroll metrics for that session.
    fn collect_review_comments_updated(&mut self, session_id: SessionId) {
        self.review_comment_session_ids.insert(session_id);
    }

    /// Stores loaded at-mention entries for one session.
    fn collect_at_mention_entries_loaded(
        &mut self,
        session_id: SessionId,
        entries: Vec<FileEntry>,
    ) {
        self.at_mention_entries_updates.insert(session_id, entries);
    }

    /// Stores one pending status-bar update.
    fn collect_update_status_changed(&mut self, update_status: UpdateStatus) {
        self.update_status = Some(update_status);
    }

    /// Marks the next reducer application as a full session refresh.
    fn collect_refresh_sessions(&mut self) {
        self.should_force_reload = true;
    }

    /// Marks git status polling for restart.
    fn collect_refresh_git_status(&mut self) {
        self.should_refresh_git_status = true;
    }

    /// Stores the latest git status event for this reducer batch.
    fn collect_git_status_updated(
        &mut self,
        session_statuses: HashMap<SessionId, SessionGitStatus>,
        status: Option<(u32, u32)>,
    ) {
        self.git_status_update = Some(GitStatusBatchUpdate { status });
        self.session_git_status_updates = session_statuses;
    }

    /// Stores the latest version availability event for this reducer batch.
    fn collect_version_availability_updated(&mut self, latest_available_version: Option<String>) {
        self.latest_available_version_update = Some(LatestAvailableVersionUpdate {
            latest_available_version,
        });
    }

    /// Stores the latest default-branch sync result for this reducer batch.
    fn collect_sync_main_completed(
        &mut self,
        result: Result<SyncMainOutcome, SyncSessionStartError>,
    ) {
        if result.is_ok() {
            self.should_refresh_git_status = true;
        }

        self.sync_main_result = Some(result);
    }

    /// Stores the latest branch-publish action result for this reducer batch.
    fn collect_branch_publish_action_completed(
        &mut self,
        restore_view: ConfirmationViewMode,
        result: BranchPublishTaskResult,
        session_id: SessionId,
    ) {
        if result.is_ok() {
            self.should_refresh_git_status = true;
        }

        self.branch_publish_action_update = Some(BranchPublishActionUpdate {
            restore_view,
            result,
            session_id,
        });
    }

    /// Stores a successful focused-review preparation result.
    fn collect_review_prepared(
        &mut self,
        diff_hash: u64,
        review_text: String,
        session_id: SessionId,
    ) {
        self.review_updates.insert(
            session_id,
            ReviewUpdate {
                diff_hash,
                result: Ok(review_text),
            },
        );
    }

    /// Stores a failed focused-review preparation result.
    fn collect_review_preparation_failed(
        &mut self,
        diff_hash: u64,
        error: String,
        session_id: SessionId,
    ) {
        self.review_updates.insert(
            session_id,
            ReviewUpdate {
                diff_hash,
                result: Err(error),
            },
        );
    }

    /// Queues one published-branch sync state transition for ordered
    /// reducer application.
    fn collect_published_branch_sync_updated(
        &mut self,
        session_id: SessionId,
        sync_operation_id: String,
        sync_status: PublishedBranchSyncStatus,
    ) {
        if matches!(
            sync_status,
            PublishedBranchSyncStatus::Idle | PublishedBranchSyncStatus::Succeeded
        ) {
            self.should_refresh_git_status = true;
        }

        self.published_branch_sync_updates.push((
            session_id,
            PublishedBranchSyncUpdate {
                sync_operation_id,
                sync_status,
            },
        ));
    }

    /// Queues one review-request status refresh result for reducer
    /// application.
    fn collect_review_request_status_updated(
        &mut self,
        result: Result<SyncReviewRequestTaskResult, String>,
        session_id: SessionId,
    ) {
        self.review_request_status_updates
            .push(ReviewRequestStatusUpdate { result, session_id });
    }

    /// Stores the latest reduced handle version for one touched session.
    fn collect_session_updated(&mut self, session_id: SessionId, version: u64) {
        self.session_ids.insert(session_id.clone());
        self.session_update_versions.insert(session_id, version);
    }

    /// Merges one completed-turn projection into the per-session batch.
    ///
    /// Agent responses also mark the session as touched so the reducer still
    /// synchronizes handle-backed status and evaluates auto-review startup
    /// even when the matching `SessionUpdated` event lands in a later tick.
    /// Latest reducer-facing fields replace the older projection, while token
    /// deltas accumulate to preserve usage across multiple queued completions
    /// for the same session.
    fn collect_agent_response_received(
        &mut self,
        session_id: SessionId,
        turn_applied_state: TurnAppliedState,
    ) {
        self.session_ids.insert(session_id.clone());

        match self.applied_turns.entry(session_id) {
            Entry::Occupied(mut occupied_entry) => {
                occupied_entry.get_mut().merge_newer(turn_applied_state);
            }
            Entry::Vacant(vacant_entry) => {
                vacant_entry.insert(turn_applied_state);
            }
        }
    }
}

impl App {
    /// Applies one or more queued app events through a single reducer path.
    ///
    /// This method drains currently queued app events, coalesces refresh and
    /// git-status updates, then applies session-handle sync for touched
    /// sessions.
    pub(crate) async fn apply_app_events(&mut self, first_event: AppEvent) {
        let drained_events = AppEventReducer::drain(&mut self.event_rx, first_event);
        let mut event_batch = AppEventBatch::default();
        for event in drained_events {
            event_batch.collect_event(event);
        }

        self.apply_app_event_batch(event_batch).await;
    }

    /// Processes currently queued app events without waiting.
    ///
    /// The foreground runtime calls this before draw so queued
    /// `SessionUpdated` events can synchronize only the touched sessions into
    /// render snapshots without polling every live handle each frame.
    pub(crate) async fn process_pending_app_events(&mut self) {
        let Ok(first_event) = self.event_rx.try_recv() else {
            return;
        };

        self.apply_app_events(first_event).await;
    }

    /// Waits for the next internal app event.
    pub(crate) async fn next_app_event(&mut self) -> Option<AppEvent> {
        self.event_rx.recv().await
    }

    /// Applies one reduced app-event batch to in-memory app state.
    ///
    /// The reducer first records whether the batch changes any render-visible
    /// state, applies global runtime updates, and then synchronizes touched
    /// session snapshots from their live handles. Any touched session that
    /// reached terminal status (`Done`, `Canceled`) then drops its worker queue
    /// so background workers can shut down provider runtimes.
    async fn apply_app_event_batch(&mut self, mut event_batch: AppEventBatch) {
        let mut should_mark_dirty = Self::app_event_batch_changes_observable_state(&event_batch);
        let previous_session_states = self.previous_session_states(&event_batch.session_ids);

        should_mark_dirty |=
            self.update_session_redraw_versions(&event_batch.session_update_versions);

        self.apply_batch_runtime_updates(&mut event_batch).await;

        self.apply_batch_session_snapshot_updates(&mut event_batch);

        let focused_review_persistence = apply_review_updates(
            &mut self.review_cache,
            &mut self.mode,
            self.sessions.state_mut(),
            event_batch.review_updates,
        );
        self.persist_focused_review_updates(focused_review_persistence)
            .await;

        if let Some(branch_publish_action_update) = event_batch.branch_publish_action_update {
            self.apply_branch_publish_action_update(branch_publish_action_update);
        }

        for review_request_status_update in event_batch.review_request_status_updates {
            self.apply_review_request_status_update(review_request_status_update)
                .await;
        }

        self.invalidate_diff_scroll_cache_for_review_comments(
            &event_batch.review_comment_session_ids,
        );

        self.apply_session_progress_updates(std::mem::take(
            &mut event_batch.session_progress_updates,
        ));

        for (session_id, turn_applied_state) in event_batch.applied_turns {
            self.apply_agent_response_received(&session_id, &turn_applied_state);
        }
        for (session_id, notices) in
            std::mem::take(&mut event_batch.session_workflow_notice_updates)
        {
            for notice in notices {
                self.sessions.append_workflow_notice(&session_id, notice);
            }
        }
        for (session_id, sync_update) in event_batch.published_branch_sync_updates {
            self.apply_published_branch_sync_update(&session_id, sync_update);
        }

        self.sync_touched_sessions(&event_batch.session_ids);

        auto_start_reviews(
            &mut self.review_cache,
            &event_batch.session_ids,
            self.sessions.state_mut(),
            &mut self.mode,
            self.services.git_client(),
            self.services.event_sender(),
            self.settings.default_review_model,
        )
        .await;

        if let Some(sync_main_result) = event_batch.sync_main_result {
            let sync_popup_context = self.sync_popup_context();

            self.mode = Self::sync_main_popup_mode(sync_main_result, &sync_popup_context);
        }

        self.handle_merge_queue_progress(&event_batch.session_ids, &previous_session_states)
            .await;
        self.retain_valid_session_progress_messages();
        self.sessions.retain_active_prompt_outputs();

        if should_mark_dirty {
            self.mark_dirty();
        }
    }

    /// Clears the diff scroll limit cache when review comments change for the
    /// currently visible diff session.
    fn invalidate_diff_scroll_cache_for_review_comments(
        &mut self,
        review_comment_session_ids: &HashSet<SessionId>,
    ) {
        let AppMode::Diff {
            scroll_cache,
            session_id,
            ..
        } = &mut self.mode
        else {
            return;
        };

        if review_comment_session_ids.contains(session_id) {
            *scroll_cache = None;
        }
    }

    /// Applies reducer-batch updates that affect global app runtime state
    /// before session-local projections are synchronized.
    async fn apply_batch_runtime_updates(&mut self, event_batch: &mut AppEventBatch) {
        if event_batch.should_force_reload {
            self.refresh_sessions_now().await;
            self.reload_projects().await;
        }

        if event_batch.should_refresh_git_status {
            self.restart_git_status_task();
        }

        if let Some(git_status_update) = &event_batch.git_status_update {
            self.projects.set_git_status(git_status_update.status);
            self.sessions
                .replace_session_git_statuses(event_batch.session_git_status_updates.clone());
        }

        if let Some((generation, project_id, result)) = event_batch.requested_reviews.take()
            && project_id == self.projects.active_project_id()
            && self
                .requested_reviews
                .matches_loading_request(project_id, generation)
        {
            self.requested_reviews = match result {
                Ok(items) => app::RequestedReviewState::Loaded { items, project_id },
                Err(message) => app::RequestedReviewState::Failed {
                    message,
                    project_id,
                },
            };
        }

        self.apply_status_bar_updates(
            event_batch.latest_available_version_update.as_ref(),
            event_batch.update_status.take(),
        );
    }

    /// Synchronizes touched sessions from their runtime handles and drops
    /// worker queues for sessions that reached a terminal status.
    fn sync_touched_sessions(&mut self, session_ids: &HashSet<SessionId>) {
        for session_id in session_ids {
            self.sessions.sync_session_from_handle(session_id);
        }

        self.sessions.clear_terminal_session_workers(session_ids);
    }

    /// Applies status-bar state updates carried by one reducer batch.
    fn apply_status_bar_updates(
        &mut self,
        latest_available_version_update: Option<&LatestAvailableVersionUpdate>,
        update_status: Option<UpdateStatus>,
    ) {
        if let Some(latest_available_version_update) = latest_available_version_update {
            self.latest_available_version
                .clone_from(&latest_available_version_update.latest_available_version);
        }

        if let Some(update_status) = update_status {
            self.update_status = Some(update_status);
        }
    }

    /// Returns status snapshots for sessions touched before applying a
    /// reducer batch.
    fn previous_session_states(
        &self,
        session_ids: &HashSet<SessionId>,
    ) -> HashMap<SessionId, Status> {
        session_ids
            .iter()
            .filter_map(|session_id| {
                self.sessions
                    .sessions()
                    .iter()
                    .find(|session| session.id == *session_id)
                    .map(|session| (session_id.clone(), session.status))
            })
            .collect()
    }

    /// Returns whether one reduced event batch changes any render-visible
    /// application state before `SessionUpdated` version deduplication.
    fn app_event_batch_changes_observable_state(event_batch: &AppEventBatch) -> bool {
        event_batch.should_force_reload
            || event_batch.git_status_update.is_some()
            || event_batch.latest_available_version_update.is_some()
            || event_batch.update_status.is_some()
            || !event_batch.applied_turns.is_empty()
            || !event_batch.at_mention_entries_updates.is_empty()
            || event_batch.branch_publish_action_update.is_some()
            || !event_batch.published_branch_sync_updates.is_empty()
            || !event_batch.review_request_status_updates.is_empty()
            || !event_batch.review_comment_session_ids.is_empty()
            || event_batch.requested_reviews.is_some()
            || !event_batch.review_updates.is_empty()
            || !event_batch.session_model_updates.is_empty()
            || !event_batch.session_progress_updates.is_empty()
            || !event_batch.session_reasoning_level_updates.is_empty()
            || !event_batch.session_size_updates.is_empty()
            || !event_batch.session_title_generation_finished.is_empty()
            || !event_batch.session_workflow_notice_updates.is_empty()
            || event_batch.sync_main_result.is_some()
    }

    /// Updates the last-seen session-handle versions and returns whether any
    /// carried version is newer than the reduced value already applied.
    fn update_session_redraw_versions(
        &mut self,
        session_update_versions: &HashMap<SessionId, u64>,
    ) -> bool {
        let mut did_change = false;

        for (session_id, version) in session_update_versions {
            let previous_version = self
                .last_seen_session_update_versions
                .insert(session_id.clone(), *version);

            if previous_version != Some(*version) {
                did_change = true;
            }
        }

        did_change
    }

    /// Applies reducer batch updates that mutate cached session snapshots or
    /// auxiliary session-view lookup state.
    fn apply_batch_session_snapshot_updates(&mut self, event_batch: &mut AppEventBatch) {
        for (session_id, session_model) in std::mem::take(&mut event_batch.session_model_updates) {
            self.sessions
                .apply_session_model_updated(&session_id, session_model);
        }

        for (session_id, reasoning_level_override) in
            std::mem::take(&mut event_batch.session_reasoning_level_updates)
        {
            self.sessions
                .apply_session_reasoning_level_updated(&session_id, reasoning_level_override);
        }

        for (session_id, (added_lines, deleted_lines, session_size)) in
            std::mem::take(&mut event_batch.session_size_updates)
        {
            self.sessions.apply_session_size_updated(
                &session_id,
                added_lines,
                deleted_lines,
                session_size,
            );
        }

        for (session_id, generation) in
            std::mem::take(&mut event_batch.session_title_generation_finished)
        {
            self.sessions
                .clear_title_generation_task_if_matches(&session_id, generation);
        }

        for (session_id, entries) in std::mem::take(&mut event_batch.at_mention_entries_updates) {
            self.sessions.set_at_mention_index_for_root(
                self.at_mention_lookup_root(&session_id),
                entries.clone(),
            );

            self.apply_prompt_at_mention_entries(&session_id, entries);
        }
    }

    /// Applies active progress message updates from one reducer batch.
    fn apply_session_progress_updates(
        &mut self,
        session_progress_updates: HashMap<SessionId, Option<String>>,
    ) {
        for (session_id, progress_message) in session_progress_updates {
            if let Some(progress_message) = progress_message {
                self.session_progress_messages
                    .insert(session_id, progress_message);
            } else {
                self.session_progress_messages.remove(&session_id);
            }
        }
    }

    /// Routes one persisted turn projection to the currently focused session
    /// UI.
    ///
    /// The session worker persists the canonical summary, clarification
    /// questions, summary, and token-usage delta before sending this
    /// event, so the reducer can apply the exact same projection in memory
    /// without waiting for a forced reload.
    fn apply_agent_response_received(
        &mut self,
        session_id: &str,
        turn_applied_state: &TurnAppliedState,
    ) {
        if !self
            .sessions
            .sessions()
            .iter()
            .any(|session| session.id == session_id)
        {
            return;
        }

        self.sessions
            .apply_turn_applied_state(session_id, turn_applied_state);
        let questions = turn_applied_state.questions.clone();
        if questions.is_empty() {
            return;
        }

        if self.is_viewing_session(session_id) {
            let (review_status_message, review_text) = self.question_mode_review_state(session_id);
            self.mode = AppMode::Question {
                at_mention_state: None,
                selected_option_index: question::default_option_index(&questions, 0),
                session_id: session_id.into(),
                questions,
                review_status_message,
                review_text,
                responses: Vec::new(),
                current_index: 0,
                focus: QuestionFocus::Answer,
                input: InputState::default(),
                scroll_offset: None,
            };
        }
    }

    /// Returns whether the active UI mode currently shows the provided
    /// session.
    fn is_viewing_session(&self, session_id: &str) -> bool {
        match &self.mode {
            AppMode::View {
                session_id: view_id,
                ..
            }
            | AppMode::Prompt {
                session_id: view_id,
                ..
            }
            | AppMode::Diff {
                session_id: view_id,
                ..
            }
            | AppMode::Question {
                session_id: view_id,
                ..
            }
            | AppMode::OpenCommandSelector {
                restore_view:
                    ConfirmationViewMode {
                        session_id: view_id,
                        ..
                    },
                ..
            }
            | AppMode::PublishBranchInput {
                restore_view:
                    ConfirmationViewMode {
                        session_id: view_id,
                        ..
                    },
                ..
            }
            | AppMode::ViewInfoPopup {
                restore_view:
                    ConfirmationViewMode {
                        session_id: view_id,
                        ..
                    },
                ..
            } => view_id == session_id,
            AppMode::List
            | AppMode::SessionCreation { .. }
            | AppMode::Confirmation { .. }
            | AppMode::SyncBlockedPopup { .. }
            | AppMode::Help { .. } => false,
        }
    }

    /// Returns the focused-review state that should remain visible when the
    /// UI enters clarification-question mode for the provided session.
    fn question_mode_review_state(&self, session_id: &str) -> (Option<String>, Option<String>) {
        match &self.mode {
            AppMode::View {
                review_status_message,
                review_text,
                ..
            }
            | AppMode::Prompt {
                review_status_message,
                review_text,
                ..
            }
            | AppMode::Question {
                review_status_message,
                review_text,
                ..
            } => (review_status_message.clone(), review_text.clone()),
            AppMode::OpenCommandSelector { restore_view, .. }
            | AppMode::PublishBranchInput { restore_view, .. }
            | AppMode::ViewInfoPopup { restore_view, .. } => (
                restore_view.review_status_message.clone(),
                restore_view.review_text.clone(),
            ),
            AppMode::Diff {
                session_id: diff_session_id,
                ..
            } if diff_session_id == session_id => self.review_view_state(session_id),
            AppMode::List
            | AppMode::SessionCreation { .. }
            | AppMode::Confirmation { .. }
            | AppMode::SyncBlockedPopup { .. }
            | AppMode::Diff { .. }
            | AppMode::Help { .. } => (None, None),
        }
    }

    /// Routes one published-branch auto-push update to the matching in-memory
    /// session snapshot.
    fn apply_published_branch_sync_update(
        &mut self,
        session_id: &str,
        sync_update: PublishedBranchSyncUpdate,
    ) {
        let PublishedBranchSyncUpdate {
            sync_operation_id,
            sync_status,
        } = sync_update;

        match sync_status {
            PublishedBranchSyncStatus::InProgress => {
                self.sessions
                    .start_published_branch_sync(session_id, sync_operation_id);
            }
            PublishedBranchSyncStatus::Idle
            | PublishedBranchSyncStatus::Succeeded
            | PublishedBranchSyncStatus::Failed => {
                self.sessions.finish_published_branch_sync(
                    session_id,
                    &sync_operation_id,
                    sync_status,
                );
            }
        }
    }

    /// Returns the lookup root for the session associated with an at-mention
    /// event.
    fn at_mention_lookup_root(&self, session_id: &str) -> PathBuf {
        let project_working_dir = self.working_dir().to_path_buf();

        self.sessions.session_for_id(session_id).map_or_else(
            || project_working_dir.clone(),
            |session| {
                let project_working_dir = project_working_dir.clone();
                let session_folder = session.folder.clone();
                let has_session_folder = self.services.fs_client().is_dir(session_folder.clone());

                at_mention::lookup_root(
                    project_working_dir,
                    Some(session_folder),
                    has_session_folder,
                )
            },
        )
    }

    /// Applies loaded at-mention entries to the currently focused prompt or
    /// question session, if the mention query is still active.
    fn apply_prompt_at_mention_entries(&mut self, session_id: &str, entries: Vec<FileEntry>) {
        let (at_mention_state, has_query) = match &mut self.mode {
            AppMode::Prompt {
                at_mention_state,
                input,
                session_id: mode_session_id,
                ..
            } if mode_session_id == session_id => {
                (at_mention_state, input.at_mention_query().is_some())
            }
            AppMode::Question {
                at_mention_state,
                input,
                session_id: mode_session_id,
                ..
            } if mode_session_id == session_id => {
                (at_mention_state, input.at_mention_query().is_some())
            }
            _ => return,
        };

        if !has_query {
            return;
        }

        if let Some(state) = at_mention_state.as_mut() {
            state.all_entries = entries;
            state.selected_index = 0;

            return;
        }

        *at_mention_state = Some(PromptAtMentionState::new(entries));
    }

    /// Applies one review assist update to cache and focused render state.
    #[cfg(test)]
    pub(super) fn apply_review_update(
        &mut self,
        session_id: &str,
        review_update: app::review::ReviewUpdate,
    ) {
        let mut review_updates = HashMap::new();
        review_updates.insert(SessionId::from(session_id), review_update);
        apply_review_updates(
            &mut self.review_cache,
            &mut self.mode,
            self.sessions.state_mut(),
            review_updates,
        );
    }

    /// Persists successful focused reviews and clears stale saved review text
    /// after failed regeneration attempts.
    async fn persist_focused_review_updates(
        &self,
        focused_review_persistence: Vec<FocusedReviewPersistence>,
    ) {
        for persistence_update in focused_review_persistence {
            let diff_hash = persistence_update
                .diff_hash
                .map(|diff_hash| diff_hash.to_string());

            let _ = self
                .services
                .db()
                .sessions()
                .update_session_focused_review(
                    persistence_update.session_id.as_str(),
                    diff_hash,
                    persistence_update.text,
                )
                .await;
        }
    }

    /// Starts focused review generation for sessions that just entered review.
    #[cfg(test)]
    pub(super) async fn auto_start_reviews(&mut self, session_ids: &HashSet<SessionId>) {
        auto_start_reviews(
            &mut self.review_cache,
            session_ids,
            self.sessions.state_mut(),
            &mut self.mode,
            self.services.git_client(),
            self.services.event_sender(),
            self.settings.default_review_model,
        )
        .await;
    }

    /// Applies one completed branch-publish action and updates the popup.
    pub(super) fn apply_branch_publish_action_update(
        &mut self,
        branch_publish_action_update: BranchPublishActionUpdate,
    ) {
        let BranchPublishActionUpdate {
            restore_view,
            result,
            session_id,
        } = branch_publish_action_update;

        let popup_mode = match result {
            Ok(BranchPublishTaskSuccess::Pushed {
                branch_name,
                review_request_creation,
                upstream_reference,
            }) => {
                self.sessions
                    .apply_published_upstream_ref(&session_id, upstream_reference);

                Self::view_info_popup_mode(
                    Self::branch_publish_success_title(PublishBranchAction::Push),
                    Self::branch_publish_success_message(
                        &branch_name,
                        review_request_creation.as_ref(),
                    ),
                    false,
                    String::new(),
                    restore_view,
                )
            }
            Ok(BranchPublishTaskSuccess::PullRequestPublished {
                branch_name,
                review_request,
                upstream_reference,
            }) => {
                self.sessions
                    .apply_published_upstream_ref(&session_id, upstream_reference);
                self.sessions
                    .apply_review_request(&session_id, review_request.clone());

                Self::view_info_popup_mode(
                    Self::review_request_publish_success_title(&review_request),
                    Self::pull_request_publish_success_message(&branch_name, &review_request),
                    false,
                    String::new(),
                    restore_view,
                )
            }
            Err(failure) => Self::view_info_popup_mode(
                failure.title,
                failure.message,
                false,
                String::new(),
                restore_view,
            ),
        };
        self.mode = popup_mode;
    }

    /// Applies one background review-request status refresh.
    pub(super) async fn apply_review_request_status_update(
        &mut self,
        review_request_status_update: ReviewRequestStatusUpdate,
    ) {
        let ReviewRequestStatusUpdate { result, session_id } = review_request_status_update;

        let Ok(task_result) = result else {
            return;
        };

        if let Some(summary) = task_result.summary {
            let _ = self
                .sessions
                .store_review_request_summary(&self.services, &session_id, summary)
                .await;
        }

        match task_result.outcome {
            crate::app::session::SyncReviewRequestOutcome::Merged { .. } => {
                if let Some(warning) = self.complete_externally_merged_session(&session_id).await {
                    self.append_output_for_session(
                        &session_id,
                        &TranscriptNotice::ReviewRequestSyncWarning.format(warning),
                    )
                    .await;
                }
            }
            crate::app::session::SyncReviewRequestOutcome::Closed { .. } => {
                self.cancel_externally_closed_session(&session_id).await;
            }
            crate::app::session::SyncReviewRequestOutcome::Open { .. }
            | crate::app::session::SyncReviewRequestOutcome::NoReviewRequest => {}
        }
    }

    /// Transitions one externally merged session to `Done` with best-effort
    /// worktree and branch cleanup.
    ///
    /// Returns an optional warning message when worktree cleanup fails. The
    /// session is still moved to `Done` because the merge already happened
    /// upstream, but the caller should surface the warning to the user.
    async fn complete_externally_merged_session(&self, session_id: &str) -> Option<String> {
        let Ok(session) = self.sessions.session_or_err(session_id) else {
            return None;
        };
        let Ok(handles) = self.sessions.session_handles_or_err(session_id) else {
            return None;
        };

        let folder = session.folder.clone();
        let source_branch = crate::app::session::session_branch(session_id);

        let cleanup_warning = crate::app::session::SessionManager::cleanup_merged_session_worktree(
            folder,
            self.services.fs_client(),
            self.services.git_client(),
            source_branch,
            None,
        )
        .await
        .err()
        .map(|error| format!("Worktree cleanup failed: {error}"));

        let app_event_tx = self.services.event_sender();

        SessionTaskService::update_status(
            handles.status.as_ref(),
            self.services.clock().as_ref(),
            self.services.db(),
            &app_event_tx,
            &self.services.session_update_versions(),
            session_id,
            Status::Done,
        )
        .await;

        cleanup_warning
    }

    /// Transitions one externally closed review session to `Canceled`.
    async fn cancel_externally_closed_session(&self, session_id: &str) {
        let Ok(handles) = self.sessions.session_handles_or_err(session_id) else {
            return;
        };
        let app_event_tx = self.services.event_sender();

        let _ = SessionTaskService::update_status(
            handles.status.as_ref(),
            self.services.clock().as_ref(),
            self.services.db(),
            &app_event_tx,
            &self.services.session_update_versions(),
            session_id,
            Status::Canceled,
        )
        .await;
    }

    /// Builds a session-view info popup mode with explicit loading metadata.
    pub(super) fn view_info_popup_mode(
        title: String,
        message: String,
        is_loading: bool,
        loading_label: String,
        restore_view: ConfirmationViewMode,
    ) -> AppMode {
        AppMode::ViewInfoPopup {
            is_loading,
            loading_label,
            message,
            restore_view,
            title,
        }
    }

    /// Returns the loading popup title for one branch-publish action.
    pub(super) fn branch_publish_loading_title(
        publish_branch_action: PublishBranchAction,
    ) -> String {
        branch_publish_loading_title_text(publish_branch_action)
    }

    /// Returns the loading popup body for one branch-publish action.
    pub(super) fn branch_publish_loading_message(
        publish_branch_action: PublishBranchAction,
        remote_branch_name: Option<&str>,
    ) -> String {
        branch_publish_loading_message_text(publish_branch_action, remote_branch_name)
    }

    /// Returns the loading spinner label for one branch-publish action.
    pub(super) fn branch_publish_loading_label(
        publish_branch_action: PublishBranchAction,
    ) -> String {
        branch_publish_loading_label_text(publish_branch_action)
    }

    /// Returns the success popup title for a completed branch-publish action.
    pub(super) fn branch_publish_success_title(
        publish_branch_action: PublishBranchAction,
    ) -> String {
        branch_publish_success_title_text(publish_branch_action)
    }

    /// Returns the success popup body for one completed branch push.
    pub(super) fn branch_publish_success_message(
        branch_name: &str,
        review_request_creation: Option<&crate::app::branch_publish::ReviewRequestCreationInfo>,
    ) -> String {
        crate::app::branch_publish::branch_push_success_message(
            branch_name,
            review_request_creation,
        )
    }

    /// Returns the success popup title for one completed review-request
    /// publish.
    pub(super) fn review_request_publish_success_title(
        review_request: &crate::domain::session::ReviewRequest,
    ) -> String {
        crate::app::branch_publish::review_request_publish_success_title(review_request)
    }

    /// Returns the success popup body for one completed review-request
    /// publish.
    pub(super) fn pull_request_publish_success_message(
        branch_name: &str,
        review_request: &crate::domain::session::ReviewRequest,
    ) -> String {
        pull_request_publish_success_message_text(branch_name, review_request)
    }

    /// Builds final sync popup mode from background sync completion result.
    ///
    /// Authentication-related push failures are normalized to actionable
    /// authorization guidance so users can recover quickly.
    pub(super) fn sync_main_popup_mode(
        sync_main_result: Result<SyncMainOutcome, SyncSessionStartError>,
        sync_popup_context: &SyncPopupContext,
    ) -> AppMode {
        match sync_main_result {
            Ok(sync_main_outcome) => AppMode::SyncBlockedPopup {
                project_name: Some(sync_popup_context.project_name.clone()),
                default_branch: Some(sync_popup_context.default_branch.clone()),
                is_loading: false,
                message: Self::sync_success_message(&sync_main_outcome),
                title: "Sync complete".to_string(),
            },
            Err(sync_error @ SyncSessionStartError::MainHasUncommittedChanges { .. }) => {
                AppMode::SyncBlockedPopup {
                    project_name: Some(sync_popup_context.project_name.clone()),
                    default_branch: Some(sync_popup_context.default_branch.clone()),
                    is_loading: false,
                    message: sync_error.detail_message(),
                    title: "Sync blocked".to_string(),
                }
            }
            Err(sync_error @ SyncSessionStartError::Other(_)) => AppMode::SyncBlockedPopup {
                project_name: Some(sync_popup_context.project_name.clone()),
                default_branch: Some(sync_popup_context.default_branch.clone()),
                is_loading: false,
                message: Self::sync_failure_message(&sync_error),
                title: "Sync failed".to_string(),
            },
        }
    }

    /// Builds success copy for sync completion with pull/push/conflict metrics
    /// rendered as markdown sections with empty lines separating pull, push,
    /// and conflict blocks.
    fn sync_success_message(sync_main_outcome: &SyncMainOutcome) -> String {
        let pulled_summary = Self::sync_commit_summary("pulled", sync_main_outcome.pulled_commits);
        let pulled_titles =
            Self::sync_pulled_commit_titles_summary(&sync_main_outcome.pulled_commit_titles);
        let pushed_titles =
            Self::sync_pushed_commit_titles_summary(&sync_main_outcome.pushed_commit_titles);
        let pushed_summary = Self::sync_commit_summary("pushed", sync_main_outcome.pushed_commits);
        let conflict_summary =
            Self::sync_conflict_summary(&sync_main_outcome.resolved_conflict_files);

        sync_blocked::format_sync_success_message(
            &pulled_summary,
            &pulled_titles,
            &pushed_summary,
            &pushed_titles,
            &conflict_summary,
        )
    }

    /// Returns pulled commit titles formatted as an indented list.
    fn sync_pulled_commit_titles_summary(pulled_commit_titles: &[String]) -> String {
        if pulled_commit_titles.is_empty() {
            return String::new();
        }

        pulled_commit_titles
            .iter()
            .map(|title| format!("  - {title}"))
            .collect::<Vec<String>>()
            .join("\n")
    }

    /// Returns pushed commit titles formatted as an indented list.
    fn sync_pushed_commit_titles_summary(pushed_commit_titles: &[String]) -> String {
        if pushed_commit_titles.is_empty() {
            return String::new();
        }

        pushed_commit_titles
            .iter()
            .map(|title| format!("  - {title}"))
            .collect::<Vec<String>>()
            .join("\n")
    }

    /// Returns sync failure copy with actionable guidance for auth failures.
    ///
    /// Authentication failures show a dismiss-only message so users can fix
    /// credentials first, then restart sync from the list. When the failing
    /// remote host is recognizable, the guidance names the matching forge CLI.
    fn sync_failure_message(sync_error: &SyncSessionStartError) -> String {
        let detail_message = sync_error.detail_message();
        if !is_git_push_authentication_error(&detail_message) {
            return detail_message;
        }

        git_push_authentication_message(
            detected_forge_kind_from_git_push_error(&detail_message),
            "run sync again",
        )
    }

    /// Returns one brief pull/push sentence fragment for sync completion.
    fn sync_commit_summary(direction: &str, commit_count: Option<u32>) -> String {
        match commit_count {
            Some(1) => format!("1 commit {direction}"),
            Some(commit_count) => format!("{commit_count} commits {direction}"),
            None => format!("commits {direction}: unknown"),
        }
    }

    /// Returns one brief conflict-resolution sentence fragment for sync
    /// completion.
    fn sync_conflict_summary(resolved_conflict_files: &[String]) -> String {
        if resolved_conflict_files.is_empty() {
            return "no conflicts fixed".to_string();
        }

        format!("conflicts fixed: {}", resolved_conflict_files.join(", "))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_requested_review_batch_keeps_newer_generation_when_stale_event_arrives_later() {
        // Arrange
        let mut event_batch = AppEventBatch::default();
        let newer_event = AppEvent::RequestedReviewsLoaded {
            generation: 2,
            project_id: 42,
            result: Ok(Vec::new()),
        };
        let stale_event = AppEvent::RequestedReviewsLoaded {
            generation: 1,
            project_id: 42,
            result: Err("stale failure".to_string()),
        };

        // Act
        event_batch.collect_event(newer_event);
        event_batch.collect_event(stale_event);

        // Assert
        let (generation, project_id, result) = event_batch
            .requested_reviews
            .expect("newer requested-review event should be retained");
        assert_eq!(generation, 2);
        assert_eq!(project_id, 42);
        assert_eq!(result.expect("newer result should be successful").len(), 0);
    }
}