purple-ssh 3.11.0

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
//! TUI event loop and the per-iteration helpers that drive it.
//!
//! Everything that runs while the TUI is on the alternate screen lives
//! here: the main `run_tui` orchestrator, its six tick-scoped helpers
//! (startup tasks, event dispatch, lazy cert check, pending SSH connect,
//! pending snippet run, teardown), plus Vault cert-cache helpers used by
//! the dispatch logic.

use anyhow::Result;

use crate::app::{self, App};
use crate::event::{self, AppEvent, EventHandler};
use crate::ssh_config::model::SshConfigFile;
use crate::{
    animation, askpass, connection, ensure_bw_session, ensure_keychain_password,
    ensure_vault_ssh_chain_if_needed, first_launch_init, handler, import, ping, preferences,
    snippet, tui, update, vault_ssh,
};

pub(crate) fn run_tui(mut app: App) -> Result<()> {
    // First-launch welcome hint (one-shot: creates .purple/ so it won't show again)
    if app.status_center.status.is_none() && !app.demo_mode {
        if let Some(home) = dirs::home_dir() {
            let purple_dir = home.join(".purple");
            if let Some(has_backup) = first_launch_init(&purple_dir, &app.reload.config_path) {
                let host_count = app.hosts_state.list.len();
                let known_hosts_count = if host_count == 0 {
                    import::count_known_hosts_candidates()
                } else {
                    0
                };
                app.known_hosts_count = known_hosts_count;
                app.screen = app::Screen::Welcome {
                    has_backup,
                    host_count,
                    known_hosts_count,
                };
            }
        }
    }

    let mut terminal = tui::Tui::new()?;
    terminal.enter()?;
    let events = EventHandler::new(50);
    let events_tx = events.sender();
    let mut last_config_check = std::time::Instant::now();

    // Skip background tasks in demo mode (ping status is pre-populated).
    if !app.demo_mode {
        spawn_startup_tasks(&mut app, &events_tx);
    }

    let mut anim = animation::AnimationState::new();

    while app.running {
        anim.detect_transitions(&mut app);
        terminal.draw(&mut app, &mut anim)?;

        // During animation, use a short timeout for smooth frames (~60fps).
        // During ping checking, use 80ms timeout for spinner.
        // Otherwise, block until the next event arrives.
        let vault_signing = app.vault.signing_cancel.is_some();
        let provider_syncing = !app.providers.syncing.is_empty();
        // Tunnels tab drives the live chart animation. While at least
        // one tunnel is running we tick at 16ms (~60 fps) so the
        // swimlane bars and sparklines drift smoothly. The tick also
        // refreshes the uptime readout every frame.
        let tunnels_anim_tick =
            matches!(app.top_page, app::TopPage::Tunnels) && !app.tunnels.active.is_empty();
        let event = if anim.is_animating(&app) || tunnels_anim_tick {
            events.next_timeout(std::time::Duration::from_millis(16))?
        } else if anim.has_checking_hosts(&app)
            || vault_signing
            || provider_syncing
            || anim.has_reachable_hosts(&app)
        {
            events.next_timeout(std::time::Duration::from_millis(60))?
        } else {
            Some(events.next()?)
        };

        if dispatch_event(
            &mut app,
            event,
            &mut anim,
            vault_signing,
            &events_tx,
            &mut terminal,
            &mut last_config_check,
        )?
        .is_break()
        {
            continue;
        }

        lazy_cert_check(&mut app, &events_tx);

        handle_pending_connect(&mut app, &mut terminal, &events, &mut last_config_check)?;
        handle_pending_container_exec(&mut app, &mut terminal, &events, &mut last_config_check)?;
        handle_pending_container_logs(&mut app, &events_tx);
        handle_pending_container_action(&mut app, &events_tx);
        // Drain any aliases queued for an initial container-cache
        // fetch (form save, sync, external edit, restore). The
        // helper drains the queue itself and routes the items into
        // the existing `RefreshBatch` driver.
        if !app.pending_container_fetch_aliases.is_empty() {
            handler::containers_overview::auto_fetch_new_hosts(&mut app, &events_tx);
        }
        handle_pending_snippet(&mut app, &mut terminal, &events, &mut last_config_check)?;
    }

    tui_teardown(&mut app, &mut terminal)
}

