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
//! Optional dependencies modal handling.

use crossterm::event::{KeyCode, KeyEvent};

use crate::state::AppState;

/// What: Open one of the setup pseudo-packages used by first-startup orchestration.
///
/// Inputs:
/// - `app`: Mutable application state.
/// - `package`: Pseudo-package id (`aur-ssh-setup`, `aur-sleuth-setup`, `virustotal-setup`, `sudo-timestamp-setup`, `doas-persist-setup`).
///
/// Output:
/// - Sets `app.modal` or spawns setup terminal command depending on selected setup.
pub(super) fn open_setup_package(app: &mut AppState, package: &str) {
    let row = crate::state::types::OptionalDepRow {
        label: package.to_string(),
        package: package.to_string(),
        installed: false,
        selectable: true,
        note: Some("Setup".to_string()),
    };
    let (new_modal, _) = handle_optional_deps_enter(app, &row);
    app.modal = new_modal;
}

/// What: Handle key events for `OptionalDeps` modal.
///
/// Inputs:
/// - `ke`: Key event
/// - `app`: Mutable application state
/// - `rows`: Optional dependency rows
/// - `selected`: Currently selected row index
///
/// Output:
/// - `Some(true)` if Enter was pressed and should stop propagation, `Some(false)` otherwise, `None` if not handled
///
/// Details:
/// - Handles Esc/q to close, navigation and Enter to install/setup optional dependencies
pub(super) fn handle_optional_deps(
    ke: KeyEvent,
    app: &mut AppState,
    rows: &[crate::state::types::OptionalDepRow],
    selected: &mut usize,
    selected_pkg_names: &mut std::collections::HashSet<String>,
) -> Option<bool> {
    match ke.code {
        KeyCode::Esc | KeyCode::Char('q') => {
            app.modal = crate::state::Modal::None;
            if !app.pending_startup_setup_steps.is_empty() {
                super::common::show_next_startup_setup_step(app);
            }
            Some(false)
        }
        KeyCode::Up | KeyCode::Char('k') => {
            if *selected > 0 {
                *selected -= 1;
            }
            Some(false)
        }
        KeyCode::Down | KeyCode::Char('j') => {
            if *selected + 1 < rows.len() {
                *selected += 1;
            }
            Some(false)
        }
        KeyCode::Char(' ') => {
            if let Some(row) = rows.get(*selected)
                && row.selectable
                && !row.installed
                && !is_setup_package(&row.package)
            {
                if selected_pkg_names.contains(&row.package) {
                    selected_pkg_names.remove(&row.package);
                } else {
                    selected_pkg_names.insert(row.package.clone());
                }
            }
            Some(false)
        }
        KeyCode::Enter | KeyCode::Char('\n' | '\r') => {
            if let Some(row) = rows.get(*selected) {
                if row.selectable && !row.installed && !is_setup_package(&row.package) {
                    let selected_rows: Vec<crate::state::types::OptionalDepRow> = rows
                        .iter()
                        .filter(|r| {
                            r.selectable
                                && !r.installed
                                && !is_setup_package(&r.package)
                                && selected_pkg_names.contains(&r.package)
                        })
                        .cloned()
                        .collect();
                    if !selected_rows.is_empty() {
                        let (new_modal, should_stop) =
                            handle_optional_deps_batch_install(app, &selected_rows);
                        app.modal = new_modal;
                        selected_pkg_names.clear();
                        return Some(should_stop);
                    }
                }
                match handle_optional_deps_enter(app, row) {
                    (new_modal, true) => {
                        app.modal = new_modal;
                        Some(true)
                    }
                    (new_modal, false) => {
                        app.modal = new_modal;
                        Some(false)
                    }
                }
            } else {
                Some(false)
            }
        }
        _ => None,
    }
}

/// What: Check whether a row package id represents a setup pseudo-package.
#[must_use]
fn is_setup_package(package: &str) -> bool {
    matches!(
        package,
        "aur-ssh-setup"
            | "virustotal-setup"
            | "sudo-timestamp-setup"
            | "doas-persist-setup"
            | "aur-sleuth-setup"
    )
}

