purple-ssh 3.18.4

Open-source terminal SSH manager that keeps ~/.ssh/config in sync with your cloud infra. Spin up a VM on AWS, GCP, Azure, Hetzner or 12 other cloud providers and it appears in your host list. Destroy it and the entry dims. Search hundreds of hosts, transfer files, manage Docker and Podman over SSH, sign Vault SSH certs. Rust TUI, MIT licensed.
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
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;

use crossterm::event::{KeyCode, KeyEvent};
use log::{debug, warn};

use super::ctx::{Nav, Notify};
use crate::app::{
    App, FormState, HostState, Screen, SnippetState, StatusCenter, TunnelState, UiSelection,
};
use crate::clipboard;
use crate::event::AppEvent;
use crate::preferences;
use crate::runtime::env::Env;

/// A narrow, explicit borrow of the App state the snippet handlers touch. The
/// handlers operate on this slice instead of `&mut App`, so the compiler
/// rejects any reach into unrelated state (vault, containers, providers, ...).
/// Every snippet operation (form submit, picker selection, param substitution,
/// output capture) mutates only these fields, so there is nothing to defer:
/// the snippet store write, the form open/close, the picker selection and the
/// background execution spawn all stay slice-local. Output runs on a worker
/// thread that owns the inputs built here, so no effect outlives the borrow.
struct SnippetCtx<'a> {
    snippets: &'a mut SnippetState,
    ui: &'a mut UiSelection,
    forms: &'a mut FormState,
    hosts: &'a mut HostState,
    tunnels: &'a TunnelState,
    status: &'a mut StatusCenter,
    screen: &'a mut Screen,
    demo_mode: bool,
    env: &'a Env,
    config_path: &'a std::path::Path,
    bw_session: Option<&'a str>,
}

impl Nav for SnippetCtx<'_> {
    fn screen_mut(&mut self) -> &mut Screen {
        self.screen
    }
}

impl Notify for SnippetCtx<'_> {
    fn status_mut(&mut self) -> &mut StatusCenter {
        self.status
    }
}

impl SnippetCtx<'_> {
    /// Move snippet picker selection down. Mirrors `App::select_next_snippet`.
    fn select_next_snippet(&mut self) {
        let len = self.snippets.store().snippets.len();
        crate::app::cycle_selection(self.ui.snippet_picker_state_mut(), len, true);
    }

    /// Move snippet picker selection up. Mirrors `App::select_prev_snippet`.
    fn select_prev_snippet(&mut self) {
        let len = self.snippets.store().snippets.len();
        crate::app::cycle_selection(self.ui.snippet_picker_state_mut(), len, false);
    }

    /// Open a blank snippet add form scoped to the given targets. Mirrors
    /// `App::open_snippet_add_form` on the slice (snippets form + baseline +
    /// screen only).
    fn open_snippet_add_form(&mut self, target_aliases: Vec<String>) {
        log::debug!(
            "[purple] open_snippet_add_form aliases={}",
            target_aliases.len()
        );
        *self.snippets.form_mut() = crate::app::SnippetForm::new();
        self.set_screen(Screen::SnippetForm {
            target_aliases,
            editing: None,
        });
        self.capture_snippet_form_baseline();
    }

    /// Open an edit form for an existing snippet. Mirrors
    /// `App::open_snippet_edit_form` on the slice.
    fn open_snippet_edit_form(
        &mut self,
        snippet: &crate::snippet::Snippet,
        target_aliases: Vec<String>,
        editing: usize,
    ) {
        log::debug!(
            "[purple] open_snippet_edit_form name={} editing={}",
            snippet.name,
            editing
        );
        *self.snippets.form_mut() = crate::app::SnippetForm::from_snippet(snippet);
        self.set_screen(Screen::SnippetForm {
            target_aliases,
            editing: Some(editing),
        });
        self.capture_snippet_form_baseline();
    }

    /// Tear down snippet form state and return to the snippet picker. Mirrors
    /// `App::close_snippet_form` on the slice.
    fn close_snippet_form(&mut self, target_aliases: Vec<String>) {
        log::debug!(
            "[purple] close_snippet_form aliases={}",
            target_aliases.len()
        );
        self.snippets.set_form_baseline(None);
        self.set_screen(Screen::SnippetPicker { target_aliases });
    }

    /// Capture a baseline of the snippet form for the dirty-check on Esc.
    /// Mirrors `App::capture_snippet_form_baseline`.
    fn capture_snippet_form_baseline(&mut self) {
        self.snippets
            .set_form_baseline(Some(crate::app::SnippetFormBaseline {
                name: self.snippets.form().name.clone(),
                command: self.snippets.form().command.clone(),
                description: self.snippets.form().description.clone(),
            }));
    }

    /// Indices of snippets matching the active picker search query. Mirrors
    /// `App::filtered_snippet_indices` on the slice.
    fn filtered_snippet_indices(&self) -> Vec<usize> {
        match self.ui.snippet_search() {
            None => (0..self.snippets.store().snippets.len()).collect(),
            Some(query) if query.is_empty() => (0..self.snippets.store().snippets.len()).collect(),
            Some(query) => self
                .snippets
                .store()
                .snippets
                .iter()
                .enumerate()
                .filter(|(_, s)| {
                    crate::app::contains_ci(&s.name, query)
                        || crate::app::contains_ci(&s.command, query)
                        || crate::app::contains_ci(&s.description, query)
                })
                .map(|(i, _)| i)
                .collect(),
        }
    }
}

