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
//! Event handling layer for Pacsea's TUI (modularized).
//!
//! This module re-exports `handle_event` and delegates pane-specific logic
//! and mouse handling to submodules to keep files small and maintainable.

use crossterm::event::{Event as CEvent, KeyCode, KeyEventKind, KeyModifiers};
use tokio::sync::mpsc;

use crate::state::{AppState, Focus, PackageItem, PkgbuildCheckRequest, QueryInput};

mod distro;
mod global;
/// Install pane event handling.
mod install;
mod modals;
mod mouse;
mod preflight;
/// Recent packages event handling module.
mod recent;
mod search;
/// Utility functions for event handling.
pub mod utils;

// Re-export open_preflight_modal for use in tests and other modules
pub use search::open_preflight_modal;

// Re-export start_execution for use in install/direct.rs and other modules
pub use preflight::start_execution;

/// What: Perform interactive privilege-tool authentication with a TUI terminal handoff.
///
/// Inputs:
/// - None (resolves the active privilege tool from settings).
///
/// Output:
/// - `Ok(true)` if the user authenticated successfully.
/// - `Ok(false)` if authentication was denied or cancelled.
///
/// # Errors
///
/// Returns `Err` if the terminal cannot be restored/setup or the tool cannot be resolved.
///
/// Details:
/// - Temporarily restores the terminal (leave alternate screen, disable raw mode)
///   so the user can interact with the privilege tool's native prompt (password, fingerprint).
/// - For sudo: runs `sudo -v` which refreshes the credential cache.
/// - For doas: runs `doas true`; works seamlessly with `persist` in `doas.conf`.
///   Without `persist`, the initial auth succeeds but subsequent PTY commands may re-prompt.
/// - Re-enters TUI (alternate screen, raw mode) regardless of auth outcome.
pub fn try_interactive_auth_handoff() -> Result<bool, String> {
    let tool = crate::logic::privilege::active_tool()?;

    crate::app::terminal::restore_terminal()
        .map_err(|e| format!("Failed to restore terminal for interactive auth: {e}"))?;

    let auth_result = crate::logic::privilege::run_interactive_auth(tool);

    if let Err(e) = crate::app::terminal::setup_terminal() {
        tracing::error!(error = %e, "Failed to re-setup terminal after interactive auth");
        return Err(format!("Failed to re-setup terminal: {e}"));
    }

    auth_result
}

/// What: Spawn the `downgrade` tool in an external terminal without Pacsea-managed password piping.
///
/// Inputs:
/// - `app`: Mutable application state.
/// - `items`: Packages to downgrade.
///
/// Output:
/// - `true` if the downgrade was spawned (or an error modal shown); `false` otherwise.
///
/// Details:
/// - Used in interactive auth mode where the external terminal handles privilege authentication.
/// - Builds a `{tool} downgrade <packages>` command (no password piping).
/// - Clears downgrade state and shows a toast message.
pub fn spawn_downgrade_in_terminal(app: &mut AppState, items: &[PackageItem]) -> bool {
    let names: Vec<String> = items.iter().map(|p| p.name.clone()).collect();
    let joined = names.join(" ");

    let tool = match crate::logic::privilege::active_tool() {
        Ok(t) => t,
        Err(msg) => {
            app.modal = crate::state::Modal::Alert { message: msg };
            return true;
        }
    };

    let downgrade_cmd =
        crate::logic::privilege::build_privilege_command(tool, &format!("downgrade {joined}"));
    let cmd = if app.dry_run {
        let quoted = crate::install::shell_single_quote(&downgrade_cmd);
        format!("echo DRY RUN: {quoted}")
    } else {
        format!(
            "if (command -v downgrade >/dev/null 2>&1) || pacman -Qi downgrade >/dev/null 2>&1; then {downgrade_cmd}; else echo 'downgrade tool not found. Install \"downgrade\" package.'; fi"
        )
    };

    app.downgrade_list.clear();
    app.downgrade_list_names.clear();
    app.downgrade_state.select(None);

    crate::install::spawn_shell_commands_in_terminal(&[cmd]);

    app.toast_message = Some(crate::i18n::t(app, "app.toasts.downgrade_started"));
    app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3));

    true
}

