ebman 0.7.0

k9s-style TUI for AWS Elastic Beanstalk
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
//! `AppMsg` dispatch.
//!
//! `handle_msg` is a thin router: it enforces the stale-result invariant
//! once, then delegates each variant to a dedicated `handle_*` method.
//! Splitting the bodies out keeps any single function from carrying the
//! whole async-result surface (it was previously one ~1,140-line `match`).

use super::*;

impl AppMsg {
    /// The context generation a result message was produced for, when it
    /// carries one. `handle_msg` drops the message if this no longer
    /// matches `App::generation` — the single enforcement point for the
    /// "results from a superseded context are discarded" invariant.
    /// `Rebuild` and `UpdateCheck` aren't tied to an AWS context, so they
    /// return `None` and are always delivered.
    fn generation(&self) -> Option<u64> {
        use AppMsg::*;
        match self {
            Rebuild(_) | UpdateCheck(_) => None,
            Refresh { gen, .. }
            | Identity { gen, .. }
            | Applications { gen, .. }
            | SolutionStacks { gen, .. }
            | AppLatestVersions { gen, .. }
            | WorkerQueueCheck { gen, .. }
            | EnvInstanceCountsCheck { gen, .. }
            | Events { gen, .. }
            | DetailEvents { gen, .. }
            | ActionResult { gen, .. }
            | DetailInstances { gen, .. }
            | DetailMetrics { gen, .. }
            | DetailLogsProgress { gen, .. }
            | DetailLogs { gen, .. }
            | TextOverlay { gen, .. }
            | AppVersions { gen, .. }
            | DryRunResult { gen, .. }
            | Alarms { gen, .. }
            | WhyRedEvents { gen, .. }
            | WhyRedAlarms { gen, .. }
            | WhyRedInstances { gen, .. }
            | WhyRedDeploys { gen, .. }
            | WhyRedQueues { gen, .. }
            | WhyRedDlqMessages { gen, .. }
            | PreflightEvents { gen, .. }
            | RollbackTarget { gen, .. }
            | DetailTags { gen, .. }
            | DeployFromLocal { gen, .. }
            | LogTailOpened { gen, .. }
            | LogTailEvents { gen, .. }
            | DetailLogGroups { gen, .. }
            | DetailAlarms { gen, .. }
            | EnvVarsForEdit { gen, .. }
            | CostsFetched { gen, .. }
            | DetailRecentVersions { gen, .. }
            | FormPrefilled { gen, .. }
            | FormMultiSelectLoaded { gen, .. }
            | DetailEnvVars { gen, .. }
            | OptionSettingsUpdate { gen, .. }
            | AlarmOp { gen, .. }
            | DeleteAppVersion { gen, .. }
            | TagUpdate { gen, .. }
            | DetailQueues { gen, .. }
            | DlqMessages { gen, .. }
            | DlqActionResult { gen, .. } => Some(*gen),
        }
    }
}

