pacsea 0.8.2

A fast, friendly TUI for browsing and installing Arch and AUR packages with built-in news and security scanning
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
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
use ratatui::Terminal;
use tokio::select;

use crate::i18n;
use crate::state::types::NewsFeedPayload;
use crate::state::{AppState, PackageItem};
use crate::ui::ui;
use crate::util::parse_update_entry;
use tracing::info;

use super::background::Channels;
use super::handlers::{
    handle_add_to_install_list, handle_dependency_result, handle_details_update,
    handle_file_result, handle_preview, handle_sandbox_result, handle_search_results,
    handle_service_result,
};
use super::tick_handler::{
    handle_comments_result, handle_news, handle_pkgbuild_check_result, handle_pkgbuild_result,
    handle_status, handle_summary_result, handle_tick,
};

/// What: Parse updates entries from the `available_updates.txt` file.
///
/// Inputs:
/// - `updates_file`: Path to the updates file
///
/// Output:
/// - Vector of (name, `old_version`, `new_version`) tuples
///
/// Details:
/// - Parses format: "name - `old_version` -> name - `new_version`"
/// - Uses `parse_update_entry` helper function for parsing individual lines
fn parse_updates_file(updates_file: &std::path::Path) -> Vec<(String, String, String)> {
    if updates_file.exists() {
        std::fs::read_to_string(updates_file)
            .ok()
            .map(|content| {
                content
                    .lines()
                    .filter_map(parse_update_entry)
                    .collect::<Vec<(String, String, String)>>()
            })
            .unwrap_or_default()
    } else {
        Vec::new()
    }
}

/// What: Handle batch of items added to install list.
///
/// Inputs:
/// - `app`: Application state
/// - `channels`: Communication channels
/// - `first`: First item in the batch
///
/// Output: None (side effect: processes items)
///
/// Details:
/// - Batch-drains imported items arriving close together to avoid repeated redraws
fn handle_add_batch(app: &mut AppState, channels: &mut Channels, first: PackageItem) {
    let mut batch = vec![first];
    while let Ok(it) = channels.add_rx.try_recv() {
        batch.push(it);
    }
    for it in batch {
        handle_add_to_install_list(
            app,
            it,
            &channels.deps_req_tx,
            &channels.files_req_tx,
            &channels.services_req_tx,
            &channels.sandbox_req_tx,
        );
    }
}

/// What: Handle file result with logging.
///
/// Inputs:
/// - `app`: Application state
/// - `channels`: Communication channels
/// - `files`: File resolution results
///
/// Output: None (side effect: processes files)
fn handle_file_result_with_logging(
    app: &mut AppState,
    channels: &Channels,
    files: &[crate::state::modal::PackageFileInfo],
) {
    tracing::debug!(
        "[Runtime] Received file result: {} entries for packages: {:?}",
        files.len(),
        files.iter().map(|f| &f.name).collect::<Vec<_>>()
    );
    for file_info in files {
        tracing::debug!(
            "[Runtime] Package '{}' - total={}, new={}, changed={}, removed={}, config={}",
            file_info.name,
            file_info.total_count,
            file_info.new_count,
            file_info.changed_count,
            file_info.removed_count,
            file_info.config_count
        );
    }
    handle_file_result(app, files, &channels.tick_tx);
}

/// What: Handle remote announcement received from async fetch.
///
/// Inputs:
/// - `app`: Application state to update
/// - `announcement`: Remote announcement fetched from configured URL
///
/// Output: None (modifies app state in place)
///
/// Details:
fn handle_remote_announcement(
    app: &mut AppState,
    announcement: crate::announcements::RemoteAnnouncement,
) {
    const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");

    // Check version range
    if !crate::announcements::version_matches(
        CURRENT_VERSION,
        announcement.min_version.as_deref(),
        announcement.max_version.as_deref(),
    ) {
        tracing::debug!(
            id = %announcement.id,
            current_version = CURRENT_VERSION,
            min_version = ?announcement.min_version,
            max_version = ?announcement.max_version,
            "announcement version range mismatch"
        );
        return;
    }

    // Check expiration
    if crate::announcements::is_expired(announcement.expires.as_deref()) {
        tracing::debug!(
            id = %announcement.id,
            expires = ?announcement.expires,
            "announcement expired"
        );
        return;
    }

    // Check if already read
    if app.announcements_read_ids.contains(&announcement.id) {
        tracing::info!(
            id = %announcement.id,
            "remote announcement already marked as read"
        );
        return;
    }

    // Only show if no modal is currently displayed
    if matches!(app.modal, crate::state::Modal::None) {
        app.modal = crate::state::Modal::Announcement {
            title: announcement.title,
            content: announcement.content,
            id: announcement.id,
            scroll: 0,
        };
        tracing::info!("showing remote announcement modal");
    } else {
        // Queue announcement to show after current modal closes
        let announcement_id = announcement.id.clone();
        app.pending_announcements.push(announcement);
        tracing::info!(
            id = %announcement_id,
            queue_size = app.pending_announcements.len(),
            "queued remote announcement (modal already open)"
        );
    }
}

/// What: Handle index notification message.
///
/// Inputs:
/// - `app`: Application state
/// - `channels`: Communication channels
///
/// Output: `false` (continue event loop)
///
/// Details:
/// - Marks index loading as complete and triggers a tick
fn handle_index_notification(app: &mut AppState, channels: &Channels) -> bool {
    app.loading_index = false;
    // Re-run query once the index is ready so first-launch results are populated.
    crate::logic::send_query(app, &channels.query_tx);
    let _ = channels.tick_tx.send(());
    false
}

/// What: Handle updates list received from background worker.
///
/// Inputs:
/// - `app`: Application state
/// - `payload`: Update check result from the background worker
///
/// Output: None (modifies app state in place)
///
/// Details:
/// - Updates app state with update count, list, and whether the official-repo probe was authoritative
/// - Shows a transient toast when the check ran in degraded mode (stale DB / sandbox issues)
/// - If pending updates modal is set, opens the updates modal
fn handle_updates_list(
    app: &mut AppState,
    payload: crate::app::runtime::workers::UpdateCheckPayload,
) {
    let count = payload.count;
    let list = payload.package_names;
    app.updates_last_check_authoritative = Some(payload.authoritative);
    app.updates_count = Some(count);
    app.updates_list = list;
    app.updates_loading = false;
    if !payload.authoritative {
        app.toast_message = Some(i18n::t(app, "app.toasts.update_check_degraded"));
        app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(8));
        tracing::info!(
            authoritative = false,
            reasons = %payload.reason_codes.join(","),
            strategy = payload.official_strategy,
            "update check completed in degraded mode for official repositories"
        );
    }
    if app.pending_updates_modal {
        app.pending_updates_modal = false;
        let updates_file = crate::theme::lists_dir().join("available_updates.txt");
        let entries = parse_updates_file(&updates_file);
        let filtered_indices: Vec<usize> = (0..entries.len()).collect();
        app.modal = crate::state::Modal::Updates {
            entries,
            scroll: 0,
            selected: 0,
            filter_active: false,
            filter_query: String::new(),
            filter_caret: 0,
            last_selected_pkg_name: None,
            filtered_indices,
            selected_pkg_names: std::collections::HashSet::new(),
        };
    }
}