/// What: Dispatch a single terminal event (keyboard/mouse) and mutate the [`AppState`].
///
/// Inputs:
/// - `ev`: Terminal event (key or mouse)
/// - `app`: Mutable application state
/// - `query_tx`: Channel to send search queries
/// - `details_tx`: Channel to request package details
/// - `preview_tx`: Channel to request preview details for Recent
/// - `add_tx`: Channel to enqueue items into the install list
/// - `pkgb_tx`: Channel to request PKGBUILD content for the current selection
/// - `comments_tx`: Channel to request AUR comments for the current selection
/// - `pkgb_check_tx`: Channel to enqueue PKGBUILD check requests (must match a long-lived receiver, e.g. the runtime worker)
///
/// Output:
/// - `true` to signal the application should exit; otherwise `false`.
///
/// Details:
/// - Thin wrapper around [`handle_event_with_pkgbuild_checks`]; callers must pass the same `pkgb_check_tx` wired to the consumer as the interactive app uses.
/// - Handles active modal interactions first (Alert/SystemUpdate/ConfirmInstall/ConfirmRemove/Help/News).
/// - Supports global shortcuts (help overlay, theme reload, exit, PKGBUILD viewer toggle, change sort).
/// - Delegates pane-specific handling to `search`, `recent`, and `install` submodules.
#[allow(clippy::too_many_arguments)]
pub fn handle_event(
    ev: &CEvent,
    app: &mut AppState,
    query_tx: &mpsc::UnboundedSender<QueryInput>,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
    preview_tx: &mpsc::UnboundedSender<PackageItem>,
    add_tx: &mpsc::UnboundedSender<PackageItem>,
    pkgb_tx: &mpsc::UnboundedSender<PackageItem>,
    comments_tx: &mpsc::UnboundedSender<String>,
    pkgb_check_tx: &mpsc::UnboundedSender<PkgbuildCheckRequest>,
) -> bool {
    handle_event_with_pkgbuild_checks(
        ev,
        app,
        query_tx,
        details_tx,
        preview_tx,
        add_tx,
        pkgb_tx,
        comments_tx,
        pkgb_check_tx,
    )
}

#[allow(clippy::too_many_arguments)]
/// What: Event dispatcher variant that includes PKGBUILD checks channel wiring.
pub fn handle_event_with_pkgbuild_checks(
    ev: &CEvent,
    app: &mut AppState,
    query_tx: &mpsc::UnboundedSender<QueryInput>,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
    preview_tx: &mpsc::UnboundedSender<PackageItem>,
    add_tx: &mpsc::UnboundedSender<PackageItem>,
    pkgb_tx: &mpsc::UnboundedSender<PackageItem>,
    comments_tx: &mpsc::UnboundedSender<String>,
    pkgb_check_tx: &mpsc::UnboundedSender<PkgbuildCheckRequest>,
) -> bool {
    if let CEvent::Key(ke) = ev {
        if ke.kind != KeyEventKind::Press {
            return false;
        }

        // Log Ctrl+T for debugging
        if ke.code == KeyCode::Char('t') && ke.modifiers.contains(KeyModifiers::CONTROL) {
            tracing::debug!(
                "[Event] Ctrl+T key event: code={:?}, mods={:?}, modal={:?}, focus={:?}",
                ke.code,
                ke.modifiers,
                app.modal,
                app.focus
            );
        }

        // Check for global keybinds first (even when preflight is open)
        // This allows global shortcuts like Ctrl+T to work regardless of modal state
        if let Some(should_exit) = global::handle_global_key(
            *ke,
            app,
            details_tx,
            pkgb_tx,
            comments_tx,
            query_tx,
            pkgb_check_tx,
        ) {
            if ke.code == KeyCode::Char('t') && ke.modifiers.contains(KeyModifiers::CONTROL) {
                tracing::debug!(
                    "[Event] Global handler returned should_exit={}",
                    should_exit
                );
            }
            if should_exit {
                return true; // Exit requested
            }
            // Key was handled by global shortcuts, don't process further
            return false;
        }

        // Log if Ctrl+T wasn't handled by global handler
        if ke.code == KeyCode::Char('t') && ke.modifiers.contains(KeyModifiers::CONTROL) {
            tracing::warn!(
                "[Event] Ctrl+T was NOT handled by global handler, continuing to other handlers"
            );
        }

        // Handle Preflight modal (it's the largest)
        if matches!(app.modal, crate::state::Modal::Preflight { .. }) {
            return preflight::handle_preflight_key(*ke, app);
        }

        // Handle all other modals
        if modals::handle_modal_key(*ke, app, add_tx) {
            return false;
        }

        // If any modal remains open after handling above, consume the key to prevent main window interaction
        if !matches!(app.modal, crate::state::Modal::None) {
            return false;
        }

        // Pane-specific handling (Search, Recent, Install)
        // Recent pane focused
        if matches!(app.focus, Focus::Recent) {
            let should_exit =
                recent::handle_recent_key(*ke, app, query_tx, details_tx, preview_tx, add_tx);
            return should_exit;
        }

        // Install pane focused
        if matches!(app.focus, Focus::Install) {
            let should_exit = install::handle_install_key(*ke, app, details_tx, preview_tx, add_tx);
            return should_exit;
        }

        // Search pane focused (delegated)
        if matches!(app.focus, Focus::Search) {
            let should_exit = search::handle_search_key(
                *ke,
                app,
                query_tx,
                details_tx,
                add_tx,
                preview_tx,
                comments_tx,
            );
            return should_exit;
        }

        // Fallback: not handled
        return false;
    }

    // Mouse handling delegated
    if let CEvent::Mouse(m) = ev {
        return mouse::handle_mouse_event_with_pkgbuild_checks(
            *m,
            app,
            details_tx,
            preview_tx,
            add_tx,
            pkgb_tx,
            comments_tx,
            query_tx,
            pkgb_check_tx,
        );
    }
    false
}

