1use ratatui::widgets::ListState;
2
3use crate::history::ConnectionHistory;
4use crate::ssh_config::model::SshConfigFile;
5
6pub(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 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
32pub(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
106impl 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 if let Some(ref cancel) = self.vault.signing_cancel {
119 cancel.store(true, std::sync::atomic::Ordering::Relaxed);
120 }
121 if let Some(handle) = self.vault.sign_thread.take() {
122 let _ = handle.join();
123 }
124 self.keys.push.shutdown();
128 }
129}
130
131pub struct App {
133 pub screen: Screen,
136 pub top_page: TopPage,
139 pub running: bool,
141 pub(crate) hosts_state: HostState,
143
144 pub status_center: StatusCenter,
147 pub(crate) ui: UiSelection,
149 pub search: SearchState,
151 pub reload: ReloadState,
153 pub conflict: ConflictState,
155
156 pub(crate) keys: KeysState,
158
159 pub tags: TagState,
161
162 pub(crate) forms: FormState,
164
165 pub history: ConnectionHistory,
167
168 pub(crate) providers: ProviderState,
170
171 pub(crate) ping: PingState,
173
174 pub vault: VaultState,
176
177 pub(crate) tunnels: TunnelState,
179
180 pub(crate) snippets: SnippetState,
182
183 pub update: UpdateState,
185
186 pub bw_session: Option<String>,
188
189 pub file_browser_state: FileBrowserState,
192 pub file_browser_session: Option<crate::file_browser::FileBrowserSession>,
194
195 pub container_state: ContainerState,
198 pub container_session: Option<ContainerSession>,
200 pub containers_overview: ContainersOverviewState,
202
203 pub demo_mode: bool,
205
206 pub jump: Option<JumpState>,
208}
209
210impl App {
211 pub fn new(config: SshConfigFile) -> Self {
212 let hosts = config.host_entries();
213 let patterns = config.pattern_entries();
214 let display_list = Self::build_display_list_from(&config, &hosts, &patterns);
215
216 let initial_selection = display_list.iter().position(|item| {
217 matches!(
218 item,
219 HostListItem::Host { .. } | HostListItem::Pattern { .. }
220 )
221 });
222
223 let reload = ReloadState::from_config(&config);
224 let hosts_state = HostState::from_config(config, hosts, patterns, display_list);
225
226 Self {
227 screen: Screen::HostList,
228 top_page: TopPage::default(),
229 running: true,
230 hosts_state,
231 status_center: StatusCenter::default(),
232 ui: UiSelection::new_with_initial_selection(initial_selection),
233 search: SearchState::default(),
234 reload,
235 conflict: ConflictState::default(),
236 keys: KeysState {
237 list: Vec::new(),
238 list_state: ratatui::widgets::ListState::default(),
239 activity: crate::key_activity::KeyActivityLog::load(),
240 push: KeyPushState::default(),
241 },
242 tags: TagState::default(),
243 forms: FormState::default(),
244 history: ConnectionHistory::load(),
245 providers: ProviderState::load(),
246 ping: PingState::from_preferences(),
247 vault: VaultState::default(),
248 tunnels: TunnelState::default(),
249 snippets: SnippetState::with_store_loaded(),
250 update: UpdateState::with_current_hint(),
251 bw_session: None,
252 file_browser_state: FileBrowserState::default(),
253 file_browser_session: None,
254 container_state: ContainerState {
255 cache: crate::containers::load_container_cache(),
256 ..ContainerState::default()
257 },
258 container_session: None,
259 containers_overview: ContainersOverviewState::default(),
260 demo_mode: false,
261 jump: None,
262 }
263 }
264
265 pub fn record_key_use(&mut self, alias: &str, now: u64) {
271 crate::key_activity::record_and_flush(&mut self.keys.activity, alias, now);
272 }
273
274 pub fn snapshot_alias_set(&self) -> std::collections::HashSet<String> {
278 self.hosts_state
279 .list
280 .iter()
281 .map(|h| h.alias.clone())
282 .collect()
283 }
284
285 pub fn queue_new_aliases_since(&mut self, before_aliases: &std::collections::HashSet<String>) {
291 for h in &self.hosts_state.list {
292 if !before_aliases.contains(&h.alias) {
293 self.container_state
294 .pending_fetch_aliases
295 .push(h.alias.clone());
296 }
297 }
298 }
299
300 pub fn reload_hosts(&mut self) {
302 let had_pending_vault_write = self.vault.pending_config_write;
303 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 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 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 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 self.hosts_state.multi_select.clear();
381
382 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 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 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 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 self.containers_overview
445 .auto_list_in_flight
446 .retain(|alias| valid_aliases.contains(alias.as_str()));
447 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 {
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 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 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 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 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 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 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 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 #[cfg(test)]
653 pub fn sorted_provider_names(&self) -> Vec<String> {
654 self.providers.sorted_names()
655 }
656
657 pub fn is_form_open(&self) -> bool {
659 matches!(
660 self.screen,
661 Screen::AddHost | Screen::EditHost { .. } | Screen::ProviderForm { .. }
662 )
663 }
664
665 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 fn resolve_recents(&self, file: &RecentsFile) -> Vec<JumpHit> {
679 let mode = self
680 .jump
681 .as_ref()
682 .map(|p| p.mode)
683 .unwrap_or(JumpMode::Hosts);
684 let mut out = Vec::with_capacity(file.entries.len());
685 for entry in &file.entries {
686 if let Some(hit) = self.resolve_recent_ref(&entry.target, mode) {
687 out.push(hit);
688 }
689 }
690 out
691 }
692
693 #[cfg(test)]
697 pub(crate) fn resolve_recent_ref_for_test(
698 &self,
699 r: &RecentRef,
700 mode: JumpMode,
701 ) -> Option<JumpHit> {
702 self.resolve_recent_ref(r, mode)
703 }
704
705 fn resolve_recent_ref(&self, r: &RecentRef, mode: JumpMode) -> Option<JumpHit> {
706 match r.kind {
707 SourceKind::Action => {
708 let key_char = r.key.chars().next()?;
709 let actions = JumpAction::for_mode(mode);
710 actions
711 .iter()
712 .find(|a| a.key == key_char)
713 .copied()
714 .map(JumpHit::Action)
715 }
716 SourceKind::Host => {
717 let host = self.hosts_state.list.iter().find(|h| h.alias == r.key)?;
718 Some(JumpHit::Host(HostHit {
719 alias: host.alias.clone(),
720 hostname: host.hostname.clone(),
721 tags: host.tags.clone(),
722 provider: host.provider.clone(),
723 user: host.user.clone(),
724 identity_file: host.identity_file.clone(),
725 proxy_jump: host.proxy_jump.clone(),
726 vault_ssh: host.vault_ssh.clone(),
727 }))
728 }
729 SourceKind::Tunnel => {
730 let (alias, port_str) = r.key.split_once(':')?;
731 let port: u16 = port_str.parse().ok()?;
732 let rules = self.hosts_state.ssh_config.find_tunnel_directives(alias);
733 let rule = rules.iter().find(|r| r.bind_port == port)?;
734 Some(JumpHit::Tunnel(TunnelHit {
735 alias: alias.to_string(),
736 bind_port: rule.bind_port,
737 bind_port_str: rule.bind_port.to_string(),
738 destination: rule.display(),
739 active: self.tunnels.active.contains_key(alias),
740 }))
741 }
742 SourceKind::Container => {
743 let (alias, name) = r.key.split_once('/')?;
744 let entry = self.container_state.cache.get(alias)?;
745 let info = entry.containers.iter().find(|c| c.names == name)?;
746 Some(JumpHit::Container(ContainerHit {
747 alias: alias.to_string(),
748 container_name: info.names.clone(),
749 container_id: info.id.clone(),
750 state: info.state.clone(),
751 }))
752 }
753 SourceKind::Snippet => {
754 let snippet = self.snippets.store.get(&r.key)?;
755 Some(JumpHit::Snippet(SnippetHit {
756 name: snippet.name.clone(),
757 command_preview: preview(&snippet.command, 40),
758 }))
759 }
760 }
761 }
762
763 pub fn recompute_jump_hits(&mut self) {
769 let Some(mut state) = self.jump.take() else {
770 return;
771 };
772 let prior_identity = state
776 .visible_hits()
777 .get(state.selected)
778 .map(|h| h.identity());
779
780 let candidates = self.collect_jump_candidates(state.mode);
781 if state.query.is_empty() {
782 state.hits = candidates;
783 state.selected = restore_selection(&state.visible_hits(), prior_identity.as_ref(), 0);
784 self.jump = Some(state);
785 return;
786 }
787
788 let (scope, effective_query) = parse_query_scope(&state.query);
793
794 use nucleo_matcher::pattern::{CaseMatching, Normalization, Pattern};
795 use nucleo_matcher::{Config, Matcher, Utf32Str};
796 let matcher_state = state
797 .matcher
798 .get_or_insert_with(|| Matcher::new(Config::DEFAULT));
799 let pattern = Pattern::parse(effective_query, CaseMatching::Smart, Normalization::Smart);
800 let mut buf: Vec<char> = Vec::new();
801 let mut scored: Vec<(JumpHit, u32)> = Vec::with_capacity(candidates.len());
802 for hit in candidates {
803 let mut best: u32 = 0;
804 let scoped_haystacks = scoped_haystacks_for(&hit, scope);
808 let haystacks: Vec<&str> = if let Some(hs) = scoped_haystacks {
809 hs
810 } else {
811 hit.haystacks()
812 };
813 for haystack in haystacks {
814 buf.clear();
815 let chars = Utf32Str::new(haystack, &mut buf);
816 if let Some(score) = pattern.score(chars, matcher_state) {
817 best = best.max(score);
818 }
819 }
820 if let JumpHit::Action(a) = &hit {
826 let single = effective_query.chars().next();
827 if effective_query.chars().count() == 1
828 && single
829 .map(|c| c.eq_ignore_ascii_case(&a.key))
830 .unwrap_or(false)
831 {
832 let mode_match = matches!(
833 (state.mode, a.target),
834 (JumpMode::Hosts, JumpActionTarget::Hosts)
835 | (JumpMode::Tunnels, JumpActionTarget::Tunnels)
836 | (JumpMode::Containers, JumpActionTarget::Containers)
837 | (JumpMode::Keys, JumpActionTarget::Keys)
838 );
839 let bump = if mode_match { 20_000 } else { 10_000 };
840 best = best.saturating_add(bump);
841 }
842 }
843 let floor = match &hit {
847 JumpHit::Action(_) => jump::PALETTE_ACTION_FLOOR,
848 _ => 1,
849 };
850 if best >= floor {
851 scored.push((hit, best));
852 }
853 }
854 scored.sort_by(|a, b| {
857 b.1.cmp(&a.1)
858 .then_with(|| kind_rank(a.0.kind()).cmp(&kind_rank(b.0.kind())))
859 });
860 let mut per_kind: [usize; 5] = [0; 5];
863 let mut filtered: Vec<JumpHit> = Vec::with_capacity(scored.len().min(160));
864 for (hit, _) in scored {
865 let slot = kind_rank(hit.kind()) as usize;
866 if per_kind[slot] < PALETTE_PER_SECTION_CAP {
867 per_kind[slot] += 1;
868 filtered.push(hit);
869 }
870 }
871 state.hits = filtered;
872 state.selected = restore_selection(&state.visible_hits(), prior_identity.as_ref(), 0);
873 self.jump = Some(state);
874 }
875
876 fn collect_jump_candidates(&self, mode: JumpMode) -> Vec<JumpHit> {
877 let mut out: Vec<JumpHit> = Vec::new();
878 for h in &self.hosts_state.list {
880 out.push(JumpHit::Host(HostHit {
881 alias: h.alias.clone(),
882 hostname: h.hostname.clone(),
883 tags: h.tags.clone(),
884 provider: h.provider.clone(),
885 user: h.user.clone(),
886 identity_file: h.identity_file.clone(),
887 proxy_jump: h.proxy_jump.clone(),
888 vault_ssh: h.vault_ssh.clone(),
889 }));
890 }
891 for h in &self.hosts_state.list {
893 let rules = self.hosts_state.ssh_config.find_tunnel_directives(&h.alias);
894 for rule in rules {
895 out.push(JumpHit::Tunnel(TunnelHit {
896 alias: h.alias.clone(),
897 bind_port: rule.bind_port,
898 bind_port_str: rule.bind_port.to_string(),
899 destination: rule.display(),
900 active: self.tunnels.active.contains_key(&h.alias),
901 }));
902 }
903 }
904 for (alias, entry) in &self.container_state.cache {
907 for info in &entry.containers {
908 out.push(JumpHit::Container(ContainerHit {
909 alias: alias.clone(),
910 container_name: info.names.clone(),
911 container_id: info.id.clone(),
912 state: info.state.clone(),
913 }));
914 }
915 }
916 for snippet in &self.snippets.store.snippets {
918 out.push(JumpHit::Snippet(SnippetHit {
919 name: snippet.name.clone(),
920 command_preview: preview(&snippet.command, 40),
921 }));
922 }
923 for a in JumpAction::for_mode(mode) {
925 out.push(JumpHit::Action(*a));
926 }
927 out
928 }
929
930 pub fn record_jump_hit(&mut self, hit: &JumpHit) {
936 if self.demo_mode {
937 log::debug!("jump: record skipped (demo mode)");
938 return;
939 }
940 let mut file = jump::load_recents();
941 jump::touch_recent(&mut file, hit.identity());
942 if let Err(e) = jump::save_recents(&file) {
943 log::warn!("[purple] failed to save recents: {e}");
944 }
945 }
946
947 pub fn flush_pending_vault_write(&mut self) -> bool {
950 if !self.vault.pending_config_write || self.is_form_open() {
951 return false;
952 }
953 self.reload_hosts();
955 true
956 }
957
958 pub fn post_init(&mut self) {
962 let outcome = crate::onboarding::evaluate();
963 if let Some(text) = outcome.upgrade_toast {
964 self.enqueue_sticky_toast(text);
965 }
966 self.scan_keys();
970 }
971
972 fn enqueue_sticky_toast(&mut self, text: String) {
973 log::debug!("[purple] enqueue sticky toast: {}", text);
974 let msg = StatusMessage {
975 text,
976 class: MessageClass::Success,
977 tick_count: 0,
978 sticky: true,
979 created_at: std::time::Instant::now(),
980 };
981 self.status_center.toast = Some(msg);
982 }
983
984 pub fn notify(&mut self, text: impl Into<String>) {
986 self.status_center.set_status(text, false);
987 }
988
989 pub fn notify_error(&mut self, text: impl Into<String>) {
991 self.status_center.set_status(text, true);
992 }
993
994 pub fn notify_background(&mut self, text: impl Into<String>) {
996 self.status_center.set_background_status(text, false);
997 }
998
999 pub fn notify_background_error(&mut self, text: impl Into<String>) {
1001 self.status_center.set_background_status(text, true);
1002 }
1003
1004 pub fn notify_warning(&mut self, text: impl Into<String>) {
1016 let msg = StatusMessage {
1017 text: text.into(),
1018 class: MessageClass::Warning,
1019 tick_count: 0,
1020 sticky: false,
1021 created_at: std::time::Instant::now(),
1022 };
1023 log::debug!("toast <- Warning: {}", msg.text);
1024 self.status_center.push_toast(msg);
1025 }
1026
1027 pub fn notify_progress(&mut self, text: impl Into<String>) {
1029 self.status_center.set_sticky_status(text, false);
1030 }
1031
1032 pub fn notify_sticky_error(&mut self, text: impl Into<String>) {
1034 self.status_center.set_sticky_status(text, true);
1035 }
1036
1037 pub fn notify_info(&mut self, text: impl Into<String>) {
1039 self.status_center.set_info_status(text);
1040 }
1041
1042 pub fn tick_status(&mut self) {
1049 if !self.providers.syncing.is_empty() {
1051 return;
1052 }
1053 if let Some(ref status) = self.status_center.status {
1054 if status.sticky {
1055 return;
1056 }
1057 let timeout_ms = status.timeout_ms();
1058 if timeout_ms != u64::MAX && status.created_at.elapsed().as_millis() as u64 > timeout_ms
1059 {
1060 log::debug!("footer status expired: {}", status.text);
1061 self.status_center.status = None;
1062 }
1063 }
1064 }
1065
1066 pub fn tick_toast(&mut self) {
1068 self.status_center.tick_toast();
1069 }
1070
1071 pub fn check_config_changed(&mut self) {
1075 if matches!(
1076 self.screen,
1077 Screen::AddHost
1078 | Screen::EditHost { .. }
1079 | Screen::ProviderForm { .. }
1080 | Screen::TunnelList { .. }
1081 | Screen::TunnelForm { .. }
1082 | Screen::HostDetail { .. }
1083 | Screen::SnippetPicker { .. }
1084 | Screen::SnippetForm { .. }
1085 | Screen::SnippetOutput { .. }
1086 | Screen::SnippetParamForm { .. }
1087 | Screen::FileBrowser { .. }
1088 | Screen::Containers { .. }
1089 | Screen::ConfirmDelete { .. }
1090 | Screen::ConfirmHostKeyReset { .. }
1091 | Screen::ConfirmPurgeStale { .. }
1092 | Screen::ConfirmImport { .. }
1093 | Screen::ConfirmVaultSign { .. }
1094 | Screen::TagPicker
1095 | Screen::BulkTagEditor
1096 | Screen::ThemePicker
1097 | Screen::WhatsNew(_)
1098 ) || self.tags.input.is_some()
1099 {
1100 return;
1101 }
1102 let current_mtime = reload_state::get_mtime(&self.reload.config_path);
1103 let changed = current_mtime != self.reload.last_modified
1104 || self
1105 .reload
1106 .include_mtimes
1107 .iter()
1108 .any(|(path, old_mtime)| reload_state::get_mtime(path) != *old_mtime)
1109 || self
1110 .reload
1111 .include_dir_mtimes
1112 .iter()
1113 .any(|(path, old_mtime)| reload_state::get_mtime(path) != *old_mtime);
1114 if changed {
1115 log::debug!(
1116 "[config] check_config_changed: mtime drift detected on {} -> reloading",
1117 self.reload.config_path.display()
1118 );
1119 if let Ok(new_config) = SshConfigFile::parse(&self.reload.config_path) {
1120 let before_aliases = self.snapshot_alias_set();
1121 self.hosts_state.ssh_config = new_config;
1122 self.hosts_state.undo_stack.clear();
1124 log::debug!(
1126 "[config] external config change: clearing {} ping result(s) + timestamps",
1127 self.ping.status.len()
1128 );
1129 self.ping.status.clear();
1130 self.ping.last_checked.clear();
1131 self.ping.filter_down_only = false;
1132 self.ping.checked_at = None;
1133 self.reload_hosts();
1134 self.reload.last_modified = current_mtime;
1135 self.reload.include_mtimes =
1136 reload_state::snapshot_include_mtimes(&self.hosts_state.ssh_config);
1137 self.reload.include_dir_mtimes =
1138 reload_state::snapshot_include_dir_mtimes(&self.hosts_state.ssh_config);
1139 let count = self.hosts_state.list.len();
1140 self.notify_background(crate::messages::config_reloaded(count));
1141 self.queue_new_aliases_since(&before_aliases);
1142 }
1143 }
1144 }
1145
1146 pub fn check_keys_changed(&mut self) {
1156 if self.demo_mode {
1157 return;
1158 }
1159 if matches!(
1160 self.screen,
1161 Screen::AddHost | Screen::EditHost { .. } | Screen::ProviderForm { .. }
1162 ) {
1163 return;
1164 }
1165 let Some(home) = dirs::home_dir() else {
1166 return;
1167 };
1168 let ssh_dir = home.join(".ssh");
1169 let current_dir_mtime = reload_state::get_mtime(&ssh_dir);
1170 let dir_changed = current_dir_mtime != self.reload.keys_dir_mtime;
1171 let files_changed = self
1172 .reload
1173 .key_file_mtimes
1174 .iter()
1175 .any(|(path, old)| reload_state::get_mtime(path) != *old);
1176 if !dir_changed && !files_changed {
1177 return;
1178 }
1179 log::debug!(
1180 "[purple] check_keys_changed: drift detected on {} (dir={} files={}) -> rescan",
1181 ssh_dir.display(),
1182 dir_changed,
1183 files_changed,
1184 );
1185 let previous = self.keys.list.len();
1186 self.scan_keys();
1187 let after = self.keys.list.len();
1188 if let Some(sel) = self.keys.list_state.selected() {
1191 if sel >= after {
1192 let next = after.checked_sub(1);
1193 self.keys.list_state.select(next);
1194 }
1195 } else if after > 0 {
1196 self.keys.list_state.select(Some(0));
1197 }
1198 if previous != after {
1199 log::debug!(
1200 "[purple] check_keys_changed: rescan {} -> {} keys",
1201 previous,
1202 after
1203 );
1204 }
1205 }
1206
1207 pub fn external_config_changed(&self) -> bool {
1216 let current_mtime = reload_state::get_mtime(&self.reload.config_path);
1217 current_mtime != self.reload.last_modified
1218 || self
1219 .reload
1220 .include_mtimes
1221 .iter()
1222 .any(|(path, old_mtime)| reload_state::get_mtime(path) != *old_mtime)
1223 || self
1224 .reload
1225 .include_dir_mtimes
1226 .iter()
1227 .any(|(path, old_mtime)| reload_state::get_mtime(path) != *old_mtime)
1228 }
1229
1230 pub fn update_last_modified(&mut self) {
1232 self.reload.last_modified = reload_state::get_mtime(&self.reload.config_path);
1233 self.reload.include_mtimes =
1234 reload_state::snapshot_include_mtimes(&self.hosts_state.ssh_config);
1235 self.reload.include_dir_mtimes =
1236 reload_state::snapshot_include_dir_mtimes(&self.hosts_state.ssh_config);
1237 }
1238
1239 pub fn has_any_vault_role(&self) -> bool {
1241 for host in &self.hosts_state.list {
1242 if host.vault_ssh.is_some() {
1243 return true;
1244 }
1245 }
1246 for section in &self.providers.config.sections {
1247 if !section.vault_role.is_empty() {
1248 return true;
1249 }
1250 }
1251 false
1252 }
1253
1254 pub fn poll_tunnels(&mut self) -> Vec<(String, String, bool)> {
1256 self.tunnels.poll()
1257 }
1258
1259 pub fn refresh_tunnel_bind_ports(&mut self) {
1264 let mut ports: Vec<(String, u16, u32)> = Vec::new();
1265 for (alias, tunnel) in &self.tunnels.active {
1266 let pid = tunnel.child.id();
1267 for rule in self.hosts_state.ssh_config.find_tunnel_directives(alias) {
1268 ports.push((alias.clone(), rule.bind_port, pid));
1269 }
1270 }
1271 self.tunnels.set_lsof_ports(ports);
1272 }
1273}
1274
1275pub(crate) fn cycle_selection(state: &mut ListState, len: usize, forward: bool) {
1277 if len == 0 {
1278 return;
1279 }
1280 let i = match state.selected() {
1281 Some(i) => {
1282 if forward {
1283 if i >= len - 1 { 0 } else { i + 1 }
1284 } else if i == 0 {
1285 len - 1
1286 } else {
1287 i - 1
1288 }
1289 }
1290 None => 0,
1291 };
1292 state.select(Some(i));
1293}
1294
1295pub(crate) fn page_down(state: &mut ListState, len: usize, page_size: usize) {
1297 if len == 0 {
1298 return;
1299 }
1300 let current = state.selected().unwrap_or(0);
1301 let next = (current + page_size).min(len - 1);
1302 state.select(Some(next));
1303}
1304
1305pub(crate) fn page_up(state: &mut ListState, len: usize, page_size: usize) {
1307 if len == 0 {
1308 return;
1309 }
1310 let current = state.selected().unwrap_or(0);
1311 let prev = current.saturating_sub(page_size);
1312 state.select(Some(prev));
1313}
1314
1315pub use jump::{
1319 ContainerHit, HostHit, JumpAction, JumpActionTarget, JumpHit, JumpMode, JumpState, RecentRef,
1320 RecentsFile, SnippetHit, SourceKind, TunnelHit,
1321};
1322
1323#[cfg(test)]
1327pub type PaletteCommand = JumpAction;
1328
1329static ALL_JUMP_ACTIONS: &[JumpAction] = &[
1336 JumpAction {
1337 key: 'a',
1338 key_str: "a",
1339 label: "Hosts: Add host",
1340 aliases: &["new", "create"],
1341 target: JumpActionTarget::Hosts,
1342 },
1343 JumpAction {
1344 key: 'A',
1345 key_str: "A",
1346 label: "Hosts: Add pattern",
1347 aliases: &["new pattern", "wildcard"],
1348 target: JumpActionTarget::Hosts,
1349 },
1350 JumpAction {
1351 key: 'e',
1352 key_str: "e",
1353 label: "Hosts: Edit host",
1354 aliases: &["modify", "change"],
1355 target: JumpActionTarget::Hosts,
1356 },
1357 JumpAction {
1358 key: 'd',
1359 key_str: "d",
1360 label: "Hosts: Delete host",
1361 aliases: &["remove", "rm"],
1362 target: JumpActionTarget::Hosts,
1363 },
1364 JumpAction {
1365 key: 'c',
1366 key_str: "c",
1367 label: "Hosts: Clone host",
1368 aliases: &["duplicate", "copy"],
1369 target: JumpActionTarget::Hosts,
1370 },
1371 JumpAction {
1372 key: 'u',
1373 key_str: "u",
1374 label: "Hosts: Undo delete",
1375 aliases: &["restore"],
1376 target: JumpActionTarget::Hosts,
1377 },
1378 JumpAction {
1379 key: 't',
1380 key_str: "t",
1381 label: "Hosts: Tag host",
1382 aliases: &["label", "category"],
1383 target: JumpActionTarget::Hosts,
1384 },
1385 JumpAction {
1386 key: 'i',
1387 key_str: "i",
1388 label: "Hosts: Show all directives",
1389 aliases: &["raw", "config", "settings"],
1390 target: JumpActionTarget::Hosts,
1391 },
1392 JumpAction {
1393 key: 'y',
1394 key_str: "y",
1395 label: "Clipboard: Copy SSH command",
1396 aliases: &["yank"],
1397 target: JumpActionTarget::Hosts,
1398 },
1399 JumpAction {
1400 key: 'x',
1401 key_str: "x",
1402 label: "Clipboard: Copy config block",
1403 aliases: &["yank config"],
1404 target: JumpActionTarget::Hosts,
1405 },
1406 JumpAction {
1407 key: 'X',
1408 key_str: "X",
1409 label: "Hosts: Purge stale hosts",
1410 aliases: &["clean", "cleanup"],
1411 target: JumpActionTarget::Hosts,
1412 },
1413 JumpAction {
1414 key: 'F',
1415 key_str: "F",
1416 label: "Files: Browse remote files",
1417 aliases: &[
1418 "browse",
1419 "filesystem",
1420 "scp",
1421 "sftp",
1422 "transfer",
1423 "explorer",
1424 "open",
1425 ],
1426 target: JumpActionTarget::Hosts,
1427 },
1428 JumpAction {
1429 key: 'C',
1430 key_str: "C",
1431 label: "Containers: List containers",
1432 aliases: &["docker", "podman", "ps", "open"],
1433 target: JumpActionTarget::Hosts,
1434 },
1435 JumpAction {
1436 key: 'K',
1437 key_str: "K",
1438 label: "Keys: Manage SSH keys",
1439 aliases: &["identity", "id_rsa", "id_ed25519", "private key", "open"],
1440 target: JumpActionTarget::Hosts,
1441 },
1442 JumpAction {
1443 key: 'S',
1444 key_str: "S",
1445 label: "Providers: Manage cloud sync",
1446 aliases: &["cloud", "aws", "gcp", "azure", "hetzner", "sync", "open"],
1447 target: JumpActionTarget::Hosts,
1448 },
1449 JumpAction {
1450 key: 'V',
1451 key_str: "V",
1452 label: "Vault: Sign certificate",
1453 aliases: &["hashicorp", "ssh cert", "vault ssh"],
1454 target: JumpActionTarget::Hosts,
1455 },
1456 JumpAction {
1457 key: 'I',
1458 key_str: "I",
1459 label: "Hosts: Import from known_hosts",
1460 aliases: &["known", "import"],
1461 target: JumpActionTarget::Hosts,
1462 },
1463 JumpAction {
1464 key: 'm',
1465 key_str: "m",
1466 label: "Settings: Switch theme",
1467 aliases: &["color", "appearance", "dark", "light"],
1468 target: JumpActionTarget::Hosts,
1469 },
1470 JumpAction {
1471 key: 'n',
1472 key_str: "n",
1473 label: "Help: What's new",
1474 aliases: &["changelog", "news", "release notes"],
1475 target: JumpActionTarget::Hosts,
1476 },
1477 JumpAction {
1478 key: 'r',
1479 key_str: "r",
1480 label: "Snippets: Run snippet",
1481 aliases: &["execute", "command"],
1482 target: JumpActionTarget::Hosts,
1483 },
1484 JumpAction {
1485 key: 'R',
1486 key_str: "R",
1487 label: "Snippets: Run on all visible",
1488 aliases: &["batch", "execute all"],
1489 target: JumpActionTarget::Hosts,
1490 },
1491 JumpAction {
1492 key: 'p',
1493 key_str: "p",
1494 label: "Hosts: Ping host",
1495 aliases: &["health", "check"],
1496 target: JumpActionTarget::Hosts,
1497 },
1498 JumpAction {
1499 key: 'P',
1500 key_str: "P",
1501 label: "Hosts: Ping all hosts",
1502 aliases: &["health all"],
1503 target: JumpActionTarget::Hosts,
1504 },
1505 JumpAction {
1506 key: '!',
1507 key_str: "!",
1508 label: "Hosts: Show down only",
1509 aliases: &["filter offline", "down only"],
1510 target: JumpActionTarget::Hosts,
1511 },
1512 JumpAction {
1516 key: 'T',
1517 key_str: "T",
1518 label: "Tunnels: Manage tunnels",
1519 aliases: &["forward", "port forward", "ssh -L", "ssh -R", "open"],
1520 target: JumpActionTarget::Hosts,
1521 },
1522 JumpAction {
1523 key: 'a',
1524 key_str: "a",
1525 label: "Tunnels: Add tunnel",
1526 aliases: &["new tunnel", "create tunnel", "forward"],
1527 target: JumpActionTarget::Tunnels,
1528 },
1529 JumpAction {
1530 key: 'e',
1531 key_str: "e",
1532 label: "Tunnels: Edit tunnel",
1533 aliases: &["modify tunnel"],
1534 target: JumpActionTarget::Tunnels,
1535 },
1536 JumpAction {
1537 key: 'd',
1538 key_str: "d",
1539 label: "Tunnels: Delete tunnel",
1540 aliases: &["remove tunnel"],
1541 target: JumpActionTarget::Tunnels,
1542 },
1543 JumpAction {
1544 key: 's',
1545 key_str: "s",
1546 label: "Tunnels: Sort",
1547 aliases: &["order tunnels"],
1548 target: JumpActionTarget::Tunnels,
1549 },
1550 JumpAction {
1551 key: 'R',
1552 key_str: "R",
1553 label: "Containers: Refresh all hosts",
1554 aliases: &["reload containers", "fetch", "rescan"],
1555 target: JumpActionTarget::Containers,
1556 },
1557 JumpAction {
1558 key: 's',
1559 key_str: "s",
1560 label: "Containers: Cycle sort",
1561 aliases: &["order containers", "sort by host", "sort by name"],
1562 target: JumpActionTarget::Containers,
1563 },
1564 JumpAction {
1565 key: 'v',
1566 key_str: "v",
1567 label: "Containers: Toggle detail panel",
1568 aliases: &["show details", "hide details", "compact view"],
1569 target: JumpActionTarget::Containers,
1570 },
1571 JumpAction {
1575 key: 'c',
1576 key_str: "c",
1577 label: "Keys: Copy public key",
1578 aliases: &["yank", "clipboard", "pubkey"],
1579 target: JumpActionTarget::Keys,
1580 },
1581 JumpAction {
1582 key: 'p',
1583 key_str: "p",
1584 label: "Keys: Push to host",
1585 aliases: &["install", "ssh-copy-id", "deploy", "upload"],
1586 target: JumpActionTarget::Keys,
1587 },
1588 JumpAction {
1589 key: 'V',
1590 key_str: "V",
1591 label: "Keys: Sign Vault SSH certificate",
1592 aliases: &["vault", "renew cert", "sign"],
1593 target: JumpActionTarget::Keys,
1594 },
1595];
1596
1597pub const PALETTE_PER_SECTION_CAP: usize = 32;
1602
1603pub fn parse_query_scope(query: &str) -> (Option<QueryScope>, &str) {
1606 if let Some((prefix, rest)) = query.split_once(':') {
1607 let scope = match prefix.trim() {
1608 "user" => Some(QueryScope::User),
1609 "host" => Some(QueryScope::Hostname),
1610 "proxy" => Some(QueryScope::ProxyJump),
1611 "vault" => Some(QueryScope::VaultSsh),
1612 "tag" => Some(QueryScope::Tag),
1613 _ => None,
1614 };
1615 if scope.is_some() {
1616 return (scope, rest.trim_start());
1617 }
1618 }
1619 (None, query)
1620}
1621
1622#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1623pub enum QueryScope {
1624 User,
1625 Hostname,
1626 ProxyJump,
1627 VaultSsh,
1628 Tag,
1629}
1630
1631fn preview(s: &str, max: usize) -> String {
1633 let s = s.replace('\n', " ");
1634 let chars: Vec<char> = s.chars().collect();
1635 if chars.len() <= max {
1636 s
1637 } else {
1638 let mut out: String = chars.iter().take(max.saturating_sub(3)).collect();
1639 out.push_str("...");
1640 out
1641 }
1642}
1643
1644fn scoped_haystacks_for(hit: &JumpHit, scope: Option<QueryScope>) -> Option<Vec<&str>> {
1649 let scope = scope?;
1650 match (hit, scope) {
1651 (JumpHit::Host(h), QueryScope::User) if !h.user.is_empty() => Some(vec![&h.user]),
1652 (JumpHit::Host(h), QueryScope::Hostname) if !h.hostname.is_empty() => {
1653 Some(vec![&h.hostname])
1654 }
1655 (JumpHit::Host(h), QueryScope::ProxyJump) if !h.proxy_jump.is_empty() => {
1656 Some(vec![&h.proxy_jump])
1657 }
1658 (JumpHit::Host(h), QueryScope::VaultSsh) => h.vault_ssh.as_deref().map(|s| vec![s]),
1659 (JumpHit::Host(h), QueryScope::Tag) => Some(h.tags.iter().map(|t| t.as_str()).collect()),
1660 _ => None,
1662 }
1663}
1664
1665pub fn match_source_for_host(host: &HostHit, query: &str) -> Option<MatchSource> {
1670 if query.is_empty() {
1671 return None;
1672 }
1673 let q = query.to_lowercase();
1674 let alias_hit = host.alias.to_lowercase().contains(&q);
1675 let hostname_hit = host.hostname.to_lowercase().contains(&q);
1676 if alias_hit || hostname_hit {
1677 return None;
1678 }
1679 if !host.user.is_empty() && host.user.to_lowercase().contains(&q) {
1680 return Some(MatchSource::User);
1681 }
1682 if !host.proxy_jump.is_empty() && host.proxy_jump.to_lowercase().contains(&q) {
1683 return Some(MatchSource::ProxyJump);
1684 }
1685 if let Some(role) = &host.vault_ssh {
1686 if role.to_lowercase().contains(&q) {
1687 return Some(MatchSource::VaultSsh);
1688 }
1689 }
1690 if !host.identity_file.is_empty() && host.identity_file.to_lowercase().contains(&q) {
1691 return Some(MatchSource::IdentityFile);
1692 }
1693 None
1694}
1695
1696#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1697pub enum MatchSource {
1698 User,
1699 ProxyJump,
1700 VaultSsh,
1701 IdentityFile,
1702}
1703
1704fn kind_rank(k: SourceKind) -> u8 {
1705 match k {
1706 SourceKind::Host => 0,
1707 SourceKind::Tunnel => 1,
1708 SourceKind::Container => 2,
1709 SourceKind::Snippet => 3,
1710 SourceKind::Action => 4,
1711 }
1712}
1713
1714fn restore_selection(hits: &[JumpHit], prior: Option<&RecentRef>, fallback: usize) -> usize {
1719 if let Some(target) = prior {
1720 if let Some(idx) = hits.iter().position(|h| &h.identity() == target) {
1721 return idx;
1722 }
1723 }
1724 fallback.min(hits.len().saturating_sub(1))
1725}
1726
1727impl JumpAction {
1728 #[cfg(test)]
1729 pub fn all() -> &'static [JumpAction] {
1730 ALL_JUMP_ACTIONS
1731 }
1732
1733 pub fn for_mode(_mode: JumpMode) -> &'static [JumpAction] {
1737 ALL_JUMP_ACTIONS
1738 }
1739}
1740
1741#[cfg(test)]
1742mod tests;