/// What: Handle AUR vote worker response and update UI feedback.
///
/// Inputs:
/// - `app`: Application state.
/// - `response`: Vote worker response with typed success/failure result.
///
/// Output:
/// - None (modifies app state in place).
///
/// Details:
/// - Success is surfaced as a short-lived toast.
/// - State-aligned failures (`AlreadyVoted`, `NotVoted`) sync local cache and show toast.
/// - Other actionable failures open `Modal::Alert` with guidance.
fn handle_aur_vote_response(
    app: &mut AppState,
    response: crate::app::runtime::workers::aur_vote::AurVoteResponse,
) {
    match response.result {
        Ok(outcome) => {
            let state = match outcome.action {
                crate::sources::VoteAction::Vote => crate::state::app_state::AurVoteStateUi::Voted,
                crate::sources::VoteAction::Unvote => {
                    crate::state::app_state::AurVoteStateUi::NotVoted
                }
            };
            if !outcome.dry_run {
                app.aur_vote_state_by_pkgbase
                    .insert(outcome.pkgbase.clone(), state);
                app.aur_vote_state_dirty = true;
            }
            app.toast_message = Some(outcome.message());
            app.toast_expires_at =
                Some(std::time::Instant::now() + std::time::Duration::from_secs(4));
        }
        Err(error) => match error {
            crate::sources::AurVoteError::AlreadyVoted(pkgbase) => {
                app.aur_vote_state_by_pkgbase.insert(
                    pkgbase.clone(),
                    crate::state::app_state::AurVoteStateUi::Voted,
                );
                app.aur_vote_state_dirty = true;
                app.toast_message = Some(format!(
                    "Already voted for '{pkgbase}'. Local vote state synced."
                ));
                app.toast_expires_at =
                    Some(std::time::Instant::now() + std::time::Duration::from_secs(4));
            }
            crate::sources::AurVoteError::NotVoted(pkgbase) => {
                app.aur_vote_state_by_pkgbase.insert(
                    pkgbase.clone(),
                    crate::state::app_state::AurVoteStateUi::NotVoted,
                );
                app.aur_vote_state_dirty = true;
                app.toast_message = Some(format!(
                    "No vote exists for '{pkgbase}'. Local vote state synced."
                ));
                app.toast_expires_at =
                    Some(std::time::Instant::now() + std::time::Duration::from_secs(4));
            }
            other_error => {
                let guidance = match &other_error {
                    crate::sources::AurVoteError::NotFound(_) => {
                        "Verify the selected package base name."
                    }
                    crate::sources::AurVoteError::AuthFailed(_) => {
                        "Upload your SSH public key to https://aur.archlinux.org/account and retry."
                    }
                    crate::sources::AurVoteError::Maintenance => {
                        "Wait for AUR maintenance to end and retry later."
                    }
                    crate::sources::AurVoteError::Banned => {
                        "Your IP is blocked from the SSH interface. Contact AUR support."
                    }
                    crate::sources::AurVoteError::Timeout(_)
                    | crate::sources::AurVoteError::NetworkError(_) => {
                        "Check network connectivity and SSH reachability."
                    }
                    crate::sources::AurVoteError::SshNotFound(_) => {
                        "Install openssh or configure aur_vote_ssh_command in settings.conf."
                    }
                    crate::sources::AurVoteError::Unexpected(_) => {
                        "Retry once, then inspect logs if the issue persists."
                    }
                    crate::sources::AurVoteError::AlreadyVoted(_)
                    | crate::sources::AurVoteError::NotVoted(_) => {
                        "Use the opposite action or leave as-is."
                    }
                };
                app.modal = crate::state::Modal::Alert {
                    message: format!("AUR vote failed: {other_error}\n\nNext step: {guidance}"),
                };
            }
        },
    }
}

/// What: Handle AUR vote-state worker responses and update cached UI state.
///
/// Inputs:
/// - `app`: Application state.
/// - `response`: Vote-state worker response with pkgbase and typed result.
///
/// Output:
/// - None (modifies app state in place).
///
/// Details:
/// - Success updates package cache to `Voted`/`NotVoted`.
/// - Failure stores a short error marker for inline rendering in results/details.
fn handle_aur_vote_state_response(
    app: &mut AppState,
    response: crate::app::runtime::workers::aur_vote::AurVoteStateResponse,
) {
    let pkgbase = response.pkgbase;
    let next_state = match response.result {
        Ok(crate::sources::AurPackageVoteState::Voted) => {
            crate::state::app_state::AurVoteStateUi::Voted
        }
        Ok(crate::sources::AurPackageVoteState::NotVoted) => {
            crate::state::app_state::AurVoteStateUi::NotVoted
        }
        Err(error) => {
            if crate::sources::is_vote_state_unsupported_error(&error) {
                app.aur_vote_state_lookup_supported = false;
                match app.aur_vote_state_by_pkgbase.get(&pkgbase) {
                    Some(crate::state::app_state::AurVoteStateUi::Voted) => {
                        crate::state::app_state::AurVoteStateUi::Voted
                    }
                    Some(crate::state::app_state::AurVoteStateUi::NotVoted) => {
                        crate::state::app_state::AurVoteStateUi::NotVoted
                    }
                    _ => crate::state::app_state::AurVoteStateUi::Unknown,
                }
            } else {
                crate::state::app_state::AurVoteStateUi::Error(format!("{error}"))
            }
        }
    };
    let should_persist = matches!(
        next_state,
        crate::state::app_state::AurVoteStateUi::Voted
            | crate::state::app_state::AurVoteStateUi::NotVoted
    );
    app.aur_vote_state_by_pkgbase.insert(pkgbase, next_state);
    if should_persist {
        app.aur_vote_state_dirty = true;
    }
}

/// What: Apply filters and sorting to news feed items.
///
/// Inputs:
/// - `app`: Application state containing news feed data and filter flags.
/// - `payload`: News feed payload containing items and metadata.
///
/// Details:
/// - Does not clear `news_loading` flag here - it will be cleared when news modal is shown.
fn handle_news_feed_items(app: &mut AppState, payload: NewsFeedPayload) {
    tracing::info!(
        items_count = payload.items.len(),
        "received aggregated news feed payload in event loop"
    );
    app.news_items = payload.items;
    app.news_seen_pkg_versions = payload.seen_pkg_versions;
    app.news_seen_pkg_versions_dirty = true;
    app.news_seen_aur_comments = payload.seen_aur_comments;
    app.news_seen_aur_comments_dirty = true;
    match serde_json::to_string_pretty(&app.news_items) {
        Ok(serialized) => {
            if let Err(e) = std::fs::write(&app.news_feed_path, serialized) {
                tracing::warn!(error = %e, path = ?app.news_feed_path, "failed to persist news feed cache");
            }
        }
        Err(e) => tracing::warn!(error = %e, "failed to serialize news feed cache"),
    }
    app.refresh_news_results();

    // News feed is now loaded - clear loading flag and toast
    app.news_loading = false;
    app.toast_message = None;
    app.toast_expires_at = None;

    info!(
        fetched = app.news_items.len(),
        visible = app.news_results.len(),
        max_age_days = app.news_max_age_days.map(i64::from),
        installed_only = app.news_filter_installed_only,
        arch_on = app.news_filter_show_arch_news,
        advisories_on = app.news_filter_show_advisories,
        "news feed updated"
    );
    // Check for network errors and show a small toast
    if crate::sources::take_network_error() {
        app.toast_message = Some("Network error: some news sources unreachable".to_string());
        app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(5));
    }
}