impl App {
    pub(super) fn handle_msg(&mut self, msg: AppMsg) {
        // Single enforcement point for the stale-result invariant: any
        // context-bound message whose generation has been superseded by a
        // context switch is dropped here, so no individual handler needs
        // its own guard.
        if let Some(gen) = msg.generation() {
            if gen != self.generation {
                return;
            }
        }
        match msg {
            AppMsg::Refresh { result, .. } => self.apply_refresh(result),
            AppMsg::Rebuild(result) => self.apply_rebuild(result),
            AppMsg::Identity { result, .. } => self.handle_identity(result),
            AppMsg::Applications { result, .. } => self.handle_applications(result),
            AppMsg::SolutionStacks { result, .. } => self.handle_solution_stacks(result),
            AppMsg::AppLatestVersions { results, .. } => self.handle_app_latest_versions(results),
            AppMsg::WorkerQueueCheck { results, .. } => self.handle_worker_queue_check(results),
            AppMsg::EnvInstanceCountsCheck { results, .. } => {
                self.handle_env_instance_counts(results)
            }
            AppMsg::Events { result, .. } => self.handle_events(result),
            AppMsg::DetailEvents {
                env_name, result, ..
            } => self.handle_detail_events(env_name, result),
            AppMsg::ActionResult {
                action,
                env_name,
                result,
                ..
            } => self.handle_action_result(action, env_name, result),
            AppMsg::DetailInstances {
                env_name, result, ..
            } => self.handle_detail_instances(env_name, result),
            AppMsg::DetailMetrics {
                env_name, result, ..
            } => self.handle_detail_metrics(env_name, result),
            AppMsg::DetailLogsProgress {
                env_name,
                stage,
                attempt,
                ..
            } => self.handle_detail_logs_progress(env_name, stage, attempt),
            AppMsg::DetailLogs {
                env_name, result, ..
            } => self.handle_detail_logs(env_name, result),
            AppMsg::TextOverlay { title, body, .. } => self.handle_text_overlay(title, body),
            AppMsg::AppVersions {
                application,
                deployed_label,
                result,
                ..
            } => self.handle_app_versions(application, deployed_label, result),
            AppMsg::UpdateCheck(latest) => self.handle_update_check(latest),
            AppMsg::DryRunResult {
                env_name, result, ..
            } => self.handle_dry_run_result(env_name, result),
            AppMsg::Alarms {
                env_name, result, ..
            } => self.handle_alarms(env_name, result),
            AppMsg::WhyRedEvents {
                session_id, result, ..
            } => self.handle_why_red_events(session_id, result),
            AppMsg::WhyRedAlarms {
                session_id, result, ..
            } => self.handle_why_red_alarms(session_id, result),
            AppMsg::WhyRedInstances {
                session_id, result, ..
            } => self.handle_why_red_instances(session_id, result),
            AppMsg::WhyRedDeploys {
                session_id, result, ..
            } => self.handle_why_red_deploys(session_id, result),
            AppMsg::WhyRedQueues {
                session_id, result, ..
            } => self.handle_why_red_queues(session_id, result),
            AppMsg::WhyRedDlqMessages {
                session_id, result, ..
            } => self.handle_why_red_dlq_messages(session_id, result),
            AppMsg::PreflightEvents {
                env_name, result, ..
            } => self.handle_preflight_events(env_name, result),
            AppMsg::RollbackTarget {
                env_name,
                current_version,
                result,
                ..
            } => self.handle_rollback_target(env_name, current_version, result),
            AppMsg::DetailTags {
                env_name, result, ..
            } => self.handle_detail_tags(env_name, result),
            AppMsg::DeployFromLocal {
                env_name,
                label,
                summary,
                result,
                ..
            } => self.handle_deploy_from_local(env_name, label, summary, result),
            AppMsg::LogTailOpened {
                session_id,
                env_name,
                log_group,
                since_ms,
                ..
            } => self.handle_log_tail_opened(session_id, env_name, log_group, since_ms),
            AppMsg::LogTailEvents {
                session_id,
                next_since_ms,
                result,
                ..
            } => self.handle_log_tail_events(session_id, next_since_ms, result),
            AppMsg::DetailLogGroups {
                env_name, groups, ..
            } => self.handle_detail_log_groups(env_name, groups),
            AppMsg::DetailAlarms {
                env_name, result, ..
            } => self.handle_detail_alarms(env_name, result),
            AppMsg::EnvVarsForEdit {
                env_name, result, ..
            } => self.handle_env_vars_for_edit(env_name, result),
            AppMsg::CostsFetched {
                account,
                region,
                result,
                ..
            } => self.handle_costs_fetched(account, region, result),
            AppMsg::DetailRecentVersions {
                env_name, result, ..
            } => self.handle_detail_recent_versions(env_name, result),
            AppMsg::FormPrefilled {
                env_name, settings, ..
            } => self.handle_form_prefilled(env_name, settings),
            AppMsg::FormMultiSelectLoaded {
                env_name,
                field_key,
                result,
                ..
            } => self.handle_form_multi_select_loaded(env_name, field_key, result),
            AppMsg::DetailEnvVars {
                env_name, result, ..
            } => self.handle_detail_env_vars(env_name, result),
            AppMsg::OptionSettingsUpdate {
                env_name,
                summary,
                result,
                ..
            } => self.handle_option_settings_update(env_name, summary, result),
            AppMsg::AlarmOp {
                verb,
                alarm_name,
                env_name,
                result,
                ..
            } => self.handle_alarm_op(verb, alarm_name, env_name, result),
            AppMsg::DeleteAppVersion {
                application,
                label,
                force,
                result,
                ..
            } => self.handle_delete_app_version(application, label, force, result),
            AppMsg::TagUpdate {
                env_name,
                summary,
                result,
                ..
            } => self.handle_tag_update(env_name, summary, result),
            AppMsg::DetailQueues {
                env_name, result, ..
            } => self.handle_detail_queues(env_name, result),
            AppMsg::DlqMessages {
                env_name, result, ..
            } => self.handle_dlq_messages(env_name, result),
            AppMsg::DlqActionResult {
                env_name, result, ..
            } => self.handle_dlq_action_result(env_name, result),
        }
    }

    fn handle_identity(&mut self, result: Result<Identity, String>) {
        match result {
            Ok(id) => {
                self.context.account_id = id.account_id;
                self.context.caller_arn = id.caller_arn;
            }
            Err(msg) => {
                tracing::warn!(error = %msg, "identity refresh failed");
            }
        }
    }

