ebman 0.34.1

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
//! The Detail pane: tabs, instances, metrics, alarms.
//!
//! Split out of the 9,515-line `app/tests.rs`. Bodies moved
//! unchanged apart from one rewrite: `super::` meant `crate::app` in
//! the flat file and would mean `crate::app::tests` here, so every
//! explicit `super::` path was re-anchored (rustfmt reflowed some
//! lines as a result, since the new path is longer).

use super::super::*;
#[allow(unused_imports)]
use super::support::*;

#[test]
fn render_env_resources_tree_marks_orphan_instances_when_no_asg() {
    let mut res = empty_resources();
    res.instances = vec!["i-stranded".into()];
    let body = crate::app::render_env_resources_tree(&res, "env", "Web");
    assert!(body.contains("orphan (no ASG attached)"));
    assert!(body.contains("i-stranded"));
}

#[tokio::test]
async fn tab_in_command_mode_cycles_through_matches() {
    let mut app = test_app();
    app.mode = Mode::Command;
    app.command_input = "bat".into();
    // First Tab → first match (batch-deploy alphabetically).
    press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
    let first = app.command_input.text().to_string();
    assert!(
        first.starts_with("bat"),
        "Tab should keep the bat-prefix; got {first:?}"
    );
    assert!(
        crate::commands::all_names().contains(&first.as_str()),
        "Tab should expand to a real command name; got {first:?}"
    );
    // Second Tab cycles forward; should differ from first.
    press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
    let second = app.command_input.text().to_string();
    assert_ne!(first, second, "second Tab should advance the cycle");
}

#[tokio::test]
async fn shift_tab_cycles_backward() {
    let mut app = test_app();
    app.mode = Mode::Command;
    app.command_input = "ba".into();
    press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
    let forward = app.command_input.clone();
    press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
    press(&mut app, KeyCode::BackTab, KeyModifiers::NONE);
    // Two forward + one back = same as one forward.
    assert_eq!(
        app.command_input, forward,
        "Tab Tab BackTab should land on the first match"
    );
}

#[tokio::test]
async fn first_tab_lands_on_the_first_candidate() {
    // Regression: first Tab used to skip to candidates[1].
    let mut app = test_app();
    app.mode = Mode::Command;
    app.command_input = "ba".into();
    let expected = crate::app::completion_candidates("ba");
    press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
    assert_eq!(
        app.command_input.text(),
        expected[0],
        "first Tab should land on the first match, not skip it"
    );
}

#[tokio::test]
async fn tab_completes_env_name_for_diff() {
    let mut app = test_app();
    app.environments = vec![
        mk_env("prod-api", "shop", "Web", "Red"),
        mk_env("prod-worker", "shop", "Worker", "Green"),
    ];
    app.mode = Mode::Command;
    app.command_input = "diff prod".into();
    press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
    // Completes the trailing token, preserving the command + space.
    assert_eq!(app.command_input.text(), "diff prod-api");
    // Second Tab cycles to the next matching env.
    press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
    assert_eq!(app.command_input.text(), "diff prod-worker");
}

#[tokio::test]
async fn tab_completes_second_env_name_for_diff() {
    // `:diff ENV-A ENV-B` — the trailing (second) token completes.
    let mut app = test_app();
    app.environments = vec![
        mk_env("prod-api", "shop", "Web", "Red"),
        mk_env("staging-api", "shop", "Web", "Green"),
    ];
    app.mode = Mode::Command;
    app.command_input = "diff prod-api sta".into();
    press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
    assert_eq!(app.command_input.text(), "diff prod-api staging-api");
}

#[tokio::test]
async fn tab_on_non_env_command_preserves_arg_tail() {
    // A non-env command still re-completes only the verb; the arg
    // after the first space passes through untouched (legacy
    // `:set-option aws` behaviour).
    let mut app = test_app();
    app.environments = vec![mk_env("prod-api", "shop", "Web", "Green")];
    app.mode = Mode::Command;
    app.command_input = "set-option aws".into();
    press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
    let out = app.command_input.text().to_string();
    assert!(
        out.starts_with("set-option") && out.ends_with(" aws"),
        "verb re-completed, arg tail preserved; got {out:?}"
    );
}