#[cfg(all(test, not(target_os = "windows")))]
mod tests {
    use super::*;
    use crossterm::event::{
        Event as CEvent, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent,
        MouseEventKind,
    };
    use std::fs;
    use std::os::unix::fs::PermissionsExt;
    use std::path::PathBuf;

    #[test]
    /// What: Ensure the system update action invokes `xfce4-terminal` with the expected command separator.
    ///
    /// Inputs:
    /// - Shimmed `xfce4-terminal` placed on `PATH`, mouse clicks to open Options → Update System, and `Enter` key event.
    ///
    /// Output:
    /// - Captured arguments begin with `--command` followed by `bash -lc ...`.
    ///
    /// Details:
    /// - Uses environment overrides plus a fake terminal script to observe the spawn command safely.
    fn ui_options_update_system_enter_triggers_xfce4_args_shape() {
        let _guard = crate::global_test_mutex_lock();
        // fake xfce4-terminal
        let mut dir: PathBuf = std::env::temp_dir();
        dir.push(format!(
            "pacsea_test_term_{}_{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("System time is before UNIX epoch")
                .as_nanos()
        ));
        fs::create_dir_all(&dir).expect("create test directory");
        let mut out_path = dir.clone();
        out_path.push("args.txt");
        let mut term_path = dir.clone();
        term_path.push("xfce4-terminal");
        let script = "#!/bin/sh\n: > \"$PACSEA_TEST_OUT\"\nfor a in \"$@\"; do printf '%s\n' \"$a\" >> \"$PACSEA_TEST_OUT\"; done\n";
        fs::write(&term_path, script.as_bytes()).expect("Failed to write test terminal script");
        let mut perms = fs::metadata(&term_path)
            .expect("Failed to read test terminal script metadata")
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&term_path, perms)
            .expect("Failed to set test terminal script permissions");
        let orig_path = std::env::var_os("PATH");
        // Prepend our fake terminal directory to PATH to ensure xfce4-terminal is found first
        let combined_path = std::env::var("PATH").map_or_else(
            |_| dir.display().to_string(),
            |p| format!("{}:{p}", dir.display()),
        );
        unsafe {
            std::env::set_var("PATH", combined_path);
            std::env::set_var("PACSEA_TEST_OUT", out_path.display().to_string());
            std::env::set_var("PACSEA_TEST_HEADLESS", "1");
        }