/// What: Start a batch install for selected optional dependency rows.
///
/// Inputs:
/// - `app`: Mutable app state.
/// - `selected_rows`: Installable, non-setup rows selected by the user.
///
/// Output:
/// - `(new_modal, should_stop_propagation)` tuple.
fn handle_optional_deps_batch_install(
    app: &mut AppState,
    selected_rows: &[crate::state::types::OptionalDepRow],
) -> (crate::state::Modal, bool) {
    use crate::state::{PackageItem, Source};

    if selected_rows.len() == 1 {
        return handle_optional_deps_enter(app, &selected_rows[0]);
    }

    let packages: Vec<PackageItem> = selected_rows
        .iter()
        .map(|row| {
            crate::index::find_package_by_name(&row.package).unwrap_or_else(|| PackageItem {
                name: row.package.clone(),
                version: String::new(),
                description: String::new(),
                source: Source::Aur,
                popularity: None,
                out_of_date: None,
                orphaned: false,
            })
        })
        .collect();

    let aur_count = packages
        .iter()
        .filter(|item| matches!(item.source, Source::Aur))
        .count();
    let header_chips = crate::state::modal::PreflightHeaderChips {
        package_count: packages.len(),
        download_bytes: 0,
        install_delta_bytes: 0,
        aur_count,
        risk_score: 0,
        risk_level: crate::state::modal::RiskLevel::Low,
    };

    // Reuse standard install flow so auth handoff/password prompt semantics stay consistent.
    let _ = crate::events::preflight::keys::handle_proceed_install(app, packages, header_chips);
    (app.modal.clone(), false)
}