#[tokio::test]
async fn tab_env_arg_with_no_match_restores_and_hints() {
    let mut app = test_app();
    app.environments = vec![mk_env("prod-api", "shop", "Web", "Green")];
    app.mode = Mode::Command;
    app.command_input = "diff zzz".into();
    press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
    assert_eq!(
        app.command_input.text(),
        "diff zzz",
        "no env match restores the typed input"
    );
    assert!(app
        .status_message
        .as_deref()
        .is_some_and(|m| m.contains("no environment matches")));
}

#[tokio::test]
async fn tab_env_arg_survives_multibyte_whitespace() {
    // Regression: rfind gives the first byte of the last whitespace
    // char; a multi-byte space (U+00A0 NBSP) used to slice mid-char
    // and panic the TUI. It must complete cleanly, not crash.
    let mut app = test_app();
    app.environments = vec![mk_env("prod-api", "shop", "Web", "Green")];
    app.mode = Mode::Command;
    app.command_input = "diff prod\u{00A0}".into();
    press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
    assert_eq!(app.command_input.text(), "diff prod\u{00A0}prod-api");
}

#[test]
fn alarm_kind_to_metric_covers_known_kinds() {
    use crate::app::alarm_kind_to_metric;
    let (m, op, _) = alarm_kind_to_metric("health").unwrap();
    assert_eq!(m, "EnvironmentHealth");
    // Health is "drop below" → LessThanOrEqualToThreshold.
    assert_eq!(op, "LessThanOrEqualToThreshold");
    let (m, op, _) = alarm_kind_to_metric("5xx").unwrap();
    assert_eq!(m, "ApplicationRequests5xx");
    assert_eq!(op, "GreaterThanThreshold");
    // Aliases.
    assert_eq!(alarm_kind_to_metric("req5xx"), alarm_kind_to_metric("5xx"));
    assert_eq!(alarm_kind_to_metric("p90"), alarm_kind_to_metric("latency"));
    // Unknown.
    assert!(alarm_kind_to_metric("cpu").is_none());
    assert!(alarm_kind_to_metric("").is_none());
}

#[test]
fn palette_score_prefers_label_prefix_then_substring_then_detail() {
    // Empty needle returns score 0 for everything.
    assert_eq!(palette_score("", "anything", "anything"), Some(0));
    // Label prefix → 0.
    assert_eq!(palette_score("reg", "region", "switch AWS region"), Some(0));
    // Label substring later in string → higher score.
    let s_label = palette_score("ion", "region", "switch AWS region").unwrap();
    assert!(s_label > 0 && s_label < 1_000);
    // Detail-only match is penalised by +1000 vs label.
    let s_detail = palette_score("aws", ":region", "switch AWS profile").unwrap();
    let s_label_match = palette_score("aws", "aws-thing", "irrelevant").unwrap();
    assert!(s_detail >= 1_000);
    assert!(s_label_match < s_detail);
    // No match → None.
    assert_eq!(palette_score("xyzzy", "region", "switch AWS region"), None);
}

#[tokio::test]
async fn ssh_no_arg_without_detail_errors_clearly() {
    // Without an arg and without Detail/Instances loaded, there's
    // nothing to populate the picker with. Surface that the
    // operator either needs to open Detail or pass an ID — don't
    // silently no-op.
    let mut app = test_app();
    app.execute_command("ssh");
    assert!(app.picker.is_none());
    let err = app.error_message.as_deref().unwrap_or("");
    assert!(
        err.contains("Detail") || err.contains("instance ID"),
        "expected guidance about Detail/Instances or instance ID, got: {err}"
    );
}

#[tokio::test]
async fn ssm_run_without_detail_errors_with_instances_guidance() {
    // No Detail open → no cached instances → command should refuse
    // rather than silently no-op.
    let mut app = test_app();
    app.execute_command("ssm-run \"uptime\"");
    let err = app.error_message.as_deref().unwrap_or("");
    assert!(
        err.contains("Detail") && err.contains("Instances"),
        "expected Detail/Instances guidance, got: {err}"
    );
}