    fn handle_applications(&mut self, result: Result<Vec<Application>, String>) {
        match result {
            Ok(mut apps) => {
                apps.sort_by_key(|a| a.name.to_lowercase());
                // Preserve the previously-fetched LATEST values across
                // refreshes so the column doesn't flicker to "—" every
                // tick while the follow-up fan-out is in flight.
                merge_app_latest_versions(&self.applications, &mut apps);
                self.applications = apps;
                // Pinned-first sort runs every refresh so newly-arrived
                // apps don't shuffle the pinned ones off the top row.
                self.resort_applications();
                if self.applications.is_empty() {
                    self.app_table_state.select(None);
                } else if self
                    .app_table_state
                    .selected()
                    .map(|s| s >= self.applications.len())
                    .unwrap_or(true)
                {
                    self.app_table_state.select(Some(0));
                }
                // Fan out latest-version fetches only when the operator is
                // actually looking at the apps view. Otherwise we'd burn N
                // DescribeApplicationVersions calls on every refresh tick
                // for users who live in the envs view all day. Switching
                // scope to Apps (Tab / BackTab) kicks off the fetch on
                // demand; the periodic refresh then keeps it fresh.
                if self.scope == Scope::Apps {
                    self.spawn_app_latest_versions();
                }
            }
            Err(msg) => tracing::warn!(error = %msg, "applications fetch failed"),
        }
    }

    fn handle_solution_stacks(&mut self, result: Result<Vec<String>, String>) {
        match result {
            Ok(stacks) => {
                self.latest_stacks = crate::aws::latest_stack_versions(&stacks);
                // Refresh the derived stale-platform cache now that the
                // catalogue is available — the env list itself is unchanged.
                self.rebuild_view();
            }
            Err(msg) => tracing::warn!(error = %msg, "solution stacks fetch failed"),
        }
    }

    fn handle_app_latest_versions(
        &mut self,
        results: Vec<(
            String,
            Option<String>,
            Option<chrono::DateTime<chrono::Utc>>,
        )>,
    ) {
        let by_name: std::collections::HashMap<_, _> = results
            .into_iter()
            .map(|(name, label, created)| (name, (label, created)))
            .collect();
        for app in self.applications.iter_mut() {
            if let Some((label, created)) = by_name.get(&app.name) {
                app.latest_version_label = label.clone();
                app.latest_version_created = *created;
            }
        }
    }

    fn handle_worker_queue_check(&mut self, results: Vec<(String, i64)>) {
        // Rebuild the cache from scratch so workers whose DLQ drained back
        // to zero are reflected. Missing entries = "fetch failed this
        // tick"; we drop them so a transient SQS error doesn't blank the
        // chip for everyone.
        self.worker_dlq_depths.clear();
        for (env_name, depth) in results {
            self.worker_dlq_depths.insert(env_name, depth);
        }
        // Recompute alerts now that the cache is fresh — the count set
        // during apply_refresh used the *previous* tick's cache. Workers
        // newly above DLQ=0 join the alert pill on the next draw.
        self.alerts = compute_red_alerts(&self.environments, &self.worker_dlq_depths);
    }

    fn handle_env_instance_counts(
        &mut self,
        results: Vec<(String, crate::aws::EnvInstanceCounts)>,
    ) {
        // Same shape as the DLQ cache: full rebuild per refresh so envs
        // whose instances reach Green clear back to a healthy count.
        self.env_instance_counts.clear();
        for (env_name, counts) in results {
            self.env_instance_counts.insert(env_name, counts);
        }
    }

    fn handle_events(&mut self, result: Result<Vec<EbEvent>, String>) {
        match result {
            // The API returns events in time-descending order already.
            Ok(events) => self.event_panel.events = events,
            Err(msg) => tracing::warn!(error = %msg, "event fetch failed"),
        }
    }

    fn handle_detail_events(&mut self, env_name: String, result: Result<Vec<EbEvent>, String>) {
        self.apply_detail_msg(&env_name, result, |d, r| {
            d.loading_events = false;
            match r {
                Ok(events) => {
                    d.events = events;
                    d.error = None;
                }
                Err(msg) => d.error = Some(msg),
            }
        });
    }

    fn handle_action_result(
        &mut self,
        action: Action,
        env_name: String,
        result: Result<(), String>,
    ) {
        write_audit_outcome(
            self.context.account_id.as_deref(),
            self.context.profile.as_deref(),
            &self.context.region,
            action,
            &env_name,
            result.as_ref().map(|_| ()).map_err(|e| e.as_str()),
        );
        // Stamp the matching pending-actions entry with the outcome so the
        // panel shows ✓ / ✗ instead of "in flight".
        self.complete_pending(
            action.label(),
            &env_name,
            result.as_ref().map(|_| ()).map_err(|e| e.clone()),
        );
        match result {
            Ok(()) => {
                self.close_action_flow();
                self.status_message = Some(format!("{} on {env_name} dispatched", action.label()));
                self.spawn_refresh();
            }
            Err(msg) => {
                // Keep the confirm modal open via a Running→error
                // transition; simpler: close flow, surface the error.
                self.close_action_flow();
                self.error_message =
                    Some(format!("{} on {env_name} failed: {msg}", action.label()));
            }
        }
    }

    fn handle_detail_instances(&mut self, env_name: String, result: Result<Vec<Instance>, String>) {
        self.apply_detail_msg(&env_name, result, |d, r| {
            d.loading_instances = false;
            match r {
                Ok(instances) => {
                    d.instances = instances;
                    d.error = None;
                }
                Err(msg) => d.error = Some(msg),
            }
        });
    }