/// Borrow the disjoint App fields the snippet handlers need into one slice.
fn ctx_from_app(app: &mut App) -> SnippetCtx<'_> {
    SnippetCtx {
        snippets: &mut app.snippets,
        ui: &mut app.ui,
        forms: &mut app.forms,
        hosts: &mut app.hosts_state,
        tunnels: &app.tunnels,
        status: &mut app.status_center,
        screen: &mut app.screen,
        demo_mode: app.demo_mode,
        env: app.env.as_ref(),
        config_path: app.reload.config_path(),
        bw_session: app.bw_session.as_deref(),
    }
}

pub(super) fn open_snippet_picker(app: &mut App, aliases: Vec<String>) {
    let mut ctx = ctx_from_app(app);
    *ctx.snippets.store_mut() = crate::snippet::SnippetStore::load(ctx.env.paths());
    *ctx.ui.snippet_picker_state_mut() = ratatui::widgets::ListState::default();
    if !ctx.snippets.store().snippets.is_empty() {
        ctx.ui.snippet_picker_state_mut().select(Some(0));
    }
    ctx.set_screen(Screen::SnippetPicker {
        target_aliases: aliases,
    });
}

pub(super) fn handle_picker_key(app: &mut App, key: KeyEvent, events_tx: &mpsc::Sender<AppEvent>) {
    let mut ctx = ctx_from_app(app);
    picker_key(&mut ctx, key, events_tx);
}

fn picker_key(ctx: &mut SnippetCtx, key: KeyEvent, events_tx: &mpsc::Sender<AppEvent>) {
    let target_aliases = match &*ctx.screen {
        Screen::SnippetPicker { target_aliases } => target_aliases.clone(),
        _ => return,
    };

    // Allow ? to open help even during search
    if key.code == KeyCode::Char('?') {
        let old = std::mem::replace(&mut *ctx.screen, Screen::HostList);
        ctx.set_screen(Screen::Help {
            return_screen: Box::new(old),
        });
        return;
    }

    // Search mode dispatch
    if ctx.ui.snippet_search().is_some() {
        handle_snippet_picker_search(ctx, key, &target_aliases, events_tx);
        return;
    }

    // Handle pending snippet delete confirmation via the shared confirm router.
    if ctx.snippets.pending_delete().is_some() && key.code != KeyCode::Char('?') {
        match super::route_confirm_key(key) {
            super::ConfirmAction::Yes => {
                let Some(sel) = ctx.snippets.take_pending_delete() else {
                    return;
                };
                if sel < ctx.snippets.store().snippets.len() {
                    let removed = ctx.snippets.store_mut().snippets.remove(sel);
                    if let Err(e) = ctx.snippets.store_mut().save() {
                        ctx.snippets.store_mut().snippets.insert(sel, removed);
                        ctx.notify_error(crate::messages::failed_to_save(&e));
                    } else {
                        if ctx.snippets.store().snippets.is_empty() {
                            ctx.ui.snippet_picker_state_mut().select(None);
                        } else if sel >= ctx.snippets.store().snippets.len() {
                            ctx.ui
                                .snippet_picker_state_mut()
                                .select(Some(ctx.snippets.store().snippets.len() - 1));
                        }
                        ctx.notify(crate::messages::snippet_removed(&removed.name));
                    }
                }
            }
            super::ConfirmAction::No => {
                ctx.snippets.cancel_delete();
            }
            super::ConfirmAction::Ignored => {}
        }
        return;
    }

    match key.code {
        KeyCode::Esc | KeyCode::Char('q') => {
            ctx.ui.close_snippet_search();
            ctx.snippets.cancel_delete();
            ctx.set_screen(Screen::HostList);
        }
        KeyCode::Char('/') => {
            ctx.ui.open_snippet_search();
        }
        KeyCode::Char('j') | KeyCode::Down => {
            ctx.select_next_snippet();
        }
        KeyCode::Char('k') | KeyCode::Up => {
            ctx.select_prev_snippet();
        }
        KeyCode::PageDown => {
            let len = ctx.snippets.store().snippets.len();
            crate::app::page_down(ctx.ui.snippet_picker_state_mut(), len, 10);
        }
        KeyCode::PageUp => {
            let len = ctx.snippets.store().snippets.len();
            crate::app::page_up(ctx.ui.snippet_picker_state_mut(), len, 10);
        }
        KeyCode::Char('a') => {
            ctx.open_snippet_add_form(target_aliases.clone());
        }
        KeyCode::Char('e') => {
            if let Some(sel) = ctx.ui.snippet_picker_state().selected() {
                if let Some(snippet) = ctx.snippets.store().snippets.get(sel).cloned() {
                    ctx.open_snippet_edit_form(&snippet, target_aliases.clone(), sel);
                }
            }
        }
        KeyCode::Char('d') => {
            if let Some(sel) = ctx.ui.snippet_picker_state().selected() {
                if sel < ctx.snippets.store().snippets.len() {
                    ctx.snippets.request_delete(sel);
                }
            }
        }
        KeyCode::Enter => {
            if let Some(sel) = ctx.ui.snippet_picker_state().selected() {
                if let Some(snippet) = ctx.snippets.store().snippets.get(sel).cloned() {
                    run_or_prompt_params(ctx, snippet, target_aliases, false, events_tx);
                }
            }
        }
        KeyCode::Char('!') => {
            if let Some(sel) = ctx.ui.snippet_picker_state().selected() {
                if let Some(snippet) = ctx.snippets.store().snippets.get(sel).cloned() {
                    run_or_prompt_params(ctx, snippet, target_aliases, true, events_tx);
                }
            }
        }
        _ => {}
    }
}