#[test]
fn format_alarm_history_renders_entries_and_empty_stub() {
    use chrono::TimeZone;
    let ts = |h, mi| chrono::Utc.with_ymd_and_hms(2026, 5, 24, h, mi, 0).unwrap();
    let mk = |t, kind: &str, summary: &str| crate::aws::AlarmHistoryEntry {
        at: Some(t),
        kind: kind.into(),
        summary: summary.into(),
    };
    // Empty entries → stub body + the 90-day retention hint so an
    // operator looking at an alarm with no recent transitions
    // doesn't assume the fetch broke.
    let stub = crate::app::format_alarm_history("high-cpu", &[]);
    assert!(stub.contains("No history items"));
    assert!(stub.contains("90 days"));
    // Real entries → each row carries timestamp, kind in brackets,
    // and the summary line. Order preserved (newest-first per the
    // SDK's default).
    let entries = vec![
        mk(ts(12, 5), "StateUpdate", "Alarm updated from OK to ALARM"),
        mk(ts(11, 0), "ConfigurationUpdate", "Threshold changed to 80"),
    ];
    let body = crate::app::format_alarm_history("high-cpu", &entries);
    assert!(body.contains("[StateUpdate]"));
    assert!(body.contains("[ConfigurationUpdate]"));
    assert!(body.contains("Alarm updated from OK to ALARM"));
    assert!(body.contains("Threshold changed to 80"));
    // Newest-first preserved: StateUpdate appears before ConfigurationUpdate.
    let p_state = body.find("StateUpdate").unwrap();
    let p_cfg = body.find("ConfigurationUpdate").unwrap();
    assert!(p_state < p_cfg);
}

#[test]
fn format_alarm_history_handles_missing_timestamp() {
    // A history item without a timestamp shouldn't blank out the
    // row — render `—` so the kind/summary still scan.
    let entries = vec![crate::aws::AlarmHistoryEntry {
        at: None,
        kind: "StateUpdate".into(),
        summary: "Alarm went ALARM".into(),
    }];
    let body = crate::app::format_alarm_history("high-cpu", &entries);
    assert!(body.contains(""));
    assert!(body.contains("Alarm went ALARM"));
}

#[test]
fn format_alarms_handles_empty_and_error() {
    let none = format_alarms(Ok(vec![]));
    assert!(none.contains("no CloudWatch alarms"));
    let err = format_alarms(Err("boom".into()));
    assert!(err.contains("error"));
    let alarms = format_alarms(Ok(vec![CwAlarm {
        name: "high-cpu".into(),
        state: "ALARM".into(),
        state_reason: "CPU > 80%".into(),
        metric_name: "CPUUtilization".into(),
        namespace: "AWS/EC2".into(),
    }]));
    assert!(alarms.contains("ALARM"));
    assert!(alarms.contains("high-cpu"));
    assert!(alarms.contains("CPU > 80%"));
}

#[test]
fn detail_tab_titles_are_distinct() {
    use std::collections::HashSet;
    let titles: HashSet<&str> = [
        DetailTab::Health,
        DetailTab::Events,
        DetailTab::Instances,
        DetailTab::Metrics,
        DetailTab::Queue,
        DetailTab::Config,
    ]
    .iter()
    .map(|t| t.title())
    .collect();
    assert_eq!(titles.len(), 6);
}

#[tokio::test]
async fn tab_cycles_scope_envs_to_apps_and_back() {
    let mut app = test_app();
    assert_eq!(app.scope, Scope::Envs);
    press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
    assert_eq!(app.scope, Scope::Apps);
    press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
    assert_eq!(app.scope, Scope::Envs);
}

// --- coverage for the panic-site totalisations ------------------------

#[tokio::test]
async fn tab_completes_an_env_name_after_an_env_taking_command() {
    // Exercises `command_completion_step`'s env-mode branch — the one
    // that splits the input at the last whitespace. Previously that
    // `rfind` was an `expect` resting on the earlier `find`.
    let mut app = test_app();
    app.environments = vec![
        fake_env_with("api-prod", "Ready", "Green", None),
        fake_env_with("web-prod", "Ready", "Green", None),
    ];
    app.rebuild_view();
    app.mode = Mode::Command;
    app.command_input = "config-diff api".into();
    press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
    assert_eq!(
        app.command_input.text(),
        "config-diff api-prod",
        "the command prefix is preserved and the env name completed"
    );
}