/// What: Handle Enter key in `OptionalDeps` modal.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `row`: Selected optional dependency row
///
/// Output:
/// - `(new_modal, should_stop_propagation)` tuple
///
/// Details:
/// - Handles setup for virustotal/aur-sleuth (keeps terminal spawn for interactive setup)
/// - Shows reinstall confirmation for already installed dependencies
/// - Installs optional dependencies using executor pattern
#[allow(clippy::too_many_lines)] // Complex function handling multiple installation paths (function has 227 lines)
fn handle_optional_deps_enter(
    app: &mut AppState,
    row: &crate::state::types::OptionalDepRow,
) -> (crate::state::Modal, bool) {
    use crate::state::{PackageItem, Source};

    // Setup flows need interactive terminal, keep as-is
    if row.package == "aur-ssh-setup" {
        let mut status_lines = vec![
            "This setup will create '~/.ssh/aur_key' if missing.".to_string(),
            "It will add/update Host aur.archlinux.org in '~/.ssh/config'.".to_string(),
            "Then it validates with: ssh aur@aur.archlinux.org help".to_string(),
            format!(
                "After setup, upload '~/.ssh/aur_key.pub' to {}",
                crate::logic::ssh_setup::AUR_ACCOUNT_URL
            ),
            "Press Enter to run, O to open account page, Esc to cancel.".to_string(),
        ];
        if !crate::logic::ssh_setup::is_openssh_installed() {
            status_lines.push(
                "Warning: openssh is not installed. Install openssh first, then run setup."
                    .to_string(),
            );
        }
        return (
            crate::state::Modal::SshAurSetup {
                step: crate::state::SshSetupStep::Intro,
                status_lines,
                existing_host_block: None,
            },
            false,
        );
    }
    if row.package == "virustotal-setup" {
        let current = crate::theme::settings().virustotal_api_key;
        let cur_len = current.len();
        return (
            crate::state::Modal::VirusTotalSetup {
                input: current,
                cursor: cur_len,
            },
            false,
        );
    }
    if row.package == "sudo-timestamp-setup" {
        return (
            crate::state::Modal::SudoTimestampSetup {
                setup: crate::state::modal::SudoTimestampSetupModalState {
                    phase: crate::state::modal::SudoTimestampSetupPhase::Select,
                    select_cursor: 0,
                },
            },
            false,
        );
    }
    if row.package == "doas-persist-setup" {
        return (
            crate::state::Modal::DoasPersistSetup {
                setup: crate::state::modal::DoasPersistSetupModalState {
                    phase: crate::state::modal::DoasPersistSetupPhase::Select,
                    select_cursor: 0,
                },
            },
            false,
        );
    }
    if row.package == "aur-sleuth-setup" {
        let cmd = r##"(set -e
            if ! command -v aur-sleuth >/dev/null 2>&1; then
            echo "aur-sleuth not found."
            echo
            echo "Install aur-sleuth:"
            echo "  1) system (/usr/local) requires sudo"
            echo "  2) user (~/.local)"
            echo "  3) cancel"
            read -rp "Choose [1/2/3]: " choice
            case "$choice" in
            1)
            tmp="$(mktemp -d)"; cd "$tmp"
            git clone https://github.com/mgalgs/aur-sleuth.git
            cd aur-sleuth
            sudo make install
            ;;
            2)
            tmp="$(mktemp -d)"; cd "$tmp"
            git clone https://github.com/mgalgs/aur-sleuth.git
            cd aur-sleuth
            make install PREFIX="$HOME/.local"
            ;;
            *)
            echo "Cancelled."; echo "Press any key to close..."; read -rn1 -s _; exit 0;;
            esac
            else
            echo "aur-sleuth already installed; continuing to setup"
            fi
            conf="${XDG_CONFIG_HOME:-$HOME/.config}/aur-sleuth.conf"
            mkdir -p "$(dirname "$conf")"
            echo "# aur-sleuth configuration" > "$conf"
            echo "[default]" >> "$conf"
            read -rp "OPENAI_BASE_URL (e.g. https://openrouter.ai/api/v1 or http://localhost:11434/v1): " base
            read -rp "OPENAI_MODEL (e.g. qwen/qwen3-30b-a3b-instruct-2507 or llama3.1:8b): " model
            read -rp "OPENAI_API_KEY: " key
            read -rp "MAX_LLM_JOBS (default 3): " jobs
            read -rp "AUDIT_FAILURE_FATAL (true/false) [true]: " fatal
            jobs=${jobs:-3}
            fatal=${fatal:-true}
            [ -n "$base" ] && echo "OPENAI_BASE_URL = $base" >> "$conf"
            [ -n "$model" ] && echo "OPENAI_MODEL = $model" >> "$conf"
            echo "OPENAI_API_KEY = $key" >> "$conf"
            echo "MAX_LLM_JOBS = $jobs" >> "$conf"
            echo "AUDIT_FAILURE_FATAL = $fatal" >> "$conf"
            echo; echo "Wrote $conf"
            echo "Tip: You can run 'aur-sleuth package-name' or audit a local pkgdir with '--pkgdir .'"
            echo; echo "Press any key to close..."; read -rn1 -s _)"##
            .to_string();
        let to_run = if app.dry_run {
            // Properly quote the command to avoid syntax errors with complex shell constructs
            use crate::install::shell_single_quote;
            let quoted = shell_single_quote(&cmd);
            vec![format!("echo DRY RUN: {quoted}")]
        } else {
            vec![cmd]
        };
        crate::install::spawn_shell_commands_in_terminal(&to_run);
        return (crate::state::Modal::None, true);
    }

    // Handle reinstall for already installed dependencies
    if row.installed {
        let pkg = row.package.clone();

        // Determine if official or AUR to create proper PackageItem
        let package_item = crate::index::find_package_by_name(&pkg).unwrap_or_else(|| {
            // Assume AUR if not found in official index
            PackageItem {
                name: pkg.clone(),
                version: String::new(),
                description: String::new(),
                source: Source::Aur,
                popularity: None,
                out_of_date: None,
                orphaned: false,
            }
        });

        // Show reinstall confirmation modal
        // For optional deps, it's a single package, so items and all_items are the same
        return (
            crate::state::Modal::ConfirmReinstall {
                items: vec![package_item.clone()],
                all_items: vec![package_item],
                header_chips: crate::state::modal::PreflightHeaderChips::default(),
            },
            false,
        );
    }

    // Install optional dependencies using executor pattern
    if !row.installed && row.selectable {
        let pkg = row.package.clone();

        // Special packages that need custom installation commands (can't use AUR helpers)
        // paru and yay can't install themselves via AUR helpers (chicken-and-egg problem)
        if pkg == "paru" || pkg == "yay" {
            let cmd = if pkg == "paru" {
                // Use temporary directory to avoid conflicts with existing directories
                "tmp=$(mktemp -d) && cd \"$tmp\" && git clone https://aur.archlinux.org/paru.git && cd paru && makepkg -si"
                    .to_string()
            } else {
                // yay
                // Use temporary directory to avoid conflicts with existing directories
                "tmp=$(mktemp -d) && cd \"$tmp\" && git clone https://aur.archlinux.org/yay.git && cd yay && makepkg -si"
                    .to_string()
            };

            // Create a dummy PackageItem for display in PreflightExec modal
            let item = PackageItem {
                name: pkg,
                version: String::new(),
                description: String::new(),
                source: Source::Aur,
                popularity: None,
                out_of_date: None,
                orphaned: false,
            };

            // These commands need sudo (makepkg -si)
            // Check faillock status before proceeding
            let username = std::env::var("USER").unwrap_or_else(|_| "user".to_string());
            if let Some(lockout_msg) =
                crate::logic::faillock::get_lockout_message_if_locked(&username, app)
            {
                // User is locked out - show warning
                app.modal = crate::state::Modal::Alert {
                    message: lockout_msg,
                };
                return (crate::state::Modal::None, false);
            }

            let header_chips = crate::state::modal::PreflightHeaderChips {
                package_count: 1,
                download_bytes: 0,
                install_delta_bytes: 0,
                aur_count: 1,
                risk_score: 0,
                risk_level: crate::state::modal::RiskLevel::Low,
            };

            let settings = crate::theme::settings();
            let proceed_no_password =
                |app: &mut AppState,
                 item: PackageItem,
                 cmd: String,
                 header_chips: crate::state::modal::PreflightHeaderChips| {
                    app.pending_custom_command = Some(cmd);
                    app.modal = crate::state::Modal::PreflightExec {
                        items: vec![item],
                        action: crate::state::PreflightAction::Install,
                        tab: crate::state::PreflightTab::Summary,
                        verbose: false,
                        log_lines: Vec::new(),
                        abortable: false,
                        header_chips,
                        success: None,
                    };
                    app.pending_executor_request =
                        Some(crate::install::ExecutorRequest::CustomCommand {
                            command: app.pending_custom_command.take().unwrap_or_default(),
                            password: None,
                            dry_run: app.dry_run,
                        });
                };

            if crate::logic::password::should_use_interactive_auth_handoff(&settings) {
                match crate::events::try_interactive_auth_handoff() {
                    Ok(true) => proceed_no_password(app, item, cmd, header_chips),
                    Ok(false) => {
                        app.modal = crate::state::Modal::Alert {
                            message: crate::i18n::t(app, "app.errors.authentication_failed"),
                        };
                    }
                    Err(e) => {
                        app.modal = crate::state::Modal::Alert { message: e };
                    }
                }
            } else if crate::logic::password::resolve_auth_mode(&settings)
                == crate::logic::privilege::AuthMode::PasswordlessOnly
                && crate::logic::password::should_use_passwordless_sudo(&settings)
            {
                proceed_no_password(app, item, cmd, header_chips);
            } else {
                app.modal = crate::state::Modal::PasswordPrompt {
                    purpose: crate::state::modal::PasswordPurpose::Install,
                    items: vec![item],
                    input: crate::state::SecureString::default(),
                    cursor: 0,
                    error: None,
                };
                app.pending_custom_command = Some(cmd);
                app.pending_exec_header_chips = Some(header_chips);
            }

            return (app.modal.clone(), false);
        }

        // Regular packages: determine if official or AUR
        let (package_item, is_aur) = crate::index::find_package_by_name(&pkg).map_or_else(
            || {
                // Assume AUR if not found in official index
                (
                    PackageItem {
                        name: pkg.clone(),
                        version: String::new(),
                        description: String::new(),
                        source: Source::Aur,
                        popularity: None,
                        out_of_date: None,
                        orphaned: false,
                    },
                    true,
                )
            },
            |official_item| (official_item, false),
        );

        // For rate-mirrors and semgrep-bin, use AUR helper if available
        let use_aur_helper = is_aur || pkg == "rate-mirrors" || pkg == "semgrep-bin";

        let header_chips = crate::state::modal::PreflightHeaderChips {
            package_count: 1,
            download_bytes: 0,
            install_delta_bytes: 0,
            aur_count: usize::from(use_aur_helper),
            risk_score: 0,
            risk_level: crate::state::modal::RiskLevel::Low,
        };
        let _ = crate::events::preflight::keys::handle_proceed_install(
            app,
            vec![package_item],
            header_chips,
        );
        return (app.modal.clone(), false);
    }

    (crate::state::Modal::None, false)
}