    fn handle_detail_metrics(
        &mut self,
        env_name: String,
        result: Result<Vec<MetricSeries>, String>,
    ) {
        self.apply_detail_msg(&env_name, result, |d, r| {
            d.loading_metrics = false;
            match r {
                Ok(metrics) => {
                    d.metrics = metrics;
                    d.error = None;
                }
                Err(msg) => d.error = Some(msg),
            }
        });
    }

    fn handle_detail_logs_progress(&mut self, env_name: String, stage: LogTailStage, attempt: u32) {
        let Some(detail) = self.detail.as_mut() else {
            return;
        };
        if detail.env_name != env_name {
            return;
        }
        detail.log_tail.stage = stage;
        if matches!(stage, LogTailStage::Polling) {
            detail.log_tail.poll_attempt = attempt;
        }
    }

    fn handle_detail_logs(
        &mut self,
        env_name: String,
        result: Result<Vec<(String, String)>, String>,
    ) {
        let Some(detail) = self.detail.as_mut() else {
            return;
        };
        if detail.env_name != env_name {
            return;
        }
        match result {
            Ok(by_instance) => {
                detail.log_tail.by_instance = by_instance;
                detail.log_tail.stage = LogTailStage::Ready;
                detail.log_tail.error = None;
            }
            Err(msg) => {
                detail.log_tail.stage = LogTailStage::Ready;
                detail.log_tail.error = Some(msg);
            }
        }
    }

    fn handle_text_overlay(&mut self, title: String, body: String) {
        self.current_overlay = Some(Overlay::TextDump { title, body });
    }

    fn handle_app_versions(
        &mut self,
        application: String,
        deployed_label: Option<String>,
        result: Result<Vec<AppVersion>, String>,
    ) {
        match result {
            Ok(versions) if versions.is_empty() => {
                self.status_message = Some(format!("no application versions for {application}"));
            }
            Ok(versions) => {
                self.current_overlay = Some(Overlay::TextDump {
                    title: format!("application versions — {application}"),
                    body: format_app_versions(&versions, deployed_label.as_deref(), 20),
                });
            }
            Err(msg) => self.error_message = Some(msg),
        }
    }

    fn handle_update_check(&mut self, latest: Option<crate::update_check::LatestRelease>) {
        if let Some(release) = latest {
            tracing::info!(target: "ebman::update", current = env!("CARGO_PKG_VERSION"), latest = %release.version, "newer ebman released on crates.io");
            self.update_available = Some(release);
        }
    }

    fn handle_dry_run_result(&mut self, env_name: String, result: Result<Vec<Instance>, String>) {
        let Some(ActionFlow::Confirm(modal)) = self.action_flow.as_mut() else {
            return;
        };
        if modal.target_env != env_name {
            return;
        }
        modal.loading_dryrun = false;
        if let Ok(instances) = result {
            let azs: std::collections::HashSet<&str> = instances
                .iter()
                .map(|i| i.availability_zone.as_str())
                .filter(|az| !az.is_empty())
                .collect();
            modal.dryrun = Some(DryRunInfo {
                instance_count: instances.len(),
                az_count: azs.len(),
            });
        }
    }

    fn handle_alarms(&mut self, env_name: String, result: Result<Vec<CwAlarm>, String>) {
        // Drop stale results: the user may have closed the overlay or
        // requested alarms for a different env during the round-trip. The
        // overlay carries the env it was opened for; only replace its body
        // if that still matches the result we just received.
        match self.current_overlay.as_mut() {
            Some(Overlay::Alarms {
                env_name: requested,
                body,
            }) if requested == &env_name => {
                *body = format_alarms(result);
            }
            _ => (),
        }
    }

    fn handle_why_red_events(&mut self, session_id: u64, result: Result<Vec<EbEvent>, String>) {
        if let Some(Overlay::WhyRed {
            session_id: s,
            events,
            ..
        }) = self.current_overlay.as_mut()
        {
            if *s == session_id {
                *events = Some(result);
            }
        }
    }

    fn handle_why_red_alarms(&mut self, session_id: u64, result: Result<Vec<CwAlarm>, String>) {
        if let Some(Overlay::WhyRed {
            session_id: s,
            alarms,
            ..
        }) = self.current_overlay.as_mut()
        {
            if *s == session_id {
                *alarms = Some(result);
            }
        }
    }

    fn handle_why_red_instances(&mut self, session_id: u64, result: Result<Vec<Instance>, String>) {
        if let Some(Overlay::WhyRed {
            session_id: s,
            instances,
            ..
        }) = self.current_overlay.as_mut()
        {
            if *s == session_id {
                *instances = Some(result);
            }
        }
    }

    fn handle_why_red_deploys(&mut self, session_id: u64, result: Result<Vec<AppVersion>, String>) {
        if let Some(Overlay::WhyRed {
            session_id: s,
            deploys,
            ..
        }) = self.current_overlay.as_mut()
        {
            if *s == session_id {
                *deploys = Some(result);
            }
        }
    }