#[tokio::test]
async fn tab_completes_an_env_name_across_a_multibyte_space() {
    // U+00A0 is whitespace and three bytes wide; `rfind` returns its
    // first byte, so the split has to step over the whole char.
    let mut app = test_app();
    app.environments = vec![fake_env_with("api-prod", "Ready", "Green", None)];
    app.rebuild_view();
    app.mode = Mode::Command;
    app.command_input = "config-diff\u{00A0}api".into();
    press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
    assert!(
        app.command_input.text().ends_with("api-prod"),
        "got {:?}",
        app.command_input.text()
    );
}

#[tokio::test]
async fn config_tab_renders_the_in_place_value_editor() {
    // `draw_detail_config` matched on `editing.map(|e| e.mode)` and then
    // unwrapped `editing` inside the arm. Nothing drew this row, so the
    // rewrite to a match-on-Option was unverified. Render it.
    let mut app = test_app();
    app.environments = vec![mk_env("api-prod", "uflexi", "Web", "Green")];
    app.rebuild_view();
    app.table_state.select(Some(0));
    app.open_detail();
    let detail = app.detail.as_mut().expect("detail opened");
    detail.tags = vec![("Owner".into(), "platform".into())];
    detail.config_cursor = 0;
    detail.tab_idx = detail
        .tabs
        .iter()
        .position(|t| *t == DetailTab::Config)
        .expect("Config tab present");

    app.start_config_edit();
    let edit = app
        .detail
        .as_ref()
        .and_then(|d| d.config_edit.as_ref())
        .expect("editor open");
    assert_eq!(edit.mode, crate::app::ConfigEditMode::Value);

    let out = render(&mut app, 140, 40);
    assert!(out.contains("Owner"), "key cell still renders:\n{out}");
    assert!(
        out.contains("platform"),
        "the value being edited renders:\n{out}"
    );
}

// --- the Detail auto-refresh can't stack scans -------------------------

#[tokio::test]
async fn the_detail_tick_does_not_stack_a_slow_scan() {
    // `detail_refresh_active_tab` fires on every 15-second tick when
    // auto-refresh is on. The interactive scans behind these tabs are
    // worst-case 500 sequential round trips, so a scan slower than the
    // tick collected a new companion every 15 seconds for as long as
    // it ran — a fan of sequential AWS calls against an account that,
    // by the time anyone is looking at this screen, is usually already
    // having a bad day.
    let mut app = test_app();
    app.environments = vec![mk_env("api-prod", "uflexi", "Web", "Red")];
    app.rebuild_view();
    app.table_state.select(Some(0));
    app.open_detail();
    let detail = app.detail.as_mut().expect("detail opened");
    detail.tab_idx = detail
        .tabs
        .iter()
        .position(|t| *t == DetailTab::Instances)
        .expect("Instances tab present");
    // `open_detail` fires its own eager fetches; clear them so the
    // assertions below are about the tick, not the open.
    detail.loading_instances = false;
    detail.loading_events = false;
    app.detail_fetch_started = None;
    assert!(
        !app.detail.as_ref().unwrap().tab_loading(),
        "nothing outstanding yet"
    );

    // First refresh fires and marks the tab loading.
    app.detail_refresh_active_tab();
    assert!(app.detail.as_ref().unwrap().loading_instances);
    let fired_at = app.detail_fetch_started.expect("stamped");

    // A tick landing while it's still running is a no-op.
    app.detail_refresh_active_tab();
    assert_eq!(
        app.detail_fetch_started,
        Some(fired_at),
        "a second refresh must not have been fired"
    );

    // Once the result lands, the next tick proceeds.
    app.detail.as_mut().unwrap().loading_instances = false;
    app.detail_refresh_active_tab();
    assert_ne!(
        app.detail_fetch_started,
        Some(fired_at),
        "a finished fetch must not block the next one"
    );
}

#[tokio::test]
async fn a_lost_detail_fetch_does_not_wedge_the_tab() {
    // The guard reads the `loading_*` flags, which a dropped result —
    // a generation-guarded arrival after a context switch, say — never
    // clears. Without an age cap the tab would refuse to refresh for
    // the rest of the session.
    let mut app = test_app();
    app.environments = vec![mk_env("api-prod", "uflexi", "Web", "Red")];
    app.rebuild_view();
    app.table_state.select(Some(0));
    app.open_detail();
    let detail = app.detail.as_mut().expect("detail opened");
    detail.tab_idx = detail
        .tabs
        .iter()
        .position(|t| *t == DetailTab::Instances)
        .expect("Instances tab present");

    app.detail_refresh_active_tab();
    // Flag stuck on; the fetch is older than the stuck threshold.
    app.detail_fetch_started =
        Some(std::time::Instant::now() - std::time::Duration::from_secs(121));
    let stale = app.detail_fetch_started;
    app.detail_refresh_active_tab();
    assert_ne!(
        app.detail_fetch_started, stale,
        "an outstanding fetch this old is lost, not slow — retry it"
    );
}

#[tokio::test]
async fn every_detail_tab_reports_its_own_loading_state() {
    // `tab_loading` gates the refresh, so a tab whose flag it forgot
    // would silently lose its in-flight guard — and one that read the
    // WRONG flag would refuse to refresh whenever some unrelated tab
    // was busy.
    let mut app = test_app();
    app.environments = vec![mk_env("wk-prod", "uflexi", "Worker", "Green")];
    app.rebuild_view();
    app.table_state.select(Some(0));
    app.open_detail();
    let d = app.detail.as_mut().expect("detail opened");
    assert!(
        d.tabs.contains(&DetailTab::Queue),
        "worker envs get the Queue tab"
    );

    // `open_detail` fires eager fetches; start from a clean slate.
    d.loading_events = false;
    d.loading_instances = false;
    d.loading_queues = false;
    d.loading_metrics = false;
    d.cw_alarms = Default::default();
    d.recent_versions = Default::default();
    d.log_tail.stage = crate::app::LogTailStage::Idle;

    // Every flag off: no tab claims to be loading.
    for idx in 0..d.tabs.len() {
        d.tab_idx = idx;
        assert!(!d.tab_loading(), "{:?} with no flags set", d.tab());
    }

    // Each flag turns on exactly the tabs that own it.
    /// (label, the flag to set, the tabs that should then report loading)
    type LoadingCase = (
        &'static str,
        fn(&mut crate::app::DetailState),
        &'static [DetailTab],
    );
    let cases: &[LoadingCase] = &[
        (
            "events",
            |d| d.loading_events = true,
            &[DetailTab::Health, DetailTab::Events],
        ),
        (
            "instances",
            |d| d.loading_instances = true,
            &[DetailTab::Instances],
        ),
        (
            "queues",
            |d| d.loading_queues = true,
            &[DetailTab::Health, DetailTab::Queue],
        ),
        (
            "metrics",
            |d| d.loading_metrics = true,
            &[DetailTab::Metrics],
        ),
        ("alarms", |d| d.cw_alarms.begin(), &[DetailTab::Health]),
        (
            "recent versions",
            |d| d.recent_versions.begin(),
            &[DetailTab::Health],
        ),
        (
            "log tail",
            |d| d.log_tail.stage = crate::app::LogTailStage::Polling,
            &[DetailTab::Logs],
        ),
    ];
    for (label, set, owners) in cases {
        let d = app.detail.as_mut().unwrap();
        d.loading_events = false;
        d.loading_instances = false;
        d.loading_queues = false;
        d.loading_metrics = false;
        d.cw_alarms = Default::default();
        d.recent_versions = Default::default();
        d.log_tail.stage = crate::app::LogTailStage::Idle;
        set(d);
        for idx in 0..d.tabs.len() {
            d.tab_idx = idx;
            let tab = d.tab();
            assert_eq!(
                d.tab_loading(),
                owners.contains(&tab),
                "{label} loading, on the {tab:?} tab"
            );
        }
    }
}

// --- render smoke for the Detail tabs the coverage sweep found bare ---
//
// A sweep over all 41 `draw_*` entry points (stub each with an early
// return, run the suite, see whether anything notices) found 28 that no
// test would catch if they stopped drawing entirely. These four are the
// Detail tabs an operator reaches mid-incident, which is the same
// argument that got `draw_dlq` / `draw_shell` / `draw_events` covered.

fn detail_app_on_tab(tab: DetailTab) -> App {
    detail_app_on_tab_for_tier(tab, "Web")
}

/// The Queue tab only exists for Worker-tier environments — `open_detail`
/// builds the tab list from the tier — so the tier has to be a parameter.
fn detail_app_on_tab_for_tier(tab: DetailTab, tier: &str) -> App {
    let mut app = test_app();
    app.environments = vec![mk_env("api-prod", "uflexi", tier, "Red")];
    app.view.invalidate();
    app.rebuild_view();
    app.table_state.select(Some(0));
    app.open_detail();
    let detail = app.detail.as_mut().expect("detail opened");
    detail.tab_idx = detail
        .tabs
        .iter()
        .position(|t| *t == tab)
        .expect("tab present");
    app
}

#[tokio::test]
async fn detail_events_tab_renders_its_events() {
    let mut app = detail_app_on_tab(DetailTab::Events);
    let d = app.detail.as_mut().unwrap();
    d.loading_events = false;
    d.events = vec![make_event("EVENT-CANARY deployment failed")];

    let out = render(&mut app, 160, 44);
    assert!(out.contains("EVENT-CANARY"), "event text renders:\n{out}");
}

#[tokio::test]
async fn detail_instances_tab_renders_its_instances() {
    let mut app = detail_app_on_tab(DetailTab::Instances);
    let d = app.detail.as_mut().unwrap();
    d.loading_instances = false;
    d.instances = vec![crate::aws::Instance {
        id: "i-0canary99".into(),
        health: "Severe".into(),
        color: "Red".into(),
        causes: vec!["ELB health failing".into()],
        instance_type: "t3.medium".into(),
        availability_zone: "eu-west-2a".into(),
        launched_at: None,
    }];

    let out = render(&mut app, 160, 44);
    assert!(out.contains("i-0canary99"), "instance id renders:\n{out}");
}

#[tokio::test]
async fn detail_queue_tab_renders_its_queues() {
    let mut app = detail_app_on_tab_for_tier(DetailTab::Queue, "Worker");
    let d = app.detail.as_mut().unwrap();
    d.loading_queues = false;
    d.queues = crate::aws::WorkerQueues {
        main_url: Some("https://sqs.eu-west-2.amazonaws.com/1/awseb-CANARY".into()),
        dlq_url: None,
        main_stats: None,
        dlq_stats: None,
        dlq_origin: None,
    };

    let out = render(&mut app, 160, 44);
    assert!(out.contains("awseb-CANARY"), "queue url renders:\n{out}");
}

#[tokio::test]
async fn detail_logs_tab_draws_even_with_nothing_tailing() {
    // The empty state is the one an operator hits first, and a panic
    // here would take the whole TUI down mid-incident.
    let mut app = detail_app_on_tab(DetailTab::Logs);
    let out = render(&mut app, 160, 44);
    // Assert on the pane's OWN title, not on "Logs" (the tab strip draws
    // that) and not on the env name (the Detail header draws that). The
    // first cut of this test asserted both and passed with
    // `draw_detail_logs` stubbed out entirely — it was measuring the
    // chrome around the tab, not the tab.
    assert!(
        out.contains("instance(s)"),
        "the Logs pane's own title counts instances and lines:\n{out}"
    );
}

/// Characterisation test, written BEFORE the `Fetch<T>` refactor and
/// kept afterwards, re-expressed through the new API. The assertions are
/// unchanged; only the spelling moved.
///
/// The BACKLOG called `Option<T>` + `loading_*: bool` "4 representable
/// states for 3 real ones". That is a misreading, and this test is the
/// evidence — which is why `Fetch<T>` is a struct holding both facts and
/// not the four-variant enum that entry implies. All four combinations
/// are reachable and each means something different: the settled value
/// says whether we hold data, the in-flight flag says whether a request
/// is running right now.
///
/// The state that makes them orthogonal is settled-and-in-flight: a
/// refresh running while the previous result is still on screen.
/// `spawn_detail_alarms` calls `begin()` without clearing the value,
/// deliberately, so a refresh does not blank the panel. A four-variant
/// enum would lose it and `tab_loading()` would stop reporting a refresh
/// as in flight whenever data was already present.
#[tokio::test]
async fn the_alarms_pair_encodes_two_orthogonal_facts_not_one_redundant_state() {
    let mut app = test_app();
    app.environments = vec![mk_env("api-prod", "uflexi", "WebServer", "Green")];
    app.rebuild_view();
    app.table_state.select(Some(0));
    app.open_detail();
    let d = app.detail.as_mut().expect("detail opened");
    d.tab_idx = d
        .tabs
        .iter()
        .position(|t| *t == DetailTab::Health)
        .expect("Health tab");
    // `open_detail` fires eager fetches; start from a clean slate.
    d.loading_events = false;
    d.loading_queues = false;
    d.recent_versions = Default::default();

    let alarm = || {
        vec![crate::aws::CwAlarm {
            name: "cpu-high".into(),
            state: "ALARM".into(),
            state_reason: String::new(),
            metric_name: "CPUUtilization".into(),
            namespace: "AWS/EC2".into(),
        }]
    };

    // Idle: nothing held, nothing running.
    d.cw_alarms = Default::default();
    assert!(!d.tab_loading(), "idle must not claim to be loading");
    assert!(!d.cw_alarms.is_first_load());
    assert!(d.cw_alarms.ready().is_none() && d.cw_alarms.error().is_none());

    // First load: running, nothing to show, so the spinner is on.
    d.cw_alarms.begin();
    assert!(d.tab_loading(), "first load is in flight");
    assert!(
        d.cw_alarms.is_first_load(),
        "nothing to show yet, so ui/detail.rs draws `fetching alarms…`"
    );

    // Settled with data.
    d.cw_alarms.settle(Ok(alarm()));
    assert!(!d.tab_loading(), "settled must not claim to be loading");
    assert!(!d.cw_alarms.is_first_load());
    assert_eq!(d.cw_alarms.ready().map(Vec::len), Some(1));

    // THE state a four-variant enum would lose: a refresh in flight with
    // the previous result still displayed.
    d.cw_alarms.begin();
    assert!(
        d.tab_loading(),
        "a refresh must still report in-flight even when data is present"
    );
    assert!(
        !d.cw_alarms.is_first_load(),
        "but it must NOT draw the spinner — the old data stays visible"
    );
    assert_eq!(
        d.cw_alarms.ready().map(Vec::len),
        Some(1),
        "and the previous result must survive `begin()`"
    );

    // Settled and failed. Distinct from idle, and `ready` must not lie.
    d.cw_alarms.settle(Err("DescribeAlarms denied".into()));
    assert!(!d.tab_loading());
    assert!(d.cw_alarms.ready().is_none(), "a failure is not a value");
    assert!(d.cw_alarms.error().is_some_and(|e| e.contains("denied")));
}

/// Does a successful fetch erase an unrelated fetch's error?
///
/// `open_detail` fires events / instances / metrics / queues
/// concurrently, and all four handlers settle into the SAME
/// `DetailState::error` slot — `Some(msg)` on failure, and `None` on
/// success. So whichever AWS response lands last decides what the
/// operator sees, and a success can silently wipe a real failure.
///
/// Written to find out rather than to assert: if this passes, the
/// concern is unfounded and the test documents that.
#[tokio::test]
async fn a_successful_fetch_does_not_erase_another_fetchs_error() {
    let mut app = test_app();
    app.environments = vec![mk_env("wk-prod", "uflexi", "Worker", "Green")];
    app.rebuild_view();
    app.table_state.select(Some(0));
    app.open_detail();

    let gen = app.generation;
    // Events fetch fails — AccessDenied on DescribeEvents, say.
    app.handle_msg(crate::app::AppMsg::DetailEvents {
        gen,
        env_name: "wk-prod".to_string(),
        result: Err("AccessDenied: DescribeEvents".to_string()),
    });
    let after_failure = app
        .detail
        .as_ref()
        .and_then(|d| d.error.as_ref().map(|e| e.message.clone()));
    assert_eq!(
        after_failure.as_deref(),
        Some("AccessDenied: DescribeEvents"),
        "the failure must be recorded"
    );

    // An UNRELATED fetch then succeeds.
    app.handle_msg(crate::app::AppMsg::DetailInstances {
        gen,
        env_name: "wk-prod".to_string(),
        result: Ok(Vec::new()),
    });

    let after_success = app
        .detail
        .as_ref()
        .and_then(|d| d.error.as_ref().map(|e| e.message.clone()));
    assert_eq!(
        after_success.as_deref(),
        Some("AccessDenied: DescribeEvents"),
        "an unrelated success must NOT erase it — the operator would see \
         a clean panel and never learn the events fetch was denied"
    );
}