Skip to main content

purple_ssh/
messages.rs

1//! Centralized user-facing messages.
2//!
3//! Every string the user can see (toasts, CLI output, error messages) lives
4//! here. Handler, CLI and UI code reference these constants and functions
5//! instead of inlining string literals. This makes copy consistent, auditable
6//! and future-proof for i18n.
7
8// ── General / shared ────────────────────────────────────────────────
9
10pub const FAILED_TO_SAVE: &str = "Failed to save";
11pub fn failed_to_save(e: &impl std::fmt::Display) -> String {
12    format!("{}: {}", FAILED_TO_SAVE, e)
13}
14
15pub const CONFIG_CHANGED_EXTERNALLY: &str =
16    "Config changed externally. Press Esc and re-open to pick up changes.";
17
18// ── Demo mode ───────────────────────────────────────────────────────
19
20pub const DEMO_CONNECTION_DISABLED: &str = "Demo mode. Connection disabled.";
21pub const DEMO_SYNC_DISABLED: &str = "Demo mode. Sync disabled.";
22pub const DEMO_TUNNELS_DISABLED: &str = "Demo mode. Tunnels disabled.";
23pub const DEMO_VAULT_SIGNING_DISABLED: &str = "Demo mode. Vault SSH signing disabled.";
24pub const DEMO_FILE_BROWSER_DISABLED: &str = "Demo mode. File browser disabled.";
25pub const DEMO_CONTAINER_REFRESH_DISABLED: &str = "Demo mode. Container refresh disabled.";
26pub const DEMO_CONTAINER_ACTIONS_DISABLED: &str = "Demo mode. Container actions disabled.";
27pub const DEMO_EXECUTION_DISABLED: &str = "Demo mode. Execution disabled.";
28pub const DEMO_PROVIDER_CHANGES_DISABLED: &str = "Demo mode. Provider config changes disabled.";
29
30// ── Stale host ──────────────────────────────────────────────────────
31
32/// Compose a "Stale host." warning with an optional hint clause.
33/// Trims the hint, drops a trailing period to avoid doubling, and uses
34/// a space separator so the result reads as one sentence. With an empty
35/// hint the bare "Stale host." remains.
36pub fn stale_host(hint: &str) -> String {
37    let trimmed = hint.trim().trim_end_matches('.');
38    if trimmed.is_empty() {
39        "Stale host.".to_string()
40    } else {
41        format!("Stale host. {}.", trimmed)
42    }
43}
44
45// ── Host list ───────────────────────────────────────────────────────
46
47pub fn copied_ssh_command(alias: &str) -> String {
48    format!("Copied SSH command for {}.", alias)
49}
50
51pub fn copied_config_block(alias: &str) -> String {
52    format!("Copied config block for {}.", alias)
53}
54
55pub fn showing_unreachable(count: usize) -> String {
56    format!(
57        "Showing {} unreachable host{}.",
58        count,
59        if count == 1 { "" } else { "s" }
60    )
61}
62
63pub fn sorted_by(label: &str) -> String {
64    format!("Sorted by {}.", label)
65}
66
67pub fn sorted_by_save_failed(label: &str, e: &impl std::fmt::Display) -> String {
68    format!("Sorted by {}. (save failed: {})", label, e)
69}
70
71pub fn grouped_by(label: &str) -> String {
72    format!("Grouped by {}.", label)
73}
74
75pub fn grouped_by_save_failed(label: &str, e: &impl std::fmt::Display) -> String {
76    format!("Grouped by {}. (save failed: {})", label, e)
77}
78
79pub const UNGROUPED: &str = "Ungrouped.";
80
81pub fn ungrouped_save_failed(e: &impl std::fmt::Display) -> String {
82    format!("Ungrouped. (save failed: {})", e)
83}
84
85pub const GROUPED_BY_TAG: &str = "Grouped by tag.";
86
87pub fn grouped_by_tag_save_failed(e: &impl std::fmt::Display) -> String {
88    format!("Grouped by tag. (save failed: {})", e)
89}
90
91pub fn host_restored(alias: &str) -> String {
92    format!("{} is back from the dead.", alias)
93}
94
95pub fn restored_tags(count: usize) -> String {
96    format!(
97        "Restored tags on {} host{}.",
98        count,
99        if count == 1 { "" } else { "s" }
100    )
101}
102
103pub const NOTHING_TO_UNDO: &str = "Nothing to undo.";
104pub const NO_IMPORTABLE_HOSTS: &str = "No importable hosts in known_hosts.";
105pub const NO_STALE_HOSTS: &str = "No stale hosts.";
106pub const NO_HOST_SELECTED: &str = "No host selected.";
107pub const NO_HOSTS_TO_RUN: &str = "No hosts to run on.";
108pub const NO_HOSTS_TO_TAG: &str = "No hosts to tag.";
109pub const PING_FIRST: &str = "Ping first (p/P), then filter with !.";
110pub const PINGING_ALL: &str = "Pinging all the things...";
111pub const ESC_QUIT_HINT: &str = "Nothing to cancel. Press q to quit.";
112
113pub fn included_file_edit(name: &str) -> String {
114    format!("{} is in an included file. Edit it there.", name)
115}
116
117pub fn included_file_delete(name: &str) -> String {
118    format!("{} is in an included file. Delete it there.", name)
119}
120
121pub fn included_file_clone(name: &str) -> String {
122    format!("{} is in an included file. Clone it there.", name)
123}
124
125pub fn included_host_lives_in(alias: &str, path: &impl std::fmt::Display) -> String {
126    format!("{} lives in {}. Edit it there.", alias, path)
127}
128
129pub fn included_host_clone_there(alias: &str, path: &impl std::fmt::Display) -> String {
130    format!("{} lives in {}. Clone it there.", alias, path)
131}
132
133pub fn included_host_tag_there(alias: &str, path: &impl std::fmt::Display) -> String {
134    format!("{} is included from {}. Tag it there.", alias, path)
135}
136
137pub const HOST_NOT_FOUND_IN_CONFIG: &str = "Host not found in config.";
138
139// ── Host form ───────────────────────────────────────────────────────
140
141pub const SMART_PARSED: &str = "Smart-parsed that for you. Check the fields.";
142pub const LOOKS_LIKE_ADDRESS: &str = "Looks like an address. Suggested as Host.";
143
144// ── Form validation (HostForm) ──────────────────────────────────────
145//
146// Surfaced via `notify_error(msg)` after `HostForm::validate()`. All
147// strings live here so the central message audit (`check-messages.sh`)
148// covers them and so the wording stays consistent with the rest of the
149// TUI copy.
150
151pub const HOST_ALIAS_EMPTY: &str = "Alias can't be empty. Every host needs a name!";
152pub const HOST_PATTERN_EMPTY: &str = "Pattern can't be empty.";
153pub const HOST_PATTERN_NEEDS_WILDCARD: &str =
154    "Pattern needs a wildcard (*, ?, [) or multiple hosts.";
155pub const HOST_ALIAS_WHITESPACE: &str = "Alias can't contain whitespace. Keep it simple.";
156pub const HOST_ALIAS_HASH: &str =
157    "Alias can't contain '#'. That's a comment character in SSH config.";
158pub const HOST_ALIAS_PATTERN_CHARS: &str =
159    "Alias can't contain pattern characters. That creates a match pattern, not a host.";
160pub const HOST_HOSTNAME_EMPTY: &str = "Hostname can't be empty. Where should we connect to?";
161pub const HOST_HOSTNAME_WHITESPACE: &str = "Hostname can't contain whitespace.";
162pub const HOST_PORT_INVALID: &str = "That's not a port number. Ports are 1-65535, not poetry.";
163pub const HOST_PORT_ZERO: &str = "Port 0? Bold choice, but no. Try 1-65535.";
164pub const HOST_VAULT_ROLE_INVALID: &str = "Vault SSH role: only letters, digits, /, _ and - \
165     are allowed (e.g. ssh-client-signer/sign/my-role).";
166pub const HOST_VAULT_ADDR_INVALID: &str = "Vault SSH address: must be a non-empty URL \
167     without spaces or control characters (e.g. http://127.0.0.1:8200).";
168
169/// Long-form "{} contains control characters." used by `HostForm::validate`
170/// where the toast doubles as guidance ("that's not going to work").
171pub fn field_control_chars(name: &str) -> String {
172    format!(
173        "{} contains control characters. That's not going to work.",
174        name
175    )
176}
177
178// ── Form validation (TunnelForm) ────────────────────────────────────
179
180pub const TUNNEL_BIND_PORT_INVALID: &str = "Bind port must be 1-65535.";
181pub const TUNNEL_BIND_PORT_ZERO: &str = "Bind port can't be 0.";
182pub const TUNNEL_REMOTE_HOST_EMPTY: &str = "Remote host can't be empty.";
183pub const TUNNEL_REMOTE_HOST_SPACES: &str = "Remote host can't contain spaces.";
184pub const TUNNEL_REMOTE_PORT_INVALID: &str = "Remote port must be 1-65535.";
185pub const TUNNEL_REMOTE_PORT_ZERO: &str = "Remote port can't be 0.";
186
187/// Short form of `field_control_chars` used by TunnelForm where the
188/// toast is purely informational and does not need the guidance suffix.
189pub fn field_control_chars_short(name: &str) -> String {
190    format!("{} contains control characters.", name)
191}
192
193// ── Form validation (SnippetForm + snippet store) ───────────────────
194
195pub const SNIPPET_NAME_EMPTY: &str = "Snippet name cannot be empty.";
196pub const SNIPPET_NAME_WHITESPACE: &str =
197    "Snippet name cannot have leading or trailing whitespace.";
198pub const SNIPPET_NAME_INVALID_CHARS: &str = "Snippet name cannot contain #, [ or ].";
199pub const SNIPPET_NAME_CONTROL_CHARS: &str = "Snippet name cannot contain control characters.";
200pub const SNIPPET_COMMAND_EMPTY: &str = "Command cannot be empty.";
201pub const SNIPPET_COMMAND_CONTROL_CHARS: &str = "Command cannot contain control characters.";
202pub const SNIPPET_DESCRIPTION_CONTROL_CHARS: &str = "Description contains control characters.";
203
204// ── Host CRUD (add / edit) ──────────────────────────────────────────
205
206pub fn pattern_already_exists(alias: &str) -> String {
207    format!("Pattern '{}' already exists.", alias)
208}
209
210pub fn host_alias_already_exists(alias: &str) -> String {
211    format!("'{}' already exists. Aliases must be unique.", alias)
212}
213
214pub const PATTERN_NO_LONGER_EXISTS: &str = "Pattern no longer exists.";
215pub const HOST_NO_LONGER_EXISTS: &str = "Host no longer exists.";
216
217pub fn cert_path_resolve_failed(e: &impl std::fmt::Display) -> String {
218    format!("Failed to resolve cert path: {}", e)
219}
220
221/// Toast shown after a host is added through the TUI form. The CLI
222/// `purple add` flow shares this string via `messages::cli::welcome`.
223pub fn welcome_aboard(alias: &str) -> String {
224    format!("Welcome aboard, {}!", alias)
225}
226
227// ── Bulk tag editor ─────────────────────────────────────────────────
228
229pub const BULK_TAG_NO_HOSTS_SELECTED: &str = "No hosts selected.";
230
231// ── Confirm delete ──────────────────────────────────────────────────
232
233pub fn goodbye_host(alias: &str) -> String {
234    format!("Goodbye, {}. We barely knew ye. (u to undo)", alias)
235}
236
237pub fn host_not_found(alias: &str) -> String {
238    format!("Host '{}' not found.", alias)
239}
240
241/// Toast after stripping an alias token from a shared `Host` line. Undo is
242/// not offered because re-inserting a whole block would not reverse a token
243/// strip (sibling aliases and their directives stay in place).
244pub fn siblings_stripped(alias: &str, sibling_count: usize) -> String {
245    if sibling_count == 1 {
246        format!(
247            "Stripped {}. 1 sibling alias kept its shared config.",
248            alias
249        )
250    } else {
251        format!(
252            "Stripped {}. {} sibling aliases kept their shared config.",
253            alias, sibling_count
254        )
255    }
256}
257
258/// One-line note rendered inside the confirm-delete dialog when the target
259/// alias shares its `Host` block with siblings. Explains that the other
260/// tokens survive.
261pub fn confirm_delete_siblings_note(siblings: &[String]) -> String {
262    let shown: Vec<&str> = siblings.iter().take(3).map(String::as_str).collect();
263    let tail = if siblings.len() > shown.len() {
264        format!(" +{} more", siblings.len() - shown.len())
265    } else {
266        String::new()
267    };
268    format!("Siblings kept: {}{}", shown.join(", "), tail)
269}
270
271pub fn cert_cleanup_warning(path: &impl std::fmt::Display, e: &impl std::fmt::Display) -> String {
272    format!("Warning: failed to clean up Vault SSH cert {}: {}", path, e)
273}
274
275// ── Clone ───────────────────────────────────────────────────────────
276
277pub const CLONED_VAULT_CLEARED: &str = "Cloned. Vault SSH role cleared on copy.";
278
279// ── Tunnels ─────────────────────────────────────────────────────────
280
281pub const TUNNEL_REMOVED: &str = "Tunnel removed.";
282pub const TUNNEL_SAVED: &str = "Tunnel saved.";
283pub const TUNNEL_NOT_FOUND: &str = "Tunnel not found in config.";
284pub const TUNNEL_INCLUDED_READ_ONLY: &str = "Included host. Tunnels are read-only.";
285pub const TUNNEL_ORIGINAL_NOT_FOUND: &str = "Original tunnel not found in config.";
286pub const TUNNEL_LIST_CHANGED: &str = "Tunnel list changed externally. Press Esc and re-open.";
287pub const TUNNEL_DUPLICATE: &str = "Duplicate tunnel already configured.";
288pub const TUNNEL_NO_EDITABLE_HOSTS: &str = "No editable hosts. Add a host first.";
289pub const TUNNEL_HOST_PICKER_NO_MATCH: &str = "No matches.";
290
291/// Shown when the user opens a picker that needs hosts (containers `a`,
292/// keys `p` push, etc.) but no hosts exist in ~/.ssh/config yet.
293/// Identical "Add a host first" closing across surfaces so the user
294/// reads the same prerequisite regardless of which picker they tried.
295pub const PICKER_NO_HOSTS: &str = "No hosts yet. Add a host first.";
296
297pub fn tunnel_stopped(alias: &str) -> String {
298    format!("Tunnel for {} stopped.", alias)
299}
300
301pub fn tunnel_started(alias: &str) -> String {
302    format!("Tunnel for {} started.", alias)
303}
304
305pub fn tunnel_start_failed(e: &impl std::fmt::Display) -> String {
306    format!("Failed to start tunnel: {}", e)
307}
308
309// ── Ping ────────────────────────────────────────────────────────────
310
311pub fn pinging_host(alias: &str, show_hint: bool) -> String {
312    if show_hint {
313        format!("Pinging {}... (Shift+P pings all)", alias)
314    } else {
315        format!("Pinging {}...", alias)
316    }
317}
318
319pub fn bastion_not_found(alias: &str) -> String {
320    format!("Bastion {} not found in config.", alias)
321}
322
323// ── Providers ───────────────────────────────────────────────────────
324
325pub fn provider_removed(display_name: &str) -> String {
326    format!(
327        "Removed {} configuration. Synced hosts remain in your SSH config.",
328        display_name
329    )
330}
331
332pub fn label_invalid(reason: &str) -> String {
333    format!("Invalid name: {}", reason)
334}
335
336pub const LABEL_MUST_DIFFER: &str = "The two names must be different.";
337
338pub const LABEL_MIGRATION_FIELD_CURRENT: &str = " Name for your current config ";
339pub const LABEL_MIGRATION_FIELD_NEW: &str = " Name for the new config ";
340
341pub const EXPAND_TO_REMOVE_CONFIG: &str =
342    "Expand the provider and pick a specific config to remove.";
343
344pub fn provider_not_configured(display_name: &str) -> String {
345    format!("{} is not configured. Nothing to remove.", display_name)
346}
347
348pub fn provider_configure_first(display_name: &str) -> String {
349    format!("Configure {} first. Press Enter to set up.", display_name)
350}
351
352pub fn provider_saved_syncing(display_name: &str) -> String {
353    format!("Saved {} configuration. Syncing...", display_name)
354}
355
356pub fn provider_saved(display_name: &str) -> String {
357    format!("Saved {} configuration.", display_name)
358}
359
360pub fn no_stale_hosts_for(display_name: &str) -> String {
361    format!("No stale hosts for {}.", display_name)
362}
363
364pub fn contains_control_chars(name: &str) -> String {
365    format!("{} contains control characters.", name)
366}
367
368pub const TOKEN_FORMAT_AWS: &str = "Token format: AccessKeyId:SecretAccessKey";
369pub const URL_REQUIRED_PROXMOX: &str = "URL is required for Proxmox VE.";
370pub const PROJECT_REQUIRED_GCP: &str = "Project ID can't be empty. Set your GCP project ID.";
371pub const COMPARTMENT_REQUIRED_OCI: &str =
372    "Compartment can't be empty. Set your OCI compartment OCID.";
373pub const REGIONS_REQUIRED_AWS: &str = "Select at least one AWS region.";
374pub const ZONES_REQUIRED_SCALEWAY: &str = "Select at least one Scaleway zone.";
375pub const SUBSCRIPTIONS_REQUIRED_AZURE: &str = "Enter at least one Azure subscription ID.";
376pub const ALIAS_PREFIX_INVALID: &str =
377    "Alias prefix can't contain spaces or pattern characters (*, ?, [, !).";
378pub const USER_NO_WHITESPACE: &str = "User can't contain whitespace.";
379pub const VAULT_ROLE_FORMAT: &str = "Vault SSH role must be in the form <mount>/sign/<role>.";
380
381pub const PROVIDER_CONFIG_CHANGED_EXTERNALLY: &str =
382    "Provider config changed externally. Press Esc and re-open to pick up changes.";
383pub const PROVIDER_URL_REQUIRES_HTTPS: &str =
384    "URL must start with https://. Toggle Verify TLS off for self-signed certificates.";
385pub const PROVIDER_TOKEN_REQUIRED_GCP: &str =
386    "Token can't be empty. Provide a service account JSON key file path or access token.";
387pub const PROVIDER_TOKEN_REQUIRED_ORACLE: &str =
388    "Token can't be empty. Provide the path to your OCI config file (e.g. ~/.oci/config).";
389
390pub fn provider_token_required(display_name: &str) -> String {
391    format!(
392        "Token can't be empty. Grab one from your {} dashboard.",
393        display_name
394    )
395}
396
397pub fn azure_subscription_id_invalid(sub: &str) -> String {
398    format!(
399        "Invalid subscription ID '{}'. Expected UUID format \
400         (e.g. 12345678-1234-1234-1234-123456789012).",
401        sub
402    )
403}
404
405// ── Vault SSH ───────────────────────────────────────────────────────
406
407pub const VAULT_SIGNING_CANCELLED: &str = "Vault SSH signing cancelled.";
408
409/// Sticky error shown when bulk signing hits 3 consecutive failures and
410/// gives up. `failed` is the running failure count; `last_error` carries
411/// the scrubbed Vault stderr so the user can act (run `vault login`,
412/// fix the address, etc.).
413pub fn vault_signing_aborted(failed: u32, last_error: Option<&str>) -> String {
414    format!(
415        "Vault SSH signing aborted after {} consecutive failures. Press V to retry. Last error: {}",
416        failed,
417        last_error.unwrap_or("unknown")
418    )
419}
420
421/// Status line shown after a bulk Vault SSH sign run completes. Combines
422/// signed/failed/skipped counters into one line, with the first error
423/// inlined when there's room. Single-host sign runs show only the error
424/// (no stats prefix) because the counter would just be noise.
425/// Status string shown after a successful bulk tag apply. Returns an
426/// empty string when nothing was changed and nothing was skipped, so the
427/// caller can detect a no-op and skip setting a status.
428pub fn bulk_tag_apply_status(
429    changed_hosts: usize,
430    added: usize,
431    removed: usize,
432    skipped_included: usize,
433) -> String {
434    let mut parts: Vec<String> = Vec::new();
435    if changed_hosts > 0 {
436        let host_word = if changed_hosts == 1 { "" } else { "s" };
437        let mut head = format!("Updated {} host{}", changed_hosts, host_word);
438        let mut delta = Vec::new();
439        if added > 0 {
440            delta.push(format!("+{}", added));
441        }
442        if removed > 0 {
443            delta.push(format!("-{}", removed));
444        }
445        if !delta.is_empty() {
446            head = format!("{} ({})", head, delta.join(" "));
447        }
448        parts.push(head);
449    }
450    if skipped_included > 0 {
451        let file_word = if skipped_included == 1 { "" } else { "s" };
452        parts.push(format!(
453            "skipped {} in include file{}",
454            skipped_included, file_word
455        ));
456    }
457    parts.join(". ")
458}
459
460pub fn vault_sign_summary(
461    signed: u32,
462    failed: u32,
463    skipped: u32,
464    first_error: Option<&str>,
465) -> String {
466    let total = signed + failed + skipped;
467    let cert_word = if total == 1 {
468        "certificate"
469    } else {
470        "certificates"
471    };
472    if failed > 0 {
473        if let Some(err) = first_error {
474            if total == 1 {
475                return err.to_string();
476            }
477            format!(
478                "Signed {} of {} {}. {} failed: {}",
479                signed, total, cert_word, failed, err
480            )
481        } else {
482            format!(
483                "Signed {} of {} {}. {} failed",
484                signed, total, cert_word, failed
485            )
486        }
487    } else if skipped > 0 && signed == 0 {
488        format!(
489            "All {} {} already valid. Nothing to sign.",
490            total, cert_word
491        )
492    } else if skipped > 0 {
493        format!(
494            "Signed {} of {} {}. {} already valid.",
495            signed, total, cert_word, skipped
496        )
497    } else {
498        format!("Signed {} of {} {}.", signed, total, cert_word)
499    }
500}
501pub const VAULT_NO_ROLE_CONFIGURED: &str = "No Vault SSH role configured. Set one in the host form \
502     (Vault SSH role field) or on a provider for shared defaults.";
503pub const VAULT_NO_HOSTS_WITH_ROLE: &str = "No hosts with a Vault SSH role configured.";
504pub const VAULT_ALL_CERTS_VALID: &str = "All Vault SSH certificates are still valid.";
505pub const VAULT_NO_ADDRESS: &str = "No Vault address set. Edit the host (e) or provider \
506     and fill in the Vault SSH Address field.";
507
508pub fn vault_error(msg: &str) -> String {
509    format!("Vault SSH: {}", msg)
510}
511
512pub fn vault_signed(alias: &str) -> String {
513    format!("Signed Vault SSH cert for {}", alias)
514}
515
516pub fn vault_sign_failed(alias: &str, message: &str) -> String {
517    format!("Vault SSH: failed to sign {}: {}", alias, message)
518}
519
520pub fn vault_signing_progress(spinner: &str, done: usize, total: usize, alias: &str) -> String {
521    format!(
522        "{} Signing {}/{}: {} (V to cancel)",
523        spinner, done, total, alias
524    )
525}
526
527pub fn vault_cert_saved_host_gone(alias: &str) -> String {
528    format!(
529        "Vault SSH cert saved for {} but host no longer in config \
530         (renamed or deleted). CertificateFile NOT written.",
531        alias
532    )
533}
534
535pub fn vault_spawn_failed(e: &impl std::fmt::Display) -> String {
536    format!("Vault SSH: failed to spawn signing thread: {}", e)
537}
538
539pub fn vault_cert_check_failed(alias: &str, message: &str) -> String {
540    format!("Cert check failed for {}: {}", alias, message)
541}
542
543pub fn vault_role_set(role: &str) -> String {
544    format!("Vault SSH role set to {}.", role)
545}
546
547/// Toast shown after a successful pre-connect signing for a single host.
548/// Distinct from `vault_signed` (used by bulk sign and form-submit) so the
549/// connect path can mention that the cert was signed *as part of* connecting.
550pub fn vault_signed_pre_connect(alias: &str) -> String {
551    format!("Signed Vault SSH cert for {}.", alias)
552}
553
554/// Toast shown after a successful pre-connect signing covered multiple
555/// chained hosts (target + ProxyJump hops). The `count` includes only hosts
556/// that actually got a fresh cert; hosts whose cert was already valid are
557/// excluded.
558pub fn vault_signed_pre_connect_chain(target: &str, count: usize) -> String {
559    if count <= 1 {
560        format!("Signed Vault SSH cert for {}.", target)
561    } else {
562        format!("Signed Vault SSH certs for {} ({} hosts).", target, count)
563    }
564}
565
566/// Toast shown when pre-connect signing failed for a host. Includes the
567/// scrubbed Vault error so the user can act (run `vault login`, fix the
568/// address, etc.). Distinct from `vault_sign_failed` so the wording can
569/// reflect the connect context without breaking bulk-sign callers.
570pub fn vault_sign_failed_pre_connect(alias: &str, message: &str) -> String {
571    format!("Vault SSH signing failed for {}: {}", alias, message)
572}
573
574/// Toast shown when resolving the public key path for a Vault sign call
575/// failed (missing pubkey, non-UTF8 path, etc.). Surfaced at the connect
576/// step before any Vault round-trip happens.
577pub fn vault_cert_pubkey_resolve_failed(e: &impl std::fmt::Display) -> String {
578    format!("Vault SSH cert failed: {}", e)
579}
580
581/// Stderr warning emitted when a cert was signed but the matching host
582/// block is no longer present (renamed or deleted between the connect
583/// keypress and the signing call). The cert is still written to disk;
584/// the user just has no `CertificateFile` directive pointing at it.
585pub fn vault_cert_host_block_missing(alias: &str, cert_path: &std::path::Path) -> String {
586    format!(
587        "Warning: signed cert for {} but host block is no longer in ssh config; \
588         CertificateFile not written (cert saved to {})",
589        alias,
590        cert_path.display()
591    )
592}
593
594/// Stderr warning emitted when the cert was signed but writing the
595/// updated SSH config back to disk failed.
596pub fn vault_cert_config_write_failed(alias: &str, e: &impl std::fmt::Display) -> String {
597    format!(
598        "Warning: signed cert for {} but failed to update SSH config CertificateFile: {}",
599        alias, e
600    )
601}
602
603// ── Snippets ────────────────────────────────────────────────────────
604
605pub fn snippet_removed(name: &str) -> String {
606    format!("Removed snippet '{}'.", name)
607}
608
609pub fn snippet_added(name: &str) -> String {
610    format!("Added snippet '{}'.", name)
611}
612
613pub fn snippet_updated(name: &str) -> String {
614    format!("Updated snippet '{}'.", name)
615}
616
617pub fn snippet_exists(name: &str) -> String {
618    format!("'{}' already exists.", name)
619}
620
621pub const OUTPUT_COPIED: &str = "Output copied.";
622
623pub fn copy_failed(e: &impl std::fmt::Display) -> String {
624    format!("Copy failed: {}", e)
625}
626
627// ── Clipboard subprocess errors ─────────────────────────────────────
628//
629// Surfaced when `pbcopy`/`xclip`/`wl-copy` fails to spawn, write to its
630// stdin, or be reaped. The cmd name is the binary the platform picked.
631
632pub fn clipboard_run_failed(cmd: &str) -> String {
633    format!("Failed to run {}.", cmd)
634}
635
636pub fn clipboard_write_failed(cmd: &str) -> String {
637    format!("Failed to write to {}.", cmd)
638}
639
640pub fn clipboard_wait_failed(cmd: &str) -> String {
641    format!("Failed to wait for {}.", cmd)
642}
643
644pub fn clipboard_exited_error(cmd: &str) -> String {
645    format!("{} exited with error.", cmd)
646}
647
648// ── Import errors ───────────────────────────────────────────────────
649//
650// Bubble up to the CLI via `eprintln!("{}", e)` when the user runs
651// `purple import` against a missing or unreadable file.
652
653pub fn import_open_failed(path: &impl std::fmt::Display, e: &impl std::fmt::Display) -> String {
654    format!("Can't open {}: {}", path, e)
655}
656
657pub fn import_known_hosts_open_failed(e: &impl std::fmt::Display) -> String {
658    format!("Can't open known_hosts: {}", e)
659}
660
661pub const IMPORT_HOME_DIR_UNKNOWN: &str = "Could not determine home directory.";
662pub const IMPORT_KNOWN_HOSTS_MISSING: &str = "~/.ssh/known_hosts not found.";
663
664// ── Snippet runner errors ───────────────────────────────────────────
665
666pub fn snippet_ssh_launch_failed(e: &impl std::fmt::Display) -> String {
667    format!("Failed to launch ssh: {}", e)
668}
669
670// ── Vault SSH library errors ────────────────────────────────────────
671//
672// Reach the user via the anyhow chain that `ensure_vault_ssh_chain_if_needed`
673// turns into a toast. `vault_create_dir_failed` and `vault_write_cert_failed`
674// are with_context strings, so they appear after a colon in the error chain.
675
676pub fn vault_create_dir_failed(path: &impl std::fmt::Display) -> String {
677    format!("Failed to create {}", path)
678}
679
680pub fn vault_write_cert_failed(path: &impl std::fmt::Display) -> String {
681    format!("Failed to write certificate to {}", path)
682}
683
684pub fn vault_ssh_keygen_run_failed(e: &impl std::fmt::Display) -> String {
685    format!("Failed to run ssh-keygen: {}", e)
686}
687
688// ── Container library errors ────────────────────────────────────────
689//
690// Validation (`validate_container_id`) errors propagate via the
691// `ContainerActionComplete` event and become toasts. The "no runtime"
692// and "unknown sentinel" lines surface in the same path.
693
694pub const CONTAINER_ID_EMPTY: &str = "Container ID must not be empty.";
695pub const CONTAINER_RUNTIME_MISSING: &str = "No container runtime found. Install Docker or Podman.";
696
697pub fn container_id_invalid_char(c: char) -> String {
698    format!("Container ID contains invalid character: '{c}'")
699}
700
701pub fn container_unknown_sentinel(s: &str) -> String {
702    format!("Unknown sentinel: {s}")
703}
704
705pub fn container_invalid_id(reason: &str) -> String {
706    format!("Container exec blocked: {reason}")
707}
708
709/// Transient label shown on the file browser overlay while an scp transfer
710/// is running. Singular form for a single source.
711pub fn scp_copying_one(source: &str) -> String {
712    format!("Copying {}...", source)
713}
714
715/// Transient label shown on the file browser overlay while an scp transfer
716/// is running. Plural form when multiple files were selected at once.
717pub fn scp_copying_many(count: usize) -> String {
718    format!("Copying {} files...", count)
719}
720
721/// Toast shown when scp exited non-zero with no captured stderr to relay.
722/// The exit code is the only signal we have left.
723pub fn scp_failed_exit_code(code: i32) -> String {
724    format!("Copy failed (exit code {}).", code)
725}
726
727/// Toast shown when the scp subprocess itself failed to spawn or wait
728/// (e.g. binary missing, signal interrupted), distinct from a non-zero
729/// exit which uses `scp_failed_exit_code`.
730pub fn scp_spawn_failed(e: &impl std::fmt::Display) -> String {
731    format!("scp failed: {}", e)
732}
733
734// ── Picker (password source, key, proxy) ────────────────────────────
735
736pub const GLOBAL_DEFAULT_CLEARED: &str = "Global default cleared.";
737pub const PASSWORD_SOURCE_CLEARED: &str = "Password source cleared.";
738pub const ASKPASS_CUSTOM_COMMAND_HINT: &str =
739    "Type your command. Use %a (alias) and %h (hostname) as placeholders.";
740
741pub fn global_default_set(label: &str) -> String {
742    format!("Global default set to {}.", label)
743}
744
745pub fn password_source_set(label: &str) -> String {
746    format!("Password source set to {}.", label)
747}
748
749pub fn complete_path(label: &str) -> String {
750    format!("Complete the {} path.", label)
751}
752
753pub fn key_selected(name: &str) -> String {
754    format!("Locked and loaded with {}.", name)
755}
756
757// ── Keys tab ────────────────────────────────────────────────────────
758
759/// Copy succeeded. Toast tells the user which key landed on the clipboard.
760pub fn keys_copy_success(name: &str) -> String {
761    format!("Copied {}.pub to clipboard.", name)
762}
763
764/// The .pub file could not be read from disk (deleted, permission denied).
765pub fn keys_copy_read_failed(name: &str) -> String {
766    format!("Could not read {}.pub from disk.", name)
767}
768
769// ── Tab empty-state cards (design::TabEmpty) ────────────────────────────
770// One bundle per top-level tab. Each renders inside the existing outer
771// block as a centred card via `design::render_tab_empty`. Headlines
772// state the missing thing; explainers name the cause; hints surface the
773// one or two keys that populate the tab.
774
775pub const TAB_EMPTY_HOSTS_HEADLINE: &str = "It's quiet in here.";
776pub const TAB_EMPTY_HOSTS_EXPLAINER: &str = "purple reads hosts from ~/.ssh/config and from the cloud providers you connect. Add one by hand or sync a provider and the list fills up.";
777pub const TAB_EMPTY_HOSTS_HINT_ADD: &str = "add a host";
778pub const TAB_EMPTY_HOSTS_HINT_SYNC: &str = "open providers to sync from the cloud";
779
780pub const TAB_EMPTY_CONTAINERS_HEADLINE: &str = "No containers cached yet.";
781pub const TAB_EMPTY_CONTAINERS_EXPLAINER: &str = "purple snapshots docker or podman output per host and caches it locally. Pick a host below and its containers show up here.";
782pub const TAB_EMPTY_CONTAINERS_HINT_ADD: &str = "pick a host to scan";
783
784pub const TAB_EMPTY_TUNNELS_HEADLINE: &str = "No tunnels yet.";
785pub const TAB_EMPTY_TUNNELS_EXPLAINER: &str = "Tunnels are SSH port forwards stored per host in ~/.ssh/config. This tab aggregates Local, Remote and Dynamic forwards across every alias.";
786pub const TAB_EMPTY_TUNNELS_HINT_ADD: &str = "add a tunnel";
787
788pub const TAB_EMPTY_KEYS_HEADLINE: &str = "No SSH keys in ~/.ssh/ yet.";
789pub const TAB_EMPTY_KEYS_EXPLAINER: &str = "purple reads every public-key file in ~/.ssh/ along with its activity history. Generate one and the new key shows up here on next refresh.";
790pub const TAB_EMPTY_KEYS_HINT_KEYGEN: &str = "ssh-keygen -t ed25519 -C \"$(whoami)@$(hostname)\"";
791
792// ── Destructive confirm popups (design::render_destructive_popup) ──────
793// Every popup is rendered as a centred danger_block over the parent
794// overlay, never as a footer prompt. Each surface owns a title, a
795// question and an optional detail line; keep them centralised here so
796// rewording requires one diff per surface, not per call site.
797
798pub const CONFIRM_TUNNEL_DELETE_TITLE: &str = " Remove tunnel? ";
799pub const CONFIRM_TUNNEL_DELETE_QUESTION: &str = "Remove the selected tunnel rule from this host?";
800pub const CONFIRM_TUNNEL_DELETE_DETAIL: &str =
801    "Rewrites ~/.ssh/config. The rule is gone after save.";
802
803pub const CONFIRM_SNIPPET_DELETE_TITLE: &str = " Remove snippet? ";
804pub const CONFIRM_SNIPPET_DELETE_DETAIL: &str = "The snippet file is rewritten on disk.";
805pub fn confirm_snippet_delete_question(name: &str) -> String {
806    format!("Remove \"{}\" from the snippet store?", name)
807}
808
809pub const CONFIRM_PROVIDER_REMOVE_TITLE: &str = " Remove provider? ";
810pub const CONFIRM_PROVIDER_REMOVE_DETAIL: &str =
811    "Synced hosts stay in ~/.ssh/config. The integration is gone after save.";
812pub fn confirm_provider_remove_question(display: &str) -> String {
813    format!("Remove the \"{}\" provider config?", display)
814}
815pub fn confirm_provider_remove_labeled_question(display: &str, label: &str) -> String {
816    format!("Remove the \"{}\" config labelled \"{}\"?", display, label)
817}
818
819/// Empty-state message for the key-push picker when ~/.ssh/config has
820/// no host entries to target.
821pub const KEY_PUSH_NO_HOSTS: &str =
822    "No hosts in ~/.ssh/config. Add a host first, then come back here.";
823
824/// Header line for the Vault SSH strip when there is no Valid cached
825/// cert. Tells the user how to populate the strip.
826pub const VAULT_STRIP_EMPTY: &str =
827    "  No active certs. Press V to sign all Vault SSH hosts at once.";
828
829/// Inline tag appended to vault-ssh host rows in the push picker to
830/// document why they cannot be selected.
831pub const KEY_PUSH_VAULT_TAG: &str = "  (vault)";
832
833/// Picker overlay title formats.
834pub fn key_push_picker_title_eligible(key_label: &str, eligible: usize, total: usize) -> String {
835    format!(
836        "Push {} \u{203A} Select Hosts ({} eligible of {})",
837        key_label, eligible, total
838    )
839}
840
841pub fn key_push_picker_title_selected(
842    key_label: &str,
843    selected: usize,
844    total: usize,
845    eligible: usize,
846) -> String {
847    format!(
848        "Push {} \u{203A} {} selected of {} ({} eligible)",
849        key_label, selected, total, eligible
850    )
851}
852
853/// Toast when the user presses `p` but no public key file is readable.
854pub fn key_push_no_pubkey(name: &str) -> String {
855    format!(
856        "Cannot read {}.pub. The file is missing or unreadable.",
857        name
858    )
859}
860
861/// Toast when the user committed the picker with zero hosts selected.
862pub const KEY_PUSH_NONE_SELECTED: &str = "Select at least one host with Space.";
863
864/// Toast shown when the user tries to select a vault-ssh host. These
865/// hosts are managed via signed certs (`V`), not static authorized_keys
866/// appends.
867pub const KEY_PUSH_VAULT_SKIP: &str =
868    "Vault SSH host. Use V on the host list to sign a cert instead.";
869
870/// Progress toast at the start of a push run.
871pub fn key_push_in_progress(key_name: &str, host_count: usize) -> String {
872    format!("Pushing {} to {} host(s)...", key_name, host_count)
873}
874
875/// Error toast when std::thread::spawn fails (essentially OOM / rlimit).
876pub fn key_push_thread_spawn_failed() -> String {
877    "Could not spawn push worker thread. Check resource limits.".to_string()
878}
879
880/// Warning toast when the user presses `p` while a push is still
881/// running. Tells them how to recover.
882pub const KEY_PUSH_ALREADY_IN_PROGRESS: &str =
883    "A push is already running. Press Esc to cancel first.";
884
885/// Error toast when the `.pub` file is not a regular file, is a symlink,
886/// or could not be opened with `O_NOFOLLOW`. Stops the push before any
887/// remote SSH call is made.
888pub fn key_push_pubkey_not_regular(name: &str) -> String {
889    format!("{}.pub is not a regular file. Symlinks are rejected.", name)
890}
891
892/// Error toast when the `.pub` file exceeds the 16 KiB cap. The most
893/// common cause is a `.pub` symlink that resolved to a log file or a
894/// truncated dump from an unrelated tool.
895pub fn key_push_pubkey_too_large(name: &str, bytes: u64) -> String {
896    format!(
897        "{}.pub is {} bytes, larger than the 16 KiB push limit.",
898        name, bytes
899    )
900}
901
902/// Error toast when the `.pub` file does not parse as a single, valid
903/// `authorized_keys` line. Catches multi-line content (which silently
904/// installs multiple entries, including embedded `command=` clauses),
905/// unsupported algorithms, and malformed base64 blobs.
906pub fn key_push_invalid_pubkey(name: &str, detail: &str) -> String {
907    format!("{}.pub failed validation: {}. Push aborted.", name, detail)
908}
909
910/// Error toast when the picker commits with zero eligible aliases. The
911/// picker should always block this earlier, but the worker guard exists
912/// as a defence-in-depth so the progress toast never sticks.
913pub const KEY_PUSH_NO_HOSTS_SELECTED: &str =
914    "Picker committed with no eligible hosts. Push aborted.";
915
916/// Error toast when the user tries to push a certificate file. Pushing
917/// a cert into authorized_keys bypasses its TTL and undermines the
918/// signed-cert workflow.
919pub const KEY_PUSH_CERT_NOT_PUSHABLE: &str =
920    "Certificates cannot be pushed as static keys. Sign with V instead.";
921
922/// Toast after the user pressed Esc to cancel an in-flight push run.
923/// Names the per-host progress at the moment of cancel so the user
924/// knows what may or may not have already been authorized.
925pub fn key_push_cancelled(done: usize, total: usize) -> String {
926    format!(
927        "Push cancelled after {} of {} host(s). Re-run to finish the rest.",
928        done, total,
929    )
930}
931
932/// Body line shown inside the confirm dialog.
933pub fn key_push_confirm_body(key_name: &str, host_count: usize) -> String {
934    if host_count == 1 {
935        format!("Push {} to 1 host?", key_name)
936    } else {
937        format!("Push {} to {} hosts?", key_name, host_count)
938    }
939}
940
941/// Toast after a fully successful push run.
942pub fn key_push_success(appended: usize, already: usize) -> String {
943    if appended == 0 && already > 0 {
944        format!("Key already present on {} host(s). Nothing to do.", already)
945    } else if already == 0 {
946        format!("Pushed to {} host(s).", appended)
947    } else {
948        format!(
949            "Pushed to {} host(s). Already present on {}.",
950            appended, already
951        )
952    }
953}
954
955/// Toast after a partial-failure push run. The detailed per-host errors
956/// land in the sticky-error overlay rendered separately.
957pub fn key_push_partial_failure(succeeded: usize, failed: usize) -> String {
958    format!("Pushed to {} host(s). {} failed.", succeeded, failed)
959}
960
961/// Sticky-error overlay body when every host failed.
962pub fn key_push_all_failed(count: usize) -> String {
963    format!(
964        "Push failed for all {} host(s). Check the host log for details.",
965        count
966    )
967}
968
969pub fn proxy_jump_set(alias: &str) -> String {
970    format!("Jumping through {}.", alias)
971}
972
973pub fn save_default_failed(e: &impl std::fmt::Display) -> String {
974    format!("Failed to save default: {}", e)
975}
976
977// ── Containers ──────────────────────────────────────────────────────
978
979pub fn container_action_complete(action: &str) -> String {
980    format!("Container {} complete.", action)
981}
982
983pub const HOST_KEY_UNKNOWN: &str = "Host key unknown. Connect first (Enter) to trust the host.";
984pub const HOST_KEY_CHANGED: &str =
985    "Host key changed. Possible tampering or server re-install. Clear with ssh-keygen -R.";
986
987// User-friendly classifications of stderr from a remote `docker ps` /
988// `podman ps`. The raw stderr is too technical and varies across
989// distros; these phrasings give the user the actionable next step.
990pub const CONTAINER_RUNTIME_NOT_FOUND: &str = "Docker or Podman not found on remote host.";
991pub const CONTAINER_PERMISSION_DENIED: &str =
992    "Permission denied. Is your user in the docker group?";
993pub const CONTAINER_DAEMON_NOT_RUNNING: &str = "Container daemon is not running.";
994pub const CONTAINER_CONNECTION_REFUSED: &str = "Connection refused.";
995pub const CONTAINER_HOST_UNREACHABLE: &str = "Host unreachable.";
996
997/// Generic fallback when none of the container error classifiers
998/// matched. The exit code is the only signal we can show without
999/// leaking unfiltered remote stderr.
1000pub fn container_command_failed(code: i32) -> String {
1001    format!("Command failed with code {}.", code)
1002}
1003
1004/// `docker inspect` returned no JSON (empty array or empty stdout).
1005pub const CONTAINER_INSPECT_EMPTY: &str = "Inspect returned no data.";
1006
1007/// `docker inspect` stdout was not valid JSON.
1008pub fn container_inspect_parse_failed(reason: &str) -> String {
1009    format!("Inspect parse failed: {}", reason)
1010}
1011
1012// ── Container exec (Enter on containers overview) ──────────────────
1013
1014/// User pressed Enter on a non-running container.
1015pub fn container_not_running(name: &str) -> String {
1016    format!("{} is not running. Cannot exec.", name)
1017}
1018
1019/// Demo mode interactive guard.
1020pub const DEMO_CONTAINER_EXEC_DISABLED: &str = "Demo mode: container exec disabled.";
1021
1022/// Tmux mode opened a new window for the exec session.
1023pub fn container_exec_opened_in_tmux(name: &str, alias: &str) -> String {
1024    format!("Opened {} on {} in tmux window.", name, alias)
1025}
1026
1027/// Interactive shell exited cleanly.
1028pub fn container_exec_ended(name: &str) -> String {
1029    format!("Container shell ended: {}.", name)
1030}
1031
1032/// Interactive shell failed with a parsed stderr reason.
1033pub fn container_exec_failed_with_reason(name: &str, reason: &str) -> String {
1034    format!("Container exec failed for {}: {}", name, reason)
1035}
1036
1037/// Interactive shell exited non-zero with no stderr reason.
1038pub fn container_exec_exited_with_code(name: &str, code: i32) -> String {
1039    format!("Container exec for {} exited with code {}.", name, code)
1040}
1041
1042/// `Command::new("ssh").spawn()` failed.
1043pub fn container_exec_spawn_failed(name: &str) -> String {
1044    format!("Failed to launch ssh for container {}.", name)
1045}
1046
1047/// Exec prompt rejected the typed command (control chars, newline).
1048pub const CONTAINER_EXEC_INVALID_COMMAND: &str =
1049    "Command rejected: control characters not allowed.";
1050
1051// ── Container logs (l) ─────────────────────────────────────────────
1052
1053/// Title shown in the logs overlay border for "logs are loading".
1054pub const CONTAINER_LOGS_LOADING: &str = "fetching logs…";
1055
1056/// Title for "logs are ready". Uses the short relative-time format
1057/// (12s, 5m, 2h) so the badge stays compact regardless of staleness.
1058pub fn container_logs_fetched(secs_ago: u64) -> String {
1059    format!(
1060        "fetched {} ago",
1061        crate::containers::format_uptime_short(secs_ago)
1062    )
1063}
1064
1065/// Title for "logs fetch failed".
1066pub fn container_logs_failed(reason: &str) -> String {
1067    format!("logs fetch failed: {}", reason)
1068}
1069
1070/// Search position badge for the logs overlay: `3 of 12` while the
1071/// user navigates `/foo` matches with n/N.
1072pub fn container_logs_search_position(current: usize, total: usize) -> String {
1073    format!("{} of {}", current, total)
1074}
1075
1076/// Search badge when the query has no hits in the current body.
1077pub const CONTAINER_LOGS_SEARCH_NO_MATCHES: &str = "no matches";
1078
1079// ── Container restart/stop (K / S) ─────────────────────────────────
1080
1081/// Confirm body line that summarises a destructive action's mechanics.
1082pub const CONTAINER_RESTART_BODY: &str =
1083    "Sends SIGTERM, waits 10s, then SIGKILL. Live connections will drop.";
1084pub const CONTAINER_STOP_BODY: &str = "Sends SIGTERM, waits 10s, then SIGKILL. Container will not restart unless its policy reschedules it.";
1085
1086// ── Container stack restart (Ctrl-K) ───────────────────────────────
1087
1088pub fn container_stack_unknown(name: &str) -> String {
1089    format!("Stack unknown for {}: open the detail panel first.", name)
1090}
1091
1092pub fn container_stack_no_running(project: &str) -> String {
1093    format!("Stack {} has no running members to restart.", project)
1094}
1095
1096pub const CONTAINER_STACK_RESTART_BODY: &str = "Restart cycles every running member one by one. Exited members are not touched. Live connections will drop.";
1097
1098// ── Container host-wide bulk actions (K / S on a divider) ──────────
1099
1100/// Body line on the bulk-restart-host confirm dialog. Same mechanics
1101/// as a single restart but spelled out so the user knows it walks the
1102/// host one container at a time.
1103pub const CONTAINER_HOST_RESTART_ALL_BODY: &str = "Restart cycles every running container on the host one by one. Exited containers are not touched. Live connections will drop.";
1104
1105/// Body line on the bulk-stop-host confirm dialog.
1106pub const CONTAINER_HOST_STOP_ALL_BODY: &str = "Stops every running container on the host one by one. Exited containers are not touched. Restart policies may reschedule them.";
1107
1108/// Footer toast when the user presses a single-target action key (l, e)
1109/// while the cursor is parked on a host-divider row. Steers the user
1110/// back to a container row instead of silently no-op'ing. `action` is
1111/// lowercased for sentence-case readability ("logs needs..." reads
1112/// better than "Logs applies...").
1113pub fn container_action_needs_single(action: &str) -> String {
1114    format!(
1115        "{} need a single container. Place the cursor on a container row.",
1116        action.to_lowercase()
1117    )
1118}
1119
1120/// Toast when bulk K/S on a divider finds no running containers.
1121pub fn container_host_no_running(alias: &str) -> String {
1122    format!("No running containers on {}.", alias)
1123}
1124
1125// ── Container refresh (r / R / a) ──────────────────────────────────
1126
1127/// `r` keypress: single-host refresh started.
1128pub fn container_refreshing(alias: &str) -> String {
1129    format!("Refreshing {}…", alias)
1130}
1131
1132/// `R` keypress while a previous batch is still in flight.
1133pub const REFRESH_BATCH_ALREADY_RUNNING: &str = "Refresh already in progress.";
1134
1135/// `R` keypress on an empty container cache.
1136pub const REFRESH_NOTHING_TO_REFRESH: &str = "No cached hosts to refresh. Press 'a' to add a host.";
1137
1138/// Batch progress readout shown in the status footer.
1139pub fn container_refresh_progress(done: usize, total: usize) -> String {
1140    format!("Refreshing {}/{} hosts…", done, total)
1141}
1142
1143/// Batch completed.
1144pub fn container_refresh_complete(total: usize) -> String {
1145    format!(
1146        "Refreshed {} host{}.",
1147        total,
1148        if total == 1 { "" } else { "s" }
1149    )
1150}
1151
1152/// Host picker: no hosts match the live query.
1153pub const CONTAINER_HOST_PICKER_NO_MATCH: &str = "No hosts match.";
1154
1155/// Host picker: every host already has a cache entry.
1156pub const CONTAINER_HOST_PICKER_NOTHING_TO_ADD: &str =
1157    "All hosts already cached. Use 'r' or 'R' to refresh.";
1158
1159// ── Import ──────────────────────────────────────────────────────────
1160
1161pub fn imported_hosts(imported: usize, skipped: usize) -> String {
1162    format!(
1163        "Imported {} host{}, skipped {} duplicate{}.",
1164        imported,
1165        if imported == 1 { "" } else { "s" },
1166        skipped,
1167        if skipped == 1 { "" } else { "s" }
1168    )
1169}
1170
1171pub fn all_hosts_exist(skipped: usize) -> String {
1172    if skipped == 1 {
1173        "Host already exists.".to_string()
1174    } else {
1175        format!("All {} hosts already exist.", skipped)
1176    }
1177}
1178
1179// ── SSH config repair ───────────────────────────────────────────────
1180
1181pub fn config_repaired(groups: usize, orphaned: usize) -> String {
1182    format!(
1183        "Repaired SSH config ({} absorbed, {} orphaned group headers).",
1184        groups, orphaned
1185    )
1186}
1187
1188pub fn no_exact_match(alias: &str) -> String {
1189    format!("No exact match for '{}'. Here's what we found.", alias)
1190}
1191
1192pub fn group_pref_reset_failed(e: &impl std::fmt::Display) -> String {
1193    format!("Group preference reset. (save failed: {})", e)
1194}
1195
1196// ── Connection ──────────────────────────────────────────────────────
1197
1198pub fn opened_in_tmux(alias: &str) -> String {
1199    format!("Opened {} in new tmux window.", alias)
1200}
1201
1202pub fn tmux_error(e: &impl std::fmt::Display) -> String {
1203    format!("tmux: {}", e)
1204}
1205
1206pub fn connection_failed(alias: &str) -> String {
1207    format!("Connection to {} failed.", alias)
1208}
1209
1210/// Stderr line printed when the ssh subprocess itself failed to spawn or
1211/// wait (e.g. binary missing, signal interrupted), distinct from a
1212/// non-zero exit code which the user sees via the toast.
1213pub fn connection_spawn_failed(e: &impl std::fmt::Display) -> String {
1214    format!("Connection failed: {}", e)
1215}
1216
1217/// Toast shown when ssh exited non-zero with a captured stderr line we
1218/// can show. The reason is the trimmed last meaningful line of ssh stderr.
1219pub fn ssh_failed_with_reason(alias: &str, reason: &str) -> String {
1220    format!("SSH to {} failed. {}", alias, reason)
1221}
1222
1223/// Toast shown when ssh exited non-zero with no captured stderr to relay.
1224/// The exit code is the only signal we have left.
1225pub fn ssh_exited_with_code(alias: &str, code: i32) -> String {
1226    format!("SSH to {} exited with code {}.", alias, code)
1227}
1228
1229// ── Host key reset ──────────────────────────────────────────────────
1230
1231pub fn host_key_remove_failed(stderr: &str) -> String {
1232    format!("Failed to remove host key: {}", stderr)
1233}
1234
1235pub fn ssh_keygen_failed(e: &impl std::fmt::Display) -> String {
1236    format!("Failed to run ssh-keygen: {}", e)
1237}
1238
1239// ── Transfer ────────────────────────────────────────────────────────
1240
1241pub const TRANSFER_COMPLETE: &str = "Transfer complete.";
1242
1243// ── Background / event loop ─────────────────────────────────────────
1244
1245/// Per-provider sync progress line with a leading spinner frame so
1246/// `event_loop::handle_tick` animates the prefix while the message is
1247/// on screen. Format: `⠋ Proxmox VE: Resolving IPs (1/5)...`. Mirrors
1248/// the spinner contract used by `synced_progress` so the footer keeps
1249/// animating even when granular per-provider progress overrides the
1250/// batch summary mid-sync.
1251pub fn provider_progress(spinner: &str, name: &str, message: &str) -> String {
1252    format!("{} {}: {}", spinner, name, message)
1253}
1254
1255// ── Relative age (detail panel "checked" suffix) ────────────────────
1256
1257pub const AGE_JUST_NOW: &str = "just now";
1258
1259/// Compact relative age: "just now", "12s ago", "3m ago", "2h ago",
1260/// "2d ago". Used in the detail panel so the reader can tell stale
1261/// data from fresh.
1262pub fn relative_age(elapsed: std::time::Duration) -> String {
1263    let secs = elapsed.as_secs();
1264    if secs < 5 {
1265        AGE_JUST_NOW.to_string()
1266    } else if secs < 60 {
1267        format!("{}s ago", secs)
1268    } else if secs < 3600 {
1269        format!("{}m ago", secs / 60)
1270    } else if secs < 86400 {
1271        format!("{}h ago", secs / 3600)
1272    } else {
1273        format!("{}d ago", secs / 86400)
1274    }
1275}
1276
1277// ── Vault SSH bulk signing summaries (event_loop.rs) ────────────────
1278
1279pub fn vault_config_reapply_failed(signed: usize, e: &impl std::fmt::Display) -> String {
1280    format!(
1281        "External edits detected; signed {} certs but failed to re-apply CertificateFile: {}",
1282        signed, e
1283    )
1284}
1285
1286pub fn vault_external_edits_merged(summary: &str, reapplied: usize) -> String {
1287    format!(
1288        "{} External ssh config edits detected, merged {} CertificateFile directives.",
1289        summary, reapplied
1290    )
1291}
1292
1293pub fn vault_external_edits_no_write(summary: &str) -> String {
1294    format!(
1295        "{} External ssh config edits detected; certs on disk, no CertificateFile written.",
1296        summary
1297    )
1298}
1299
1300pub fn vault_reparse_failed(signed: usize, e: &impl std::fmt::Display) -> String {
1301    format!(
1302        "Signed {} certs but cannot re-parse ssh config after external edit: {}. \
1303         Certs are on disk under ~/.purple/certs/.",
1304        signed, e
1305    )
1306}
1307
1308pub fn vault_config_update_failed(signed: usize, e: &impl std::fmt::Display) -> String {
1309    format!(
1310        "Signed {} certs but failed to update SSH config: {}",
1311        signed, e
1312    )
1313}
1314
1315pub fn vault_config_write_after_sign(e: &impl std::fmt::Display) -> String {
1316    format!("Failed to update config after vault signing: {}", e)
1317}
1318
1319pub fn vault_config_skipped_external_change() -> &'static str {
1320    "Config changed on disk since signing started. Cert files are saved; re-run vault sign to wire them up."
1321}
1322
1323pub fn sync_skipped_external_change() -> &'static str {
1324    "Config changed on disk during sync. Re-run sync after reviewing your edits."
1325}
1326
1327// ── File browser ────────────────────────────────────────────────────
1328
1329// ── Confirm / host key ──────────────────────────────────────────────
1330
1331pub fn removed_host_key(hostname: &str) -> String {
1332    format!("Removed host key for {}. Reconnecting...", hostname)
1333}
1334
1335// ── Host detail (tags) ──────────────────────────────────────────────
1336
1337pub fn tagged_host(alias: &str, count: usize) -> String {
1338    format!(
1339        "Tagged {} with {} label{}.",
1340        alias,
1341        count,
1342        if count == 1 { "" } else { "s" }
1343    )
1344}
1345
1346// ── Config reload ───────────────────────────────────────────────────
1347
1348pub fn config_reloaded(count: usize) -> String {
1349    format!("Config reloaded. {} hosts.", count)
1350}
1351
1352// ── Sync background ─────────────────────────────────────────────────
1353
1354/// In-progress sync line for the footer. Format:
1355/// `⠋ Syncing AWS, Hetzner · 1/3 (+12 ~3 -1)`.
1356/// Active provider names lead so the user immediately sees which provider
1357/// is currently in flight (especially relevant when one provider is slow).
1358/// `done/total` follows as a counter. The leading character is a braille
1359/// spinner frame rotated on every tick. The `(+a ~u -s)` suffix is omitted
1360/// when all counts are zero.
1361///
1362/// Callers MUST only invoke this when `active_names` is non-empty (i.e.
1363/// at least one provider is still in flight). The only call site is
1364/// `main::set_sync_summary`, which enters this branch via `still_syncing`,
1365/// itself gated on `!providers.syncing.is_empty()` — so `active_names`
1366/// (built from `syncing.keys()`) is guaranteed non-empty.
1367pub fn synced_progress(
1368    spinner: &str,
1369    active_names: &str,
1370    done: usize,
1371    total: usize,
1372    added: usize,
1373    updated: usize,
1374    stale: usize,
1375) -> String {
1376    debug_assert!(
1377        !active_names.is_empty(),
1378        "synced_progress must only be called while a provider is still in flight"
1379    );
1380    let diff = sync_diff_suffix(added, updated, stale);
1381    format!(
1382        "{} Syncing {} \u{00B7} {}/{}{}",
1383        spinner, active_names, done, total, diff
1384    )
1385}
1386
1387/// Final sync summary for the footer once all providers in the batch have
1388/// completed. Format: `Synced 5/5 · AWS, DO, Vultr, Hetzner, Linode (+12 ~3 -1)`.
1389/// No spinner prefix, no auto-tick: the message expires by length-proportional
1390/// timeout once the batch is done.
1391pub fn synced_done(
1392    done: usize,
1393    total: usize,
1394    names: &str,
1395    added: usize,
1396    updated: usize,
1397    stale: usize,
1398) -> String {
1399    let diff = sync_diff_suffix(added, updated, stale);
1400    format!("Synced {}/{} \u{00B7} {}{}", done, total, names, diff)
1401}
1402
1403fn sync_diff_suffix(added: usize, updated: usize, stale: usize) -> String {
1404    let parts: Vec<String> = [(added, '+'), (updated, '~'), (stale, '-')]
1405        .iter()
1406        .filter(|(n, _)| *n > 0)
1407        .map(|(n, sign)| format!("{}{}", sign, n))
1408        .collect();
1409    if parts.is_empty() {
1410        String::new()
1411    } else {
1412        format!(" ({})", parts.join(" "))
1413    }
1414}
1415
1416pub const SYNC_THREAD_SPAWN_FAILED: &str = "Failed to start sync thread.";
1417
1418pub const SYNC_UNKNOWN_PROVIDER: &str = "Unknown provider.";
1419
1420// ── Vault signing cancelled summary ─────────────────────────────────
1421
1422pub fn vault_signing_cancelled_summary(
1423    signed: u32,
1424    failed: u32,
1425    first_error: Option<&str>,
1426) -> String {
1427    let mut msg = format!(
1428        "Vault SSH signing cancelled ({} signed, {} failed)",
1429        signed, failed
1430    );
1431    if let Some(err) = first_error {
1432        msg.push_str(": ");
1433        msg.push_str(err);
1434    }
1435    msg
1436}
1437
1438// ── Region picker ───────────────────────────────────────────────────
1439
1440pub fn regions_selected_count(count: usize, label: &str) -> String {
1441    let s = if count == 1 { "" } else { "s" };
1442    format!("{} {}{} selected.", count, label, s)
1443}
1444
1445// ── Purge stale ─────────────────────────────────────────────────────
1446
1447// ── Clipboard ───────────────────────────────────────────────────────
1448
1449pub const NO_CLIPBOARD_TOOL: &str =
1450    "No clipboard tool found. Install pbcopy (macOS), wl-copy (Wayland), or xclip/xsel (X11).";
1451
1452// ── MCP server ──────────────────────────────────────────────────────
1453
1454pub const MCP_TOOL_DENIED_READ_ONLY: &str = "Tool denied. Server started with --read-only. Restart without --read-only to enable state-changing tools.";
1455
1456/// Bare message body. Callers add the `[purple]` fault-domain prefix at
1457/// their `warn!` / `error!` site; the `eprintln!` startup diagnostic emits
1458/// this body directly without the tag.
1459pub fn mcp_audit_init_failed(path: &impl std::fmt::Display, e: &impl std::fmt::Display) -> String {
1460    format!(
1461        "Failed to initialise MCP audit log at {}: {}. Continuing without audit logging.",
1462        path, e
1463    )
1464}
1465
1466/// Bare message body. Callers add `[purple]` at the log macro site.
1467pub fn mcp_audit_write_failed(e: &impl std::fmt::Display) -> String {
1468    format!("Failed to write MCP audit entry: {}", e)
1469}
1470
1471/// Returned to the MCP client as `isError` content when the SSH config path
1472/// does not point to an existing file. Surfaces the bug class where a
1473/// missing-file silently yields an empty host list.
1474pub fn mcp_config_file_not_found(path: &impl std::fmt::Display) -> String {
1475    format!("SSH config file not found: {}", path)
1476}
1477
1478/// Logged when `dirs::home_dir()` cannot resolve a home for the audit log
1479/// default. Auditing is silently disabled in this state, so the operator
1480/// needs an explicit cue.
1481pub const MCP_AUDIT_HOME_DIR_UNAVAILABLE: &str = "Could not determine home directory; MCP audit log disabled. Set --audit-log <PATH> explicitly to enable auditing.";
1482
1483// ── Jump ─────────────────────────────────────────────────
1484
1485/// Placeholder shown in the jump bar input when the query is empty.
1486pub const PALETTE_PLACEHOLDER: &str = "Find anything";
1487/// Empty-state copy when the current query has no matches.
1488pub const PALETTE_NO_RESULTS: &str = "No matches.";
1489/// Toast shown when the user dispatches a snippet from the jump bar while
1490/// no host is selected (the snippet picker needs at least one target).
1491pub const PALETTE_SNIPPET_NEEDS_HOST: &str =
1492    "Pick a host first, then run a snippet from the jump bar.";
1493/// Suffix appended to the truncated row list when the visible window is
1494/// smaller than the result list.
1495pub fn jump_more_rows(n: usize) -> String {
1496    format!("+{n} more (scroll down)")
1497}
1498
1499// ── CLI messages ────────────────────────────────────────────────────
1500
1501#[path = "messages/cli.rs"]
1502pub mod cli;
1503pub mod footer;
1504
1505// ── Update messages ─────────────────────────────────────────────────
1506
1507pub mod update {
1508    pub const WHATS_NEW_HINT: &str = "Press n inside purple to see what's new.";
1509    pub const DONE: &str = "done.";
1510    pub const CHECKSUM_OK: &str = "ok.";
1511    pub const SUDO_WARNING: &str =
1512        "Running via sudo. Consider fixing directory permissions instead.";
1513
1514    /// Two-space-indented progress prefixes printed before each step.
1515    /// Trailing space is intentional so the success/fail glyph or
1516    /// `DONE` constant follows on the same line, matching the visual
1517    /// rhythm of the updater output.
1518    pub const STEP_CHECKING: &str = "  Checking for updates... ";
1519    pub const STEP_VERIFYING_CHECKSUM: &str = "  Verifying checksum... ";
1520    pub const STEP_INSTALLING: &str = "  Installing... ";
1521
1522    pub fn already_on(current: &str) -> String {
1523        format!("already on v{} (latest).", current)
1524    }
1525
1526    pub fn available(latest: &str, current: &str) -> String {
1527        format!("v{} available (current: v{}).", latest, current)
1528    }
1529
1530    /// Two-space-indented progress prefix for the download step. Matches
1531    /// the trailing-space convention of the other STEP_* constants so
1532    /// the next print resumes on the same line.
1533    pub fn step_downloading(version: &str) -> String {
1534        format!("  Downloading v{}... ", version)
1535    }
1536
1537    /// Indented sudo warning rendered before the download step. The
1538    /// caller passes a pre-bolded bang (`!`) so the line reads
1539    /// `  ! Running via sudo. ...` with the `!` emphasized.
1540    pub fn sudo_warning_line(bold_bang: &str) -> String {
1541        format!("  {} {}", bold_bang, SUDO_WARNING)
1542    }
1543
1544    pub fn header(bold_name: &str) -> String {
1545        format!("\n  {} updater\n", bold_name)
1546    }
1547
1548    pub fn binary_path(path: &std::path::Path) -> String {
1549        format!("  Binary: {}", path.display())
1550    }
1551
1552    pub fn installed_at(bold_version: &str, path: &std::path::Path) -> String {
1553        format!("\n  {} installed at {}.", bold_version, path.display())
1554    }
1555
1556    pub fn whats_new_hint_indented() -> String {
1557        format!("\n  {}", WHATS_NEW_HINT)
1558    }
1559}
1560
1561// ── Askpass / password prompts ───────────────────────────────────────
1562
1563pub mod askpass {
1564    pub const BW_NOT_FOUND: &str = "Bitwarden CLI (bw) not found. SSH will prompt for password.";
1565    pub const BW_NOT_LOGGED_IN: &str = "Bitwarden vault not logged in. Run 'bw login' first.";
1566    pub const EMPTY_PASSWORD: &str = "Empty password. SSH will prompt for password.";
1567    pub const PASSWORD_IN_KEYCHAIN: &str = "Password stored in keychain.";
1568
1569    pub fn read_failed(e: &impl std::fmt::Display) -> String {
1570        format!("Failed to read password: {}", e)
1571    }
1572
1573    pub fn unlock_failed_retry(e: &impl std::fmt::Display) -> String {
1574        format!("Unlock failed: {}. Try again.", e)
1575    }
1576
1577    pub fn unlock_failed_prompt(e: &impl std::fmt::Display) -> String {
1578        format!("Unlock failed: {}. SSH will prompt for password.", e)
1579    }
1580
1581    /// CLI prompt shown by the inline askpass path when the user has no
1582    /// stored credential yet. The trailing space is intentional — the
1583    /// reader echoes user input directly after.
1584    pub fn password_prompt(alias: &str) -> String {
1585        format!("Password for {}: ", alias)
1586    }
1587
1588    /// CLI prompt shown when keychain storage is the sink. Reminds the
1589    /// user that the entry will be persisted, not just used once.
1590    pub fn keychain_password_prompt(alias: &str) -> String {
1591        format!("Password for {} (stored in keychain): ", alias)
1592    }
1593
1594    /// Stderr line emitted when the keychain `add-generic-password` call
1595    /// failed. The user falls back to ssh's own prompt on the next try.
1596    pub fn keychain_store_failed(e: &impl std::fmt::Display) -> String {
1597        format!(
1598            "Failed to store in keychain: {}. SSH will prompt for password.",
1599            e
1600        )
1601    }
1602
1603    pub const PROTON_NOT_FOUND: &str =
1604        "Proton Pass CLI (pass-cli) not found. SSH will prompt for password.";
1605
1606    pub const PROTON_LOGIN_PROMPT: &str = "Proton Pass PAT: ";
1607
1608    pub const PROTON_LOGIN_SUCCESS: &str = "Logged in to Proton Pass.";
1609
1610    pub fn proton_login_failed_retry(e: &impl std::fmt::Display) -> String {
1611        format!("Proton Pass login failed: {}. Try again.", e)
1612    }
1613
1614    pub fn proton_login_failed_prompt(e: &impl std::fmt::Display) -> String {
1615        format!(
1616            "Proton Pass login failed: {}. SSH will prompt for password.",
1617            e
1618        )
1619    }
1620}
1621
1622// ── Logging ─────────────────────────────────────────────────────────
1623
1624pub mod logging {
1625    pub fn init_failed(e: &impl std::fmt::Display) -> String {
1626        format!("[purple] Failed to initialize logger: {}", e)
1627    }
1628
1629    pub const SSH_VERSION_FAILED: &str = "[purple] Failed to detect SSH version. Is ssh installed?";
1630}
1631
1632// ── Form field hints / placeholders ─────────────────────────────────
1633//
1634// Dimmed placeholder text shown in empty form fields. Centralized here
1635// so every user-visible string lives in one place and is auditable.
1636
1637pub mod hints {
1638    // ── Shared ──────────────────────────────────────────────────────
1639    // Picker hints mention "Space" because per the design system keyboard
1640    // invariants, Enter always submits a form; pickers open on Space.
1641    // Keep these strings in sync with scripts/check-keybindings.sh.
1642    pub const IDENTITY_FILE_PICK: &str = "Space to pick a key";
1643    pub const DEFAULT_SSH_USER: &str = "root";
1644
1645    // ── Host form ───────────────────────────────────────────────────
1646    pub const HOST_ALIAS: &str = "e.g. prod or db-01";
1647    pub const HOST_ALIAS_PATTERN: &str = "10.0.0.* or *.example.com";
1648    pub const HOST_HOSTNAME: &str = "192.168.1.1 or example.com";
1649    pub const HOST_PORT: &str = "22";
1650    pub const HOST_PROXY_JUMP: &str = "Space to pick a host";
1651    pub const HOST_VAULT_SSH: &str = "e.g. ssh-client-signer/sign/my-role (auth via vault login)";
1652    pub const HOST_VAULT_SSH_PICKER: &str = "Space to pick a role or type one";
1653    pub const HOST_VAULT_ADDR: &str =
1654        "e.g. http://127.0.0.1:8200 (inherits from provider or env when empty)";
1655    pub const HOST_TAGS: &str = "e.g. prod, staging, us-east (comma-separated)";
1656    pub const HOST_ASKPASS_PICK: &str = "Space to pick a source";
1657
1658    pub fn askpass_default(default: &str) -> String {
1659        format!("default: {}", default)
1660    }
1661
1662    pub fn inherits_from(value: &str, provider: &str) -> String {
1663        format!("inherits {} from {}", value, provider)
1664    }
1665
1666    // ── Tunnel form ─────────────────────────────────────────────────
1667    pub const TUNNEL_BIND_PORT: &str = "8080";
1668    pub const TUNNEL_REMOTE_HOST: &str = "localhost";
1669    pub const TUNNEL_REMOTE_PORT: &str = "80";
1670
1671    // ── Snippet form ────────────────────────────────────────────────
1672    pub const SNIPPET_NAME: &str = "check-disk";
1673    pub const SNIPPET_COMMAND: &str = "df -h";
1674    pub const SNIPPET_OPTIONAL: &str = "(optional)";
1675
1676    // ── Provider form ───────────────────────────────────────────────
1677    pub const PROVIDER_URL: &str = "https://pve.example.com:8006";
1678    pub const PROVIDER_TOKEN_DEFAULT: &str = "your-api-token";
1679    pub const PROVIDER_TOKEN_PROXMOX: &str = "user@pam!token=secret";
1680    pub const PROVIDER_TOKEN_AWS: &str = "AccessKeyId:Secret (or use Profile)";
1681    pub const PROVIDER_TOKEN_GCP: &str = "/path/to/service-account.json (or access token)";
1682    pub const PROVIDER_TOKEN_AZURE: &str = "/path/to/service-principal.json (or access token)";
1683    pub const PROVIDER_TOKEN_TAILSCALE: &str = "API key (leave empty for local CLI)";
1684    pub const PROVIDER_TOKEN_ORACLE: &str = "~/.oci/config";
1685    pub const PROVIDER_TOKEN_OVH: &str = "app_key:app_secret:consumer_key";
1686    pub const PROVIDER_PROFILE: &str = "Name from ~/.aws/credentials (or use Token)";
1687    pub const PROVIDER_PROJECT_DEFAULT: &str = "my-gcp-project-id";
1688    pub const PROVIDER_PROJECT_OVH: &str = "Public Cloud project ID";
1689    pub const PROVIDER_COMPARTMENT: &str = "ocid1.compartment.oc1..aaaa...";
1690    pub const PROVIDER_REGIONS_DEFAULT: &str = "Space to select regions";
1691    pub const PROVIDER_REGIONS_GCP: &str = "Space to select zones (empty = all)";
1692    pub const PROVIDER_REGIONS_SCALEWAY: &str = "Space to select zones";
1693    // Azure regions is a text input (not a picker), so no key is mentioned.
1694    pub const PROVIDER_REGIONS_AZURE: &str = "comma-separated subscription IDs";
1695    pub const PROVIDER_REGIONS_OVH: &str = "Space to select endpoint (default: EU)";
1696    pub const PROVIDER_USER_AWS: &str = "ec2-user";
1697    pub const PROVIDER_USER_GCP: &str = "ubuntu";
1698    pub const PROVIDER_USER_AZURE: &str = "azureuser";
1699    pub const PROVIDER_USER_ORACLE: &str = "opc";
1700    pub const PROVIDER_USER_OVH: &str = "ubuntu";
1701    pub const PROVIDER_VAULT_ROLE: &str =
1702        "e.g. ssh-client-signer/sign/my-role (vault login; inherited)";
1703    pub const PROVIDER_VAULT_ADDR: &str = "e.g. http://127.0.0.1:8200 (inherited by all hosts)";
1704    pub const PROVIDER_ALIAS_PREFIX_DEFAULT: &str = "prefix";
1705}
1706
1707#[cfg(test)]
1708mod hints_tests {
1709    use super::hints;
1710
1711    #[test]
1712    fn askpass_default_formats() {
1713        assert_eq!(hints::askpass_default("keychain"), "default: keychain");
1714    }
1715
1716    #[test]
1717    fn askpass_default_formats_empty() {
1718        assert_eq!(hints::askpass_default(""), "default: ");
1719    }
1720
1721    #[test]
1722    fn inherits_from_formats() {
1723        assert_eq!(
1724            hints::inherits_from("role/x", "aws"),
1725            "inherits role/x from aws"
1726        );
1727    }
1728
1729    #[test]
1730    fn picker_hints_mention_space_not_enter() {
1731        // Per the keyboard invariants, pickers open on Space.
1732        // If these assertions fail, audit scripts/check-keybindings.sh too.
1733        for s in [
1734            hints::IDENTITY_FILE_PICK,
1735            hints::HOST_PROXY_JUMP,
1736            hints::HOST_VAULT_SSH_PICKER,
1737            hints::HOST_ASKPASS_PICK,
1738            hints::PROVIDER_REGIONS_DEFAULT,
1739            hints::PROVIDER_REGIONS_GCP,
1740            hints::PROVIDER_REGIONS_SCALEWAY,
1741            hints::PROVIDER_REGIONS_OVH,
1742        ] {
1743            assert!(
1744                s.starts_with("Space "),
1745                "picker hint must mention Space: {s}"
1746            );
1747            assert!(!s.contains("Enter "), "picker hint must not say Enter: {s}");
1748        }
1749    }
1750}
1751
1752#[path = "messages/whats_new.rs"]
1753pub mod whats_new;
1754
1755#[path = "messages/whats_new_toast.rs"]
1756pub mod whats_new_toast;
1757
1758#[cfg(test)]
1759mod stale_host_tests {
1760    use super::stale_host;
1761
1762    #[test]
1763    fn empty_hint_returns_bare_sentence() {
1764        assert_eq!(stale_host(""), "Stale host.");
1765    }
1766
1767    #[test]
1768    fn empty_after_trim_returns_bare_sentence() {
1769        assert_eq!(stale_host("   "), "Stale host.");
1770    }
1771
1772    #[test]
1773    fn provider_hint_is_appended_with_space_and_period() {
1774        assert_eq!(
1775            stale_host("Gone from DigitalOcean"),
1776            "Stale host. Gone from DigitalOcean."
1777        );
1778    }
1779
1780    #[test]
1781    fn trailing_period_in_hint_is_not_doubled() {
1782        assert_eq!(
1783            stale_host("Gone from DigitalOcean."),
1784            "Stale host. Gone from DigitalOcean."
1785        );
1786    }
1787
1788    #[test]
1789    fn leading_space_in_hint_is_trimmed() {
1790        assert_eq!(stale_host(" Gone from AWS"), "Stale host. Gone from AWS.");
1791    }
1792}
1793
1794#[cfg(test)]
1795mod relative_age_tests {
1796    use super::relative_age;
1797    use std::time::Duration;
1798
1799    #[test]
1800    fn relative_age_boundaries() {
1801        assert_eq!(relative_age(Duration::from_secs(0)), "just now");
1802        assert_eq!(relative_age(Duration::from_secs(4)), "just now");
1803        assert_eq!(relative_age(Duration::from_secs(5)), "5s ago");
1804        assert_eq!(relative_age(Duration::from_secs(59)), "59s ago");
1805        assert_eq!(relative_age(Duration::from_secs(60)), "1m ago");
1806        assert_eq!(relative_age(Duration::from_secs(3599)), "59m ago");
1807        assert_eq!(relative_age(Duration::from_secs(3600)), "1h ago");
1808        assert_eq!(relative_age(Duration::from_secs(86399)), "23h ago");
1809        assert_eq!(relative_age(Duration::from_secs(86400)), "1d ago");
1810        assert_eq!(relative_age(Duration::from_secs(86400 * 7)), "7d ago");
1811    }
1812}