    fn handle_why_red_queues(&mut self, session_id: u64, result: Result<WorkerQueues, String>) {
        // Land the queues result, then kick the DLQ peek if the DLQ has
        // visible messages. The peek is a second-stage fetch — it only
        // fires when the first stage shows something worth peeking at,
        // avoiding pointless SQS calls on healthy workers.
        let mut dlq_url_to_peek: Option<String> = None;
        if let Some(Overlay::WhyRed {
            session_id: s,
            queues,
            dlq_messages,
            ..
        }) = self.current_overlay.as_mut()
        {
            if *s == session_id {
                if let Ok(ref qs) = result {
                    let dlq_visible = qs.dlq_stats.as_ref().map(|s| s.visible).unwrap_or(0);
                    if dlq_visible > 0 {
                        if let Some(url) = qs.dlq_url.clone() {
                            dlq_url_to_peek = Some(url);
                        }
                    } else {
                        // Mark dlq_messages as resolved-empty so the
                        // renderer doesn't show "loading…" forever for a
                        // clean DLQ.
                        *dlq_messages = Some(Ok(Vec::new()));
                    }
                }
                *queues = Some(result);
            }
        }
        if let Some(url) = dlq_url_to_peek {
            self.spawn_why_red_dlq_peek(url, session_id);
        }
    }

    fn handle_why_red_dlq_messages(
        &mut self,
        session_id: u64,
        result: Result<Vec<QueueMessage>, String>,
    ) {
        if let Some(Overlay::WhyRed {
            session_id: s,
            dlq_messages,
            ..
        }) = self.current_overlay.as_mut()
        {
            if *s == session_id {
                *dlq_messages = Some(result);
            }
        }
    }

    fn handle_preflight_events(&mut self, env_name: String, result: Result<Vec<EbEvent>, String>) {
        let Some(ActionFlow::Confirm(modal)) = self.action_flow.as_mut() else {
            return;
        };
        if modal.target_env != env_name {
            return;
        }
        modal.loading_events = false;
        if let Ok(events) = result {
            modal.recent_events = Some(events);
        }
    }

    fn handle_rollback_target(
        &mut self,
        env_name: String,
        current_version: String,
        result: Result<Vec<EbEvent>, String>,
    ) {
        match result {
            Err(e) => self.error_message = Some(format!("rollback: {e}")),
            Ok(events) => match previous_version_label(&events, &current_version) {
                None => {
                    self.error_message = Some(format!(
                        "rollback: no prior version in {env_name}'s recent events — use :versions then :deploy"
                    ));
                }
                // The deploy-confirm modal targets the *selected* env; if
                // the cursor moved off the env `:rollback` was issued for,
                // bail rather than roll back the wrong one.
                Some(_)
                    if self.selected_env().map(|e| e.name.as_str()) != Some(env_name.as_str()) =>
                {
                    self.error_message =
                        Some("rollback cancelled — selection moved off the target env".into());
                }
                Some(prev) => {
                    self.status_message = Some(format!(
                        "rollback {env_name}: redeploying previous version {prev}"
                    ));
                    self.open_parameterised_action(
                        Action::Deploy,
                        ParameterisedAction {
                            deploy_version: Some(prev),
                            ..Default::default()
                        },
                    );
                }
            },
        }
    }

    fn handle_detail_tags(
        &mut self,
        env_name: String,
        result: Result<Vec<(String, String)>, String>,
    ) {
        self.apply_detail_msg(&env_name, result, |d, r| {
            d.loading_tags = false;
            match r {
                Ok(tags) => {
                    d.tags = tags;
                    // A delete may have shrunk the list / removed the row
                    // mid-edit.
                    d.clamp_config_cursor();
                    d.revalidate_config_edit();
                }
                Err(msg) => tracing::warn!(error = %msg, "tags fetch failed"),
            }
        });
    }

    fn handle_deploy_from_local(
        &mut self,
        env_name: String,
        label: String,
        summary: String,
        result: Result<(), String>,
    ) {
        self.complete_pending(
            &summary,
            &env_name,
            result.as_ref().map(|_| ()).map_err(|e| e.clone()),
        );
        match result {
            Ok(()) => {
                self.push_toast(
                    ToastKind::Info,
                    format!("{summary}{env_name} (version {label})"),
                );
            }
            Err(msg) => {
                self.push_toast(
                    ToastKind::Error,
                    format!("{summary} on {env_name} failed: {msg}"),
                );
            }
        }
    }

    fn handle_log_tail_opened(
        &mut self,
        session_id: u64,
        env_name: String,
        log_group: String,
        since_ms: i64,
    ) {
        if session_id != self.log_tail_session {
            return;
        }
        self.current_overlay = Some(Overlay::LogTail {
            log_group,
            env_name,
            events: std::collections::VecDeque::with_capacity(LOG_TAIL_MAX_LINES),
            scroll: 0,
            following: true,
            since_ms,
            filter_input: String::new(),
            filter_active: false,
            filter_pattern: None,
            last_err: None,
            session_id,
        });
        self.status_message = None;
    }