/// What: Handle key events for `SshAurSetup` modal.
///
/// Inputs:
/// - `ke`: Key event from terminal.
/// - `app`: Mutable application state.
/// - `step`: Current setup step.
/// - `status_lines`: Mutable status lines shown in modal.
/// - `existing_host_block`: Mutable optional conflicting host block text.
///
/// Output:
/// - `Some(true)` when event is handled and should stop propagation.
/// - `Some(false)` when handled without stop.
/// - `None` when event is not handled.
pub(super) fn handle_ssh_setup_modal(
    ke: KeyEvent,
    app: &mut AppState,
    step: &mut crate::state::SshSetupStep,
    status_lines: &mut Vec<String>,
    existing_host_block: &mut Option<String>,
) -> Option<bool> {
    match (*step, ke.code) {
        (_, KeyCode::Char('o' | 'O')) => {
            crate::util::open_url(crate::logic::ssh_setup::AUR_ACCOUNT_URL);
            Some(false)
        }
        (_, KeyCode::Char('c' | 'C')) => {
            match crate::logic::ssh_setup::try_copy_aur_ssh_public_key_from_status_lines(
                status_lines,
            ) {
                None => None,
                Some(Ok(())) => {
                    app.toast_message = Some(crate::i18n::t(app, "app.toasts.copied_to_clipboard"));
                    app.toast_expires_at =
                        Some(std::time::Instant::now() + std::time::Duration::from_secs(3));
                    Some(false)
                }
                Some(Err(msg)) => {
                    app.toast_message = Some(msg);
                    app.toast_expires_at =
                        Some(std::time::Instant::now() + std::time::Duration::from_secs(5));
                    Some(false)
                }
            }
        }
        (
            crate::state::SshSetupStep::Intro
            | crate::state::SshSetupStep::ApplyKeyOnAur
            | crate::state::SshSetupStep::Result,
            KeyCode::Esc | KeyCode::Char('q'),
        ) => {
            app.modal = crate::state::Modal::None;
            if !app.pending_startup_setup_steps.is_empty() {
                super::common::show_next_startup_setup_step(app);
            }
            Some(true)
        }
        (crate::state::SshSetupStep::Intro, KeyCode::Enter | KeyCode::Char('\n' | '\r')) => {
            if !crate::logic::ssh_setup::is_openssh_installed() {
                let warning =
                    "Warning: openssh is not installed. Install openssh first, then run setup."
                        .to_string();
                if !status_lines.iter().any(|line| line == &warning) {
                    status_lines.push(warning);
                }
                tracing::warn!("SSH setup blocked: openssh is not installed");
                return Some(false);
            }
            match crate::logic::ssh_setup::run_aur_ssh_setup(false) {
                crate::logic::ssh_setup::AurSshSetupResult::Completed(report) => {
                    let failed = !report.success;
                    *status_lines = report.lines;
                    *existing_host_block = None;
                    if failed {
                        *step = crate::state::SshSetupStep::Result;
                        tracing::error!("SSH setup failed: {}", status_lines.join(" | "));
                        app.toast_message = Some(
                            "SSH setup failed. Review details in the SSH setup window.".to_string(),
                        );
                        app.toast_expires_at =
                            Some(std::time::Instant::now() + std::time::Duration::from_secs(4));
                    } else {
                        *step = crate::state::SshSetupStep::ApplyKeyOnAur;
                    }
                }
                crate::logic::ssh_setup::AurSshSetupResult::NeedsOverwrite {
                    existing_block,
                    lines,
                } => {
                    *step = crate::state::SshSetupStep::ConfirmOverwrite;
                    *status_lines = lines;
                    *existing_host_block = Some(existing_block);
                }
            }
            Some(false)
        }
        (
            crate::state::SshSetupStep::ConfirmOverwrite,
            KeyCode::Char('n' | 'N' | 'q') | KeyCode::Esc,
        ) => {
            app.modal = crate::state::Modal::None;
            app.toast_message = Some("SSH setup cancelled (existing config kept).".to_string());
            app.toast_expires_at =
                Some(std::time::Instant::now() + std::time::Duration::from_secs(4));
            if !app.pending_startup_setup_steps.is_empty() {
                super::common::show_next_startup_setup_step(app);
            }
            Some(true)
        }
        (
            crate::state::SshSetupStep::ConfirmOverwrite,
            KeyCode::Char('y' | 'Y' | '\n' | '\r') | KeyCode::Enter,
        ) => {
            let report = match crate::logic::ssh_setup::run_aur_ssh_setup(true) {
                crate::logic::ssh_setup::AurSshSetupResult::Completed(report) => report,
                crate::logic::ssh_setup::AurSshSetupResult::NeedsOverwrite { lines, .. } => {
                    crate::logic::ssh_setup::AurSshSetupReport {
                        success: false,
                        lines,
                    }
                }
            };
            let failed = !report.success;
            *status_lines = report.lines;
            *existing_host_block = None;
            if failed {
                *step = crate::state::SshSetupStep::Result;
                tracing::error!(
                    "SSH setup failed after overwrite confirm: {}",
                    status_lines.join(" | ")
                );
                app.toast_message =
                    Some("SSH setup failed. Review details in the SSH setup window.".to_string());
                app.toast_expires_at =
                    Some(std::time::Instant::now() + std::time::Duration::from_secs(4));
            } else {
                *step = crate::state::SshSetupStep::ApplyKeyOnAur;
            }
            Some(false)
        }
        (
            crate::state::SshSetupStep::ApplyKeyOnAur,
            KeyCode::Char('y' | 'Y' | '\n' | '\r') | KeyCode::Enter,
        ) => {
            let ssh_command = crate::theme::settings().aur_vote_ssh_command;
            let report = crate::logic::ssh_setup::validate_aur_ssh_setup_connection(&ssh_command);
            let failed = !report.success;
            *step = crate::state::SshSetupStep::Result;
            *status_lines = report.lines;
            *existing_host_block = None;
            if failed {
                tracing::error!(
                    "SSH setup validation failed after user confirmation: {}",
                    status_lines.join(" | ")
                );
                app.toast_message = Some(
                    "SSH validation failed. Review details in the SSH setup window.".to_string(),
                );
            } else {
                app.toast_message = Some("AUR SSH connection verified successfully.".to_string());
            }
            app.toast_expires_at =
                Some(std::time::Instant::now() + std::time::Duration::from_secs(4));
            Some(true)
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests;