Skip to main content

purple_ssh/
app.rs

1use ratatui::widgets::ListState;
2
3use crate::history::ConnectionHistory;
4use crate::ssh_config::model::SshConfigFile;
5
6/// Case-insensitive substring check without allocation.
7/// Uses a byte-window approach for ASCII strings (the common case for SSH
8/// hostnames and aliases). Falls back to a char-based scan when either
9/// string contains non-ASCII bytes to avoid false matches across UTF-8
10/// character boundaries.
11pub(super) fn contains_ci(haystack: &str, needle: &str) -> bool {
12    if needle.is_empty() {
13        return true;
14    }
15    if haystack.is_ascii() && needle.is_ascii() {
16        return haystack
17            .as_bytes()
18            .windows(needle.len())
19            .any(|window| window.eq_ignore_ascii_case(needle.as_bytes()));
20    }
21    // Non-ASCII fallback: compare char-by-char (case fold ASCII only)
22    let needle_lower: Vec<char> = needle.chars().map(|c| c.to_ascii_lowercase()).collect();
23    let haystack_chars: Vec<char> = haystack.chars().collect();
24    haystack_chars.windows(needle_lower.len()).any(|window| {
25        window
26            .iter()
27            .zip(needle_lower.iter())
28            .all(|(h, n)| h.to_ascii_lowercase() == *n)
29    })
30}
31
32/// Case-insensitive equality check without allocation.
33pub(super) fn eq_ci(a: &str, b: &str) -> bool {
34    a.eq_ignore_ascii_case(b)
35}
36
37mod baselines;
38mod container_state;
39mod containers_overview;
40mod display_list;
41mod file_browser_state;
42mod form_state;
43mod forms;
44mod groups;
45mod host_state;
46mod hosts;
47pub(crate) use hosts::migrate_renames_persistent_state;
48pub(crate) mod jump;
49mod key_push_state;
50mod keys_state;
51mod pickers;
52pub(crate) mod ping;
53mod provider_state;
54mod reload_state;
55mod screen;
56mod search;
57mod selection;
58mod snippet_state;
59mod status_state;
60mod tag_state;
61mod tunnel_state;
62mod ui_state;
63mod update;
64mod vault;
65
66pub use baselines::{FormBaseline, ProviderFormBaseline, SnippetFormBaseline, TunnelFormBaseline};
67pub use container_state::{ContainerSession, ContainerState};
68pub use containers_overview::{
69    ContainerActionRequest, ContainerExecRequest, ContainerLogsRequest, ContainersOverviewState,
70    ContainersSortMode, InspectCacheEntry, LIST_CACHE_TTL_SECS, LOGS_TAIL, LogsCacheEntry,
71    REFRESH_MAX_PARALLEL, RefreshBatch, RefreshQueueItem,
72};
73pub use file_browser_state::FileBrowserState;
74pub use form_state::FormState;
75pub(crate) use forms::char_to_byte_pos;
76pub use forms::{
77    FormField, HostForm, ProviderFormField, ProviderFormFields, SnippetForm, SnippetFormField,
78    SnippetHostOutput, SnippetOutputState, SnippetParamFormState, TunnelForm, TunnelFormField,
79};
80pub use host_state::{
81    DeletedHost, GroupBy, HostListItem, HostState, ProxyJumpCandidate, SortMode, ViewMode,
82    health_summary_spans, health_summary_spans_for,
83};
84pub use key_push_state::KeyPushState;
85pub use keys_state::KeysState;
86pub use ping::{
87    PingState, PingStatus, classify_ping, ping_sort_key, propagate_ping_to_dependents, status_glyph,
88};
89pub use provider_state::{
90    LabelMigrationField, PendingLabelMigration, ProviderRow, ProviderState, SyncRecord,
91};
92pub use reload_state::{ConflictState, ReloadState};
93pub use screen::{ContainerLogsSearch, Screen, StackMember, TopPage, WhatsNewState};
94pub use search::SearchState;
95pub use snippet_state::SnippetState;
96pub use status_state::{MessageClass, StatusCenter, StatusMessage};
97pub use tag_state::{
98    BulkTagAction, BulkTagApplyResult, BulkTagEditorState, BulkTagRow, TagState,
99    select_display_tags,
100};
101pub use tunnel_state::{TunnelSortMode, TunnelState};
102pub use ui_state::UiSelection;
103pub use update::UpdateState;
104pub use vault::VaultState;
105
106/// Kill active tunnel processes when App is dropped (e.g. on panic).
107impl Drop for App {
108    fn drop(&mut self) {
109        for (alias, mut tunnel) in self.tunnels.active.drain() {
110            if let Err(e) = tunnel.child.kill() {
111                log::debug!("[external] Failed to kill tunnel for {alias} on shutdown: {e}");
112            }
113            let _ = tunnel.child.wait();
114        }
115        // Cancel and join any in-flight Vault SSH bulk-sign worker so it
116        // cannot keep writing to ~/.purple/certs/ after teardown (panic
117        // unwind, normal exit, etc.).
118        if let Some(handle) = self.vault.cancel_signing_run() {
119            let _ = handle.join();
120        }
121        // Same dance for key-push workers: signal cancel, join, so a
122        // panic or early exit cannot leave a thread writing to remote
123        // authorized_keys after the App is gone.
124        self.keys.push.shutdown();
125    }
126}
127
128/// Main application state.
129pub struct App {
130    // Core
131    /// Currently rendered screen identifier; navigation only, never carries state heaps.
132    pub screen: Screen,
133    /// Top-level page (Hosts, Tunnels, Containers). Selected by Tab/Shift+Tab
134    /// in the navigation bar. Independent of `screen`, which tracks overlays.
135    pub top_page: TopPage,
136    /// App lifecycle flag; flip to false to exit the event loop.
137    pub running: bool,
138    /// All host entries plus selection state.
139    pub(crate) hosts_state: HostState,
140
141    // Sub-structs
142    /// Toast queue, sticky messages, status routing.
143    pub(crate) status_center: StatusCenter,
144    /// Cursor reveal, detail-toggle, welcome timestamps and overlay meta.
145    pub(crate) ui: UiSelection,
146    /// Host-list incremental search query and matched hits.
147    pub(crate) search: SearchState,
148    /// Reload-from-disk state when ~/.ssh/config changes externally.
149    pub(crate) reload: ReloadState,
150    /// Conflict detection when an external edit clashes with our pending write.
151    pub(crate) conflict: ConflictState,
152
153    /// Keys-tab state: discovered keys, push runs, activity log.
154    pub(crate) keys: KeysState,
155
156    /// Tag library and per-host tag mappings.
157    pub(crate) tags: TagState,
158
159    /// Host form and bulk tag editor scratch state.
160    pub(crate) forms: FormState,
161
162    /// Connection history persisted to ~/.purple/history.
163    pub(crate) history: ConnectionHistory,
164
165    /// Provider configs, sync runs, host conflict resolution.
166    pub(crate) providers: ProviderState,
167
168    /// Ping/health-check state per host.
169    pub(crate) ping: PingState,
170
171    /// Vault SSH certificate cache and signing run state.
172    pub(crate) vault: VaultState,
173
174    /// Tunnel definitions per host and active tunnel processes.
175    pub(crate) tunnels: TunnelState,
176
177    /// Snippet library, parameter forms, output buffers.
178    pub(crate) snippets: SnippetState,
179
180    /// Self-update polling and badge state.
181    pub(crate) update: UpdateState,
182
183    /// askpass session token; not Keys-tab state.
184    pub bw_session: Option<String>,
185
186    // File browser
187    /// Persistent per-host last-visited paths; always present.
188    pub(crate) file_browser_state: FileBrowserState,
189    /// Per-host overlay session; Some when the file browser is open.
190    pub(crate) file_browser_session: Option<crate::file_browser::FileBrowserSession>,
191
192    // Containers
193    /// Cache and cross-host pending operations; always present.
194    pub(crate) container_state: ContainerState,
195    /// Per-host overlay session state; Some when the containers overlay is open.
196    pub(crate) container_session: Option<ContainerSession>,
197    /// Containers tab data: per-host docker ps cache, selection.
198    pub(crate) containers_overview: ContainersOverviewState,
199
200    /// Demo mode: all mutations are in-memory only, no disk writes.
201    pub demo_mode: bool,
202
203    /// Jump state. Some when the jump bar is open.
204    pub(crate) jump: Option<JumpState>,
205}
206
207impl App {
208    pub fn new(config: SshConfigFile) -> Self {
209        let hosts = config.host_entries();
210        let patterns = config.pattern_entries();
211        let display_list = Self::build_display_list_from(&config, &hosts, &patterns);
212
213        let initial_selection = display_list.iter().position(|item| {
214            matches!(
215                item,
216                HostListItem::Host { .. } | HostListItem::Pattern { .. }
217            )
218        });
219
220        let reload = ReloadState::from_config(&config);
221        let hosts_state = HostState::from_config(config, hosts, patterns, display_list);
222
223        Self {
224            screen: Screen::HostList,
225            top_page: TopPage::default(),
226            running: true,
227            hosts_state,
228            status_center: StatusCenter::default(),
229            ui: UiSelection::new_with_initial_selection(initial_selection),
230            search: SearchState::default(),
231            reload,
232            conflict: ConflictState::default(),
233            keys: KeysState {
234                list: Vec::new(),
235                list_state: ratatui::widgets::ListState::default(),
236                activity: crate::key_activity::KeyActivityLog::load(),
237                push: KeyPushState::default(),
238            },
239            tags: TagState::default(),
240            forms: FormState::default(),
241            history: ConnectionHistory::load(),
242            providers: ProviderState::load(),
243            ping: PingState::from_preferences(),
244            vault: VaultState::default(),
245            tunnels: TunnelState::default(),
246            snippets: SnippetState::with_store_loaded(),
247            update: UpdateState::with_current_hint(),
248            bw_session: None,
249            file_browser_state: FileBrowserState::default(),
250            file_browser_session: None,
251            container_state: ContainerState {
252                cache: crate::containers::load_container_cache(),
253                ..ContainerState::default()
254            },
255            container_session: None,
256            containers_overview: ContainersOverviewState::default(),
257            demo_mode: false,
258            jump: None,
259        }
260    }
261
262    /// Record an SSH session against `alias` in the activity log. Appends
263    /// in memory and flushes to `~/.purple/key_activity.json`. Failures
264    /// during flush are logged at debug level only; an activity-log write
265    /// failure must never interrupt the user's connect flow. Caller
266    /// passes `now`; production call sites pass `key_activity::now_secs()`.
267    pub fn record_key_use(&mut self, alias: &str, now: u64) {
268        crate::key_activity::record_and_flush(&mut self.keys.activity, alias, now);
269    }
270
271    /// Snapshot the alias of every host currently loaded. Used as
272    /// the "before" set for `queue_new_aliases_since` after a
273    /// reload that may have added or removed hosts.
274    pub fn snapshot_alias_set(&self) -> std::collections::HashSet<String> {
275        self.hosts_state
276            .list
277            .iter()
278            .map(|h| h.alias.clone())
279            .collect()
280    }
281
282    /// Push aliases that are in the current host list but were NOT
283    /// in `before_aliases` to the auto-fetch queue. Sync handlers
284    /// and external-config-edit detection use this so only freshly
285    /// introduced hosts trigger an initial `docker ps`. pre-existing
286    /// cache-missing hosts are explicitly left alone.
287    pub fn queue_new_aliases_since(&mut self, before_aliases: &std::collections::HashSet<String>) {
288        let new_aliases: Vec<String> = self
289            .hosts_state
290            .list
291            .iter()
292            .filter(|h| !before_aliases.contains(&h.alias))
293            .map(|h| h.alias.clone())
294            .collect();
295        for alias in new_aliases {
296            self.container_state.queue_fetch(alias);
297        }
298    }
299
300    /// Reload hosts from config.
301    pub fn reload_hosts(&mut self) {
302        let had_pending_vault_write = self.vault.pending_config_write;
303        // Synchronously flush any deferred vault config write before reloading,
304        // so on-disk state matches in-memory state (no TOCTOU with auto-reload).
305        // Skip when a form is open (flush handler would bail anyway) and do not
306        // call flush_pending_vault_write() itself to avoid recursion.
307        //
308        // Before flushing, check whether the on-disk config changed since the
309        // in-memory model was loaded. If so, the deferred write would overwrite
310        // those external edits silently. Surface a notification and skip the
311        // flush; the user can re-trigger vault sign after reviewing their
312        // changes. The cert files themselves were already written by the bulk
313        // sign worker — only the config-side `CertificateFile` directives are
314        // skipped, which the user can wire up via a fresh sign.
315        let mut flushed_vault_write = false;
316        if self.vault.pending_config_write && !self.is_form_open() {
317            if self.external_config_changed() {
318                self.notify_error(
319                    crate::messages::vault_config_skipped_external_change().to_string(),
320                );
321                log::warn!(
322                    "[config] reload_hosts: skipping deferred vault write — external config changed"
323                );
324            } else {
325                match self.hosts_state.ssh_config.write() {
326                    Ok(()) => flushed_vault_write = true,
327                    Err(e) => self.notify_error(crate::messages::vault_config_write_after_sign(&e)),
328                }
329            }
330        }
331        // Always clear the flag: either we flushed, we surfaced a conflict, or
332        // the form-submit path has already written the full config.
333        self.vault.pending_config_write = false;
334        log::debug!(
335            "[config] reload_hosts: pending_vault_write={had_pending_vault_write} flushed={flushed_vault_write}"
336        );
337        let had_search = self.search.query.take();
338        let selected_alias = self
339            .selected_host()
340            .map(|h| h.alias.clone())
341            .or_else(|| self.selected_pattern().map(|p| p.pattern.clone()));
342
343        self.tunnels.summaries_cache.clear();
344        self.hosts_state.render_cache.invalidate();
345        self.hosts_state.list = self.hosts_state.ssh_config.host_entries();
346        self.hosts_state.patterns = self.hosts_state.ssh_config.pattern_entries();
347        // Prune cert status cache and in-flight set: retain only entries whose
348        // host alias still exists after the reload.
349        let valid_for_certs: std::collections::HashSet<&str> = self
350            .hosts_state
351            .list
352            .iter()
353            .map(|h| h.alias.as_str())
354            .collect();
355        self.vault
356            .cert_cache
357            .retain(|alias, _| valid_for_certs.contains(alias.as_str()));
358        self.vault
359            .cert_checks_in_flight
360            .retain(|alias| valid_for_certs.contains(alias.as_str()));
361        if self.hosts_state.sort_mode == SortMode::Original
362            && matches!(self.hosts_state.group_by, GroupBy::None)
363        {
364            self.hosts_state.display_list = Self::build_display_list_from(
365                &self.hosts_state.ssh_config,
366                &self.hosts_state.list,
367                &self.hosts_state.patterns,
368            );
369        } else {
370            self.apply_sort();
371        }
372
373        // Close tag pickers if open. tags.list is stale after reload
374        if matches!(self.screen, Screen::TagPicker | Screen::BulkTagEditor) {
375            self.set_screen(Screen::HostList);
376            self.forms.bulk_tag_editor = BulkTagEditorState::default();
377        }
378
379        // Multi-select stores indices into hosts; clear to avoid stale refs
380        self.hosts_state.multi_select.clear();
381
382        // Prune ping status for hosts that no longer exist
383        let valid_aliases: std::collections::HashSet<&str> = self
384            .hosts_state
385            .list
386            .iter()
387            .map(|h| h.alias.as_str())
388            .collect();
389
390        // Drop container-cache entries for hosts that disappeared
391        // since the last reload (manual delete, stale purge, or an
392        // external `~/.ssh/config` edit). Persist the trimmed cache
393        // so `~/.purple/container_cache.jsonl` does not keep
394        // serving orphan entries on the next purple start. Demo
395        // mode skips disk writes via `save_container_cache` itself.
396        let pre_container_cache = self.container_state.cache.len();
397        self.container_state
398            .cache
399            .retain(|alias, _| valid_aliases.contains(alias.as_str()));
400        let dropped_container_hosts =
401            pre_container_cache.saturating_sub(self.container_state.cache.len());
402        if dropped_container_hosts > 0 {
403            log::debug!(
404                "[purple] reload_hosts: dropped {} orphan container_cache host(s)",
405                dropped_container_hosts
406            );
407            crate::containers::save_container_cache(&self.container_state.cache);
408        }
409
410        // Inspect cache is keyed on full container ID. Any ID whose
411        // host just got dropped is by definition orphan; build the
412        // valid-id set from the (just-pruned) container_cache.
413        let valid_container_ids: std::collections::HashSet<String> = self
414            .container_state
415            .cache
416            .values()
417            .flat_map(|e| e.containers.iter().map(|c| c.id.clone()))
418            .collect();
419        let pre_inspect = self.containers_overview.inspect_cache.entries.len();
420        self.containers_overview
421            .inspect_cache
422            .entries
423            .retain(|id, _| valid_container_ids.contains(id));
424        self.containers_overview
425            .inspect_cache
426            .in_flight
427            .retain(|id| valid_container_ids.contains(id));
428        // Logs cache shares the inspect-cache lifetime: orphan entries
429        // (containers whose host was just removed) are dropped together.
430        self.containers_overview
431            .logs_cache
432            .entries
433            .retain(|id, _| valid_container_ids.contains(id));
434        self.containers_overview
435            .logs_cache
436            .in_flight
437            .retain(|id| valid_container_ids.contains(id));
438        // Prune auto-list in-flight markers for deleted hosts. The
439        // listing thread still posts a result that hits the race
440        // guard in `handle_container_listing` and removes it there,
441        // but pruning here keeps debug state clean and avoids a
442        // false-positive dedup hit if the same alias is re-added
443        // before the stray listing returns.
444        self.containers_overview
445            .auto_list_in_flight
446            .retain(|alias| valid_aliases.contains(alias.as_str()));
447        // Container-overview refresh batch (R). Tracks in-flight aliases to
448        // gate counter updates against non-batch listings. Prune so that a
449        // host removed mid-batch cannot linger.
450        if let Some(batch) = self.containers_overview.refresh_batch.as_mut() {
451            let pre = batch.in_flight_aliases.len();
452            batch
453                .in_flight_aliases
454                .retain(|alias| valid_aliases.contains(alias.as_str()));
455            let dropped = pre.saturating_sub(batch.in_flight_aliases.len());
456            if dropped > 0 {
457                log::debug!(
458                    "[purple] reload_hosts: dropped {} orphan refresh_batch in_flight alias(es)",
459                    dropped
460                );
461            }
462        }
463        // Bulk vault-sign tracker. Worker self-prunes its own entries via
464        // `remove_in_flight`, but a host removed mid-sign would linger. On
465        // poison recover via `into_inner` instead of dropping the work. A
466        // poisoned worker still owns live aliases that must not be cleared.
467        {
468            let mut sign = match self.vault.sign_in_flight.lock() {
469                Ok(g) => g,
470                Err(p) => p.into_inner(),
471            };
472            let pre = sign.len();
473            sign.retain(|alias| valid_aliases.contains(alias.as_str()));
474            let dropped = pre.saturating_sub(sign.len());
475            if dropped > 0 {
476                log::debug!(
477                    "[purple] reload_hosts: dropped {} orphan sign_in_flight alias(es)",
478                    dropped
479                );
480            }
481        }
482        // Per-host last-visited file-browser path. Pure host-keyed state
483        // with no self-pruning, so a rename leaves the old alias behind.
484        let pre_paths = self.file_browser_state.host_paths.len();
485        self.file_browser_state
486            .host_paths
487            .retain(|alias, _| valid_aliases.contains(alias.as_str()));
488        let dropped_paths = pre_paths.saturating_sub(self.file_browser_state.host_paths.len());
489        if dropped_paths > 0 {
490            log::debug!(
491                "[purple] reload_hosts: dropped {} orphan file_browser host_paths entrie(s)",
492                dropped_paths
493            );
494        }
495        // Demo-mode tunnel snapshot seed. The detail panel reads from this
496        // map when `demo_mode == true`. Outside demo it stays empty, but a
497        // demo workflow that renames or deletes a host should not leak.
498        let pre_demo = self.tunnels.demo_live_snapshots.len();
499        self.tunnels
500            .demo_live_snapshots
501            .retain(|alias, _| valid_aliases.contains(alias.as_str()));
502        let dropped_demo = pre_demo.saturating_sub(self.tunnels.demo_live_snapshots.len());
503        if dropped_demo > 0 {
504            log::debug!(
505                "[purple] reload_hosts: dropped {} orphan demo_live_snapshots entrie(s)",
506                dropped_demo
507            );
508        }
509        // Containers-overview collapsed groups. Persisted to disk via
510        // preferences, so leftover aliases survive restart. Rename is
511        // already handled by `apply_alias_renames`; this covers delete.
512        let pre_collapsed = self.containers_overview.collapsed_hosts.len();
513        self.containers_overview
514            .collapsed_hosts
515            .retain(|alias| valid_aliases.contains(alias.as_str()));
516        let dropped_collapsed =
517            pre_collapsed.saturating_sub(self.containers_overview.collapsed_hosts.len());
518        if dropped_collapsed > 0 {
519            log::debug!(
520                "[purple] reload_hosts: dropped {} orphan collapsed_hosts entrie(s)",
521                dropped_collapsed
522            );
523            if let Err(e) = crate::preferences::save_containers_collapsed_hosts(
524                &self.containers_overview.collapsed_hosts,
525            ) {
526                log::warn!("[config] failed to save collapsed_hosts after prune: {e}");
527            }
528        }
529        let dropped_inspect =
530            pre_inspect.saturating_sub(self.containers_overview.inspect_cache.entries.len());
531        if dropped_inspect > 0 {
532            log::debug!(
533                "[purple] reload_hosts: dropped {} orphan inspect_cache entrie(s)",
534                dropped_inspect
535            );
536        }
537
538        let pre_status = self.ping.status.len();
539        let pre_checked = self.ping.last_checked.len();
540        self.ping
541            .status
542            .retain(|alias, _| valid_aliases.contains(alias.as_str()));
543        self.ping
544            .last_checked
545            .retain(|alias, _| valid_aliases.contains(alias.as_str()));
546        let dropped = pre_status.saturating_sub(self.ping.status.len())
547            + pre_checked.saturating_sub(self.ping.last_checked.len());
548        if dropped > 0 {
549            log::debug!(
550                "[purple] reload_hosts: pruned {} orphan ping entrie(s); {} aliases remain",
551                dropped,
552                valid_aliases.len()
553            );
554        }
555
556        // Restore search if it was active, otherwise reset
557        if let Some(query) = had_search {
558            self.search.query = Some(query);
559            self.apply_filter();
560        } else {
561            self.search.query = None;
562            self.search.filtered_indices.clear();
563            self.search.filtered_pattern_indices.clear();
564            // Fix selection for display list mode
565            if self.hosts_state.list.is_empty() && self.hosts_state.patterns.is_empty() {
566                self.ui.list_state.select(None);
567            } else if let Some(pos) = self.hosts_state.display_list.iter().position(|item| {
568                matches!(
569                    item,
570                    HostListItem::Host { .. } | HostListItem::Pattern { .. }
571                )
572            }) {
573                let current = self.ui.list_state.selected().unwrap_or(0);
574                if current >= self.hosts_state.display_list.len()
575                    || !matches!(
576                        self.hosts_state.display_list.get(current),
577                        Some(HostListItem::Host { .. } | HostListItem::Pattern { .. })
578                    )
579                {
580                    self.ui.list_state.select(Some(pos));
581                }
582            } else {
583                self.ui.list_state.select(None);
584            }
585        }
586
587        // Restore selection by alias (e.g. after SSH connect changed sort order)
588        if let Some(alias) = selected_alias {
589            self.select_host_by_alias(&alias);
590        }
591
592        log::debug!(
593            "[config] reload_hosts: hosts={} patterns={} display_items={}",
594            self.hosts_state.list.len(),
595            self.hosts_state.patterns.len(),
596            self.hosts_state.display_list.len(),
597        );
598    }
599
600    /// Synchronously re-check a host's Vault SSH certificate and update
601    /// `vault.cert_cache` with fresh status + on-disk mtime.
602    ///
603    /// Every sign path (V-key bulk sign, host form submit, connect-time
604    /// `ensure_vault_ssh_if_needed`, CLI) funnels through this helper so the
605    /// detail panel never lies about cert state after a successful sign.
606    ///
607    /// No-op in demo mode. If the host is missing, has no resolvable vault
608    /// role, or the cert path cannot be resolved, any stale entry for the
609    /// alias is removed to avoid showing ghost status.
610    pub fn refresh_cert_cache(&mut self, alias: &str) {
611        if crate::demo_flag::is_demo() {
612            return;
613        }
614        let Some(host) = self.hosts_state.list.iter().find(|h| h.alias == alias) else {
615            self.vault.cert_cache.remove(alias);
616            return;
617        };
618        let role_some = crate::vault_ssh::resolve_vault_role(
619            host.vault_ssh.as_deref(),
620            host.provider.as_deref(),
621            host.provider_label.as_deref(),
622            &self.providers.config,
623        )
624        .is_some();
625        if !role_some {
626            self.vault.cert_cache.remove(alias);
627            return;
628        }
629        let cert_path = match crate::vault_ssh::resolve_cert_path(alias, &host.certificate_file) {
630            Ok(p) => p,
631            Err(_) => {
632                self.vault.cert_cache.remove(alias);
633                return;
634            }
635        };
636        let status = crate::vault_ssh::check_cert_validity(&cert_path);
637        let mtime = std::fs::metadata(&cert_path)
638            .ok()
639            .and_then(|m| m.modified().ok());
640        self.vault.cert_cache.insert(
641            alias.to_string(),
642            (std::time::Instant::now(), status, mtime),
643        );
644    }
645
646    // --- Search methods ---
647
648    /// Shim. Routes to `ProviderState::sorted_names`.
649    /// Test-only: production code uses `provider_list_rows()` for the
650    /// tree-style list, so this wrapper exists to keep older test fixtures
651    /// concise.
652    #[cfg(test)]
653    pub fn sorted_provider_names(&self) -> Vec<String> {
654        self.providers.sorted_names()
655    }
656
657    /// Check whether a form screen is currently open (host or provider forms).
658    pub fn is_form_open(&self) -> bool {
659        matches!(
660            self.screen,
661            Screen::AddHost | Screen::EditHost { .. } | Screen::ProviderForm { .. }
662        )
663    }
664
665    /// Open the unified jump in the given mode. Loads recents
666    /// from disk and seeds the empty-query view. Recomputes hits.
667    pub fn open_jump(&mut self, mode: JumpMode) {
668        log::debug!("jump: open mode={:?}", mode);
669        let mut state = JumpState::for_mode(mode);
670        let recents_file = jump::load_recents();
671        state.recents = self.resolve_recents(&recents_file);
672        self.jump = Some(state);
673        self.recompute_jump_hits();
674    }
675
676    /// Close the unified jump overlay. Idempotent: a no-op when no jump
677    /// is open. Pairs with `open_jump`; the three handler arms (Esc,
678    /// Enter-after-dispatch, Backspace-on-empty) all route through here.
679    pub(crate) fn close_jump(&mut self) {
680        self.jump = None;
681    }
682
683    /// Translate the on-disk recents log into live `JumpHit`s, dropping
684    /// dangling references silently.
685    fn resolve_recents(&self, file: &RecentsFile) -> Vec<JumpHit> {
686        let mode = self
687            .jump
688            .as_ref()
689            .map(|p| p.mode)
690            .unwrap_or(JumpMode::Hosts);
691        let mut out = Vec::with_capacity(file.entries.len());
692        for entry in &file.entries {
693            if let Some(hit) = self.resolve_recent_ref(&entry.target, mode) {
694                out.push(hit);
695            }
696        }
697        out
698    }
699
700    /// Test seam: exposes `resolve_recent_ref` as `pub(crate)` so the unit
701    /// tests in `app::tests` can drive each `SourceKind` branch without
702    /// going through `open_jump`.
703    #[cfg(test)]
704    pub(crate) fn resolve_recent_ref_for_test(
705        &self,
706        r: &RecentRef,
707        mode: JumpMode,
708    ) -> Option<JumpHit> {
709        self.resolve_recent_ref(r, mode)
710    }
711
712    fn resolve_recent_ref(&self, r: &RecentRef, mode: JumpMode) -> Option<JumpHit> {
713        match r.kind {
714            SourceKind::Action => {
715                let key_char = r.key.chars().next()?;
716                let actions = JumpAction::for_mode(mode);
717                actions
718                    .iter()
719                    .find(|a| a.key == key_char)
720                    .copied()
721                    .map(JumpHit::Action)
722            }
723            SourceKind::Host => {
724                let host = self.hosts_state.list.iter().find(|h| h.alias == r.key)?;
725                Some(JumpHit::Host(HostHit {
726                    alias: host.alias.clone(),
727                    hostname: host.hostname.clone(),
728                    tags: host.tags.clone(),
729                    provider: host.provider.clone(),
730                    user: host.user.clone(),
731                    identity_file: host.identity_file.clone(),
732                    proxy_jump: host.proxy_jump.clone(),
733                    vault_ssh: host.vault_ssh.clone(),
734                }))
735            }
736            SourceKind::Tunnel => {
737                let (alias, port_str) = r.key.split_once(':')?;
738                let port: u16 = port_str.parse().ok()?;
739                let rules = self.hosts_state.ssh_config.find_tunnel_directives(alias);
740                let rule = rules.iter().find(|r| r.bind_port == port)?;
741                Some(JumpHit::Tunnel(TunnelHit {
742                    alias: alias.to_string(),
743                    bind_port: rule.bind_port,
744                    bind_port_str: rule.bind_port.to_string(),
745                    destination: rule.display(),
746                    active: self.tunnels.active.contains_key(alias),
747                }))
748            }
749            SourceKind::Container => {
750                let (alias, name) = r.key.split_once('/')?;
751                let entry = self.container_state.cache.get(alias)?;
752                let info = entry.containers.iter().find(|c| c.names == name)?;
753                Some(JumpHit::Container(ContainerHit {
754                    alias: alias.to_string(),
755                    container_name: info.names.clone(),
756                    container_id: info.id.clone(),
757                    state: info.state.clone(),
758                }))
759            }
760            SourceKind::Snippet => {
761                let snippet = self.snippets.store.get(&r.key)?;
762                Some(JumpHit::Snippet(SnippetHit {
763                    name: snippet.name.clone(),
764                    command_preview: preview(&snippet.command, 40),
765                }))
766            }
767        }
768    }
769
770    /// Recompute the jump bar hit list against the current query. Pulls
771    /// candidates from every live source and ranks them with nucleo-matcher.
772    /// Preserves the previously-selected hit's identity across the
773    /// recompute so mid-typing arrow-key navigation does not jump back to
774    /// row 0.
775    pub fn recompute_jump_hits(&mut self) {
776        let Some(mut state) = self.jump.take() else {
777            return;
778        };
779        // Identity of the row the user was on before the recompute. We
780        // re-resolve it after rebuilding `hits` to keep selection stable
781        // when the user types and the matched row is still in the list.
782        let prior_identity = state
783            .visible_hits()
784            .get(state.selected)
785            .map(|h| h.identity());
786
787        let candidates = self.collect_jump_candidates(state.mode);
788        if state.query.is_empty() {
789            state.hits = candidates;
790            state.selected = restore_selection(&state.visible_hits(), prior_identity.as_ref(), 0);
791            self.jump = Some(state);
792            return;
793        }
794
795        // Field-prefix syntax: `user:eric` scopes to one field. Empty
796        // remainder after the prefix is treated as no query (empty
797        // scope-search). Mode is held in `query_scope` for the row
798        // renderer to surface a "via <field>" hint.
799        let (scope, effective_query) = parse_query_scope(&state.query);
800
801        use nucleo_matcher::pattern::{CaseMatching, Normalization, Pattern};
802        use nucleo_matcher::{Config, Matcher, Utf32Str};
803        let matcher_state = state
804            .matcher
805            .get_or_insert_with(|| Matcher::new(Config::DEFAULT));
806        let pattern = Pattern::parse(effective_query, CaseMatching::Smart, Normalization::Smart);
807        let mut buf: Vec<char> = Vec::new();
808        let mut scored: Vec<(JumpHit, u32)> = Vec::with_capacity(candidates.len());
809        for hit in candidates {
810            let mut best: u32 = 0;
811            // Score over the right haystack set: scoped queries narrow to
812            // a single field; unscoped queries score over everything the
813            // hit advertises.
814            let scoped_haystacks = scoped_haystacks_for(&hit, scope);
815            let haystacks: Vec<&str> = if let Some(hs) = scoped_haystacks {
816                hs
817            } else {
818                hit.haystacks()
819            };
820            for haystack in haystacks {
821                buf.clear();
822                let chars = Utf32Str::new(haystack, &mut buf);
823                if let Some(score) = pattern.score(chars, matcher_state) {
824                    best = best.max(score);
825                }
826            }
827            // Boost: a single-char query that exactly matches an action's
828            // hotkey letter (case-insensitive) lands the action at the top.
829            // When two actions share the same hotkey (e.g. 'a' for `Hosts:
830            // Add host` and `Tunnels: Add tunnel`), the one whose target
831            // matches the current mode wins, so muscle memory survives.
832            if let JumpHit::Action(a) = &hit {
833                let single = effective_query.chars().next();
834                if effective_query.chars().count() == 1
835                    && single
836                        .map(|c| c.eq_ignore_ascii_case(&a.key))
837                        .unwrap_or(false)
838                {
839                    let mode_match = matches!(
840                        (state.mode, a.target),
841                        (JumpMode::Hosts, JumpActionTarget::Hosts)
842                            | (JumpMode::Tunnels, JumpActionTarget::Tunnels)
843                            | (JumpMode::Containers, JumpActionTarget::Containers)
844                            | (JumpMode::Keys, JumpActionTarget::Keys)
845                    );
846                    let bump = if mode_match { 20_000 } else { 10_000 };
847                    best = best.saturating_add(bump);
848                }
849            }
850            // Score floor: actions need to clear a higher bar than data
851            // rows. Stops query 'eric' from dragging in 'Containers: List
852            // containers' on stray e/r/i/c char overlap.
853            let floor = match &hit {
854                JumpHit::Action(_) => jump::PALETTE_ACTION_FLOOR,
855                _ => 1,
856            };
857            if best >= floor {
858                scored.push((hit, best));
859            }
860        }
861        // Stable sort: higher score first, ties broken by render-order kind so
862        // hosts come before actions when scores tie.
863        scored.sort_by(|a, b| {
864            b.1.cmp(&a.1)
865                .then_with(|| kind_rank(a.0.kind()).cmp(&kind_rank(b.0.kind())))
866        });
867        // Cap per-section using a fixed-size array so a broad query (one
868        // char that matches everything) cannot blow the visible list.
869        let mut per_kind: [usize; 5] = [0; 5];
870        let mut filtered: Vec<JumpHit> = Vec::with_capacity(scored.len().min(160));
871        for (hit, _) in scored {
872            let slot = kind_rank(hit.kind()) as usize;
873            if per_kind[slot] < PALETTE_PER_SECTION_CAP {
874                per_kind[slot] += 1;
875                filtered.push(hit);
876            }
877        }
878        state.hits = filtered;
879        state.selected = restore_selection(&state.visible_hits(), prior_identity.as_ref(), 0);
880        self.jump = Some(state);
881    }
882
883    fn collect_jump_candidates(&self, mode: JumpMode) -> Vec<JumpHit> {
884        let mut out: Vec<JumpHit> = Vec::new();
885        // Hosts
886        for h in &self.hosts_state.list {
887            out.push(JumpHit::Host(HostHit {
888                alias: h.alias.clone(),
889                hostname: h.hostname.clone(),
890                tags: h.tags.clone(),
891                provider: h.provider.clone(),
892                user: h.user.clone(),
893                identity_file: h.identity_file.clone(),
894                proxy_jump: h.proxy_jump.clone(),
895                vault_ssh: h.vault_ssh.clone(),
896            }));
897        }
898        // Tunnels: every configured rule from every host with a directive.
899        for h in &self.hosts_state.list {
900            let rules = self.hosts_state.ssh_config.find_tunnel_directives(&h.alias);
901            for rule in rules {
902                out.push(JumpHit::Tunnel(TunnelHit {
903                    alias: h.alias.clone(),
904                    bind_port: rule.bind_port,
905                    bind_port_str: rule.bind_port.to_string(),
906                    destination: rule.display(),
907                    active: self.tunnels.active.contains_key(&h.alias),
908                }));
909            }
910        }
911        // Containers: cached only. Triggering an SSH fetch on jump bar open
912        // would be unbounded latency.
913        for (alias, entry) in &self.container_state.cache {
914            for info in &entry.containers {
915                out.push(JumpHit::Container(ContainerHit {
916                    alias: alias.clone(),
917                    container_name: info.names.clone(),
918                    container_id: info.id.clone(),
919                    state: info.state.clone(),
920                }));
921            }
922        }
923        // Snippets
924        for snippet in &self.snippets.store.snippets {
925            out.push(JumpHit::Snippet(SnippetHit {
926                name: snippet.name.clone(),
927                command_preview: preview(&snippet.command, 40),
928            }));
929        }
930        // Actions last
931        for a in JumpAction::for_mode(mode) {
932            out.push(JumpHit::Action(*a));
933        }
934        out
935    }
936
937    /// Persist a jump dispatch to the on-disk MRU log. Best-effort; a
938    /// write error logs and is otherwise swallowed so user navigation is
939    /// never blocked by a recents-file failure. Takes `&mut self` so the
940    /// type system reflects that this performs I/O and mutates persistent
941    /// state, even though `jump::save_recents` only needs `&File`.
942    pub fn record_jump_hit(&mut self, hit: &JumpHit) {
943        if self.demo_mode {
944            log::debug!("jump: record skipped (demo mode)");
945            return;
946        }
947        let mut file = jump::load_recents();
948        jump::touch_recent(&mut file, hit.identity());
949        if let Err(e) = jump::save_recents(&file) {
950            log::warn!("[purple] failed to save recents: {e}");
951        }
952    }
953
954    /// Open the file-browser overlay with the given session. Stores the
955    /// session and switches to `Screen::FileBrowser` for the session's
956    /// alias. Any previously-open session is replaced.
957    pub(crate) fn open_file_browser(&mut self, session: crate::file_browser::FileBrowserSession) {
958        let alias = session.alias.clone();
959        self.file_browser_session = Some(session);
960        self.set_screen(Screen::FileBrowser { alias });
961    }
962
963    /// Close the file-browser overlay. Persists the current pane paths to
964    /// `file_browser_state.host_paths` so the next open re-seeds them,
965    /// drops the session, and returns to the host list.
966    pub(crate) fn close_file_browser(&mut self) {
967        if let Some(fb) = self.file_browser_session.take() {
968            self.file_browser_state
969                .host_paths
970                .insert(fb.alias, (fb.local_path, fb.remote_path));
971        }
972        self.set_screen(Screen::HostList);
973    }
974
975    /// Flush a deferred vault config write if one is pending and no form is open.
976    /// Returns true if a write was performed.
977    pub fn flush_pending_vault_write(&mut self) -> bool {
978        if !self.vault.pending_config_write || self.is_form_open() {
979            return false;
980        }
981        // reload_hosts() performs the write and clears the flag.
982        self.reload_hosts();
983        true
984    }
985
986    /// Run once after App::new: queue the upgrade toast if the user just
987    /// upgraded past their last-seen version, otherwise seed the preference
988    /// so the next launch is silent.
989    pub fn post_init(&mut self) {
990        let outcome = crate::onboarding::evaluate();
991        if let Some(text) = outcome.upgrade_toast {
992            self.enqueue_sticky_toast(text);
993        }
994        // Seed the Keys tab so the first Tab navigation lands on a
995        // populated list. Subsequent reloads run via R or after a host
996        // form save / provider sync.
997        self.scan_keys();
998    }
999
1000    fn enqueue_sticky_toast(&mut self, text: String) {
1001        log::debug!("[purple] enqueue sticky toast: {}", text);
1002        let msg = StatusMessage {
1003            text,
1004            class: MessageClass::Success,
1005            tick_count: 0,
1006            sticky: true,
1007            created_at: std::time::Instant::now(),
1008        };
1009        self.status_center.toast = Some(msg);
1010    }
1011
1012    /// User action feedback. Success toast, length-proportional timeout.
1013    pub fn notify(&mut self, text: impl Into<String>) {
1014        self.status_center.set_status(text, false);
1015    }
1016
1017    /// User action error. Error toast, sticky by default, queued.
1018    pub fn notify_error(&mut self, text: impl Into<String>) {
1019        self.status_center.set_status(text, true);
1020    }
1021
1022    /// Background event. Info footer, suppressed if sticky active.
1023    pub fn notify_background(&mut self, text: impl Into<String>) {
1024        self.status_center.set_background_status(text, false);
1025    }
1026
1027    /// Background error. Sticky toast, bypasses sticky suppression.
1028    pub fn notify_background_error(&mut self, text: impl Into<String>) {
1029        self.status_center.set_background_status(text, true);
1030    }
1031
1032    /// Caution / degraded state → Warning toast (length-proportional
1033    /// timeout, queued). For: precondition violations ("Nothing to undo."),
1034    /// validation hints ("Project ID can't be empty."), empty-state
1035    /// notices ("No stale hosts."), stale-host warnings, deprecated
1036    /// config detected, partial sync results. Warnings are NOT sticky;
1037    /// the user acknowledges them by continuing to interact.
1038    ///
1039    /// Use `notify_error` only for system-level failures (I/O, network,
1040    /// subprocess) that require explicit acknowledgement. Use
1041    /// `notify_warning` for everything that is "this can't happen given
1042    /// current state" or "you forgot something".
1043    pub fn notify_warning(&mut self, text: impl Into<String>) {
1044        let msg = StatusMessage {
1045            text: text.into(),
1046            class: MessageClass::Warning,
1047            tick_count: 0,
1048            sticky: false,
1049            created_at: std::time::Instant::now(),
1050        };
1051        log::debug!("toast <- Warning: {}", msg.text);
1052        self.status_center.push_toast(msg);
1053    }
1054
1055    /// Long-running progress. Footer sticky, never expires automatically.
1056    pub fn notify_progress(&mut self, text: impl Into<String>) {
1057        self.status_center.set_sticky_status(text, false);
1058    }
1059
1060    /// Sticky error. Footer sticky, never expires automatically.
1061    pub fn notify_sticky_error(&mut self, text: impl Into<String>) {
1062        self.status_center.set_sticky_status(text, true);
1063    }
1064
1065    /// Explicit info. Footer, 4s timeout, not suppressed by sticky.
1066    pub fn notify_info(&mut self, text: impl Into<String>) {
1067        self.status_center.set_info_status(text);
1068    }
1069
1070    /// Drop the footer status unconditionally. Use when a new user action
1071    /// makes the prior status stale. Symmetric with the `notify_*` family
1072    /// so handlers stay on the App surface instead of reaching into
1073    /// `status_center` directly.
1074    pub(crate) fn clear_status(&mut self) {
1075        self.status_center.clear_status();
1076    }
1077
1078    /// Tick the footer status message timer. Uses wall-clock time.
1079    /// Sticky/Progress messages never expire automatically.
1080    ///
1081    /// Stays on `App` (not moved to `StatusCenter`) because expiry is
1082    /// suppressed while any provider sync is in flight, which requires
1083    /// reading `self.providers.syncing`.
1084    pub fn tick_status(&mut self) {
1085        // Don't expire status while providers are still syncing
1086        if !self.providers.syncing.is_empty() {
1087            return;
1088        }
1089        if let Some(ref status) = self.status_center.status {
1090            if status.sticky {
1091                return;
1092            }
1093            let timeout_ms = status.timeout_ms();
1094            if timeout_ms != u64::MAX && status.created_at.elapsed().as_millis() as u64 > timeout_ms
1095            {
1096                log::debug!("footer status expired: {}", status.text);
1097                self.status_center.status = None;
1098            }
1099        }
1100    }
1101
1102    /// Shim. Routes to `StatusCenter::tick_toast`.
1103    pub fn tick_toast(&mut self) {
1104        self.status_center.tick_toast();
1105    }
1106
1107    /// Check if config or any Include file has changed externally and reload if so.
1108    /// Skips reload when the user is in a form (AddHost/EditHost) to avoid
1109    /// overwriting in-memory config while the user is editing.
1110    pub fn check_config_changed(&mut self) {
1111        if matches!(
1112            self.screen,
1113            Screen::AddHost
1114                | Screen::EditHost { .. }
1115                | Screen::ProviderForm { .. }
1116                | Screen::TunnelList { .. }
1117                | Screen::TunnelForm { .. }
1118                | Screen::HostDetail { .. }
1119                | Screen::SnippetPicker { .. }
1120                | Screen::SnippetForm { .. }
1121                | Screen::SnippetOutput { .. }
1122                | Screen::SnippetParamForm { .. }
1123                | Screen::FileBrowser { .. }
1124                | Screen::Containers { .. }
1125                | Screen::ConfirmDelete { .. }
1126                | Screen::ConfirmHostKeyReset { .. }
1127                | Screen::ConfirmPurgeStale { .. }
1128                | Screen::ConfirmImport { .. }
1129                | Screen::ConfirmVaultSign { .. }
1130                | Screen::TagPicker
1131                | Screen::BulkTagEditor
1132                | Screen::ThemePicker
1133                | Screen::WhatsNew(_)
1134        ) || self.tags.input.is_some()
1135        {
1136            return;
1137        }
1138        let current_mtime = reload_state::get_mtime(&self.reload.config_path);
1139        let changed = current_mtime != self.reload.last_modified
1140            || self
1141                .reload
1142                .include_mtimes
1143                .iter()
1144                .any(|(path, old_mtime)| reload_state::get_mtime(path) != *old_mtime)
1145            || self
1146                .reload
1147                .include_dir_mtimes
1148                .iter()
1149                .any(|(path, old_mtime)| reload_state::get_mtime(path) != *old_mtime);
1150        if changed {
1151            log::debug!(
1152                "[config] check_config_changed: mtime drift detected on {} -> reloading",
1153                self.reload.config_path.display()
1154            );
1155            if let Ok(new_config) = SshConfigFile::parse(&self.reload.config_path) {
1156                let before_aliases = self.snapshot_alias_set();
1157                self.hosts_state.ssh_config = new_config;
1158                // Invalidate undo state. config structure may have changed externally
1159                self.hosts_state.undo_stack.clear();
1160                // Clear stale ping status. hosts may have changed
1161                log::debug!(
1162                    "[config] external config change: clearing {} ping result(s) + timestamps",
1163                    self.ping.status.len()
1164                );
1165                self.ping.status.clear();
1166                self.ping.last_checked.clear();
1167                self.ping.filter_down_only = false;
1168                self.ping.checked_at = None;
1169                self.reload_hosts();
1170                self.reload.last_modified = current_mtime;
1171                self.reload.include_mtimes =
1172                    reload_state::snapshot_include_mtimes(&self.hosts_state.ssh_config);
1173                self.reload.include_dir_mtimes =
1174                    reload_state::snapshot_include_dir_mtimes(&self.hosts_state.ssh_config);
1175                let count = self.hosts_state.list.len();
1176                self.notify_background(crate::messages::config_reloaded(count));
1177                self.queue_new_aliases_since(&before_aliases);
1178            }
1179        }
1180    }
1181
1182    /// Detect external changes to `~/.ssh/` keys and refresh `self.keys.list`
1183    /// when something has moved. Mirrors `check_config_changed` for the
1184    /// keys tab so users see new key files (or deletions, or rotations)
1185    /// without pressing R. Cheap: a single dir stat plus one stat per
1186    /// tracked key. Called from the 4-second throttle in `handle_tick`.
1187    ///
1188    /// Skips during demo mode (the demo seeds a fixed key list and never
1189    /// reads from disk) and when a form is open that could be mutating
1190    /// the same data.
1191    pub fn check_keys_changed(&mut self) {
1192        if self.demo_mode {
1193            return;
1194        }
1195        if matches!(
1196            self.screen,
1197            Screen::AddHost | Screen::EditHost { .. } | Screen::ProviderForm { .. }
1198        ) {
1199            return;
1200        }
1201        let Some(home) = dirs::home_dir() else {
1202            return;
1203        };
1204        let ssh_dir = home.join(".ssh");
1205        let current_dir_mtime = reload_state::get_mtime(&ssh_dir);
1206        let dir_changed = current_dir_mtime != self.reload.keys_dir_mtime;
1207        let files_changed = self
1208            .reload
1209            .key_file_mtimes
1210            .iter()
1211            .any(|(path, old)| reload_state::get_mtime(path) != *old);
1212        if !dir_changed && !files_changed {
1213            return;
1214        }
1215        log::debug!(
1216            "[purple] check_keys_changed: drift detected on {} (dir={} files={}) -> rescan",
1217            ssh_dir.display(),
1218            dir_changed,
1219            files_changed,
1220        );
1221        let previous = self.keys.list.len();
1222        self.scan_keys();
1223        let after = self.keys.list.len();
1224        // Keep the selection valid after a rescan: clamp to the new list
1225        // length, or land on the first row when the list grew from empty.
1226        if let Some(sel) = self.keys.list_state.selected() {
1227            if sel >= after {
1228                let next = after.checked_sub(1);
1229                self.keys.list_state.select(next);
1230            }
1231        } else if after > 0 {
1232            self.keys.list_state.select(Some(0));
1233        }
1234        if previous != after {
1235            log::debug!(
1236                "[purple] check_keys_changed: rescan {} -> {} keys",
1237                previous,
1238                after
1239            );
1240        }
1241    }
1242
1243    /// Non-mutating check: has the on-disk config (or any tracked Include)
1244    /// been modified since `self.reload.last_modified` was captured? Used by
1245    /// async write paths (e.g. the Vault SSH bulk-sign completion handler)
1246    /// to refuse writing when an external editor changed the file underneath
1247    /// us. overwriting those edits would silently discard user work. The
1248    /// backup-on-write mechanism in `SshConfigFile::write()` would still
1249    /// recover them, but detecting the conflict BEFORE writing is strictly
1250    /// better than after.
1251    pub fn external_config_changed(&self) -> bool {
1252        let current_mtime = reload_state::get_mtime(&self.reload.config_path);
1253        current_mtime != self.reload.last_modified
1254            || self
1255                .reload
1256                .include_mtimes
1257                .iter()
1258                .any(|(path, old_mtime)| reload_state::get_mtime(path) != *old_mtime)
1259            || self
1260                .reload
1261                .include_dir_mtimes
1262                .iter()
1263                .any(|(path, old_mtime)| reload_state::get_mtime(path) != *old_mtime)
1264    }
1265
1266    /// Update the last_modified timestamp (call after writing config).
1267    pub fn update_last_modified(&mut self) {
1268        self.reload.last_modified = reload_state::get_mtime(&self.reload.config_path);
1269        self.reload.include_mtimes =
1270            reload_state::snapshot_include_mtimes(&self.hosts_state.ssh_config);
1271        self.reload.include_dir_mtimes =
1272            reload_state::snapshot_include_dir_mtimes(&self.hosts_state.ssh_config);
1273    }
1274
1275    /// Returns true if any host or provider has a vault role configured.
1276    pub fn has_any_vault_role(&self) -> bool {
1277        for host in &self.hosts_state.list {
1278            if host.vault_ssh.is_some() {
1279                return true;
1280            }
1281        }
1282        for section in &self.providers.config.sections {
1283            if !section.vault_role.is_empty() {
1284                return true;
1285            }
1286        }
1287        false
1288    }
1289
1290    /// Poll active tunnels for exit. Returns (alias, message, is_error) tuples.
1291    pub fn poll_tunnels(&mut self) -> Vec<(String, String, bool)> {
1292        self.tunnels.poll()
1293    }
1294
1295    /// Recompute the lsof poller's bind-port list from the current
1296    /// `active` map plus each host's directives in the SSH config.
1297    /// Called after every tunnel start/stop. The poller picks up the
1298    /// new list on its next iteration.
1299    pub fn refresh_tunnel_bind_ports(&mut self) {
1300        let mut ports: Vec<(String, u16, u32)> = Vec::new();
1301        for (alias, tunnel) in &self.tunnels.active {
1302            let pid = tunnel.child.id();
1303            for rule in self.hosts_state.ssh_config.find_tunnel_directives(alias) {
1304                ports.push((alias.clone(), rule.bind_port, pid));
1305            }
1306        }
1307        self.tunnels.set_lsof_ports(ports);
1308    }
1309}
1310
1311/// Cycle list selection forward or backward with wraparound.
1312pub(crate) fn cycle_selection(state: &mut ListState, len: usize, forward: bool) {
1313    if len == 0 {
1314        return;
1315    }
1316    let i = match state.selected() {
1317        Some(i) => {
1318            if forward {
1319                if i >= len - 1 { 0 } else { i + 1 }
1320            } else if i == 0 {
1321                len - 1
1322            } else {
1323                i - 1
1324            }
1325        }
1326        None => 0,
1327    };
1328    state.select(Some(i));
1329}
1330
1331/// Jump forward by page_size items, clamping at the end (no wrap).
1332pub(crate) fn page_down(state: &mut ListState, len: usize, page_size: usize) {
1333    if len == 0 {
1334        return;
1335    }
1336    let current = state.selected().unwrap_or(0);
1337    let next = (current + page_size).min(len - 1);
1338    state.select(Some(next));
1339}
1340
1341/// Jump backward by page_size items, clamping at 0 (no wrap).
1342pub(crate) fn page_up(state: &mut ListState, len: usize, page_size: usize) {
1343    if len == 0 {
1344        return;
1345    }
1346    let current = state.selected().unwrap_or(0);
1347    let prev = current.saturating_sub(page_size);
1348    state.select(Some(prev));
1349}
1350
1351// Re-export the jump bar types so call sites keep referring to them via
1352// `crate::app::JumpHit` / `crate::app::JumpAction` without caring
1353// which submodule they live in.
1354pub use jump::{
1355    ContainerHit, HostHit, JumpAction, JumpActionTarget, JumpHit, JumpMode, JumpState, RecentRef,
1356    RecentsFile, SnippetHit, SourceKind, TunnelHit,
1357};
1358
1359/// Backwards-compatible alias for the old `PaletteCommand` (now `JumpAction`) name. The
1360/// renamed type is `JumpAction`. Test-only. there is no production
1361/// caller.
1362#[cfg(test)]
1363pub type PaletteCommand = JumpAction;
1364
1365/// Unified action set. Every action declares its `target` so dispatch
1366/// switches `top_page` first, then synthesises the hotkey for the right
1367/// handler. The jump bar shows this same list regardless of which
1368/// top-page was active when it opened. so the overlay size is
1369/// consistent and `Tunnels: Add tunnel` is reachable from the Hosts
1370/// tab and vice versa.
1371static ALL_JUMP_ACTIONS: &[JumpAction] = &[
1372    JumpAction {
1373        key: 'a',
1374        key_str: "a",
1375        label: "Hosts: Add host",
1376        aliases: &["new", "create"],
1377        target: JumpActionTarget::Hosts,
1378    },
1379    JumpAction {
1380        key: 'A',
1381        key_str: "A",
1382        label: "Hosts: Add pattern",
1383        aliases: &["new pattern", "wildcard"],
1384        target: JumpActionTarget::Hosts,
1385    },
1386    JumpAction {
1387        key: 'e',
1388        key_str: "e",
1389        label: "Hosts: Edit host",
1390        aliases: &["modify", "change"],
1391        target: JumpActionTarget::Hosts,
1392    },
1393    JumpAction {
1394        key: 'd',
1395        key_str: "d",
1396        label: "Hosts: Delete host",
1397        aliases: &["remove", "rm"],
1398        target: JumpActionTarget::Hosts,
1399    },
1400    JumpAction {
1401        key: 'c',
1402        key_str: "c",
1403        label: "Hosts: Clone host",
1404        aliases: &["duplicate", "copy"],
1405        target: JumpActionTarget::Hosts,
1406    },
1407    JumpAction {
1408        key: 'u',
1409        key_str: "u",
1410        label: "Hosts: Undo delete",
1411        aliases: &["restore"],
1412        target: JumpActionTarget::Hosts,
1413    },
1414    JumpAction {
1415        key: 't',
1416        key_str: "t",
1417        label: "Hosts: Tag host",
1418        aliases: &["label", "category"],
1419        target: JumpActionTarget::Hosts,
1420    },
1421    JumpAction {
1422        key: 'i',
1423        key_str: "i",
1424        label: "Hosts: Show all directives",
1425        aliases: &["raw", "config", "settings"],
1426        target: JumpActionTarget::Hosts,
1427    },
1428    JumpAction {
1429        key: 'y',
1430        key_str: "y",
1431        label: "Clipboard: Copy SSH command",
1432        aliases: &["yank"],
1433        target: JumpActionTarget::Hosts,
1434    },
1435    JumpAction {
1436        key: 'x',
1437        key_str: "x",
1438        label: "Clipboard: Copy config block",
1439        aliases: &["yank config"],
1440        target: JumpActionTarget::Hosts,
1441    },
1442    JumpAction {
1443        key: 'X',
1444        key_str: "X",
1445        label: "Hosts: Purge stale hosts",
1446        aliases: &["clean", "cleanup"],
1447        target: JumpActionTarget::Hosts,
1448    },
1449    JumpAction {
1450        key: 'F',
1451        key_str: "F",
1452        label: "Files: Browse remote files",
1453        aliases: &[
1454            "browse",
1455            "filesystem",
1456            "scp",
1457            "sftp",
1458            "transfer",
1459            "explorer",
1460            "open",
1461        ],
1462        target: JumpActionTarget::Hosts,
1463    },
1464    JumpAction {
1465        key: 'C',
1466        key_str: "C",
1467        label: "Containers: List containers",
1468        aliases: &["docker", "podman", "ps", "open"],
1469        target: JumpActionTarget::Hosts,
1470    },
1471    JumpAction {
1472        key: 'K',
1473        key_str: "K",
1474        label: "Keys: Manage SSH keys",
1475        aliases: &["identity", "id_rsa", "id_ed25519", "private key", "open"],
1476        target: JumpActionTarget::Hosts,
1477    },
1478    JumpAction {
1479        key: 'S',
1480        key_str: "S",
1481        label: "Providers: Manage cloud sync",
1482        aliases: &["cloud", "aws", "gcp", "azure", "hetzner", "sync", "open"],
1483        target: JumpActionTarget::Hosts,
1484    },
1485    JumpAction {
1486        key: 'V',
1487        key_str: "V",
1488        label: "Vault: Sign certificate",
1489        aliases: &["hashicorp", "ssh cert", "vault ssh"],
1490        target: JumpActionTarget::Hosts,
1491    },
1492    JumpAction {
1493        key: 'I',
1494        key_str: "I",
1495        label: "Hosts: Import from known_hosts",
1496        aliases: &["known", "import"],
1497        target: JumpActionTarget::Hosts,
1498    },
1499    JumpAction {
1500        key: 'm',
1501        key_str: "m",
1502        label: "Settings: Switch theme",
1503        aliases: &["color", "appearance", "dark", "light"],
1504        target: JumpActionTarget::Hosts,
1505    },
1506    JumpAction {
1507        key: 'n',
1508        key_str: "n",
1509        label: "Help: What's new",
1510        aliases: &["changelog", "news", "release notes"],
1511        target: JumpActionTarget::Hosts,
1512    },
1513    JumpAction {
1514        key: 'r',
1515        key_str: "r",
1516        label: "Snippets: Run snippet",
1517        aliases: &["execute", "command"],
1518        target: JumpActionTarget::Hosts,
1519    },
1520    JumpAction {
1521        key: 'R',
1522        key_str: "R",
1523        label: "Snippets: Run on all visible",
1524        aliases: &["batch", "execute all"],
1525        target: JumpActionTarget::Hosts,
1526    },
1527    JumpAction {
1528        key: 'p',
1529        key_str: "p",
1530        label: "Hosts: Ping host",
1531        aliases: &["health", "check"],
1532        target: JumpActionTarget::Hosts,
1533    },
1534    JumpAction {
1535        key: 'P',
1536        key_str: "P",
1537        label: "Hosts: Ping all hosts",
1538        aliases: &["health all"],
1539        target: JumpActionTarget::Hosts,
1540    },
1541    JumpAction {
1542        key: '!',
1543        key_str: "!",
1544        label: "Hosts: Show down only",
1545        aliases: &["filter offline", "down only"],
1546        target: JumpActionTarget::Hosts,
1547    },
1548    // Tunnel-tab actions. Disambiguated by label so they coexist with
1549    // hosts-tab hotkey letters in the same list. Dispatch switches to
1550    // Tunnels top-page before synthesising the keypress.
1551    JumpAction {
1552        key: 'T',
1553        key_str: "T",
1554        label: "Tunnels: Manage tunnels",
1555        aliases: &["forward", "port forward", "ssh -L", "ssh -R", "open"],
1556        target: JumpActionTarget::Hosts,
1557    },
1558    JumpAction {
1559        key: 'a',
1560        key_str: "a",
1561        label: "Tunnels: Add tunnel",
1562        aliases: &["new tunnel", "create tunnel", "forward"],
1563        target: JumpActionTarget::Tunnels,
1564    },
1565    JumpAction {
1566        key: 'e',
1567        key_str: "e",
1568        label: "Tunnels: Edit tunnel",
1569        aliases: &["modify tunnel"],
1570        target: JumpActionTarget::Tunnels,
1571    },
1572    JumpAction {
1573        key: 'd',
1574        key_str: "d",
1575        label: "Tunnels: Delete tunnel",
1576        aliases: &["remove tunnel"],
1577        target: JumpActionTarget::Tunnels,
1578    },
1579    JumpAction {
1580        key: 's',
1581        key_str: "s",
1582        label: "Tunnels: Sort",
1583        aliases: &["order tunnels"],
1584        target: JumpActionTarget::Tunnels,
1585    },
1586    JumpAction {
1587        key: 'R',
1588        key_str: "R",
1589        label: "Containers: Refresh all hosts",
1590        aliases: &["reload containers", "fetch", "rescan"],
1591        target: JumpActionTarget::Containers,
1592    },
1593    JumpAction {
1594        key: 's',
1595        key_str: "s",
1596        label: "Containers: Cycle sort",
1597        aliases: &["order containers", "sort by host", "sort by name"],
1598        target: JumpActionTarget::Containers,
1599    },
1600    JumpAction {
1601        key: 'v',
1602        key_str: "v",
1603        label: "Containers: Toggle detail panel",
1604        aliases: &["show details", "hide details", "compact view"],
1605        target: JumpActionTarget::Containers,
1606    },
1607    // Keys tab. Mirror the footer + handler bindings on the Keys tab so
1608    // typing `:` followed by part of a verb (e.g. `push`, `sign`, `copy`)
1609    // surfaces the same actions the keyboard shortcuts already trigger.
1610    JumpAction {
1611        key: 'c',
1612        key_str: "c",
1613        label: "Keys: Copy public key",
1614        aliases: &["yank", "clipboard", "pubkey"],
1615        target: JumpActionTarget::Keys,
1616    },
1617    JumpAction {
1618        key: 'p',
1619        key_str: "p",
1620        label: "Keys: Push to host",
1621        aliases: &["install", "ssh-copy-id", "deploy", "upload"],
1622        target: JumpActionTarget::Keys,
1623    },
1624    JumpAction {
1625        key: 'V',
1626        key_str: "V",
1627        label: "Keys: Sign Vault SSH certificate",
1628        aliases: &["vault", "renew cert", "sign"],
1629        target: JumpActionTarget::Keys,
1630    },
1631];
1632
1633/// Cap on hits rendered per section. Broad queries (e.g. one character)
1634/// match thousands of candidates; capping keeps the jump bar legible without
1635/// virtualizing the render. The selected hit always falls within the cap
1636/// because results are sorted by score before truncation.
1637pub const PALETTE_PER_SECTION_CAP: usize = 32;
1638
1639/// Field-prefix parser: `user:eric` → (`Some(QueryScope::User)`, "eric").
1640/// Returns `(None, query)` for queries without a recognised scope.
1641pub fn parse_query_scope(query: &str) -> (Option<QueryScope>, &str) {
1642    if let Some((prefix, rest)) = query.split_once(':') {
1643        let scope = match prefix.trim() {
1644            "user" => Some(QueryScope::User),
1645            "host" => Some(QueryScope::Hostname),
1646            "proxy" => Some(QueryScope::ProxyJump),
1647            "vault" => Some(QueryScope::VaultSsh),
1648            "tag" => Some(QueryScope::Tag),
1649            _ => None,
1650        };
1651        if scope.is_some() {
1652            return (scope, rest.trim_start());
1653        }
1654    }
1655    (None, query)
1656}
1657
1658#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1659pub enum QueryScope {
1660    User,
1661    Hostname,
1662    ProxyJump,
1663    VaultSsh,
1664    Tag,
1665}
1666
1667/// Truncate a string to `max` characters, appending "..." if cut.
1668fn preview(s: &str, max: usize) -> String {
1669    let s = s.replace('\n', " ");
1670    let chars: Vec<char> = s.chars().collect();
1671    if chars.len() <= max {
1672        s
1673    } else {
1674        let mut out: String = chars.iter().take(max.saturating_sub(3)).collect();
1675        out.push_str("...");
1676        out
1677    }
1678}
1679
1680/// Restrict scoring to a single field when the user prefixes the query
1681/// with `user:` / `host:` / `proxy:` / `vault:` / `tag:`. Returns `None`
1682/// when no scope is set OR when the scope does not apply to the hit
1683/// (e.g. `vault:` on a snippet). caller falls back to the full set.
1684fn scoped_haystacks_for(hit: &JumpHit, scope: Option<QueryScope>) -> Option<Vec<&str>> {
1685    let scope = scope?;
1686    match (hit, scope) {
1687        (JumpHit::Host(h), QueryScope::User) if !h.user.is_empty() => Some(vec![&h.user]),
1688        (JumpHit::Host(h), QueryScope::Hostname) if !h.hostname.is_empty() => {
1689            Some(vec![&h.hostname])
1690        }
1691        (JumpHit::Host(h), QueryScope::ProxyJump) if !h.proxy_jump.is_empty() => {
1692            Some(vec![&h.proxy_jump])
1693        }
1694        (JumpHit::Host(h), QueryScope::VaultSsh) => h.vault_ssh.as_deref().map(|s| vec![s]),
1695        (JumpHit::Host(h), QueryScope::Tag) => Some(h.tags.iter().map(|t| t.as_str()).collect()),
1696        // Scoped queries do not match other kinds.
1697        _ => None,
1698    }
1699}
1700
1701/// Determine which field caused the host hit to match. The renderer uses
1702/// this to append a `via user`, `via proxy`, `vault: <role>` hint to the
1703/// row when the matched field is not part of the visible columns. Returns
1704/// `None` if the alias/hostname (already visible) matched.
1705pub fn match_source_for_host(host: &HostHit, query: &str) -> Option<MatchSource> {
1706    if query.is_empty() {
1707        return None;
1708    }
1709    let q = query.to_lowercase();
1710    let alias_hit = host.alias.to_lowercase().contains(&q);
1711    let hostname_hit = host.hostname.to_lowercase().contains(&q);
1712    if alias_hit || hostname_hit {
1713        return None;
1714    }
1715    if !host.user.is_empty() && host.user.to_lowercase().contains(&q) {
1716        return Some(MatchSource::User);
1717    }
1718    if !host.proxy_jump.is_empty() && host.proxy_jump.to_lowercase().contains(&q) {
1719        return Some(MatchSource::ProxyJump);
1720    }
1721    if let Some(role) = &host.vault_ssh {
1722        if role.to_lowercase().contains(&q) {
1723            return Some(MatchSource::VaultSsh);
1724        }
1725    }
1726    if !host.identity_file.is_empty() && host.identity_file.to_lowercase().contains(&q) {
1727        return Some(MatchSource::IdentityFile);
1728    }
1729    None
1730}
1731
1732#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1733pub enum MatchSource {
1734    User,
1735    ProxyJump,
1736    VaultSsh,
1737    IdentityFile,
1738}
1739
1740fn kind_rank(k: SourceKind) -> u8 {
1741    match k {
1742        SourceKind::Host => 0,
1743        SourceKind::Tunnel => 1,
1744        SourceKind::Container => 2,
1745        SourceKind::Snippet => 3,
1746        SourceKind::Action => 4,
1747    }
1748}
1749
1750/// Find `prior` in `hits` and return its index, or `fallback` if the prior
1751/// hit is gone (e.g. the typed query no longer matches it). Used by
1752/// `recompute_jump_hits` so mid-typing arrow navigation does not lose
1753/// the user's place.
1754fn restore_selection(hits: &[JumpHit], prior: Option<&RecentRef>, fallback: usize) -> usize {
1755    if let Some(target) = prior {
1756        if let Some(idx) = hits.iter().position(|h| &h.identity() == target) {
1757            return idx;
1758        }
1759    }
1760    fallback.min(hits.len().saturating_sub(1))
1761}
1762
1763impl JumpAction {
1764    #[cfg(test)]
1765    pub fn all() -> &'static [JumpAction] {
1766        ALL_JUMP_ACTIONS
1767    }
1768
1769    /// The jump bar surfaces the same action set regardless of mode now.
1770    /// `mode` is preserved on the API so the dispatcher and test helpers
1771    /// can still pass through, but it no longer narrows the visible list.
1772    pub fn for_mode(_mode: JumpMode) -> &'static [JumpAction] {
1773        ALL_JUMP_ACTIONS
1774    }
1775}
1776
1777#[cfg(test)]
1778mod tests;