    fn handle_log_tail_events(
        &mut self,
        session_id: u64,
        next_since_ms: i64,
        result: Result<Vec<crate::aws::LogEvent>, String>,
    ) {
        if session_id != self.log_tail_session {
            return;
        }
        // Route to whichever overlay slot currently holds the LogTail —
        // `current_overlay` normally, or `pre_help_overlay` if the user
        // pressed `?` mid-tail. Without the second slot, events arriving
        // during the help round-trip would be lost.
        let target = if matches!(
            self.current_overlay.as_ref(),
            Some(Overlay::LogTail { session_id: s, .. }) if *s == session_id
        ) {
            self.current_overlay.as_mut()
        } else if matches!(
            self.help.pre_overlay.as_ref(),
            Some(Overlay::LogTail { session_id: s, .. }) if *s == session_id
        ) {
            self.help.pre_overlay.as_mut()
        } else {
            return;
        };
        let Some(Overlay::LogTail {
            events,
            since_ms,
            last_err,
            ..
        }) = target
        else {
            return;
        };
        *since_ms = next_since_ms;
        match result {
            Ok(new_events) => {
                *last_err = None;
                for ev in new_events {
                    if events.len() >= LOG_TAIL_MAX_LINES {
                        events.pop_front();
                    }
                    events.push_back(ev);
                }
            }
            Err(msg) => {
                *last_err = Some(msg);
            }
        }
    }

    fn handle_detail_log_groups(&mut self, env_name: String, groups: Vec<String>) {
        let Some(detail) = self.detail.as_mut() else {
            return;
        };
        if detail.env_name != env_name {
            return;
        }
        detail.cw_log_groups = Some(groups);
    }

    fn handle_detail_alarms(
        &mut self,
        env_name: String,
        result: Result<Vec<crate::aws::CwAlarm>, String>,
    ) {
        let Some(detail) = self.detail.as_mut() else {
            return;
        };
        if detail.env_name != env_name {
            return;
        }
        detail.loading_cw_alarms = false;
        detail.cw_alarms = Some(result);
    }

    fn handle_env_vars_for_edit(
        &mut self,
        env_name: String,
        result: Result<Vec<(String, String)>, String>,
    ) {
        match result {
            Ok(vars) => {
                // Stash for the main loop to consume. The editor shell-out
                // has to happen there because that's where the `Tui`
                // handle is.
                self.pending_env_edit = Some((env_name, vars));
            }
            Err(msg) => {
                self.error_message = Some(format!("env-edit fetch: {msg}"));
            }
        }
    }

    fn handle_costs_fetched(
        &mut self,
        account: Option<String>,
        region: String,
        result: Result<Vec<crate::aws::EnvCost>, String>,
    ) {
        match result {
            Ok(rows) => {
                let now = chrono::Utc::now();
                self.costs.clear();
                for row in &rows {
                    self.costs.insert(row.env_name.clone(), row.cost_usd);
                }
                self.costs_fetched_at = Some(now);
                // Persist to ~/.cache/ebman/cost-{account}-{region}.toml so
                // subsequent sessions render immediately.
                let account_key = account.unwrap_or_else(|| "unknown".into());
                let cache = crate::cost_cache::CostCache {
                    fetched_at: Some(now),
                    costs: self.costs.clone(),
                };
                if let Err(e) = crate::cost_cache::save(&account_key, &region, &cache) {
                    tracing::warn!(
                        target: "ebman::cost",
                        error = %e,
                        "cost cache write failed (non-fatal)"
                    );
                }
                let n = rows.len();
                self.status_message = Some(format!("cost: refreshed {n} env(s)"));
            }
            Err(msg) => {
                self.error_message = Some(format!("cost fetch: {msg}"));
            }
        }
    }

    fn handle_detail_recent_versions(
        &mut self,
        env_name: String,
        result: Result<Vec<crate::aws::AppVersion>, String>,
    ) {
        let Some(detail) = self.detail.as_mut() else {
            return;
        };
        if detail.env_name != env_name {
            return;
        }
        detail.loading_recent_versions = false;
        detail.recent_versions = Some(result);
    }

    fn handle_form_prefilled(
        &mut self,
        env_name: String,
        settings: Result<Vec<(String, String, String)>, String>,
    ) {
        let Some(form) = self.form.as_mut() else {
            return;
        };
        if form.env_name != env_name {
            return;
        }
        match settings {
            Err(msg) => {
                // Surface the fetch failure on the form's first field as a
                // global error; operator can dismiss or fill values
                // manually.
                if let Some(first) = form.fields.first_mut() {
                    first.error = Some(format!("pre-fill failed: {msg}"));
                }
                form.state = crate::form::FormState::Ready;
            }
            Ok(rows) => {
                // Build a (ns, name) -> value lookup; populate the form's
                // fields using the mappings stored on submit.
                use std::collections::HashMap;
                let lookup: HashMap<(String, String), String> = rows
                    .into_iter()
                    .map(|(ns, name, value)| ((ns, name), value))
                    .collect();
                let mappings = match &form.submit {
                    crate::form::FormSubmit::OptionSettings { mappings } => mappings.clone(),
                    // LocalConfig forms skip the AWS pre-fill in `open_form`
                    // so the FormPrefilled msg never fires for them — drop
                    // the result if one arrives anyway (stale message after
                    // the user switched form types).
                    crate::form::FormSubmit::LocalConfig => return,
                };
                for (key, ns, opt) in mappings {
                    if let Some(value) = lookup.get(&(ns, opt)) {
                        if let Some(field) = form.fields.iter_mut().find(|f| f.key == key) {
                            field.value = value.clone();
                        }
                    }
                }
                form.state = crate::form::FormState::Ready;
            }
        }
    }