/// What: Handle a single incremental news item from background continuation.
///
/// Inputs:
/// - `app`: Application state
/// - `item`: The news feed item to add
///
/// Details:
/// - Appends the item to `news_items` if not already present (by id).
/// - Refreshes filtered/sorted results.
/// - Persists the updated feed cache to disk.
fn handle_incremental_news_item(app: &mut AppState, item: crate::state::types::NewsFeedItem) {
    // Check if item already exists (by id)
    if app.news_items.iter().any(|existing| existing.id == item.id) {
        tracing::debug!(
            item_id = %item.id,
            "incremental news item already exists, skipping"
        );
        return;
    }

    tracing::info!(
        item_id = %item.id,
        source = ?item.source,
        title = %item.title,
        "received incremental news item"
    );

    // Add the new item
    app.news_items.push(item);

    // Refresh filtered/sorted results
    app.refresh_news_results();

    // Persist to disk
    if let Ok(serialized) = serde_json::to_string_pretty(&app.news_items)
        && let Err(e) = std::fs::write(&app.news_feed_path, serialized)
    {
        tracing::warn!(error = %e, path = ?app.news_feed_path, "failed to persist incremental news feed cache");
    }
}

/// What: Handle news article content response.
///
/// Inputs:
/// - `app`: Application state
/// - `url`: The URL that was fetched
/// - `content`: The article content
fn handle_news_content(app: &mut AppState, url: &str, content: String) {
    // Only cache successful content, not error messages
    // Error messages start with "Failed to load content:" and should not be persisted
    let is_error = content.starts_with("Failed to load content:");
    if is_error {
        tracing::debug!(
            url,
            "news_content: not caching error response to allow retry"
        );
    } else {
        app.news_content_cache
            .insert(url.to_string(), content.clone());
        app.news_content_cache_dirty = true;
    }

    // Update displayed content if this is for the currently selected item
    if let Some(selected_url) = app
        .news_results
        .get(app.news_selected)
        .and_then(|selected| selected.url.as_deref())
        && selected_url == url
    {
        tracing::debug!(
            url,
            len = content.len(),
            selected = app.news_selected,
            "news_content: response matches selection"
        );
        app.news_content_loading = false;
        app.news_content = if content.is_empty() {
            None
        } else {
            Some(content)
        };
    } else {
        // Clear loading flag even if selection changed; a new request will be issued on next tick.
        tracing::debug!(
            url,
            len = content.len(),
            selected = app.news_selected,
            selected_url = ?app
                .news_results
                .get(app.news_selected)
                .and_then(|selected| selected.url.as_deref()),
            "news_content: response does not match current selection"
        );
        app.news_content_loading = false;
    }
    app.news_content_loading_since = None;
}

/// What: Process one iteration of channel message handling.
///
/// Inputs:
/// - `app`: Application state
/// - `channels`: Communication channels for background workers
///
/// Output: `true` if the event loop should exit, `false` to continue
///
/// Details:
/// - Waits for and processes a single message from any channel
/// - Returns `true` when an event handler indicates exit (e.g., quit command)
/// - Uses select! to wait on multiple channels concurrently
#[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
async fn process_channel_messages(app: &mut AppState, channels: &mut Channels) -> bool {
    select! {
        Some(ev) = channels.event_rx.recv() => {
            crate::events::handle_event_with_pkgbuild_checks(
                &ev,
                app,
                &channels.query_tx,
                &channels.details_req_tx,
                &channels.preview_tx,
                &channels.add_tx,
                &channels.pkgb_req_tx,
                &channels.comments_req_tx,
                &channels.pkgb_check_req_tx,
            )
        }
        Some(()) = channels.index_notify_rx.recv() => {
            handle_index_notification(app, channels)
        }
        Some(new_results) = channels.results_rx.recv() => {
            handle_search_results(
                app,
                new_results,
                &channels.details_req_tx,
                &channels.index_notify_tx,
            );
            false
        }
        Some(details) = channels.details_res_rx.recv() => {
            handle_details_update(app, &details, &channels.tick_tx);
            false
        }
        Some(item) = channels.preview_rx.recv() => {
            handle_preview(app, item, &channels.details_req_tx);
            false
        }
        Some(first) = channels.add_rx.recv() => {
            handle_add_batch(app, channels, first);
            false
        }
        Some(deps) = channels.deps_res_rx.recv() => {
            handle_dependency_result(app, &deps, &channels.tick_tx);
            false
        }
        Some(files) = channels.files_res_rx.recv() => {
            handle_file_result_with_logging(app, channels, &files);
            false
        }
        Some(services) = channels.services_res_rx.recv() => {
            handle_service_result(app, &services, &channels.tick_tx);
            false
        }
        Some(sandbox_info) = channels.sandbox_res_rx.recv() => {
            handle_sandbox_result(app, &sandbox_info, &channels.tick_tx);
            false
        }
        Some(summary_outcome) = channels.summary_res_rx.recv() => {
            handle_summary_result(app, summary_outcome, &channels.tick_tx);
            false
        }
        Some((pkgname, text)) = channels.pkgb_res_rx.recv() => {
            handle_pkgbuild_result(app, pkgname, text, &channels.tick_tx);
            false
        }
        Some((pkgname, result)) = channels.comments_res_rx.recv() => {
            handle_comments_result(app, pkgname, result, &channels.tick_tx);
            false
        }
        Some(response) = channels.pkgb_check_res_rx.recv() => {
            handle_pkgbuild_check_result(app, response, &channels.tick_tx);
            false
        }
        Some(feed) = channels.news_feed_rx.recv() => {
            handle_news_feed_items(app, feed);
            false
        }
        Some(item) = channels.news_incremental_rx.recv() => {
            handle_incremental_news_item(app, item);
            false
        }
        Some((url, content)) = channels.news_content_res_rx.recv() => {
            handle_news_content(app, &url, content);
            false
        }
        Some(msg) = channels.net_err_rx.recv() => {
            tracing::warn!(error = %msg, "Network error received");
            #[cfg(not(windows))]
            {
                // Package-details-unavailable errors are expected when scrolling with flaky
                // network or circuit breaker; do not show a modal for each failed package.
                let is_details_unavailable = msg.starts_with("Official package details unavailable for")
                    || msg.starts_with("AUR package details unavailable for");
                if !is_details_unavailable {
                    app.modal = crate::state::Modal::Alert {
                        message: msg,
                    };
                }
            }
            // On Windows, only log (no popup)
            false
        }
        Some(()) = channels.tick_rx.recv() => {
            handle_tick(
                app,
                &channels.query_tx,
                &channels.details_req_tx,
                &channels.pkgb_req_tx,
                &channels.deps_req_tx,
                &channels.files_req_tx,
                &channels.services_req_tx,
                &channels.sandbox_req_tx,
                &channels.summary_req_tx,
                &channels.updates_tx,
                &channels.aur_vote_req_tx,
                &channels.aur_vote_state_req_tx,
                &channels.executor_req_tx,
                &channels.post_summary_req_tx,
                &channels.news_content_req_tx,
            );
            false
        }
        Some(items) = channels.news_rx.recv() => {
            tracing::info!(
                items_count = items.len(),
                news_loading_before = app.news_loading,
                "received news items from channel"
            );
            handle_news(app, &items);
            tracing::info!(
                news_loading_after = app.news_loading,
                modal = ?app.modal,
                "handle_news completed"
            );
            false
        }
        Some(announcement) = channels.announcement_rx.recv() => {
            handle_remote_announcement(app, announcement);
            false
        }
        Some((txt, color)) = channels.status_rx.recv() => {
            handle_status(app, &txt, color);
            false
        }
        Some(payload) = channels.updates_rx.recv() => { handle_updates_list(app, payload); false }
        Some(aur_vote_response) = channels.aur_vote_res_rx.recv() => { handle_aur_vote_response(app, aur_vote_response); false }
        Some(aur_vote_state_response) = channels.aur_vote_state_res_rx.recv() => { handle_aur_vote_state_response(app, aur_vote_state_response); false }
        Some(executor_output) = channels.executor_res_rx.recv() => {
            handle_executor_output(app, executor_output);
            false
        }
        Some(post_summary_data) = channels.post_summary_res_rx.recv() => {
            handle_post_summary_result(app, post_summary_data);
            false
        }
        else => false
    }
}