/// Run a snippet (captured output) or open param form if it has parameters.
fn run_or_prompt_params(
    ctx: &mut SnippetCtx,
    snippet: crate::snippet::Snippet,
    target_aliases: Vec<String>,
    terminal_mode: bool,
    events_tx: &mpsc::Sender<AppEvent>,
) {
    if ctx.demo_mode {
        ctx.notify_warning(crate::messages::DEMO_EXECUTION_DISABLED);
        return;
    }
    let params = crate::snippet::parse_params(&snippet.command);
    if !params.is_empty() {
        ctx.snippets
            .set_param_form(Some(crate::app::SnippetParamFormState::new(&params)));
        ctx.snippets.set_pending_terminal(terminal_mode);
        ctx.set_screen(Screen::SnippetParamForm {
            snippet,
            target_aliases,
        });
    } else if terminal_mode {
        ctx.snippets.set_pending(Some((snippet, target_aliases)));
        ctx.hosts.clear_multi_select();
        ctx.set_screen(Screen::HostList);
    } else {
        ctx.hosts.clear_multi_select();
        start_snippet_output(ctx, &snippet, &target_aliases, events_tx);
    }
}

/// Monotonically increasing run ID to distinguish snippet execution runs.
static SNIPPET_RUN_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

/// Start in-TUI snippet execution.
fn start_snippet_output(
    ctx: &mut SnippetCtx,
    snippet: &crate::snippet::Snippet,
    target_aliases: &[String],
    events_tx: &mpsc::Sender<AppEvent>,
) {
    let cancel = Arc::new(AtomicBool::new(false));

    let askpass_map: Vec<(String, Option<String>)> = target_aliases
        .iter()
        .map(|alias| {
            let askpass = ctx
                .hosts
                .list()
                .iter()
                .find(|h| h.alias == *alias)
                .and_then(|h| h.askpass.clone())
                .or_else(|| preferences::load_askpass_default(ctx.env.paths()));
            (alias.clone(), askpass)
        })
        .collect();

    let tunnel_aliases: std::collections::HashSet<String> =
        ctx.tunnels.active().keys().cloned().collect();

    let run_id = SNIPPET_RUN_COUNTER.fetch_add(1, Ordering::Relaxed);
    debug!(
        "[purple] snippet run started: run_id={} name={:?} hosts={}",
        run_id,
        snippet.name,
        target_aliases.len()
    );

    ctx.snippets
        .set_output(Some(crate::app::SnippetOutputState {
            run_id,
            results: Vec::new(),
            scroll_offset: 0,
            completed: 0,
            total: target_aliases.len(),
            all_done: false,
            cancel: cancel.clone(),
        }));

    ctx.set_screen(Screen::SnippetOutput {
        snippet_name: snippet.name.clone(),
        target_aliases: target_aliases.to_vec(),
    });

    crate::snippet::spawn_snippet_execution(
        run_id,
        askpass_map,
        ctx.config_path.to_path_buf(),
        std::sync::Arc::new(ctx.env.clone()),
        snippet.command.clone(),
        ctx.bw_session.map(str::to_string),
        tunnel_aliases,
        cancel,
        events_tx.clone(),
        target_aliases.len() > 1,
    );
}

