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