        let mut app = AppState::default();
        let (qtx, _qrx) = mpsc::unbounded_channel();
        let (dtx, _drx) = mpsc::unbounded_channel();
        let (ptx, _prx) = mpsc::unbounded_channel();
        let (atx, _arx) = mpsc::unbounded_channel();
        let (pkgb_tx, _pkgb_rx) = mpsc::unbounded_channel();
        let (pkgb_check_tx, _pkgb_check_rx) = mpsc::unbounded_channel::<PkgbuildCheckRequest>();
        app.options_button_rect = Some((5, 5, 10, 1));
        let click_options = CEvent::Mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: 6,
            row: 5,
            modifiers: KeyModifiers::empty(),
        });
        let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>();
        let _ = super::handle_event(
            &click_options,
            &mut app,
            &qtx,
            &dtx,
            &ptx,
            &atx,
            &pkgb_tx,
            &comments_tx,
            &pkgb_check_tx,
        );
        assert!(app.options_menu_open);
        app.options_menu_rect = Some((5, 6, 20, 3));
        let click_menu_update = CEvent::Mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: 6,
            row: 7,
            modifiers: KeyModifiers::empty(),
        });
        let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>();
        let _ = super::handle_event(
            &click_menu_update,
            &mut app,
            &qtx,
            &dtx,
            &ptx,
            &atx,
            &pkgb_tx,
            &comments_tx,
            &pkgb_check_tx,
        );
        let enter = CEvent::Key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()));
        let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>();
        let _ = super::handle_event(
            &enter,
            &mut app,
            &qtx,
            &dtx,
            &ptx,
            &atx,
            &pkgb_tx,
            &comments_tx,
            &pkgb_check_tx,
        );
        // Wait for file to be created with retries
        let mut attempts = 0;
        while !out_path.exists() && attempts < 50 {
            std::thread::sleep(std::time::Duration::from_millis(10));
            attempts += 1;
        }
        // Give the process time to complete writing to avoid race conditions with other tests
        std::thread::sleep(std::time::Duration::from_millis(100));
        let body = fs::read_to_string(&out_path).expect("fake terminal args file written");
        let lines: Vec<&str> = body.lines().collect();
        // Verify that xfce4-terminal was actually used by checking for --command argument
        // (xfce4-terminal is the only terminal that uses --command format)
        // Find the last --command to handle cases where multiple spawns might have occurred
        let command_idx = lines.iter().rposition(|&l| l == "--command");
        if command_idx.is_none() {
            // If --command wasn't found, xfce4-terminal wasn't used (another terminal was chosen)
            // This can happen when other terminals are on PATH and chosen first
            eprintln!(
                "Warning: xfce4-terminal was not used (no --command found, got: {lines:?}), skipping xfce4-specific assertion"
            );
            unsafe {
                if let Some(v) = orig_path {
                    std::env::set_var("PATH", v);
                } else {
                    std::env::remove_var("PATH");
                }
                std::env::remove_var("PACSEA_TEST_OUT");
            }
            return;
        }
        let command_idx = command_idx.expect("command_idx should be Some after is_none() check");
        assert!(
            command_idx + 1 < lines.len(),
            "--command found at index {command_idx} but no following argument. Lines: {lines:?}"
        );
        assert!(
            lines[command_idx + 1].starts_with("bash -lc "),
            "Expected argument after --command to start with 'bash -lc ', got: '{}'. All lines: {:?}",
            lines[command_idx + 1],
            lines
        );
        unsafe {
            if let Some(v) = orig_path {
                std::env::set_var("PATH", v);
            } else {
                std::env::remove_var("PATH");
            }
            std::env::remove_var("PACSEA_TEST_OUT");
        }
    }

    #[test]
    /// What: Validate optional dependency rows reflect installed editors/terminals and X11-specific tooling.
    ///
    /// Inputs:
    /// - Temporary `PATH` exposing `nvim` and `kitty`, with `WAYLAND_DISPLAY` cleared to emulate X11.
    ///
    /// Output:
    /// - Optional deps list shows installed entries as non-selectable and missing tooling as selectable rows for clipboard/mirror/AUR helpers.
    ///
    /// Details:
    /// - Drives the Options menu to render optional dependencies while observing row attributes.
    fn optional_deps_rows_reflect_installed_and_x11_and_reflector() {
        let _guard = crate::global_test_mutex_lock();
        let (dir, orig_path, orig_wl) = setup_test_executables();
        let (mut app, channels) = setup_app_with_translations();
        open_optional_deps_modal(&mut app, &channels);

        verify_optional_deps_rows(&app.modal);
        teardown_test_environment(orig_path, orig_wl, &dir);
    }

    /// What: Setup test executables and environment for optional deps test.
    ///
    /// Inputs: None.
    ///
    /// Output:
    /// - Returns (`temp_dir`, `original_path`, `original_wayland_display`) for cleanup.
    ///
    /// Details:
    /// - Creates `nvim` and `kitty` executables, sets `PATH`, clears `WAYLAND_DISPLAY`.
    fn setup_test_executables() -> (
        std::path::PathBuf,
        Option<std::ffi::OsString>,
        Option<std::ffi::OsString>,
    ) {
        use std::fs;
        use std::os::unix::fs::PermissionsExt;
        use std::path::PathBuf;

        let mut dir: PathBuf = std::env::temp_dir();
        dir.push(format!(
            "pacsea_test_optional_deps_{}_{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("System time is before UNIX epoch")
                .as_nanos()
        ));
        let _ = fs::create_dir_all(&dir);

        let make_exec = |name: &str| {
            let mut p = dir.clone();
            p.push(name);
            fs::write(&p, b"#!/bin/sh\nexit 0\n").expect("Failed to write test executable stub");
            let mut perms = fs::metadata(&p)
                .expect("Failed to read test executable stub metadata")
                .permissions();
            perms.set_mode(0o755);
            fs::set_permissions(&p, perms).expect("Failed to set test executable stub permissions");
        };

        make_exec("nvim");
        make_exec("kitty");

        let orig_path = std::env::var_os("PATH");
        unsafe {
            std::env::set_var("PATH", dir.display().to_string());
            std::env::set_var("PACSEA_TEST_HEADLESS", "1");
        };
        let orig_wl = std::env::var_os("WAYLAND_DISPLAY");
        unsafe { std::env::remove_var("WAYLAND_DISPLAY") };
        (dir, orig_path, orig_wl)
    }

    /// Type alias for application communication channels tuple.
    ///
    /// Contains 7 `UnboundedSender` channels for query, details, preview, add, pkgbuild, comments, and PKGBUILD checks.
    type AppChannels = (
        tokio::sync::mpsc::UnboundedSender<QueryInput>,
        tokio::sync::mpsc::UnboundedSender<PackageItem>,
        tokio::sync::mpsc::UnboundedSender<PackageItem>,
        tokio::sync::mpsc::UnboundedSender<PackageItem>,
        tokio::sync::mpsc::UnboundedSender<PackageItem>,
        tokio::sync::mpsc::UnboundedSender<String>,
        tokio::sync::mpsc::UnboundedSender<PkgbuildCheckRequest>,
    );

    /// Type alias for setup app result tuple.
    ///
    /// Contains `AppState` and `AppChannels`.
    type SetupAppResult = (AppState, AppChannels);

    /// What: Setup app state with translations and return channels.
    ///
    /// Inputs: None.
    ///
    /// Output:
    /// - Returns (`app_state`, `channels` tuple).
    ///
    /// Details:
    /// - Initializes translations for optional deps categories.
    fn setup_app_with_translations() -> SetupAppResult {
        use std::collections::HashMap;
        let mut app = AppState::default();
        let mut translations = HashMap::new();
        translations.insert(
            "app.optional_deps.categories.editor".to_string(),
            "Editor".to_string(),
        );
        translations.insert(
            "app.optional_deps.categories.terminal".to_string(),
            "Terminal".to_string(),
        );
        translations.insert(
            "app.optional_deps.categories.clipboard".to_string(),
            "Clipboard".to_string(),
        );
        translations.insert(
            "app.optional_deps.categories.aur_helper".to_string(),
            "AUR Helper".to_string(),
        );
        translations.insert(
            "app.optional_deps.categories.security".to_string(),
            "Security".to_string(),
        );
        app.translations.clone_from(&translations);
        app.translations_fallback = translations;
        let (qtx, _qrx) = mpsc::unbounded_channel();
        let (dtx, _drx) = mpsc::unbounded_channel();
        let (ptx, _prx) = mpsc::unbounded_channel();
        let (atx, _arx) = mpsc::unbounded_channel();
        let (pkgb_tx, _pkgb_rx) = mpsc::unbounded_channel();
        let (comments_tx, _comments_rx) = mpsc::unbounded_channel();
        let (pkgb_check_tx, _pkgb_check_rx) = mpsc::unbounded_channel::<PkgbuildCheckRequest>();
        (
            app,
            (qtx, dtx, ptx, atx, pkgb_tx, comments_tx, pkgb_check_tx),
        )
    }

    /// What: Open optional deps modal via UI interactions.
    ///
    /// Inputs:
    /// - `app`: Mutable application state
    /// - `channels`: Tuple of channel senders for event handling
    ///
    /// Output: None (modifies app state).
    ///
    /// Details:
    /// - Clicks options button, then presses '4' to open Optional Deps.
    fn open_optional_deps_modal(app: &mut AppState, channels: &AppChannels) {
        app.options_button_rect = Some((5, 5, 12, 1));
        let click_options = CEvent::Mouse(crossterm::event::MouseEvent {
            kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
            column: 6,
            row: 5,
            modifiers: KeyModifiers::empty(),
        });
        let _ = super::handle_event(
            &click_options,
            app,
            &channels.0,
            &channels.1,
            &channels.2,
            &channels.3,
            &channels.4,
            &channels.5,
            &channels.6,
        );
        assert!(app.options_menu_open);

        // In Package mode, TUI Optional Deps is at index 3 (key '3')
        // In News mode, TUI Optional Deps is at index 2 (key '2')
        // Since tests default to Package mode, use '3'
        let mut key_three_event =
            crossterm::event::KeyEvent::new(KeyCode::Char('3'), KeyModifiers::empty());
        key_three_event.kind = KeyEventKind::Press;
        let key_three = CEvent::Key(key_three_event);
        let _ = super::handle_event(
            &key_three,
            app,
            &channels.0,
            &channels.1,
            &channels.2,
            &channels.3,
            &channels.4,
            &channels.5,
            &channels.6,
        );
    }

    /// What: Verify optional deps rows match expected state.
    ///
    /// Inputs:
    /// - `modal`: Modal state to verify
    ///
    /// Output: None (panics on assertion failure).
    ///
    /// Details:
    /// - Checks editor, terminal, clipboard, mirrors, and AUR helper rows.
    fn verify_optional_deps_rows(modal: &crate::state::Modal) {
        match modal {
            crate::state::Modal::OptionalDeps { rows, .. } => {
                let find = |prefix: &str| rows.iter().find(|r| r.label.starts_with(prefix));

                let ed = find("Editor: nvim").expect("editor row nvim");
                assert!(ed.installed, "nvim should be marked installed");
                assert!(!ed.selectable, "installed editor should not be selectable");

                let term = find("Terminal: kitty").expect("terminal row kitty");
                assert!(term.installed, "kitty should be marked installed");
                assert!(
                    !term.selectable,
                    "installed terminal should not be selectable"
                );

                let clip = find("Clipboard: xclip").expect("clipboard xclip row");
                assert!(
                    !clip.installed,
                    "xclip should not appear installed by default"
                );
                assert!(
                    clip.selectable,
                    "xclip should be selectable when not installed"
                );
                assert_eq!(clip.note.as_deref(), Some("X11"));

                let mirrors = find("Mirrors: reflector").expect("reflector row");
                assert!(
                    !mirrors.installed,
                    "reflector should not be installed by default"
                );
                assert!(mirrors.selectable, "reflector should be selectable");

                let paru = find("AUR Helper: paru").expect("paru row");
                assert!(!paru.installed);
                assert!(paru.selectable);
                let yay = find("AUR Helper: yay").expect("yay row");
                assert!(!yay.installed);
                assert!(yay.selectable);
            }
            other => panic!("Expected OptionalDeps modal, got {other:?}"),
        }
    }

    /// What: Restore environment and cleanup test directory.
    ///
    /// Inputs:
    /// - `orig_path`: Original `PATH` value to restore
    /// - `orig_wl`: Original `WAYLAND_DISPLAY` value to restore
    /// - `dir`: Temporary directory to remove
    ///
    /// Output: None.
    ///
    /// Details:
    /// - Restores `PATH` and `WAYLAND_DISPLAY`, removes temp directory.
    fn teardown_test_environment(
        orig_path: Option<std::ffi::OsString>,
        orig_wl: Option<std::ffi::OsString>,
        dir: &std::path::PathBuf,
    ) {
        unsafe {
            if let Some(v) = orig_path {
                std::env::set_var("PATH", v);
            } else {
                std::env::remove_var("PATH");
            }
            if let Some(v) = orig_wl {
                std::env::set_var("WAYLAND_DISPLAY", v);
            } else {
                std::env::remove_var("WAYLAND_DISPLAY");
            }
        }
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    /// What: Optional Deps shows Wayland clipboard (`wl-clipboard`) when `WAYLAND_DISPLAY` is set
    ///
    /// - Setup: Empty PATH; set `WAYLAND_DISPLAY`
    /// - Expect: A row "Clipboard: wl-clipboard" with note "Wayland", not installed and selectable
    fn optional_deps_rows_wayland_shows_wl_clipboard() {
        use std::collections::HashMap;
        use std::fs;
        use std::path::PathBuf;
        let _guard = crate::global_test_mutex_lock();

        // Temp PATH directory (empty)
        let mut dir: PathBuf = std::env::temp_dir();
        dir.push(format!(
            "pacsea_test_optional_deps_wl_{}_{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("System time is before UNIX epoch")
                .as_nanos()
        ));
        let _ = fs::create_dir_all(&dir);

        let orig_path = std::env::var_os("PATH");
        unsafe {
            std::env::set_var("PATH", dir.display().to_string());
            std::env::set_var("PACSEA_TEST_HEADLESS", "1");
        };
        let orig_wl = std::env::var_os("WAYLAND_DISPLAY");
        unsafe { std::env::set_var("WAYLAND_DISPLAY", "1") };

        let mut app = AppState::default();
        // Initialize i18n translations for optional deps
        let mut translations = HashMap::new();
        translations.insert(
            "app.optional_deps.categories.editor".to_string(),
            "Editor".to_string(),
        );
        translations.insert(
            "app.optional_deps.categories.terminal".to_string(),
            "Terminal".to_string(),
        );
        translations.insert(
            "app.optional_deps.categories.clipboard".to_string(),
            "Clipboard".to_string(),
        );
        translations.insert(
            "app.optional_deps.categories.aur_helper".to_string(),
            "AUR Helper".to_string(),
        );
        translations.insert(
            "app.optional_deps.categories.security".to_string(),
            "Security".to_string(),
        );
        app.translations.clone_from(&translations);
        app.translations_fallback = translations;
        let (qtx, _qrx) = mpsc::unbounded_channel();
        let (dtx, _drx) = mpsc::unbounded_channel();
        let (ptx, _prx) = mpsc::unbounded_channel();
        let (atx, _arx) = mpsc::unbounded_channel();
        let (pkgb_tx, _pkgb_rx) = mpsc::unbounded_channel();
        let (pkgb_check_tx, _pkgb_check_rx) = mpsc::unbounded_channel::<PkgbuildCheckRequest>();

        // Open Options via click
        app.options_button_rect = Some((5, 5, 12, 1));
        let click_options = CEvent::Mouse(crossterm::event::MouseEvent {
            kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
            column: 6,
            row: 5,
            modifiers: KeyModifiers::empty(),
        });
        let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>();
        let _ = super::handle_event(
            &click_options,
            &mut app,
            &qtx,
            &dtx,
            &ptx,
            &atx,
            &pkgb_tx,
            &comments_tx,
            &pkgb_check_tx,
        );
        assert!(app.options_menu_open);

        // Press '3' to open Optional Deps (Package mode: List installed=1, Update system=2, TUI Optional Deps=3, News management=4)
        let mut key_three_event =
            crossterm::event::KeyEvent::new(KeyCode::Char('3'), KeyModifiers::empty());
        key_three_event.kind = KeyEventKind::Press;
        let key_three = CEvent::Key(key_three_event);
        let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>();
        let _ = super::handle_event(
            &key_three,
            &mut app,
            &qtx,
            &dtx,
            &ptx,
            &atx,
            &pkgb_tx,
            &comments_tx,
            &pkgb_check_tx,
        );

        match &app.modal {
            crate::state::Modal::OptionalDeps { rows, .. } => {
                let clip = rows
                    .iter()
                    .find(|r| r.label.starts_with("Clipboard: wl-clipboard"))
                    .expect("wl-clipboard row");
                assert_eq!(clip.note.as_deref(), Some("Wayland"));
                assert!(!clip.installed);
                assert!(clip.selectable);
                // Ensure xclip is not presented when Wayland is active
                assert!(
                    !rows.iter().any(|r| r.label.starts_with("Clipboard: xclip")),
                    "xclip should not be listed on Wayland"
                );
            }
            other => panic!("Expected OptionalDeps modal, got {other:?}"),
        }

        // Restore env and cleanup
        unsafe {
            if let Some(v) = orig_path {
                std::env::set_var("PATH", v);
            } else {
                std::env::remove_var("PATH");
            }
            if let Some(v) = orig_wl {
                std::env::set_var("WAYLAND_DISPLAY", v);
            } else {
                std::env::remove_var("WAYLAND_DISPLAY");
            }
        }
        let _ = fs::remove_dir_all(&dir);
    }
}