/// Spawn auto-sync, auto-ping and the background version check on TUI startup.
fn spawn_startup_tasks(app: &mut App, events_tx: &std::sync::mpsc::Sender<AppEvent>) {
    for section in app.providers.config.configured_providers().to_vec() {
        if !section.auto_sync {
            continue;
        }
        let key = section.id.to_string();
        if !app.providers.syncing.contains_key(&key) {
            app.providers.reset_batch_if_idle();
            let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
            app.providers.syncing.insert(key, cancel.clone());
            app.providers.batch_total = app
                .providers
                .batch_total
                .max(app.providers.sync_done.len() + app.providers.syncing.len());
            handler::spawn_provider_sync(&section, events_tx.clone(), cancel);
            crate::set_sync_summary(app);
        }
    }

    if app.ping.auto_ping {
        let hosts_to_ping: Vec<(String, String, u16)> = app
            .hosts_state
            .list
            .iter()
            .filter(|h| !h.hostname.is_empty() && h.proxy_jump.is_empty())
            .map(|h| (h.alias.clone(), h.hostname.clone(), h.port))
            .collect();
        for h in &app.hosts_state.list {
            if !h.proxy_jump.is_empty() {
                app.ping
                    .status
                    .insert(h.alias.clone(), app::PingStatus::Skipped);
            }
        }
        if !hosts_to_ping.is_empty() {
            for (alias, _, _) in &hosts_to_ping {
                app.ping
                    .status
                    .insert(alias.clone(), app::PingStatus::Checking);
            }
            ping::ping_all(&hosts_to_ping, events_tx.clone(), app.ping.generation);
        }
    }

    update::spawn_version_check(events_tx.clone());
}