/// Compute the line count for a snippet host result, matching the UI renderer.
fn snippet_result_lines(r: &crate::app::SnippetHostOutput) -> usize {
    let content = if r.stdout.is_empty() && r.stderr.is_empty() {
        1 // "[No output]" placeholder
    } else {
        let stdout_lines = if r.stdout.is_empty() {
            0
        } else {
            r.stdout.lines().count()
        };
        let stderr_lines = if r.stderr.is_empty() {
            0
        } else {
            r.stderr.lines().count()
        };
        stdout_lines + stderr_lines
    };
    // header + content + blank line
    1 + content + 1
}

pub(super) fn handle_output_key(app: &mut App, key: KeyEvent) {
    let mut ctx = ctx_from_app(app);
    output_key(&mut ctx, key);
}

fn output_key(ctx: &mut SnippetCtx, key: KeyEvent) {
    let total_lines = ctx
        .snippets
        .output()
        .map(|s| s.results.iter().map(snippet_result_lines).sum::<usize>())
        .unwrap_or(0);

    match key.code {
        KeyCode::Esc | KeyCode::Char('q') => {
            if let Some(state) = ctx.snippets.output() {
                if !state.all_done {
                    state.cancel.store(true, Ordering::Relaxed);
                }
            }
            ctx.snippets.set_output(None);
            ctx.set_screen(Screen::HostList);
        }
        KeyCode::Char('j') | KeyCode::Down => {
            if let Some(state) = ctx.snippets.output_mut() {
                state.scroll_offset = state.scroll_offset.saturating_add(1);
            }
        }
        KeyCode::Char('k') | KeyCode::Up => {
            if let Some(state) = ctx.snippets.output_mut() {
                state.scroll_offset = state.scroll_offset.saturating_sub(1);
            }
        }
        KeyCode::PageDown => {
            if let Some(state) = ctx.snippets.output_mut() {
                state.scroll_offset = state.scroll_offset.saturating_add(20);
            }
        }
        KeyCode::PageUp => {
            if let Some(state) = ctx.snippets.output_mut() {
                state.scroll_offset = state.scroll_offset.saturating_sub(20);
            }
        }
        KeyCode::Char('G') => {
            if let Some(state) = ctx.snippets.output_mut() {
                state.scroll_offset = total_lines.saturating_sub(1);
            }
        }
        KeyCode::Char('g') => {
            if let Some(state) = ctx.snippets.output_mut() {
                state.scroll_offset = 0;
            }
        }
        KeyCode::Char('n') => {
            // Jump to next host header
            if let Some(state) = ctx.snippets.output_mut() {
                let current = state.scroll_offset;
                let mut line = 0;
                for result in &state.results {
                    let section = snippet_result_lines(result);
                    if line > current {
                        state.scroll_offset = line;
                        return;
                    }
                    line += section;
                }
            }
        }
        KeyCode::Char('N') => {
            // Jump to previous host header
            if let Some(state) = ctx.snippets.output_mut() {
                let current = state.scroll_offset;
                let mut offsets = Vec::new();
                let mut line = 0;
                for result in &state.results {
                    offsets.push(line);
                    line += snippet_result_lines(result);
                }
                for &off in offsets.iter().rev() {
                    if off < current {
                        state.scroll_offset = off;
                        return;
                    }
                }
                state.scroll_offset = 0;
            }
        }
        KeyCode::Char('c') => {
            // Copy all output
            if let Some(state) = ctx.snippets.output() {
                let mut text = String::new();
                for result in &state.results {
                    text.push_str(&format!("-- {} --\n", result.alias));
                    if !result.stdout.is_empty() {
                        text.push_str(&result.stdout);
                        text.push('\n');
                    }
                    if !result.stderr.is_empty() {
                        text.push_str(&result.stderr);
                        text.push('\n');
                    }
                    text.push('\n');
                }
                match clipboard::copy_to_clipboard(&text) {
                    Ok(()) => ctx.notify(crate::messages::OUTPUT_COPIED),
                    Err(e) => ctx.notify_error(crate::messages::copy_failed(&e)),
                }
            }
        }
        KeyCode::Char('?') => {
            let old = std::mem::replace(&mut *ctx.screen, Screen::HostList);
            ctx.set_screen(Screen::Help {
                return_screen: Box::new(old),
            });
        }
        _ => {}
    }
}