/// What: Handle post-summary computation result.
///
/// Inputs:
/// - `app`: Application state
/// - `data`: Computed post-summary data
///
/// Details:
/// - Transitions from Loading modal to `PostSummary` modal
fn handle_post_summary_result(app: &mut AppState, data: crate::logic::summary::PostSummaryData) {
    // Only transition if we're in Loading state
    if matches!(app.modal, crate::state::Modal::Loading { .. }) {
        tracing::debug!(
            success = data.success,
            changed_files = data.changed_files,
            pacnew_count = data.pacnew_count,
            pacsave_count = data.pacsave_count,
            services_pending = data.services_pending.len(),
            snapshot_label = ?data.snapshot_label,
            "[EventLoop] Transitioning modal: Loading -> PostSummary"
        );
        app.modal = crate::state::Modal::PostSummary {
            success: data.success,
            changed_files: data.changed_files,
            pacnew_count: data.pacnew_count,
            pacsave_count: data.pacsave_count,
            services_pending: data.services_pending,
            snapshot_label: data.snapshot_label,
        };
    }
}

/// What: Handle successful executor completion for Install action.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `items`: Package items that were installed
///
/// Output:
/// - None (modifies app state in place)
///
/// Details:
/// - Tracks installed packages and triggers refresh of installed packages pane
/// - Only tracks pending install names if items is non-empty (system updates use empty items)
fn handle_install_success(app: &mut AppState, items: &[crate::state::PackageItem]) {
    // Only track pending install names if items is non-empty.
    // System updates use empty items, and setting pending_install_names
    // to empty would cause install_list to be cleared in tick handler
    // due to vacuously true check (all elements of empty set satisfy any predicate).
    if !items.is_empty() {
        let installed_names: Vec<String> = items.iter().map(|p| p.name.clone()).collect();
        // Set pending install names to track installation completion
        app.pending_install_names = Some(installed_names);
    }

    // Trigger refresh of installed packages
    app.refresh_installed_until =
        Some(std::time::Instant::now() + std::time::Duration::from_secs(8));

    // Refresh updates count after installation completes
    app.refresh_updates = true;

    tracing::info!(
        "Install operation completed: triggered refresh of installed packages and updates"
    );
}

/// What: Handle successful executor completion for Remove action.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `items`: Package items that were removed
///
/// Output:
/// - None (modifies app state in place)
///
/// Details:
/// - Clears remove list and triggers refresh of installed packages pane
fn handle_remove_success(app: &mut AppState, items: &[crate::state::PackageItem]) {
    let removed_names: Vec<String> = items.iter().map(|p| p.name.clone()).collect();

    // Clear remove list
    app.remove_list.clear();
    app.remove_list_names.clear();
    app.remove_state.select(None);

    // Set pending remove names to track removal completion
    app.pending_remove_names = Some(removed_names);

    // Trigger refresh of installed packages
    app.refresh_installed_until =
        Some(std::time::Instant::now() + std::time::Duration::from_secs(8));

    // Refresh updates count after removal completes
    app.refresh_updates = true;

    // Keep PreflightExec modal open so user can see completion message
    // User can close it with Esc/q, and refresh happens in background
    tracing::info!("Remove operation completed: cleared remove list and triggered refresh");
}

/// What: Handle successful executor completion for Downgrade action.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `items`: Package items that were downgraded
///
/// Output:
/// - None (modifies app state in place)
///
/// Details:
/// - Clears downgrade list and triggers refresh of installed packages pane
fn handle_downgrade_success(app: &mut AppState, items: &[crate::state::PackageItem]) {
    let downgraded_names: Vec<String> = items.iter().map(|p| p.name.clone()).collect();

    // Clear downgrade list
    app.downgrade_list.clear();
    app.downgrade_list_names.clear();
    app.downgrade_state.select(None);

    // Set pending downgrade names to track downgrade completion
    app.pending_remove_names = Some(downgraded_names);

    // Trigger refresh of installed packages
    app.refresh_installed_until =
        Some(std::time::Instant::now() + std::time::Duration::from_secs(8));

    // Refresh updates count after downgrade completes
    app.refresh_updates = true;

    // Keep PreflightExec modal open so user can see completion message
    // User can close it with Esc/q, and refresh happens in background
    tracing::info!("Downgrade operation completed: cleared downgrade list and triggered refresh");
}

/// What: Handle executor output and update UI state accordingly.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `output`: Executor output to process
///
/// Output:
/// - None (modifies app state in place)
///
/// Details:
/// - Updates `PreflightExec` modal with log lines or completion status
/// - Processes `Line`, `ReplaceLastLine`, `Finished`, and `Error` outputs
/// - Handles success/failure cases for Install, Remove, and Downgrade actions
/// - Shows confirmation popup for AUR update when pacman fails
#[allow(clippy::too_many_lines)] // Function handles multiple executor output types and modal transitions (function has 187 lines)
fn handle_executor_output(app: &mut AppState, output: crate::install::ExecutorOutput) {
    // Log what we received (at trace level to avoid spam)
    match &output {
        crate::install::ExecutorOutput::Line(line) => {
            tracing::trace!(
                "[EventLoop] Received executor line: {}...",
                &line[..line.len().min(50)]
            );
        }
        crate::install::ExecutorOutput::ReplaceLastLine(line) => {
            tracing::trace!(
                "[EventLoop] Received executor replace line: {}...",
                &line[..line.len().min(50)]
            );
        }
        crate::install::ExecutorOutput::Finished {
            success,
            exit_code,
            failed_command: _,
        } => {
            tracing::debug!(
                "[EventLoop] Received executor Finished: success={}, exit_code={:?}",
                success,
                exit_code
            );
        }
        crate::install::ExecutorOutput::Error(err) => {
            tracing::warn!("[EventLoop] Received executor Error: {}", err);
        }
    }

    if let crate::state::Modal::PreflightExec {
        ref mut log_lines,
        ref mut abortable,
        ref mut success,
        ref items,
        ref action,
        ..
    } = app.modal
    {
        match output {
            crate::install::ExecutorOutput::Line(line) => {
                log_lines.push(line);
                // Keep only last 1000 lines to avoid memory issues
                if log_lines.len() > 1000 {
                    log_lines.remove(0);
                }
                tracing::debug!(
                    "[EventLoop] PreflightExec log_lines count: {}",
                    log_lines.len()
                );
            }
            crate::install::ExecutorOutput::ReplaceLastLine(line) => {
                // Replace the last line (for progress bar updates via \r)
                if log_lines.is_empty() {
                    log_lines.push(line);
                } else {
                    let last_idx = log_lines.len() - 1;
                    log_lines[last_idx] = line;
                }
            }
            crate::install::ExecutorOutput::Finished {
                success: exec_success,
                exit_code,
                failed_command: _,
            } => {
                tracing::info!(
                    "Received Finished: success={exec_success}, exit_code={exit_code:?}"
                );
                *abortable = false;
                if !exec_success {
                    app.pending_repo_apply_overlap_check = None;
                    app.pending_repositories_modal_resume = None;
                }
                // Store the execution result in the modal
                *success = Some(exec_success);
                log_lines.push(String::new()); // Empty line before completion message
                if exec_success {
                    let completion_msg = match action {
                        crate::state::PreflightAction::Install => {
                            "Installation successfully completed!".to_string()
                        }
                        crate::state::PreflightAction::Remove => {
                            "Removal successfully completed!".to_string()
                        }
                        crate::state::PreflightAction::Downgrade => {
                            "Downgrade successfully completed!".to_string()
                        }
                    };
                    log_lines.push(completion_msg);
                    tracing::info!(
                        "Added completion message, log_lines.len()={}",
                        log_lines.len()
                    );

                    // Clone items to avoid borrow checker issues when calling handlers
                    let items_clone = items.clone();
                    let action_clone = *action;

                    // Handle successful operations: refresh installed packages and update UI
                    match action_clone {
                        crate::state::PreflightAction::Install => {
                            handle_install_success(app, &items_clone);
                        }
                        crate::state::PreflightAction::Remove => {
                            handle_remove_success(app, &items_clone);
                        }
                        crate::state::PreflightAction::Downgrade => {
                            handle_downgrade_success(app, &items_clone);
                        }
                    }
                } else {
                    log_lines.push(format!("Execution failed (exit code: {exit_code:?})"));

                    // If this was a system update (empty items) and AUR update is pending, show confirmation
                    if items.is_empty() && app.pending_aur_update_command.is_some() {
                        tracing::info!(
                            "[EventLoop] System update failed (exit_code: {:?}), AUR update pending - showing confirmation popup",
                            exit_code
                        );
                        // Preserve password and header_chips for AUR update if user confirms
                        // (they're already stored in app state, so we just need to show the modal)

                        // Determine which command failed by checking the command list
                        let failed_command_name = app
                            .pending_update_commands
                            .as_ref()
                            .and_then(|cmds| {
                                // Extract command name from the first command (since commands are chained with &&,
                                // the first command that fails stops execution)
                                cmds.first().map(|cmd| {
                                    // Extract command name: "sudo pacman -Syu" -> "pacman", "paru -Sua" -> "paru"
                                    if cmd.contains("pacman") {
                                        "pacman"
                                    } else if cmd.contains("paru") {
                                        "paru"
                                    } else if cmd.contains("yay") {
                                        "yay"
                                    } else if cmd.contains("reflector") {
                                        "reflector"
                                    } else if cmd.contains("pacman-mirrors") {
                                        "pacman-mirrors"
                                    } else if cmd.contains("eos-rankmirrors") {
                                        "eos-rankmirrors"
                                    } else if cmd.contains("cachyos-rate-mirrors") {
                                        "cachyos-rate-mirrors"
                                    } else {
                                        "update command"
                                    }
                                })
                            })
                            .unwrap_or("update command");

                        // Close PreflightExec and show confirmation modal
                        let exit_code_str =
                            exit_code.map_or_else(|| "unknown".to_string(), |c| c.to_string());
                        app.modal = crate::state::Modal::ConfirmAurUpdate {
                            message: format!(
                                "{}\n\n{}\n{}\n\n{}",
                                i18n::t_fmt2(
                                    app,
                                    "app.modals.confirm_aur_update.command_failed",
                                    failed_command_name,
                                    &exit_code_str
                                ),
                                i18n::t(app, "app.modals.confirm_aur_update.continue_prompt"),
                                i18n::t(app, "app.modals.confirm_aur_update.warning"),
                                i18n::t(app, "app.modals.confirm_aur_update.hint")
                            ),
                        };
                    } else {
                        tracing::debug!(
                            "[EventLoop] System update failed but no confirmation popup - items.is_empty(): {}, pending_aur_update_command.is_some(): {}",
                            items.is_empty(),
                            app.pending_aur_update_command.is_some()
                        );
                    }
                }
            }
            crate::install::ExecutorOutput::Error(err) => {
                *abortable = false;
                log_lines.push(format!("Error: {err}"));
            }
        }
    } else {
        tracing::warn!(
            "[EventLoop] Received executor output but modal is not PreflightExec, modal={:?}",
            std::mem::discriminant(&app.modal)
        );
    }
}

/// What: Trigger startup news fetch using current startup news settings.
///
/// Inputs:
/// - `channels`: Communication channels for background workers
/// - `app`: Application state for read sets
///
/// Output: None
///
/// Details:
/// - Fetches news feed using startup news settings and sends to `news_tx` channel
/// - Called when `trigger_startup_news_fetch` flag is set after `NewsSetup` completion
/// - Sets `news_loading` flag to show loading modal
fn trigger_startup_news_fetch(channels: &Channels, app: &mut AppState) {
    use crate::sources;
    use crate::state::types::NewsSortMode;
    use std::collections::HashSet;

    let prefs = crate::theme::settings();
    if !prefs.startup_news_configured {
        return;
    }

    // Set loading flag to show loading modal
    app.news_loading = true;
    tracing::info!("news_loading set to true, triggering startup news fetch");

    let news_tx = channels.news_tx.clone();
    let read_urls = app.news_read_urls.clone();
    let read_ids = app.news_read_ids.clone();
    let installed: HashSet<String> = crate::index::explicit_names().into_iter().collect();
    // Create mutable copies for the fetch (won't be persisted, but needed for API)
    let mut seen_versions = app.news_seen_pkg_versions.clone();
    let mut seen_aur_comments = app.news_seen_aur_comments.clone();

    tokio::spawn(async move {
        tracing::info!("on-demand startup news fetch task started");
        let mut installed_set = installed;
        if installed_set.is_empty() {
            crate::index::refresh_installed_cache().await;
            crate::index::refresh_explicit_cache(crate::state::InstalledPackagesMode::AllExplicit)
                .await;
            let refreshed: HashSet<String> = crate::index::explicit_names().into_iter().collect();
            if !refreshed.is_empty() {
                installed_set = refreshed;
            }
        }
        let include_pkg_updates =
            prefs.startup_news_show_pkg_updates || prefs.startup_news_show_aur_updates;
        // Use lower limit for startup popup (20) vs main feed (50)
        // If both official and AUR updates are requested, double the limit so both types can be included
        #[allow(clippy::items_after_statements)]
        const STARTUP_NEWS_LIMIT: usize = 20;
        let updates_limit =
            if prefs.startup_news_show_pkg_updates && prefs.startup_news_show_aur_updates {
                STARTUP_NEWS_LIMIT * 2
            } else {
                STARTUP_NEWS_LIMIT
            };
        let ctx = sources::NewsFeedContext {
            force_emit_all: true,
            updates_list_path: Some(crate::theme::lists_dir().join("available_updates.txt")),
            limit: updates_limit,
            include_arch_news: prefs.startup_news_show_arch_news,
            include_advisories: prefs.startup_news_show_advisories,
            include_pkg_updates,
            include_aur_comments: prefs.startup_news_show_aur_comments,
            installed_filter: Some(&installed_set),
            installed_only: false,
            sort_mode: NewsSortMode::DateDesc,
            seen_pkg_versions: &mut seen_versions,
            seen_aur_comments: &mut seen_aur_comments,
            max_age_days: prefs.startup_news_max_age_days,
        };
        tracing::info!(
            limit = updates_limit,
            include_arch_news = prefs.startup_news_show_arch_news,
            include_advisories = prefs.startup_news_show_advisories,
            include_pkg_updates,
            include_aur_comments = prefs.startup_news_show_aur_comments,
            max_age_days = ?prefs.startup_news_max_age_days,
            installed_count = installed_set.len(),
            "starting on-demand startup news fetch"
        );
        match sources::fetch_news_feed(ctx).await {
            Ok(feed) => {
                tracing::info!(
                    total_items = feed.len(),
                    "on-demand startup news fetch completed successfully"
                );
                // Filter by source type for package updates (AUR vs official are mixed in fetch_installed_updates)
                let source_filtered: Vec<crate::state::types::NewsFeedItem> = feed
                    .into_iter()
                    .filter(|item| match item.source {
                        crate::state::types::NewsFeedSource::ArchNews => {
                            prefs.startup_news_show_arch_news
                        }
                        crate::state::types::NewsFeedSource::SecurityAdvisory => {
                            prefs.startup_news_show_advisories
                        }
                        crate::state::types::NewsFeedSource::InstalledPackageUpdate => {
                            prefs.startup_news_show_pkg_updates
                        }
                        crate::state::types::NewsFeedSource::AurPackageUpdate => {
                            prefs.startup_news_show_aur_updates
                        }
                        crate::state::types::NewsFeedSource::AurComment => {
                            prefs.startup_news_show_aur_comments
                        }
                    })
                    .collect();
                // Filter by max age days
                let filtered: Vec<crate::state::types::NewsFeedItem> =
                    if let Some(max_days) = prefs.startup_news_max_age_days {
                        let cutoff_date = chrono::Utc::now()
                            .checked_sub_signed(chrono::Duration::days(i64::from(max_days)))
                            .map(|dt| dt.format("%Y-%m-%d").to_string());
                        #[allow(clippy::unnecessary_map_or)]
                        let filtered_items = source_filtered
                            .into_iter()
                            .filter(|item| {
                                cutoff_date
                                    .as_ref()
                                    .map_or(true, |cutoff| &item.date >= cutoff)
                            })
                            .collect();
                        filtered_items
                    } else {
                        source_filtered
                    };
                // Filter out already-read items
                #[allow(clippy::unnecessary_map_or)]
                let unread: Vec<crate::state::types::NewsFeedItem> = filtered
                    .into_iter()
                    .filter(|item| {
                        !read_ids.contains(&item.id)
                            && item.url.as_ref().is_none_or(|url| !read_urls.contains(url))
                    })
                    .collect();
                tracing::info!(
                    unread_count = unread.len(),
                    "sending on-demand startup news items to channel"
                );
                match news_tx.send(unread) {
                    Ok(()) => {
                        tracing::info!("on-demand startup news items sent to channel successfully");
                    }
                    Err(e) => {
                        tracing::error!(
                            error = %e,
                            "failed to send on-demand startup news items to channel (receiver dropped?)"
                        );
                    }
                }
            }
            Err(e) => {
                tracing::warn!(error = %e, "on-demand startup news fetch failed");
                tracing::info!("sending empty array to clear loading flag after fetch error");
                let _ = news_tx.send(Vec::new());
            }
        }
    });
}

#[cfg(test)]
mod startup_news_tests {
    use crate::state::types::{NewsFeedItem, NewsFeedSource};
    use std::collections::HashSet;

    #[test]
    /// What: Test filtering logic for already-read news items.
    ///
    /// Inputs:
    /// - News items with some marked as read (by ID and URL).
    ///
    /// Output:
    /// - Only unread items returned.
    ///
    /// Details:
    /// - Verifies read filtering excludes items by both ID and URL.
    fn test_filter_already_read_items() {
        let read_ids: HashSet<String> = HashSet::from(["id-1".to_string()]);

        let read_urls: HashSet<String> = HashSet::from(["https://example.com/news/2".to_string()]);

        let items = vec![
            NewsFeedItem {
                id: "id-1".to_string(),
                date: "2025-01-01".to_string(),
                title: "Item 1".to_string(),
                summary: None,
                url: Some("https://example.com/news/1".to_string()),
                source: NewsFeedSource::ArchNews,
                severity: None,
                packages: Vec::new(),
            },
            NewsFeedItem {
                id: "id-2".to_string(),
                date: "2025-01-02".to_string(),
                title: "Item 2".to_string(),
                summary: None,
                url: Some("https://example.com/news/2".to_string()),
                source: NewsFeedSource::ArchNews,
                severity: None,
                packages: Vec::new(),
            },
            NewsFeedItem {
                id: "id-3".to_string(),
                date: "2025-01-03".to_string(),
                title: "Item 3".to_string(),
                summary: None,
                url: Some("https://example.com/news/3".to_string()),
                source: NewsFeedSource::ArchNews,
                severity: None,
                packages: Vec::new(),
            },
        ];

        let unread: Vec<NewsFeedItem> = items
            .into_iter()
            .filter(|item| {
                !read_ids.contains(&item.id)
                    && item.url.as_ref().is_none_or(|url| !read_urls.contains(url))
            })
            .collect();

        assert_eq!(unread.len(), 1);
        assert_eq!(unread[0].id, "id-3");
    }
}