/// Dispatch a single tick's event. Returns `Break` when the outer loop
/// should `continue` without running the post-dispatch helpers.
#[allow(clippy::too_many_arguments)]
fn dispatch_event(
    app: &mut App,
    event: Option<AppEvent>,
    anim: &mut animation::AnimationState,
    vault_signing: bool,
    events_tx: &std::sync::mpsc::Sender<AppEvent>,
    terminal: &mut tui::Tui,
    last_config_check: &mut std::time::Instant,
) -> Result<std::ops::ControlFlow<()>> {
    match event {
        Some(AppEvent::Key(key)) => {
            handler::handle_key_event(app, key, events_tx)?;
        }
        Some(AppEvent::Tick) | None => {
            handler::event_loop::handle_tick(app, anim, vault_signing, last_config_check);
        }
        Some(AppEvent::PingResult {
            alias,
            rtt_ms,
            generation,
        }) => {
            handler::event_loop::handle_ping_result(app, alias, rtt_ms, generation);
        }
        Some(AppEvent::SyncProgress { provider, message }) => {
            handler::event_loop::handle_sync_progress(app, provider, message);
        }
        Some(AppEvent::SyncComplete { provider, hosts }) => {
            handler::event_loop::handle_sync_complete(app, provider, hosts, last_config_check);
        }
        Some(AppEvent::SyncPartial {
            provider,
            hosts,
            failures,
            total,
        }) => {
            handler::event_loop::handle_sync_partial(
                app,
                provider,
                hosts,
                failures,
                total,
                last_config_check,
            );
        }
        Some(AppEvent::SyncError { provider, message }) => {
            handler::event_loop::handle_sync_error(app, provider, message, last_config_check);
        }
        Some(AppEvent::UpdateAvailable { version, headline }) => {
            handler::event_loop::handle_update_available(app, version, headline);
        }
        Some(AppEvent::FileBrowserListing {
            alias,
            path,
            entries,
        }) => {
            handler::event_loop::handle_file_browser_listing(app, alias, path, entries, terminal);
        }
        Some(AppEvent::ScpComplete {
            alias,
            success,
            message,
        }) => {
            handler::event_loop::handle_scp_complete(
                app, alias, success, message, events_tx, terminal,
            );
        }
        Some(AppEvent::SnippetHostDone {
            run_id,
            alias,
            stdout,
            stderr,
            exit_code,
        }) => {
            handler::event_loop::handle_snippet_host_done(
                app, run_id, alias, stdout, stderr, exit_code,
            );
        }
        Some(AppEvent::SnippetProgress {
            run_id,
            completed,
            total,
        }) => {
            handler::event_loop::handle_snippet_progress(app, run_id, completed, total);
        }
        Some(AppEvent::SnippetAllDone { run_id }) => {
            handler::event_loop::handle_snippet_all_done(app, run_id);
        }
        Some(AppEvent::ContainerListing { alias, result }) => {
            handler::event_loop::handle_container_listing(app, alias, result, events_tx);
        }
        Some(AppEvent::ContainerActionComplete {
            alias,
            action,
            result,
        }) => {
            handler::event_loop::handle_container_action_complete(
                app, alias, action, result, events_tx,
            );
        }
        Some(AppEvent::ContainerLogsComplete {
            alias,
            container_id,
            container_name,
            result,
        }) => {
            handler::event_loop::handle_container_logs_complete(
                app,
                alias,
                container_id,
                container_name,
                result,
            );
        }
        Some(AppEvent::ContainerInspectComplete {
            alias,
            container_id,
            result,
        }) => {
            handler::event_loop::handle_container_inspect_complete(
                app,
                alias,
                container_id,
                *result,
            );
        }
        Some(AppEvent::ContainerLogsTailComplete {
            alias,
            container_id,
            result,
        }) => {
            handler::event_loop::handle_container_logs_tail_complete(
                app,
                alias,
                container_id,
                *result,
            );
        }
        Some(AppEvent::VaultSignResult {
            alias,
            certificate_file: existing_cert_file,
            success,
            message,
        }) => {
            handler::event_loop::handle_vault_sign_result(
                app,
                alias,
                existing_cert_file,
                success,
                message,
            );
        }
        Some(AppEvent::VaultSignProgress { alias, done, total }) => {
            handler::event_loop::handle_vault_sign_progress(
                app,
                alias,
                done,
                total,
                anim.spinner_tick,
            );
        }
        Some(AppEvent::VaultSignAllDone {
            signed,
            failed,
            skipped,
            cancelled,
            aborted_message,
            first_error,
        }) => {
            if handler::event_loop::handle_vault_sign_all_done(
                app,
                signed,
                failed,
                skipped,
                cancelled,
                aborted_message,
                first_error,
            )
            .is_break()
            {
                return Ok(std::ops::ControlFlow::Break(()));
            }
        }
        Some(AppEvent::CertCheckResult { alias, status }) => {
            handler::event_loop::handle_cert_check_result(app, alias, status);
        }
        Some(AppEvent::CertCheckError { alias, message }) => {
            handler::event_loop::handle_cert_check_error(app, alias, message);
        }
        Some(AppEvent::PollError) => {
            app.running = false;
        }
    }
    Ok(std::ops::ControlFlow::Continue(()))
}

/// When the selected host has a vault role and the cached cert status is
/// missing, stale or has been touched externally, spawn a background check.
fn lazy_cert_check(app: &mut App, events_tx: &std::sync::mpsc::Sender<AppEvent>) {
    if let Some(selected) = app.selected_host() {
        if vault_ssh::resolve_vault_role(
            selected.vault_ssh.as_deref(),
            selected.provider.as_deref(),
            selected.provider_label.as_deref(),
            &app.providers.config,
        )
        .is_some()
        {
            // Stat the cert file once per iteration to detect external writes
            // (CLI sign, another purple instance) within one frame. Compared
            // against the mtime recorded when the cache entry was populated;
            // any mismatch forces a re-check, no matter the TTL.
            let current_mtime =
                vault_ssh::resolve_cert_path(&selected.alias, &selected.certificate_file)
                    .ok()
                    .and_then(|p| std::fs::metadata(&p).ok())
                    .and_then(|m| m.modified().ok());
            let cache_stale = cache_entry_is_stale(
                app.vault.cert_cache.get(&selected.alias),
                current_mtime,
                |t| t.elapsed().as_secs(),
            );

            let sign_in_flight = app
                .vault
                .sign_in_flight
                .lock()
                .map(|g| g.contains(&selected.alias))
                .unwrap_or(false);
            if cache_stale
                && !app.vault.cert_checks_in_flight.contains(&selected.alias)
                && !sign_in_flight
            {
                let alias = selected.alias.clone();
                let cert_file = selected.certificate_file.clone();
                app.vault.cert_checks_in_flight.insert(alias.clone());
                let tx = events_tx.clone();
                std::thread::spawn(move || {
                    let check_path = match vault_ssh::resolve_cert_path(&alias, &cert_file) {
                        Ok(p) => p,
                        Err(e) => {
                            let _ = tx.send(event::AppEvent::CertCheckError {
                                alias,
                                message: e.to_string(),
                            });
                            return;
                        }
                    };
                    let status = vault_ssh::check_cert_validity(&check_path);
                    let _ = tx.send(event::AppEvent::CertCheckResult { alias, status });
                });
            }
        }
    }
}

/// Drain any queued SSH connection request. In tmux mode we open a new
/// window and leave the TUI alive; otherwise we suspend the TUI, run ssh
/// inline, then restore it. Vault SSH signing and askpass pre-flight
/// (Bitwarden, keychain) run on the bare terminal to allow prompts.
fn handle_pending_connect(
    app: &mut App,
    terminal: &mut tui::Tui,
    events: &EventHandler,
    last_config_check: &mut std::time::Instant,
) -> Result<()> {
    let Some((alias, host_askpass)) = app.pending_connect.take() else {
        return Ok(());
    };
    let vault_host = app
        .hosts_state
        .list
        .iter()
        .find(|h| h.alias == alias)
        .cloned();
    let askpass = host_askpass.or_else(preferences::load_askpass_default);
    let has_active_tunnel = app.tunnels.active.contains_key(&alias);
    let use_tmux = connection::is_in_tmux() && askpass.is_none();

    if use_tmux {
        // Tmux mode: open SSH in a new tmux window. TUI stays alive.
        // Vault SSH cert signing runs first (eprintln warnings are harmless
        // on the alternate screen. ratatui repaints over them on the next
        // draw cycle). Sign the entire ProxyJump chain so the proxy hop's
        // cert is in place before ssh tries to use it.
        let vault_msg = if vault_host.is_some() {
            let msg = ensure_vault_ssh_chain_if_needed(
                &alias,
                &app.reload.config_path,
                &app.providers.config,
                &mut app.hosts_state.ssh_config,
            );
            if msg.is_some() {
                app.reload_hosts();
                for hop in vault_ssh::resolve_proxy_chain(&app.reload.config_path, &alias) {
                    app.refresh_cert_cache(&hop);
                }
            }
            msg
        } else {
            None
        };

        match connection::connect_tmux_window(&alias, &app.reload.config_path, has_active_tunnel) {
            Ok(()) => {
                if let Some((ref msg, is_error)) = vault_msg {
                    if is_error {
                        app.notify_error(msg.clone());
                    } else {
                        app.notify(msg.clone());
                    }
                } else {
                    app.notify(crate::messages::opened_in_tmux(&alias));
                }
            }
            Err(e) => {
                app.notify_error(crate::messages::tmux_error(&e));
            }
        }
        return Ok(());
    }

    // Standard mode: suspend TUI, run SSH inline, restore TUI.
    // Order preserved: pause events, exit TUI, THEN run vault signing and
    // password setup (which may eprintln or prompt for input on the real
    // terminal). Sign the entire ProxyJump chain so the proxy hop's cert is
    // in place before ssh tries to use it.
    events.pause();
    terminal.exit()?;
    let vault_msg = if vault_host.is_some() {
        let msg = ensure_vault_ssh_chain_if_needed(
            &alias,
            &app.reload.config_path,
            &app.providers.config,
            &mut app.hosts_state.ssh_config,
        );
        if msg.is_some() {
            app.reload_hosts();
            for hop in vault_ssh::resolve_proxy_chain(&app.reload.config_path, &alias) {
                app.refresh_cert_cache(&hop);
            }
        }
        msg
    } else {
        None
    };
    if let Some(token) = ensure_bw_session(app.bw_session.as_deref(), askpass.as_deref()) {
        app.bw_session = Some(token);
    }
    ensure_keychain_password(&alias, askpass.as_deref());
    print!("{}", crate::messages::cli::beaming_up(&alias));
    let result = connection::connect(
        &alias,
        &app.reload.config_path,
        askpass.as_deref(),
        app.bw_session.as_deref(),
        has_active_tunnel,
    );
    println!();
    match &result {
        Ok(cr) => {
            let code = cr.status.code().unwrap_or(1);
            if code != 255 {
                app.history.record(&alias);
                app.hosts_state.render_cache.invalidate();
            }
            if code != 0 {
                if let Some((hostname, known_hosts_path)) =
                    connection::parse_host_key_error(&cr.stderr_output)
                {
                    app.screen = app::Screen::ConfirmHostKeyReset {
                        alias: alias.clone(),
                        hostname,
                        known_hosts_path,
                        askpass,
                    };
                } else {
                    // A failed Vault sign that came alongside a failed SSH
                    // is almost always the CAUSE of the SSH failure (no cert
                    // → permission denied). Surface the vault error first so
                    // the user can fix the actual problem; otherwise they
                    // chase the generic ssh error.
                    if let Some((ref vmsg, true)) = vault_msg {
                        app.notify_error(vmsg.clone());
                    }
                    let reason = connection::stderr_summary(&cr.stderr_output);
                    let msg = if let Some(reason) = reason {
                        crate::messages::ssh_failed_with_reason(&alias, &reason)
                    } else {
                        crate::messages::ssh_exited_with_code(&alias, code)
                    };
                    app.notify_error(msg);
                }
            } else if let Some((ref msg, is_error)) = vault_msg {
                if is_error {
                    app.notify_error(msg.clone());
                } else {
                    app.notify(msg.clone());
                }
            }
        }
        Err(e) => {
            eprintln!("{}", crate::messages::connection_spawn_failed(&e));
            app.notify_error(crate::messages::connection_failed(&alias));
        }
    }
    askpass::cleanup_marker(&alias);
    terminal.enter()?;
    events.resume();
    *last_config_check = std::time::Instant::now();
    app.hosts_state.ssh_config = SshConfigFile::parse(&app.reload.config_path)?;
    app.reload_hosts();
    app.update_last_modified();
    Ok(())
}

/// Drain any queued container-exec request. Same lifecycle as
/// `handle_pending_connect` but the spawned command is
/// `ssh -t <alias> <runtime> exec -it <id> sh -c 'bash || sh'` instead
/// of a plain shell login.
fn handle_pending_container_exec(
    app: &mut App,
    terminal: &mut tui::Tui,
    events: &EventHandler,
    last_config_check: &mut std::time::Instant,
) -> Result<()> {
    let Some(req) = app.pending_container_exec.take() else {
        return Ok(());
    };

    // Defense-in-depth: container_id is currently gated by
    // `selected_running_row_with_runtime` (which calls validate_container_id)
    // before pending_container_exec is populated. This second validation
    // covers any future entry point (MCP tool call, paste-via-jump, etc.)
    // that might populate the request without going through that gate.
    if let Err(e) = crate::containers::validate_container_id(&req.container_id) {
        log::warn!(
            "[purple] container exec blocked on '{}': invalid container_id: {}",
            req.alias,
            e
        );
        app.notify(crate::messages::container_invalid_id(&e));
        return Ok(());
    }

    let askpass = req.askpass.or_else(preferences::load_askpass_default);
    let has_active_tunnel = app.tunnels.active.contains_key(&req.alias);
    let use_tmux = connection::is_in_tmux() && askpass.is_none();

    let remote_cmd = if let Some(ref user_cmd) = req.command {
        // User-typed exec command from the `e` prompt. The remote runs
        // `sh -c '<cmd>'`; embedded single-quotes are escaped as the
        // standard POSIX `'\''` so the wrapping quotes survive a token
        // like `it's-fine`. The prompt handler already rejects newlines.
        let escaped = user_cmd.replace('\'', "'\\''");
        format!(
            "{} exec -it {} sh -c '{}'",
            req.runtime.as_str(),
            req.container_id,
            escaped
        )
    } else {
        format!(
            "{} exec -it {} sh -c 'bash || sh'",
            req.runtime.as_str(),
            req.container_id
        )
    };

    if use_tmux {
        let label = format!("{}/{}", req.alias, req.container_name);
        match connection::connect_tmux_window_with_remote_command(
            &req.alias,
            &app.reload.config_path,
            has_active_tunnel,
            &remote_cmd,
            &label,
        ) {
            Ok(()) => {
                app.notify(crate::messages::container_exec_opened_in_tmux(
                    &req.container_name,
                    &req.alias,
                ));
            }
            Err(e) => {
                app.notify_error(crate::messages::tmux_error(&e));
            }
        }
        return Ok(());
    }

    events.pause();
    terminal.exit()?;

    let result = connection::connect_with_remote_command(
        &req.alias,
        &app.reload.config_path,
        askpass.as_deref(),
        app.bw_session.as_deref(),
        has_active_tunnel,
        &remote_cmd,
    );

    match result {
        Ok(cr) => {
            let code = cr.status.code().unwrap_or(1);
            // SSH exit 255 = ssh itself failed (auth, network, host-key
            // mismatch); anything else means ssh connected and the
            // remote command exited with that code. Recording history
            // for non-255 mirrors the host-list connect flow so a
            // mid-shell crash still counts as a successful login.
            if code != 255 {
                app.history.record(&req.alias);
                app.hosts_state.render_cache.invalidate();
            }
            if code == 0 {
                app.notify(crate::messages::container_exec_ended(&req.container_name));
            } else if let Some((hostname, known_hosts_path)) =
                connection::parse_host_key_error(&cr.stderr_output)
            {
                // Same recovery surface as the host-list `i` path:
                // park the user on ConfirmHostKeyReset so they can
                // delete the stale known_hosts entry and retry.
                app.screen = app::Screen::ConfirmHostKeyReset {
                    alias: req.alias.clone(),
                    hostname,
                    known_hosts_path,
                    askpass: askpass.clone(),
                };
            } else {
                let reason = connection::stderr_summary(&cr.stderr_output);
                let msg = match reason {
                    Some(r) => {
                        crate::messages::container_exec_failed_with_reason(&req.container_name, &r)
                    }
                    None => {
                        crate::messages::container_exec_exited_with_code(&req.container_name, code)
                    }
                };
                app.notify_error(msg);
            }
        }
        Err(e) => {
            eprintln!("{}", crate::messages::connection_spawn_failed(&e));
            app.notify_error(crate::messages::container_exec_spawn_failed(
                &req.container_name,
            ));
        }
    }
    askpass::cleanup_marker(&req.alias);
    terminal.enter()?;
    events.resume();
    *last_config_check = std::time::Instant::now();
    Ok(())
}

/// Drain `pending_container_logs`. Spawns a background SSH
/// thread that runs `<runtime> logs --tail N <id>` and emits an
/// `AppEvent::ContainerLogsComplete` with the captured output. The
/// receiving handler in `event_loop.rs` fills the open
/// `Screen::ContainerLogs` overlay's body.
fn handle_pending_container_logs(app: &mut App, events_tx: &std::sync::mpsc::Sender<AppEvent>) {
    let Some(req) = app.pending_container_logs.take() else {
        return;
    };
    let askpass = req.askpass.or_else(preferences::load_askpass_default);
    let has_tunnel = app.tunnels.active.contains_key(&req.alias);
    let ctx = crate::ssh_context::OwnedSshContext {
        alias: req.alias,
        config_path: app.reload.config_path.clone(),
        askpass,
        bw_session: app.bw_session.clone(),
        has_tunnel,
    };
    let tx = events_tx.clone();
    log::debug!(
        "[purple] container_logs_fetch: spawning alias={} id={}",
        ctx.alias,
        req.container_id
    );
    crate::containers::spawn_container_logs_fetch(
        ctx,
        req.runtime,
        req.container_id,
        req.container_name,
        crate::handler::container_logs::DEFAULT_TAIL,
        move |alias, container_id, container_name, result| {
            let _ = tx.send(AppEvent::ContainerLogsComplete {
                alias,
                container_id,
                container_name,
                result,
            });
        },
    );
}

/// Drain `pending_container_action`. Reuses the existing
/// `spawn_container_action` helper and `AppEvent::ContainerActionComplete`
/// event so the result handler can stay one path. The action's
/// container_id+name are logged here; the toast on completion uses
/// the alias because the existing event payload does not carry the
/// per-container labels.
fn handle_pending_container_action(app: &mut App, events_tx: &std::sync::mpsc::Sender<AppEvent>) {
    // Drain at most one action per tick. Stack-restart pushes N
    // requests but the SSH workers should not all sprint off the
    // same tick. staggering keeps load on the remote sshd lower.
    let Some(req) = app.pending_container_actions.pop_front() else {
        return;
    };
    let askpass = req.askpass.or_else(preferences::load_askpass_default);
    let has_tunnel = app.tunnels.active.contains_key(&req.alias);
    let ctx = crate::ssh_context::OwnedSshContext {
        alias: req.alias.clone(),
        config_path: app.reload.config_path.clone(),
        askpass,
        bw_session: app.bw_session.clone(),
        has_tunnel,
    };
    let tx = events_tx.clone();
    log::info!(
        "[purple] container_action_drain: spawning alias={} id={} action={:?} name={}",
        req.alias,
        req.container_id,
        req.action,
        req.container_name
    );
    crate::containers::spawn_container_action(
        ctx,
        req.runtime,
        req.action,
        req.container_id,
        move |alias, action, result| {
            let _ = tx.send(AppEvent::ContainerActionComplete {
                alias,
                action,
                result,
            });
        },
    );
}

/// Drain any queued snippet-run request: suspend the TUI, run the command
/// across all selected hosts, record history on success, wait for Enter,
/// then restore the TUI and reload the SSH config.
fn handle_pending_snippet(
    app: &mut App,
    terminal: &mut tui::Tui,
    events: &EventHandler,
    last_config_check: &mut std::time::Instant,
) -> Result<()> {
    let Some((snip, aliases)) = app.snippets.pending.take() else {
        return Ok(());
    };
    events.pause();
    terminal.exit()?;

    let multi = aliases.len() > 1;
    for alias in &aliases {
        let askpass = app
            .hosts_state
            .list
            .iter()
            .find(|h| h.alias == *alias)
            .and_then(|h| h.askpass.clone())
            .or_else(preferences::load_askpass_default);
        if let Some(token) = ensure_bw_session(app.bw_session.as_deref(), askpass.as_deref()) {
            app.bw_session = Some(token);
        }
        ensure_keychain_password(alias, askpass.as_deref());

        if multi {
            println!("{}", crate::messages::cli::host_separator(alias));
        } else {
            print!(
                "{}",
                crate::messages::cli::running_snippet_on(&snip.name, alias)
            );
        }
        let has_tunnel = app.tunnels.active.contains_key(alias);
        match snippet::run_snippet(
            alias,
            &app.reload.config_path,
            &snip.command,
            askpass.as_deref(),
            app.bw_session.as_deref(),
            false,
            has_tunnel,
        ) {
            Ok(r) => {
                if r.status.success() {
                    app.history.record(alias);
                    app.hosts_state.render_cache.invalidate();
                } else if multi {
                    eprintln!(
                        "{}",
                        crate::messages::cli::exited_with_code(r.status.code().unwrap_or(1))
                    );
                } else {
                    println!(
                        "\n{}",
                        crate::messages::cli::exited_with_code(r.status.code().unwrap_or(1))
                    );
                }
            }
            Err(e) => eprintln!("{}", crate::messages::cli::host_failed(alias, &e)),
        }
        if multi {
            println!();
        }
    }

    if !multi {
        println!("\n{}", crate::messages::cli::DONE);
    } else {
        println!(
            "{}",
            crate::messages::cli::done_multi(&snip.name, aliases.len())
        );
    }
    println!("\n{}", crate::messages::cli::PRESS_ENTER);
    let _ = std::io::stdin().read_line(&mut String::new());
    terminal.enter()?;
    events.resume();
    *last_config_check = std::time::Instant::now();
    // Reload so sort order (e.g. most recent) reflects the new history.
    app.hosts_state.ssh_config = SshConfigFile::parse(&app.reload.config_path)?;
    app.reload_hosts();
    app.update_last_modified();
    Ok(())
}

/// Flush any deferred vault-config writes, join the background signing
/// thread and kill active tunnels before leaving the TUI.
fn tui_teardown(app: &mut App, terminal: &mut tui::Tui) -> Result<()> {
    app.flush_pending_vault_write();

    if let Some(ref cancel) = app.vault.signing_cancel {
        cancel.store(true, std::sync::atomic::Ordering::Relaxed);
    }
    if let Some(handle) = app.vault.sign_thread.take() {
        let _ = handle.join();
    }

    for (_, mut tunnel) in app.tunnels.active.drain() {
        let _ = tunnel.child.kill();
        let _ = tunnel.child.wait();
    }

    terminal.exit()?;
    Ok(())
}

pub(crate) fn current_cert_mtime(alias: &str, app: &app::App) -> Option<std::time::SystemTime> {
    let host = app.hosts_state.list.iter().find(|h| h.alias == alias)?;
    let cert_path = vault_ssh::resolve_cert_path(alias, &host.certificate_file).ok()?;
    std::fs::metadata(&cert_path)
        .ok()
        .and_then(|m| m.modified().ok())
}

/// Decide whether a `vault.cert_cache` entry should be re-checked.
///
/// Returns true when:
/// - there is no cached entry at all, or
/// - the cert file's current mtime differs from the cached mtime
///   (an external actor signed or deleted the cert behind our back), or
/// - the entry's age exceeds its TTL. `CertStatus::Invalid` uses a shorter
///   backoff so transient errors recover quickly without hammering the
///   background check thread on every poll tick.
///
/// The `elapsed_secs` closure is taken as a parameter so tests can inject
/// deterministic elapsed times instead of calling the real clock.
pub(crate) fn cache_entry_is_stale<F>(
    entry: Option<&(
        std::time::Instant,
        vault_ssh::CertStatus,
        Option<std::time::SystemTime>,
    )>,
    current_mtime: Option<std::time::SystemTime>,
    elapsed_secs: F,
) -> bool
where
    F: FnOnce(std::time::Instant) -> u64,
{
    let Some((checked_at, status, cached_mtime)) = entry else {
        return true;
    };
    if current_mtime != *cached_mtime {
        return true;
    }
    let ttl = if matches!(status, vault_ssh::CertStatus::Invalid(_)) {
        vault_ssh::CERT_ERROR_BACKOFF_SECS
    } else {
        vault_ssh::CERT_STATUS_CACHE_TTL_SECS
    };
    elapsed_secs(*checked_at) > ttl
}