/// Reset snippet picker selection to first match after search query changes.
fn reset_snippet_search_selection(ctx: &mut SnippetCtx) {
    let filtered = ctx.filtered_snippet_indices();
    if filtered.is_empty() {
        ctx.ui.snippet_picker_state_mut().select(None);
    } else {
        ctx.ui.snippet_picker_state_mut().select(Some(0));
    }
}

fn handle_snippet_picker_search(
    ctx: &mut SnippetCtx,
    key: KeyEvent,
    target_aliases: &[String],
    events_tx: &mpsc::Sender<AppEvent>,
) {
    match key.code {
        KeyCode::Esc => {
            ctx.ui.close_snippet_search();
            // Restore selection to full list
            if !ctx.snippets.store().snippets.is_empty()
                && ctx.ui.snippet_picker_state().selected().is_none()
            {
                ctx.ui.snippet_picker_state_mut().select(Some(0));
            }
        }
        KeyCode::Enter => {
            let filtered = ctx.filtered_snippet_indices();
            if let Some(sel) = ctx.ui.snippet_picker_state().selected() {
                if sel < filtered.len() {
                    let real_idx = filtered[sel];
                    if let Some(snippet) = ctx.snippets.store().snippets.get(real_idx).cloned() {
                        ctx.ui.close_snippet_search();
                        run_or_prompt_params(
                            ctx,
                            snippet,
                            target_aliases.to_vec(),
                            false,
                            events_tx,
                        );
                    }
                }
            }
        }
        KeyCode::Char(c) => {
            if let Some(query) = ctx.ui.snippet_search_mut() {
                query.push(c);
            }
            reset_snippet_search_selection(ctx);
        }
        KeyCode::Backspace => {
            if let Some(query) = ctx.ui.snippet_search_mut() {
                query.pop();
                if query.is_empty() {
                    ctx.ui.close_snippet_search();
                    if !ctx.snippets.store().snippets.is_empty() {
                        ctx.ui.snippet_picker_state_mut().select(Some(0));
                    }
                    return;
                }
            }
            reset_snippet_search_selection(ctx);
        }
        KeyCode::Down => {
            let count = ctx.filtered_snippet_indices().len();
            if let Some(sel) = ctx.ui.snippet_picker_state().selected() {
                if sel + 1 < count {
                    ctx.ui.snippet_picker_state_mut().select(Some(sel + 1));
                }
            }
        }
        KeyCode::Up => {
            if let Some(sel) = ctx.ui.snippet_picker_state().selected() {
                if sel > 0 {
                    ctx.ui.snippet_picker_state_mut().select(Some(sel - 1));
                }
            }
        }
        _ => {}
    }
}

pub(super) fn handle_param_form_key(
    app: &mut App,
    key: KeyEvent,
    events_tx: &mpsc::Sender<AppEvent>,
) {
    let mut ctx = ctx_from_app(app);
    param_form_key(&mut ctx, key, events_tx);
}

fn param_form_key(ctx: &mut SnippetCtx, key: KeyEvent, events_tx: &mpsc::Sender<AppEvent>) {
    let (snippet, target_aliases) = match &*ctx.screen {
        Screen::SnippetParamForm {
            snippet,
            target_aliases,
        } => (snippet.clone(), target_aliases.clone()),
        _ => return,
    };

    let form = match ctx.snippets.param_form_mut() {
        Some(f) => f,
        None => return,
    };

    // Handle discard confirmation dialog via the shared confirm router.
    if ctx.forms.is_discard_pending() {
        match super::route_confirm_key(key) {
            super::ConfirmAction::Yes => {
                ctx.forms.dismiss_discard_confirm();
                ctx.snippets.close_param_form();
                ctx.set_screen(Screen::SnippetPicker { target_aliases });
            }
            super::ConfirmAction::No => {
                ctx.forms.dismiss_discard_confirm();
            }
            super::ConfirmAction::Ignored => {}
        }
        return;
    }

    match key.code {
        KeyCode::Esc => {
            if form.is_dirty() {
                ctx.forms.request_discard_confirm();
            } else {
                ctx.snippets.close_param_form();
                ctx.set_screen(Screen::SnippetPicker { target_aliases });
            }
        }
        KeyCode::Tab | KeyCode::Down if form.focused_index + 1 < form.params.len() => {
            form.focused_index += 1;
            form.cursor_pos = form.values[form.focused_index].chars().count();
            let vis = form.visible_count.max(1);
            if form.focused_index >= form.scroll_offset + vis {
                form.scroll_offset = form.focused_index.saturating_sub(vis - 1);
            }
        }
        KeyCode::BackTab | KeyCode::Up if form.focused_index > 0 => {
            form.focused_index -= 1;
            form.cursor_pos = form.values[form.focused_index].chars().count();
            if form.focused_index < form.scroll_offset {
                form.scroll_offset = form.focused_index;
            }
        }
        KeyCode::Left if form.cursor_pos > 0 => {
            form.cursor_pos -= 1;
        }
        KeyCode::Right => {
            let len = form.values[form.focused_index].chars().count();
            if form.cursor_pos < len {
                form.cursor_pos += 1;
            }
        }
        KeyCode::Enter => {
            let values_map = form.values_map();
            let mut resolved = snippet.clone();
            resolved.command = crate::snippet::substitute_params(&snippet.command, &values_map);

            let terminal_mode = ctx.snippets.pending_terminal();
            ctx.snippets.close_param_form();

            if terminal_mode {
                ctx.snippets.set_pending(Some((resolved, target_aliases)));
                ctx.hosts.clear_multi_select();
                ctx.set_screen(Screen::HostList);
            } else {
                ctx.hosts.clear_multi_select();
                start_snippet_output(ctx, &resolved, &target_aliases, events_tx);
            }
        }
        KeyCode::Char(c) => {
            if c.is_control() {
                return;
            }
            form.insert_char(c);
        }
        KeyCode::Backspace => {
            form.delete_char_before_cursor();
        }
        _ => {}
    }
}

pub(super) fn handle_form_key(app: &mut App, key: KeyEvent) {
    let mut ctx = ctx_from_app(app);
    form_key(&mut ctx, key);
}

fn form_key(ctx: &mut SnippetCtx, key: KeyEvent) {
    let (target_aliases, editing) = match &*ctx.screen {
        Screen::SnippetForm {
            target_aliases,
            editing,
        } => (target_aliases.clone(), *editing),
        _ => return,
    };

    // Handle discard confirmation dialog via the shared confirm router.
    if ctx.forms.is_discard_pending() {
        match super::route_confirm_key(key) {
            super::ConfirmAction::Yes => {
                ctx.forms.dismiss_discard_confirm();
                ctx.close_snippet_form(target_aliases.clone());
            }
            super::ConfirmAction::No => {
                ctx.forms.dismiss_discard_confirm();
            }
            super::ConfirmAction::Ignored => {}
        }
        return;
    }

    match key.code {
        KeyCode::Esc => {
            if ctx.snippets.form_is_dirty() {
                ctx.forms.request_discard_confirm();
            } else {
                ctx.close_snippet_form(target_aliases.clone());
            }
        }
        KeyCode::Tab | KeyCode::Down => {
            ctx.snippets.form_mut().focus_next();
        }
        KeyCode::BackTab | KeyCode::Up => {
            ctx.snippets.form_mut().focus_prev();
        }
        KeyCode::Left if ctx.snippets.form_mut().cursor_pos > 0 => {
            ctx.snippets.form_mut().cursor_pos -= 1;
        }
        KeyCode::Right => {
            let len = ctx.snippets.form_mut().focused_value().chars().count();
            if ctx.snippets.form_mut().cursor_pos < len {
                ctx.snippets.form_mut().cursor_pos += 1;
            }
        }
        KeyCode::Home => {
            ctx.snippets.form_mut().cursor_pos = 0;
        }
        KeyCode::End => {
            ctx.snippets.form_mut().sync_cursor_to_end();
        }
        KeyCode::Enter => {
            submit_snippet_form(ctx, &target_aliases, editing);
        }
        KeyCode::Char(c) => {
            ctx.snippets.form_mut().insert_char(c);
        }
        KeyCode::Backspace => {
            ctx.snippets.form_mut().delete_char_before_cursor();
        }
        _ => {}
    }
}

fn submit_snippet_form(ctx: &mut SnippetCtx, target_aliases: &[String], editing: Option<usize>) {
    if let Err(msg) = ctx.snippets.form_mut().validate() {
        ctx.notify_error(msg);
        return;
    }

    let new_name = ctx.snippets.form_mut().name.trim().to_string();
    let new_command = ctx.snippets.form_mut().command.trim().to_string();
    let new_description = ctx.snippets.form_mut().description.trim().to_string();

    // Check for duplicate name (skip the snippet being edited)
    let old_name = editing.and_then(|idx| {
        ctx.snippets
            .store()
            .snippets
            .get(idx)
            .map(|s| s.name.clone())
    });
    let name_taken = ctx
        .snippets
        .store()
        .snippets
        .iter()
        .any(|s| s.name == new_name && Some(&s.name) != old_name.as_ref());
    if name_taken {
        ctx.notify_warning(crate::messages::snippet_exists(&new_name));
        return;
    }

    let snippet = crate::snippet::Snippet {
        name: new_name,
        command: new_command,
        description: new_description,
    };

    // Save a snapshot for rollback
    let snapshot = ctx.snippets.store().snippets.clone();

    // If editing and name changed, remove the old one
    if let Some(old_name) = &old_name {
        if *old_name != snippet.name {
            ctx.snippets.store_mut().remove(old_name);
        }
    }

    let is_new = editing.is_none();
    ctx.snippets.store_mut().set(snippet);

    if let Err(e) = ctx.snippets.store_mut().save() {
        warn!("[config] snippet store save failed, rolling back: {e}");
        ctx.snippets.store_mut().snippets = snapshot;
        ctx.notify_error(crate::messages::failed_to_save(&e));
        return;
    }

    // Re-select in picker
    let name = ctx.snippets.form_mut().name.trim().to_string();
    let new_idx = ctx
        .snippets
        .store()
        .snippets
        .iter()
        .position(|s| s.name == name);
    ctx.ui.snippet_picker_state_mut().select(new_idx);

    if is_new {
        ctx.notify(crate::messages::snippet_added(&name));
    } else {
        ctx.notify(crate::messages::snippet_updated(&name));
    }
    ctx.close_snippet_form(target_aliases.to_vec());
}

#[cfg(test)]
mod param_form_tests {
    use super::*;
    use crate::app::SnippetParamFormState;
    use crate::ssh_config::model::SshConfigFile;
    use crossterm::event::KeyModifiers;

    fn make_app() -> App {
        let scratch = tempfile::tempdir().expect("tempdir").keep();
        let config = SshConfigFile {
            elements: SshConfigFile::parse_content(""),
            path: scratch.join("test_config"),
            crlf: false,
            bom: false,
        };
        let mut app = App::new(config);
        let snippet = crate::snippet::Snippet {
            name: "test".to_string(),
            command: "echo hi".to_string(),
            description: String::new(),
        };
        app.screen = Screen::SnippetParamForm {
            snippet,
            target_aliases: vec!["h1".to_string()],
        };
        app.snippets
            .set_param_form(Some(SnippetParamFormState::new(&[])));
        app
    }

    fn k(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    #[test]
    fn esc_on_clean_form_returns_to_snippet_picker() {
        let _lock = crate::demo_flag::GLOBAL_TEST_LOCK.lock().unwrap();
        let mut app = make_app();
        let (tx, _rx) = mpsc::channel();
        handle_param_form_key(&mut app, k(KeyCode::Esc), &tx);
        assert!(matches!(app.screen, Screen::SnippetPicker { .. }));
        assert!(app.snippets.param_form().is_none());
    }

    #[test]
    fn typing_a_char_inserts_into_focused_param() {
        let _lock = crate::demo_flag::GLOBAL_TEST_LOCK.lock().unwrap();
        let mut app = make_app();
        let params = vec![crate::snippet::SnippetParam {
            name: "name".to_string(),
            default: None,
        }];
        app.snippets
            .set_param_form(Some(SnippetParamFormState::new(&params)));
        if let Screen::SnippetParamForm { snippet, .. } = &mut app.screen {
            snippet.command = "echo {{name}}".to_string();
        }
        let (tx, _rx) = mpsc::channel();
        handle_param_form_key(&mut app, k(KeyCode::Char('h')), &tx);
        handle_param_form_key(&mut app, k(KeyCode::Char('i')), &tx);
        let state = app.snippets.param_form().expect("form state");
        assert_eq!(state.values[0], "hi");
    }

    fn make_dirty_app() -> App {
        let mut app = make_app();
        let params = vec![crate::snippet::SnippetParam {
            name: "name".to_string(),
            default: None,
        }];
        app.snippets
            .set_param_form(Some(SnippetParamFormState::new(&params)));
        if let Screen::SnippetParamForm { snippet, .. } = &mut app.screen {
            snippet.command = "echo {{name}}".to_string();
        }
        app.snippets
            .param_form_mut()
            .expect("form state")
            .insert_char('x');
        // Pre-set pending_terminal so the y-branch reset is observable;
        // without this the assertion in discard_confirm_y_... would pass
        // vacuously against the default false value.
        app.snippets.set_pending_terminal(true);
        app
    }

    #[test]
    fn dirty_esc_arms_discard_confirmation() {
        let _lock = crate::demo_flag::GLOBAL_TEST_LOCK.lock().unwrap();
        let mut app = make_dirty_app();
        let (tx, _rx) = mpsc::channel();
        handle_param_form_key(&mut app, k(KeyCode::Esc), &tx);
        assert!(app.forms.is_discard_pending());
        assert!(matches!(app.screen, Screen::SnippetParamForm { .. }));
    }

    #[test]
    fn discard_confirm_y_closes_form_and_returns_to_picker() {
        let _lock = crate::demo_flag::GLOBAL_TEST_LOCK.lock().unwrap();
        let mut app = make_dirty_app();
        let (tx, _rx) = mpsc::channel();
        handle_param_form_key(&mut app, k(KeyCode::Esc), &tx);
        handle_param_form_key(&mut app, k(KeyCode::Char('y')), &tx);
        assert!(!app.forms.is_discard_pending());
        assert!(app.snippets.param_form().is_none());
        assert!(!app.snippets.pending_terminal());
        assert!(matches!(app.screen, Screen::SnippetPicker { .. }));
    }

    #[test]
    fn discard_confirm_n_clears_pending_and_keeps_form() {
        let _lock = crate::demo_flag::GLOBAL_TEST_LOCK.lock().unwrap();
        let mut app = make_dirty_app();
        let (tx, _rx) = mpsc::channel();
        handle_param_form_key(&mut app, k(KeyCode::Esc), &tx);
        handle_param_form_key(&mut app, k(KeyCode::Char('n')), &tx);
        assert!(!app.forms.is_discard_pending());
        assert!(app.snippets.param_form().is_some());
        assert!(matches!(app.screen, Screen::SnippetParamForm { .. }));
    }

    // Pins the route_confirm_key Ignored contract: a stray key must NOT
    // silently cancel the discard prompt (no false positive on Yes, no
    // false negative on No that would dismiss the discard confirm).
    #[test]
    fn discard_confirm_unrelated_key_keeps_pending() {
        let _lock = crate::demo_flag::GLOBAL_TEST_LOCK.lock().unwrap();
        let mut app = make_dirty_app();
        let (tx, _rx) = mpsc::channel();
        handle_param_form_key(&mut app, k(KeyCode::Esc), &tx);
        handle_param_form_key(&mut app, k(KeyCode::Char('x')), &tx);
        assert!(app.forms.is_discard_pending());
        assert!(app.snippets.param_form().is_some());
    }
}

#[cfg(test)]
mod output_tests {
    use super::*;
    use crate::app::{SnippetHostOutput, SnippetOutputState};
    use crate::ssh_config::model::SshConfigFile;
    use crossterm::event::KeyModifiers;
    use std::sync::Arc;
    use std::sync::atomic::AtomicBool;

    fn make_app_on_output(line_count: usize) -> App {
        let scratch = tempfile::tempdir().expect("tempdir").keep();
        let config = SshConfigFile {
            elements: SshConfigFile::parse_content(""),
            path: scratch.join("test_config"),
            crlf: false,
            bom: false,
        };
        let mut app = App::new(config);
        let results = (0..line_count)
            .map(|i| SnippetHostOutput {
                alias: format!("h{i}"),
                stdout: "ok".to_string(),
                stderr: String::new(),
                exit_code: Some(0),
            })
            .collect();
        app.snippets.set_output(Some(SnippetOutputState {
            run_id: 1,
            results,
            scroll_offset: 0,
            completed: line_count,
            total: line_count,
            all_done: true,
            cancel: Arc::new(AtomicBool::new(false)),
        }));
        app.screen = Screen::SnippetOutput {
            snippet_name: "echo".to_string(),
            target_aliases: vec!["h0".to_string()],
        };
        app
    }

    fn k(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    #[test]
    fn j_scrolls_output_down_one_line() {
        let _lock = crate::demo_flag::GLOBAL_TEST_LOCK.lock().unwrap();
        let mut app = make_app_on_output(5);
        handle_output_key(&mut app, k(KeyCode::Char('j')));
        let state = app.snippets.output().expect("output state");
        assert_eq!(state.scroll_offset, 1);
    }

    #[test]
    fn esc_closes_overlay_and_clears_output_state() {
        let _lock = crate::demo_flag::GLOBAL_TEST_LOCK.lock().unwrap();
        let mut app = make_app_on_output(3);
        handle_output_key(&mut app, k(KeyCode::Esc));
        assert!(matches!(app.screen, Screen::HostList));
        assert!(app.snippets.output().is_none());
    }
}