/// What: Run the main event loop, processing all channel messages and rendering the UI.
///
/// Inputs:
/// - `terminal`: Optional terminal for rendering (None in headless mode)
/// - `app`: Application state
/// - `channels`: Communication channels for background workers
///
/// Output: None (runs until exit condition is met)
///
/// Details:
/// - Renders UI frames and handles all channel messages (events, search results, details,
///   preflight data, PKGBUILD, news, status, etc.)
/// - Exits when event handler returns true (e.g., quit command)
/// - Checks for `trigger_startup_news_fetch` flag and triggers fetch if set
pub async fn run_event_loop(
    terminal: &mut Option<Terminal<ratatui::backend::CrosstermBackend<std::io::Stdout>>>,
    app: &mut AppState,
    channels: &mut Channels,
) {
    loop {
        // Check if we need to trigger startup news fetch
        if app.trigger_startup_news_fetch {
            app.trigger_startup_news_fetch = false;
            trigger_startup_news_fetch(channels, &mut *app);
        }

        if let Some(t) = terminal.as_mut() {
            let _ = t.draw(|f| ui(f, app));
        }

        if process_channel_messages(app, channels).await {
            break;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::handle_aur_vote_response;
    use super::handle_aur_vote_state_response;
    use super::handle_index_notification;
    use super::handle_news_content;
    use super::handle_updates_list;
    use crate::app::runtime::background::Channels;
    use crate::app::runtime::workers::UpdateCheckPayload;
    use crate::state::AppState;
    use crate::state::types::{NewsFeedItem, NewsFeedSource};

    /// What: Build a minimal `NewsFeedItem` for news content tests.
    ///
    /// Inputs:
    /// - `id`: Stable identifier for the item.
    /// - `url`: URL to associate with the item.
    ///
    /// Output:
    /// - `NewsFeedItem` with Arch news source and empty optional fields.
    ///
    /// Details:
    /// - Uses a fixed date to keep assertions deterministic.
    fn make_news_item(id: &str, url: &str) -> NewsFeedItem {
        NewsFeedItem {
            id: id.to_string(),
            date: "2024-01-01".to_string(),
            title: format!("Title {id}"),
            summary: None,
            url: Some(url.to_string()),
            source: NewsFeedSource::ArchNews,
            severity: None,
            packages: Vec::new(),
        }
    }

    #[test]
    /// What: Ensure stale news content responses do not clear loading for the active selection.
    ///
    /// Inputs:
    /// - App with selection on item `b` and loading flagged true.
    /// - Content response for outdated item `a`.
    ///
    /// Output:
    /// - `news_content_loading` remains true and displayed content stays `None`.
    ///
    /// Details:
    /// - Prevents stale responses from cancelling the fetch for the current item.
    fn handle_news_content_keeps_loading_for_mismatched_url() {
        let mut app = AppState {
            news_results: vec![
                make_news_item("a", "https://example.com/a"),
                make_news_item("b", "https://example.com/b"),
            ],
            news_selected: 1,
            news_content_loading: true,
            ..AppState::default()
        };

        handle_news_content(&mut app, "https://example.com/a", "old".to_string());

        assert!(!app.news_content_loading);
        assert!(app.news_content.is_none());
        assert!(app.news_content_cache.contains_key("https://example.com/a"));
    }

    #[test]
    /// What: Ensure news content responses for the selected item clear loading and set content.
    ///
    /// Inputs:
    /// - App with selection on item `a` and loading flagged true.
    /// - Content response for the same item.
    ///
    /// Output:
    /// - Loading flag clears and content is stored.
    ///
    /// Details:
    /// - Confirms the happy path still updates UI state correctly.
    fn handle_news_content_updates_current_selection() {
        let mut app = AppState {
            news_results: vec![make_news_item("a", "https://example.com/a")],
            news_content_loading: true,
            ..AppState::default()
        };

        handle_news_content(&mut app, "https://example.com/a", "payload".to_string());

        assert!(!app.news_content_loading);
        assert_eq!(app.news_content, Some("payload".to_string()));
        assert!(app.news_content_cache.contains_key("https://example.com/a"));
    }

    #[test]
    /// What: Verify degraded update-check payloads set authoritative flag and user toast.
    ///
    /// Inputs:
    /// - Default `AppState` and a synthetic [`UpdateCheckPayload`] with `authoritative` false.
    ///
    /// Output:
    /// - `updates_last_check_authoritative` is `Some(false)` and a toast is scheduled.
    ///
    /// Details:
    /// - Ensures silent failure modes surface guidance instead of looking like a clean zero-update state.
    fn handle_updates_list_degraded_surfaces_toast() {
        let mut app = AppState::default();
        let payload = UpdateCheckPayload {
            count: 0,
            package_names: Vec::new(),
            authoritative: false,
            reason_codes: vec!["stale_db_fallback".to_string()],
            official_strategy: "stale_pacman_qu",
        };
        handle_updates_list(&mut app, payload);
        assert_eq!(app.updates_last_check_authoritative, Some(false));
        assert!(app.toast_message.is_some());
        assert!(app.toast_expires_at.is_some());
    }

    #[test]
    /// What: Verify authoritative update-check payloads do not set a degraded toast.
    ///
    /// Inputs:
    /// - Default `AppState` and a synthetic authoritative [`UpdateCheckPayload`].
    ///
    /// Output:
    /// - `updates_last_check_authoritative` is `Some(true)`; no toast from this handler.
    ///
    /// Details:
    /// - Guards against noisy toasts on the happy path.
    fn handle_updates_list_authoritative_skips_degraded_toast() {
        let mut app = AppState::default();
        let payload = UpdateCheckPayload {
            count: 2,
            package_names: vec!["a".to_string(), "b".to_string()],
            authoritative: true,
            reason_codes: Vec::new(),
            official_strategy: "checkupdates_db",
        };
        handle_updates_list(&mut app, payload);
        assert_eq!(app.updates_last_check_authoritative, Some(true));
        assert!(app.toast_message.is_none());
    }

    #[tokio::test]
    /// What: Ensure index-ready notification re-runs current query.
    ///
    /// Inputs:
    /// - `AppState` with `loading_index=true` and default query counters.
    /// - Runtime channels instance.
    ///
    /// Output:
    /// - `loading_index` is cleared.
    /// - `latest_query_id` advances, confirming a query dispatch was triggered.
    ///
    /// Details:
    /// - Prevents first-launch empty result list after async index refresh finishes.
    async fn handle_index_notification_retriggers_query() {
        let mut app = AppState {
            loading_index: true,
            ..AppState::default()
        };
        let channels = Channels::new(std::path::PathBuf::from("/tmp"));
        let latest_before = app.latest_query_id;

        let should_exit = handle_index_notification(&mut app, &channels);

        assert!(!should_exit);
        assert!(!app.loading_index);
        assert!(app.latest_query_id > latest_before);
    }

    #[test]
    /// What: Ensure successful AUR vote responses are surfaced as toasts.
    ///
    /// Inputs:
    /// - `AppState` default and a synthetic success vote response.
    ///
    /// Output:
    /// - Toast message and expiration are set.
    ///
    /// Details:
    /// - Confirms UI-safe success feedback path from runtime worker results.
    fn handle_aur_vote_response_success_sets_toast() {
        let mut app = AppState::default();
        let response = crate::app::runtime::workers::aur_vote::AurVoteResponse {
            result: Ok(crate::sources::AurVoteOutcome {
                action: crate::sources::VoteAction::Vote,
                pkgbase: "pacsea-bin".to_string(),
                dry_run: false,
            }),
        };

        handle_aur_vote_response(&mut app, response);

        let toast = app
            .toast_message
            .as_ref()
            .expect("success vote should set a toast");
        assert!(toast.contains("Voted for"));
        assert!(app.toast_expires_at.is_some());
    }

    #[test]
    /// What: Ensure dry-run vote responses do not persist local vote state.
    ///
    /// Inputs:
    /// - `AppState` default and a synthetic dry-run success vote response.
    ///
    /// Output:
    /// - Vote-state cache remains unchanged and dirty flag stays false.
    ///
    /// Details:
    /// - Dry-run must not mark package votes as changed because no remote mutation occurred.
    fn handle_aur_vote_response_dry_run_does_not_mark_cache_dirty() {
        let mut app = AppState::default();
        let before_vote_state = app.aur_vote_state_by_pkgbase.clone();
        let before_dirty = app.aur_vote_state_dirty;
        let response = crate::app::runtime::workers::aur_vote::AurVoteResponse {
            result: Ok(crate::sources::AurVoteOutcome {
                action: crate::sources::VoteAction::Vote,
                pkgbase: "pacsea-bin".to_string(),
                dry_run: true,
            }),
        };

        handle_aur_vote_response(&mut app, response);

        assert_eq!(app.aur_vote_state_by_pkgbase, before_vote_state);
        assert_eq!(app.aur_vote_state_dirty, before_dirty);
        let toast = app
            .toast_message
            .as_ref()
            .expect("dry-run vote should set a toast");
        assert!(toast.contains("[dry-run]"));
        assert!(app.toast_expires_at.is_some());
    }

    #[test]
    /// What: Ensure failed AUR vote responses are surfaced as actionable alerts.
    ///
    /// Inputs:
    /// - `AppState` default and synthetic auth failure response.
    ///
    /// Output:
    /// - Modal transitions to `Modal::Alert` with actionable guidance.
    ///
    /// Details:
    /// - Verifies runtime failure mapping reaches user-visible guidance text.
    fn handle_aur_vote_response_auth_failure_sets_alert() {
        let mut app = AppState::default();
        let response = crate::app::runtime::workers::aur_vote::AurVoteResponse {
            result: Err(crate::sources::AurVoteError::AuthFailed(
                "Permission denied".to_string(),
            )),
        };

        handle_aur_vote_response(&mut app, response);

        match app.modal {
            crate::state::Modal::Alert { message } => {
                assert!(message.contains("AUR vote failed"));
                assert!(message.contains("Upload your SSH public key"));
            }
            other => panic!("expected alert modal, got {other:?}"),
        }
    }

    #[test]
    /// What: Ensure `AlreadyVoted` syncs local vote cache without blocking alert.
    ///
    /// Inputs:
    /// - `AppState` default and synthetic `AlreadyVoted` response for one pkgbase.
    ///
    /// Output:
    /// - Vote-state cache is set to `Voted`, persistence dirty flag is set, and toast is shown.
    ///
    /// Details:
    /// - Keeps local state aligned with AUR when duplicate vote attempts occur.
    fn handle_aur_vote_response_already_voted_syncs_cache() {
        let mut app = AppState::default();
        let response = crate::app::runtime::workers::aur_vote::AurVoteResponse {
            result: Err(crate::sources::AurVoteError::AlreadyVoted(
                "pacsea-bin".to_string(),
            )),
        };

        handle_aur_vote_response(&mut app, response);

        assert!(matches!(
            app.aur_vote_state_by_pkgbase.get("pacsea-bin"),
            Some(crate::state::app_state::AurVoteStateUi::Voted)
        ));
        assert!(app.aur_vote_state_dirty);
        assert!(matches!(app.modal, crate::state::Modal::None));
        assert!(
            app.toast_message
                .as_ref()
                .is_some_and(|msg| msg.contains("Already voted"))
        );
    }

    #[test]
    /// What: Ensure `NotVoted` syncs local vote cache without blocking alert.
    ///
    /// Inputs:
    /// - `AppState` default and synthetic `NotVoted` response for one pkgbase.
    ///
    /// Output:
    /// - Vote-state cache is set to `NotVoted`, persistence dirty flag is set, and toast is shown.
    ///
    /// Details:
    /// - Keeps local state aligned with AUR when duplicate unvote attempts occur.
    fn handle_aur_vote_response_not_voted_syncs_cache() {
        let mut app = AppState::default();
        let response = crate::app::runtime::workers::aur_vote::AurVoteResponse {
            result: Err(crate::sources::AurVoteError::NotVoted(
                "pacsea-bin".to_string(),
            )),
        };

        handle_aur_vote_response(&mut app, response);

        assert!(matches!(
            app.aur_vote_state_by_pkgbase.get("pacsea-bin"),
            Some(crate::state::app_state::AurVoteStateUi::NotVoted)
        ));
        assert!(app.aur_vote_state_dirty);
        assert!(matches!(app.modal, crate::state::Modal::None));
        assert!(
            app.toast_message
                .as_ref()
                .is_some_and(|msg| msg.contains("No vote exists"))
        );
    }

    #[test]
    /// What: Ensure vote-state worker responses update the app vote-state cache.
    ///
    /// Inputs:
    /// - `AppState` default and a synthetic `Voted` vote-state response.
    ///
    /// Output:
    /// - Vote-state cache stores `AurVoteStateUi::Voted` for pkgbase.
    ///
    /// Details:
    /// - Verifies event-loop mapping for live check responses.
    fn handle_aur_vote_state_response_updates_cache() {
        let mut app = AppState::default();
        let response = crate::app::runtime::workers::aur_vote::AurVoteStateResponse {
            pkgbase: "pacsea-bin".to_string(),
            result: Ok(crate::sources::AurPackageVoteState::Voted),
        };

        handle_aur_vote_state_response(&mut app, response);

        assert!(matches!(
            app.aur_vote_state_by_pkgbase.get("pacsea-bin"),
            Some(crate::state::app_state::AurVoteStateUi::Voted)
        ));
    }

    #[test]
    /// What: Ensure unsupported vote-state command errors degrade to `Unknown`.
    ///
    /// Inputs:
    /// - `AppState` default and synthetic unsupported-command vote-state response.
    ///
    /// Output:
    /// - Vote-state cache stores `AurVoteStateUi::Unknown` for pkgbase.
    ///
    /// Details:
    /// - Prevents noisy inline error rendering when upstream SSH endpoint
    ///   does not expose `list-votes`.
    fn handle_aur_vote_state_response_unsupported_maps_to_unknown() {
        let mut app = AppState::default();
        let pkgbase = "pkg-unsupported-unknown-test";
        let response = crate::app::runtime::workers::aur_vote::AurVoteStateResponse {
            pkgbase: pkgbase.to_string(),
            result: Err(crate::sources::AurVoteError::Unexpected(
                "AUR SSH server does not support vote-state lookup.".to_string(),
            )),
        };

        handle_aur_vote_state_response(&mut app, response);

        assert!(matches!(
            app.aur_vote_state_by_pkgbase.get(pkgbase),
            Some(crate::state::app_state::AurVoteStateUi::Unknown)
        ));
        assert!(!app.aur_vote_state_lookup_supported);
    }

    #[test]
    /// What: Ensure unsupported live lookup does not override stable persisted vote-state.
    ///
    /// Inputs:
    /// - Existing `Voted` cache entry and unsupported-command vote-state response.
    ///
    /// Output:
    /// - Cache remains `Voted` and live lookup is disabled for the runtime session.
    ///
    /// Details:
    /// - Prevents "Loading..." followed by losing the visible vote-state when `list-votes`
    ///   is unavailable upstream.
    fn handle_aur_vote_state_response_unsupported_keeps_stable_cache() {
        let mut app = AppState::default();
        app.aur_vote_state_by_pkgbase.insert(
            "pacsea-bin".to_string(),
            crate::state::app_state::AurVoteStateUi::Voted,
        );
        let response = crate::app::runtime::workers::aur_vote::AurVoteStateResponse {
            pkgbase: "pacsea-bin".to_string(),
            result: Err(crate::sources::AurVoteError::Unexpected(
                "AUR SSH server does not support vote-state lookup.".to_string(),
            )),
        };

        handle_aur_vote_state_response(&mut app, response);

        assert!(matches!(
            app.aur_vote_state_by_pkgbase.get("pacsea-bin"),
            Some(crate::state::app_state::AurVoteStateUi::Voted)
        ));
        assert!(!app.aur_vote_state_lookup_supported);
    }
}