    fn handle_form_multi_select_loaded(
        &mut self,
        env_name: String,
        field_key: String,
        result: Result<MultiSelectOptions, String>,
    ) {
        let Some(form) = self.form.as_mut() else {
            return;
        };
        if form.env_name != env_name {
            return;
        }
        let Some(field) = form.fields.iter_mut().find(|f| f.key == field_key) else {
            return;
        };
        match result {
            Err(msg) => {
                field.error = Some(format!("load failed: {msg}"));
                form.state = crate::form::FormState::Ready;
            }
            Ok(opts) => {
                let initial_filtered: Vec<String> = opts
                    .initial
                    .iter()
                    .filter(|v| opts.options.iter().any(|o| o == *v))
                    .cloned()
                    .collect();
                field.value = initial_filtered.join(",");
                field.kind = crate::form::FieldKind::MultiSelect {
                    options: opts.options.clone(),
                };
                if opts.annotations.len() == opts.options.len() && !opts.annotations.is_empty() {
                    field.option_annotations = Some(opts.annotations);
                }
                field.option_cursor = 0;
                form.state = crate::form::FormState::Ready;
            }
        }
    }

    fn handle_detail_env_vars(
        &mut self,
        env_name: String,
        result: Result<Vec<(String, String)>, String>,
    ) {
        self.apply_detail_msg(&env_name, result, |d, r| {
            d.loading_env_vars = false;
            match r {
                Ok(vars) => {
                    d.env_vars = vars;
                    // A delete may have shrunk the list / removed the row
                    // mid-edit.
                    d.clamp_config_cursor();
                    d.revalidate_config_edit();
                }
                Err(msg) => tracing::warn!(error = %msg, "env vars fetch failed"),
            }
        });
    }

    fn handle_option_settings_update(
        &mut self,
        env_name: String,
        summary: String,
        result: Result<(), String>,
    ) {
        self.complete_pending(
            &summary,
            &env_name,
            result.as_ref().map(|_| ()).map_err(|e| e.clone()),
        );
        match result {
            Ok(()) => {
                self.push_toast(ToastKind::Success, format!("{summary}{env_name}"));
                // If it was an env-var set/unset/rename and the Detail view
                // is open on the same env, refresh the Config tab's env
                // vars so the change reflects without waiting for the next
                // 15s tick.
                if summary.starts_with("env set ")
                    || summary.starts_with("env unset ")
                    || summary.starts_with("env rename ")
                {
                    if let Some(d) = self.detail.as_ref() {
                        if d.env_name == env_name {
                            self.spawn_detail_env_vars();
                        }
                    }
                }
            }
            Err(msg) => {
                self.push_toast(
                    ToastKind::Error,
                    format!("{summary} on {env_name} failed: {msg}"),
                );
            }
        }
    }

    fn handle_alarm_op(
        &mut self,
        verb: &'static str,
        alarm_name: String,
        env_name: String,
        result: Result<(), String>,
    ) {
        let label = match verb {
            "create" => "Create alarm",
            "delete" => "Delete alarm",
            _ => "Alarm op",
        };
        let target = format!("{env_name}/{alarm_name}");
        self.complete_pending(
            label,
            &target,
            result.as_ref().map(|_| ()).map_err(|e| e.clone()),
        );
        match result {
            Ok(()) => {
                let past = if verb == "create" {
                    "created"
                } else {
                    "deleted"
                };
                self.push_toast(ToastKind::Success, format!("alarm '{alarm_name}' {past}"));
            }
            Err(msg) => {
                self.push_toast(
                    ToastKind::Error,
                    format!("alarm '{alarm_name}' {verb} failed: {msg}"),
                );
            }
        }
    }

    fn handle_delete_app_version(
        &mut self,
        application: String,
        label: String,
        force: bool,
        result: Result<(), String>,
    ) {
        let force_str = if force { " (+source bundle)" } else { "" };
        let pending_label = if force {
            "Delete app version (+source)"
        } else {
            "Delete app version"
        };
        let pending_target = format!("{application}/{label}");
        self.complete_pending(
            pending_label,
            &pending_target,
            result.as_ref().map(|_| ()).map_err(|e| e.clone()),
        );
        match result {
            Ok(()) => {
                self.push_toast(
                    ToastKind::Info,
                    format!("deleted {application}/{label}{force_str}"),
                );
                // If the user has the matching `:versions` overlay open,
                // re-fetch so the deleted entry disappears instead of
                // lingering as stale text.
                let want_title = format!("application versions — {application}");
                if matches!(
                    self.current_overlay.as_ref(),
                    Some(Overlay::TextDump { title, .. }) if title == &want_title
                ) {
                    let aws = self.aws.clone();
                    let tx = self.msg_tx.clone();
                    let gen = self.generation;
                    let app_name = application.clone();
                    // Look up the env's currently-deployed version to
                    // re-mark it after the refresh. Picks the first env in
                    // this application — single-env case is the norm;
                    // multi-env case is rare and the marker is best-effort
                    // anyway.
                    let deployed_label = self
                        .environments
                        .iter()
                        .find(|e| e.application == application)
                        .filter(|e| !e.version_label.is_empty())
                        .map(|e| e.version_label.clone());
                    tokio::spawn(async move {
                        let result = aws
                            .list_application_versions(&app_name)
                            .await
                            .map_err(|e| flatten_err("list_application_versions", e));
                        let _ = tx.send(AppMsg::AppVersions {
                            gen,
                            application: app_name,
                            deployed_label,
                            result,
                        });
                    });
                }
            }
            Err(msg) => {
                self.push_toast(
                    ToastKind::Error,
                    format!("delete {application}/{label}{force_str} failed: {msg}"),
                );
            }
        }
    }

    fn handle_tag_update(&mut self, env_name: String, summary: String, result: Result<(), String>) {
        self.complete_pending(
            &summary,
            &env_name,
            result.as_ref().map(|_| ()).map_err(|e| e.clone()),
        );
        match result {
            Ok(()) => {
                self.push_toast(ToastKind::Info, format!("{summary} on {env_name}"));
                if let Some(d) = self.detail.as_ref() {
                    if d.env_name == env_name {
                        self.spawn_detail_tags();
                    }
                }
            }
            Err(msg) => {
                self.push_toast(
                    ToastKind::Error,
                    format!("{summary} on {env_name} failed: {msg}"),
                );
            }
        }
    }

    fn handle_detail_queues(&mut self, env_name: String, result: Result<WorkerQueues, String>) {
        self.apply_detail_msg(&env_name, result, |d, r| {
            d.loading_queues = false;
            match r {
                Ok(queues) => {
                    d.queues = queues;
                    d.error = None;
                }
                Err(msg) => d.error = Some(msg),
            }
        });
    }

    fn handle_dlq_messages(&mut self, env_name: String, result: Result<Vec<QueueMessage>, String>) {
        let Some(dlq) = self.dlq.as_mut() else { return };
        if dlq.env_name != env_name {
            return;
        }
        dlq.loading = false;
        match result {
            Ok(messages) => {
                dlq.messages = messages;
                let cur = dlq.list_state.selected().unwrap_or(0);
                if dlq.messages.is_empty() {
                    dlq.list_state.select(None);
                } else if cur >= dlq.messages.len() {
                    dlq.list_state.select(Some(0));
                }
                dlq.error = None;
            }
            Err(msg) => dlq.error = Some(msg),
        }
    }

    fn handle_dlq_action_result(&mut self, env_name: String, result: Result<DlqOp, String>) {
        let mut refetch = false;
        {
            let Some(dlq) = self.dlq.as_mut() else { return };
            if dlq.env_name != env_name {
                return;
            }
            match result {
                Ok(DlqOp::Resent { message_id }) => {
                    dlq.messages.retain(|m| m.id != message_id);
                    self.status_message = Some(format!("message {message_id} resent"));
                }
                Ok(DlqOp::Purged) => {
                    dlq.messages.clear();
                    self.status_message = Some("DLQ purged".into());
                }
                Ok(DlqOp::Replayed { count, failures }) => {
                    if failures == 0 {
                        self.status_message =
                            Some(format!("replayed {count} message(s) to the main queue"));
                    } else {
                        self.error_message =
                            Some(format!("replayed {count}, {failures} failed — see log"));
                    }
                    // The loaded page changed substantially — refetch rather
                    // than reconcile message ids one by one.
                    refetch = true;
                }
                Err(msg) => dlq.error = Some(msg),
            }
        }
        if refetch {
            self.spawn_dlq_fetch();
        }
    }
}

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

    #[test]
    fn generation_is_none_for_context_independent_messages() {
        // `Rebuild` / `UpdateCheck` aren't tied to an AWS context — they
        // must always be delivered, never gen-dropped.
        assert_eq!(AppMsg::UpdateCheck(None).generation(), None);
        assert_eq!(AppMsg::Rebuild(Err("boom".into())).generation(), None);
    }

    #[test]
    fn generation_extracts_gen_from_context_bound_messages() {
        assert_eq!(
            AppMsg::Refresh {
                gen: 7,
                result: Ok(Vec::new()),
            }
            .generation(),
            Some(7)
        );
        assert_eq!(
            AppMsg::Events {
                gen: 42,
                result: Ok(Vec::new()),
            }
            .generation(),
            Some(42)
        );
    }
}