Skip to main content

purple_ssh/
containers.rs

1use std::collections::HashMap;
2use std::time::{SystemTime, UNIX_EPOCH};
3
4use log::{error, info};
5
6use serde::{Deserialize, Serialize};
7
8use crate::ssh_context::{OwnedSshContext, SshContext};
9
10// ---------------------------------------------------------------------------
11// ContainerInfo model
12// ---------------------------------------------------------------------------
13
14/// Metadata for a single container (from `docker ps -a` / `podman ps -a`).
15///
16/// Deserialization is tolerant of both docker and podman JSON shapes.
17/// Docker uses `ID` plus scalar `Names`/`Ports`; podman uses `Id` plus
18/// `Names` as an array and `Ports` as an array of objects. The custom
19/// helpers below coerce both into the docker-shaped scalar fields the
20/// rest of purple (UI, cache, MCP) already understands.
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
22pub struct ContainerInfo {
23    #[serde(rename = "ID", alias = "Id")]
24    pub id: String,
25    #[serde(rename = "Names", deserialize_with = "deserialize_names_field")]
26    pub names: String,
27    #[serde(rename = "Image")]
28    pub image: String,
29    #[serde(rename = "State")]
30    pub state: String,
31    #[serde(rename = "Status", default)]
32    pub status: String,
33    // `default` covers the missing-key case directly via Default::default()
34    // and bypasses `deserialize_with`. The custom deserializer therefore
35    // only runs when `Ports` is present (scalar, array or explicit null).
36    #[serde(
37        rename = "Ports",
38        deserialize_with = "deserialize_ports_field",
39        default
40    )]
41    pub ports: String,
42}
43
44/// Accept `Names` as either a scalar string (docker) or an array of
45/// strings (podman). Multiple names join with `,` to match docker's
46/// own comma-joined rendering. Unexpected shapes (number, object,
47/// null) propagate as serde errors; `parse_container_ps` drops the
48/// offending row via `.ok()`, which is the right behaviour for a row
49/// that has lost its identity.
50fn deserialize_names_field<'de, D>(deserializer: D) -> Result<String, D::Error>
51where
52    D: serde::Deserializer<'de>,
53{
54    #[derive(Deserialize)]
55    #[serde(untagged)]
56    enum NamesField {
57        Scalar(String),
58        Array(Vec<String>),
59    }
60    match NamesField::deserialize(deserializer)? {
61        NamesField::Scalar(s) => Ok(s),
62        NamesField::Array(arr) => Ok(arr.join(",")),
63    }
64}
65
66/// Accept `Ports` as either a scalar string (docker) or an array of
67/// port objects (podman). Podman entries are rendered into the same
68/// `host_ip:host_port->container_port/proto` form docker emits, so
69/// downstream UI rendering stays uniform. An explicit JSON null is
70/// tolerated and produces an empty string: podman uses `null` to mean
71/// "no ports published", which is semantically valid and the row must
72/// remain visible.
73fn deserialize_ports_field<'de, D>(deserializer: D) -> Result<String, D::Error>
74where
75    D: serde::Deserializer<'de>,
76{
77    #[derive(Deserialize)]
78    #[serde(untagged)]
79    enum PortsField {
80        Scalar(String),
81        Array(Vec<PodmanPort>),
82    }
83    match Option::<PortsField>::deserialize(deserializer)? {
84        Some(PortsField::Scalar(s)) => Ok(s),
85        Some(PortsField::Array(arr)) => Ok(format_podman_ports(&arr)),
86        None => Ok(String::new()),
87    }
88}
89
90#[derive(Deserialize)]
91struct PodmanPort {
92    #[serde(default)]
93    host_ip: String,
94    #[serde(default)]
95    container_port: u32,
96    #[serde(default)]
97    host_port: u32,
98    #[serde(default = "podman_port_default_range")]
99    range: u32,
100    #[serde(default)]
101    protocol: String,
102}
103
104fn podman_port_default_range() -> u32 {
105    1
106}
107
108fn format_podman_ports(ports: &[PodmanPort]) -> String {
109    // ~24 chars per typical port entry. Pre-allocating avoids the
110    // intermediate Vec<String> + repeated re-allocations that the prior
111    // map/collect/join chain produced for compose stacks with many
112    // published ports.
113    let mut out = String::with_capacity(ports.len().saturating_mul(24));
114    for (i, p) in ports.iter().enumerate() {
115        if i > 0 {
116            out.push_str(", ");
117        }
118        write_podman_port(p, &mut out);
119    }
120    out
121}
122
123fn write_podman_port(p: &PodmanPort, out: &mut String) {
124    use std::fmt::Write as _;
125    let protocol = if p.protocol.is_empty() {
126        "tcp"
127    } else {
128        p.protocol.as_str()
129    };
130    if p.host_port != 0 {
131        // Podman emits an empty `host_ip` for both IPv4 wildcard and IPv6
132        // wildcard binds. Omit the prefix when unknown rather than
133        // mis-claim IPv4. Concrete addresses (e.g. 127.0.0.1, ::1) render
134        // verbatim with the docker `addr:port->...` form.
135        if !p.host_ip.is_empty() {
136            let _ = write!(out, "{}:", p.host_ip);
137        }
138        if p.range > 1 {
139            let _ = write!(
140                out,
141                "{}-{}->",
142                p.host_port,
143                p.host_port.saturating_add(p.range.saturating_sub(1))
144            );
145        } else {
146            let _ = write!(out, "{}->", p.host_port);
147        }
148    }
149    if p.range > 1 {
150        let _ = write!(
151            out,
152            "{}-{}",
153            p.container_port,
154            p.container_port.saturating_add(p.range.saturating_sub(1))
155        );
156    } else {
157        let _ = write!(out, "{}", p.container_port);
158    }
159    let _ = write!(out, "/{protocol}");
160}
161
162/// Try to parse one NDJSON line into `ContainerInfo`. Returns `None`
163/// for blank/non-JSON lines (MOTD/banner) without logging. JSON-shaped
164/// lines that fail to match the schema log at debug level so missing
165/// containers can be correlated to a concrete parse error rather than
166/// guessed from a shrunken list.
167fn try_parse_container_line(trimmed: &str) -> Option<ContainerInfo> {
168    if trimmed.is_empty() {
169        return None;
170    }
171    match serde_json::from_str(trimmed) {
172        Ok(c) => Some(c),
173        Err(e) if trimmed.starts_with('{') => {
174            log::debug!(
175                "[external] container parse: dropped JSON line: {} (err: {})",
176                &trimmed[..trimmed.len().min(120)],
177                e
178            );
179            None
180        }
181        Err(_) => None,
182    }
183}
184
185/// Parse NDJSON output from `docker ps --format '{{json .}}'` or
186/// `podman ps --format '{{json .}}'`. Used by tests and the public
187/// crate API exposed via `lib.rs`; the live SSH path streams through
188/// `parse_container_output` directly, so the binary build sees this
189/// helper as unused and the lint must be silenced.
190#[allow(dead_code)]
191pub fn parse_container_ps(output: &str) -> Vec<ContainerInfo> {
192    output
193        .lines()
194        .filter_map(|line| try_parse_container_line(line.trim()))
195        .collect()
196}
197
198// ---------------------------------------------------------------------------
199// ContainerRuntime
200// ---------------------------------------------------------------------------
201
202/// Supported container runtimes.
203#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
204pub enum ContainerRuntime {
205    Docker,
206    Podman,
207}
208
209impl ContainerRuntime {
210    /// Returns the CLI binary name.
211    pub fn as_str(&self) -> &'static str {
212        match self {
213            ContainerRuntime::Docker => "docker",
214            ContainerRuntime::Podman => "podman",
215        }
216    }
217}
218
219/// Detect runtime from command output by matching the LAST non-empty trimmed
220/// line. Only "docker" or "podman" are accepted. MOTD-resilient.
221/// Currently unused (sentinel-based detection handles this inline) but kept
222/// as a public utility for potential future two-step detection paths.
223#[allow(dead_code)]
224pub fn parse_runtime(output: &str) -> Option<ContainerRuntime> {
225    let last = output
226        .lines()
227        .rev()
228        .map(|l| l.trim())
229        .find(|l| !l.is_empty())?;
230    match last {
231        "docker" => Some(ContainerRuntime::Docker),
232        "podman" => Some(ContainerRuntime::Podman),
233        _ => None,
234    }
235}
236
237// ---------------------------------------------------------------------------
238// ContainerAction
239// ---------------------------------------------------------------------------
240
241/// Actions that can be performed on a container.
242#[derive(Copy, Clone, Debug, PartialEq)]
243pub enum ContainerAction {
244    Start,
245    Stop,
246    Restart,
247}
248
249impl ContainerAction {
250    /// Returns the CLI sub-command string.
251    pub fn as_str(&self) -> &'static str {
252        match self {
253            ContainerAction::Start => "start",
254            ContainerAction::Stop => "stop",
255            ContainerAction::Restart => "restart",
256        }
257    }
258}
259
260/// Build the shell command to perform an action on a container.
261pub fn container_action_command(
262    runtime: ContainerRuntime,
263    action: ContainerAction,
264    container_id: &str,
265) -> String {
266    format!("{} {} {}", runtime.as_str(), action.as_str(), container_id)
267}
268
269// ---------------------------------------------------------------------------
270// Container ID validation
271// ---------------------------------------------------------------------------
272
273/// Validate a container ID or name.
274/// Accepts ASCII alphanumeric, hyphen, underscore, dot.
275/// Rejects empty, non-ASCII, shell metacharacters, colon.
276pub fn validate_container_id(id: &str) -> Result<(), String> {
277    if id.is_empty() {
278        return Err(crate::messages::CONTAINER_ID_EMPTY.to_string());
279    }
280    for c in id.chars() {
281        if !c.is_ascii_alphanumeric() && c != '-' && c != '_' && c != '.' {
282            return Err(crate::messages::container_id_invalid_char(c));
283        }
284    }
285    Ok(())
286}
287
288// ---------------------------------------------------------------------------
289// Combined SSH command + output parsing
290// ---------------------------------------------------------------------------
291
292/// Build the SSH command string for listing containers. Output is the
293/// container NDJSON, then the `##purple:engine##` sentinel, then the
294/// daemon version on its own line. The version subcall is suffixed with
295/// `|| true` so its failure cannot mask a `docker ps` error: the chain
296/// surfaces ps's exit code, while a missing version line just yields
297/// `engine_version: None` downstream.
298///
299/// - `Some(Docker)` / `Some(Podman)`: direct listing for the known runtime.
300/// - `None`: combined detection + listing with sentinel markers in one SSH call.
301pub fn container_list_command(runtime: Option<ContainerRuntime>) -> String {
302    match runtime {
303        Some(ContainerRuntime::Docker) => concat!(
304            "docker ps -a --format '{{json .}}' && ",
305            "echo '##purple:engine##' && ",
306            "{ docker version --format '{{.Server.Version}}' 2>/dev/null || true; }"
307        )
308        .to_string(),
309        Some(ContainerRuntime::Podman) => concat!(
310            "podman ps -a --format '{{json .}}' && ",
311            "echo '##purple:engine##' && ",
312            "{ podman version --format '{{.Server.Version}}' 2>/dev/null || true; }"
313        )
314        .to_string(),
315        None => concat!(
316            "if command -v docker >/dev/null 2>&1; then ",
317            "echo '##purple:docker##' && docker ps -a --format '{{json .}}' && ",
318            "echo '##purple:engine##' && ",
319            "{ docker version --format '{{.Server.Version}}' 2>/dev/null || true; }; ",
320            "elif command -v podman >/dev/null 2>&1; then ",
321            "echo '##purple:podman##' && podman ps -a --format '{{json .}}' && ",
322            "echo '##purple:engine##' && ",
323            "{ podman version --format '{{.Server.Version}}' 2>/dev/null || true; }; ",
324            "else echo '##purple:none##'; fi"
325        )
326        .to_string(),
327    }
328}
329
330/// Parsed result of a container listing command. `engine_version` is the
331/// daemon's `Server.Version` (best-effort, `None` when the version sub-call
332/// failed or the remote runtime predates the engine sentinel).
333#[derive(Debug, Clone, PartialEq)]
334pub struct ContainerListing {
335    pub runtime: ContainerRuntime,
336    pub engine_version: Option<String>,
337    pub containers: Vec<ContainerInfo>,
338}
339
340/// Parse the stdout of a container listing command.
341///
342/// When sentinels are present (combined detection run): extract runtime from
343/// the sentinel line, parse remaining lines as NDJSON. When `caller_runtime`
344/// is provided (subsequent run with known runtime): parse all lines as NDJSON.
345/// In both cases, `##purple:engine##` splits the listing from the optional
346/// trailing daemon version line.
347pub fn parse_container_output(
348    output: &str,
349    caller_runtime: Option<ContainerRuntime>,
350) -> Result<ContainerListing, String> {
351    let runtime = match output
352        .lines()
353        .map(str::trim)
354        .find(|l| l.starts_with("##purple:") && (*l != "##purple:engine##"))
355    {
356        Some("##purple:none##") => {
357            return Err(crate::messages::CONTAINER_RUNTIME_MISSING.to_string());
358        }
359        Some("##purple:docker##") => ContainerRuntime::Docker,
360        Some("##purple:podman##") => ContainerRuntime::Podman,
361        Some(other) => return Err(crate::messages::container_unknown_sentinel(other)),
362        None => match caller_runtime {
363            Some(rt) => rt,
364            None => return Err("No sentinel found and no runtime provided.".to_string()),
365        },
366    };
367
368    // Bound the version capture to the first non-empty post-sentinel line.
369    // A trailing logout banner or MOTD after `docker version` would
370    // otherwise concat into the cached engine_version and surface as
371    // "25.0.3\n-- session closed --" in the Runtime field.
372    let mut engine_version: Option<String> = None;
373    let mut after_engine = false;
374    let mut containers: Vec<ContainerInfo> = Vec::new();
375    // Stream-parse each NDJSON line during the sentinel sweep so we never
376    // build an intermediate copy of the listing block. At 1000 containers
377    // that intermediate buffer would cost ~300 KB and an extra `.lines()`
378    // walk; this loop is O(lines) with zero auxiliary allocation.
379    for line in output.lines() {
380        let trimmed = line.trim();
381        if trimmed == "##purple:engine##" {
382            after_engine = true;
383            continue;
384        }
385        if trimmed.starts_with("##purple:") {
386            continue;
387        }
388        if after_engine {
389            if !trimmed.is_empty() && engine_version.is_none() {
390                engine_version = Some(trimmed.to_string());
391            }
392            continue;
393        }
394        if let Some(c) = try_parse_container_line(trimmed) {
395            containers.push(c);
396        }
397    }
398
399    // Fedora CoreOS, podman-machine and other distros symlink `docker` to
400    // `podman`. Detection picks the docker branch but the JSON shape is
401    // pure podman (array `Names`, lowercase `Id`). When that happens we
402    // relabel the runtime so downstream consumers (MCP runtime field, host
403    // detail label, sort/filter by runtime) match reality.
404    let runtime = if matches!(runtime, ContainerRuntime::Docker) && looks_like_podman(output) {
405        log::debug!(
406            "[external] container detection: docker sentinel emitted podman-shaped JSON, relabeling runtime to Podman"
407        );
408        ContainerRuntime::Podman
409    } else {
410        runtime
411    };
412
413    log::debug!(
414        "[external] container listing parsed: runtime={:?} version={:?} containers={}",
415        runtime,
416        engine_version,
417        containers.len()
418    );
419    Ok(ContainerListing {
420        runtime,
421        engine_version,
422        containers,
423    })
424}
425
426/// Heuristic: does the raw `ps` output look like podman JSON?
427/// Podman emits `"Names":[` (array) and `"Id":` (lowercase d) for every row.
428/// Docker emits `"Names":"` (string) and `"ID":` (uppercase D). We sample the
429/// first JSON-shaped non-sentinel line. The check is fast (substring scan)
430/// and only matters when the docker sentinel was emitted by a podman shim.
431/// Accepts both `"Names":[` and `"Names": [` (pretty-printed) so handwritten
432/// test fixtures and any intermediate JSON formatter cannot defeat the
433/// detector silently.
434fn looks_like_podman(output: &str) -> bool {
435    for line in output.lines() {
436        let trimmed = line.trim();
437        if trimmed.is_empty() || trimmed.starts_with("##purple:") || !trimmed.starts_with('{') {
438            continue;
439        }
440        return trimmed.contains("\"Names\":[") || trimmed.contains("\"Names\": [");
441    }
442    false
443}
444
445// ---------------------------------------------------------------------------
446// SSH fetch functions
447// ---------------------------------------------------------------------------
448
449/// Error from a container listing operation. Preserves the detected runtime
450/// even when the `ps` command fails so it can be cached for future calls.
451#[derive(Debug)]
452pub struct ContainerError {
453    pub runtime: Option<ContainerRuntime>,
454    pub message: String,
455}
456
457impl std::fmt::Display for ContainerError {
458    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
459        write!(f, "{}", self.message)
460    }
461}
462
463/// Translate SSH stderr into a user-friendly error message.
464fn friendly_container_error(stderr: &str, code: Option<i32>) -> String {
465    let lower = stderr.to_lowercase();
466    if lower.contains("remote host identification has changed")
467        || (lower.contains("host key for") && lower.contains("has changed"))
468    {
469        log::debug!("[external] Host key CHANGED detected; returning HOST_KEY_CHANGED toast");
470        crate::messages::HOST_KEY_CHANGED.to_string()
471    } else if lower.contains("host key verification failed")
472        || lower.contains("no matching host key")
473        || lower.contains("no ed25519 host key is known")
474        || lower.contains("no rsa host key is known")
475        || lower.contains("no ecdsa host key is known")
476        || lower.contains("host key is not known")
477    {
478        log::debug!("[external] Host key UNKNOWN detected; returning HOST_KEY_UNKNOWN toast");
479        crate::messages::HOST_KEY_UNKNOWN.to_string()
480    } else if lower.contains("command not found") {
481        crate::messages::CONTAINER_RUNTIME_NOT_FOUND.to_string()
482    } else if crate::connection::auth_refused(stderr)
483        && !crate::security_key::sign_failures(stderr).is_empty()
484    {
485        // The login itself failed on the key. Checked before the generic
486        // refusal, because the docker group is not the answer here.
487        log::debug!("[external] Security key did not sign; returning the PIN hint");
488        crate::messages::CONTAINER_SECURITY_KEY_PIN.to_string()
489    } else if lower.contains("permission denied") || lower.contains("got permission denied") {
490        crate::messages::CONTAINER_PERMISSION_DENIED.to_string()
491    } else if lower.contains("cannot connect to the docker daemon")
492        || lower.contains("cannot connect to podman")
493    {
494        crate::messages::CONTAINER_DAEMON_NOT_RUNNING.to_string()
495    } else if lower.contains("connection refused") {
496        crate::messages::CONTAINER_CONNECTION_REFUSED.to_string()
497    } else if lower.contains("no route to host") || lower.contains("network is unreachable") {
498        crate::messages::CONTAINER_HOST_UNREACHABLE.to_string()
499    } else {
500        crate::messages::container_command_failed(code.unwrap_or(1))
501    }
502}
503
504/// Fetch container list synchronously via SSH.
505/// Follows the `fetch_remote_listing` pattern.
506pub fn fetch_containers(
507    ctx: &SshContext<'_>,
508    cached_runtime: Option<ContainerRuntime>,
509) -> Result<ContainerListing, ContainerError> {
510    let command = container_list_command(cached_runtime);
511    let result = crate::snippet::run_snippet_ctx(ctx, &command, true);
512    let alias = ctx.alias;
513    match result {
514        Ok(r) if r.status.success() => {
515            parse_container_output(&r.stdout, cached_runtime).map_err(|e| {
516                error!("[external] Container list parse failed: alias={alias}: {e}");
517                ContainerError {
518                    runtime: cached_runtime,
519                    message: e,
520                }
521            })
522        }
523        Ok(r) => {
524            let stderr = r.stderr.trim().to_string();
525            let msg = friendly_container_error(&stderr, r.status.code());
526            // A non-zero remote exit (docker missing, daemon down, ...) is a
527            // routine remote status, not an ssh connection failure: keep it out
528            // of the error level.
529            log::log!(
530                crate::connection::remote_exit_log_level(r.status.code().unwrap_or(-1)),
531                "[external] Container fetch failed: alias={alias}: {msg}"
532            );
533            Err(ContainerError {
534                runtime: cached_runtime,
535                message: msg,
536            })
537        }
538        Err(e) => {
539            error!("[external] Container fetch failed: alias={alias}: {e}");
540            Err(ContainerError {
541                runtime: cached_runtime,
542                message: e.to_string(),
543            })
544        }
545    }
546}
547
548/// Spawn a background thread to fetch container listings.
549/// Follows the `spawn_remote_listing` pattern.
550pub fn spawn_container_listing<F>(
551    ctx: OwnedSshContext,
552    cached_runtime: Option<ContainerRuntime>,
553    send: F,
554) where
555    F: FnOnce(String, Result<ContainerListing, ContainerError>) + Send + 'static,
556{
557    std::thread::spawn(move || {
558        let result = fetch_containers(&ctx.borrow(), cached_runtime);
559        send(ctx.alias, result);
560    });
561}
562
563/// Spawn a background thread to perform a container action (start/stop/restart).
564/// Validates the container ID before executing.
565pub fn spawn_container_action<F>(
566    ctx: OwnedSshContext,
567    runtime: ContainerRuntime,
568    action: ContainerAction,
569    container_id: String,
570    send: F,
571) where
572    F: FnOnce(String, ContainerAction, Result<(), String>) + Send + 'static,
573{
574    std::thread::spawn(move || {
575        if let Err(e) = validate_container_id(&container_id) {
576            log::debug!(
577                "[purple] container action {} blocked on alias={}: invalid container_id: {}",
578                action.as_str(),
579                ctx.alias,
580                e
581            );
582            send(ctx.alias, action, Err(e));
583            return;
584        }
585        let alias = &ctx.alias;
586        info!(
587            "[external] Container action: {} container={container_id} alias={alias}",
588            action.as_str()
589        );
590        let command = container_action_command(runtime, action, &container_id);
591        let result = crate::snippet::run_snippet_ctx(&ctx.borrow(), &command, true);
592        match result {
593            Ok(r) if r.status.success() => send(ctx.alias, action, Ok(())),
594            Ok(r) => {
595                let err = friendly_container_error(r.stderr.trim(), r.status.code());
596                // Routine remote exit (already stopped, no such container, ...)
597                // stays out of the error level; only an ssh transport failure
598                // (255) is a genuine connection error.
599                log::log!(
600                    crate::connection::remote_exit_log_level(r.status.code().unwrap_or(-1)),
601                    "[external] Container {} failed: alias={alias} container={container_id}: {err}",
602                    action.as_str()
603                );
604                send(ctx.alias, action, Err(err));
605            }
606            Err(e) => {
607                error!(
608                    "[external] Container {} failed: alias={alias} container={container_id}: {e}",
609                    action.as_str()
610                );
611                send(ctx.alias, action, Err(e.to_string()));
612            }
613        }
614    });
615}
616
617// ---------------------------------------------------------------------------
618// ContainerInspect: subset of `docker inspect` output we surface in the UI
619// ---------------------------------------------------------------------------
620
621/// Parsed subset of `docker inspect <id>` (or `podman inspect`). Only the
622/// fields purple's container detail panel renders are extracted; the rest
623/// of the JSON document is discarded so cache size stays bounded.
624#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
625pub struct ContainerInspect {
626    pub exit_code: i32,
627    pub oom_killed: bool,
628    pub started_at: String,
629    pub finished_at: String,
630    pub created_at: String,
631    /// `Some("healthy" | "unhealthy" | "starting")` when the image defines
632    /// a HEALTHCHECK. `None` when no healthcheck is configured.
633    pub health: Option<String>,
634    pub restart_count: u32,
635    pub command: Option<Vec<String>>,
636    pub entrypoint: Option<Vec<String>>,
637    pub env_count: usize,
638    pub mount_count: usize,
639    pub networks: Vec<NetworkInfo>,
640    // Audit-relevant fields surfaced in the right-side detail panel.
641    pub image_digest: Option<String>,
642    pub restart_policy: Option<String>,
643    pub user: Option<String>,
644    pub privileged: bool,
645    pub readonly_rootfs: bool,
646    pub apparmor_profile: Option<String>,
647    pub seccomp_profile: Option<String>,
648    pub cap_add: Vec<String>,
649    pub cap_drop: Vec<String>,
650    pub mounts: Vec<MountInfo>,
651    pub compose_project: Option<String>,
652    pub compose_service: Option<String>,
653    // Lifecycle / runtime details surfaced in the LIFECYCLE card.
654    pub pid: Option<u32>,
655    pub stop_signal: Option<String>,
656    pub stop_timeout: Option<u32>,
657    // App identity from OCI image labels (visible in APP card).
658    pub image_version: Option<String>,
659    pub image_revision: Option<String>,
660    pub image_source: Option<String>,
661    pub working_dir: Option<String>,
662    pub hostname: Option<String>,
663    // Resource constraints (RESOURCES card). 0 / None means unlimited.
664    pub memory_limit: Option<u64>,
665    pub cpu_limit_nanos: Option<u64>,
666    pub pids_limit: Option<i64>,
667    pub log_driver: Option<String>,
668    // Network mode (NETWORK card): bridge / host / none / container:xyz.
669    pub network_mode: Option<String>,
670    // Healthcheck definition + recent stats (HEALTH card when present).
671    pub health_test: Option<Vec<String>>,
672    pub health_interval_ns: Option<u64>,
673    pub health_failing_streak: Option<u32>,
674}
675
676#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
677pub struct NetworkInfo {
678    pub name: String,
679    pub ip_address: String,
680}
681
682#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
683pub struct MountInfo {
684    pub source: String,
685    pub destination: String,
686    pub read_only: bool,
687}
688
689/// Build the SSH command string for inspecting a single container.
690///
691/// Callers MUST validate `container_id` with `validate_container_id` before
692/// reaching this builder. Restricted to crate visibility so a future caller
693/// outside this crate cannot accidentally skip the guard.
694pub(crate) fn container_inspect_command(runtime: ContainerRuntime, container_id: &str) -> String {
695    format!("{} inspect {}", runtime.as_str(), container_id)
696}
697
698/// Translate a non-zero docker/podman exit code into a short
699/// human-readable hint. Returns `None` for codes without a well-known
700/// meaning so the UI can fall back to the bare number. Exit 0 has no
701/// entry because the detail panel only annotates failed exits.
702/// Sources: docker docs + Linux signal table.
703pub fn exit_code_meaning(code: i32) -> Option<&'static str> {
704    match code {
705        1 => Some("application error"),
706        125 => Some("docker run failed"),
707        126 => Some("command not executable"),
708        127 => Some("command not found"),
709        130 => Some("interrupted (SIGINT)"),
710        137 => Some("killed (SIGKILL / OOM)"),
711        139 => Some("segfault (SIGSEGV)"),
712        143 => Some("terminated (SIGTERM)"),
713        _ => None,
714    }
715}
716
717/// Parse `docker inspect <id>` stdout into `ContainerInspect`. The command
718/// always returns a JSON array; we take the first element. Missing fields
719/// degrade to defaults rather than fail so a partial response still
720/// renders something useful.
721pub fn parse_container_inspect(output: &str) -> Result<ContainerInspect, String> {
722    let trimmed = output.trim();
723    if trimmed.is_empty() {
724        return Err(crate::messages::CONTAINER_INSPECT_EMPTY.to_string());
725    }
726    let value: serde_json::Value = serde_json::from_str(trimmed)
727        .map_err(|e| crate::messages::container_inspect_parse_failed(&e.to_string()))?;
728    let entry = value
729        .as_array()
730        .and_then(|a| a.first())
731        .ok_or_else(|| crate::messages::CONTAINER_INSPECT_EMPTY.to_string())?;
732
733    let state = &entry["State"];
734    let config = &entry["Config"];
735    let network_settings = &entry["NetworkSettings"];
736
737    let exit_code = state["ExitCode"].as_i64().unwrap_or(0) as i32;
738    // Podman 5.x and docker both emit `OOMKilled`. Podman 3.x (still the
739    // packaged default on Ubuntu 22.04 LTS) emits `OomKilled`. Try both so
740    // OOM-killed containers surface in the ATTENTION card regardless of
741    // remote runtime version.
742    let oom_killed = state["OOMKilled"]
743        .as_bool()
744        .or_else(|| state["OomKilled"].as_bool())
745        .unwrap_or(false);
746    let started_at = state["StartedAt"].as_str().unwrap_or("").to_string();
747    let finished_at = state["FinishedAt"].as_str().unwrap_or("").to_string();
748    let health = state
749        .get("Health")
750        .and_then(|h| h.get("Status"))
751        .and_then(|s| s.as_str())
752        .map(|s| s.to_string());
753    let restart_count = entry["RestartCount"].as_u64().unwrap_or(0) as u32;
754
755    let command = config["Cmd"].as_array().map(|arr| {
756        arr.iter()
757            .filter_map(|v| v.as_str().map(|s| s.to_string()))
758            .collect()
759    });
760    let entrypoint = config["Entrypoint"].as_array().map(|arr| {
761        arr.iter()
762            .filter_map(|v| v.as_str().map(|s| s.to_string()))
763            .collect()
764    });
765    let env_count = config["Env"].as_array().map(|arr| arr.len()).unwrap_or(0);
766    let mount_count = entry["Mounts"].as_array().map(|arr| arr.len()).unwrap_or(0);
767
768    let networks = network_settings
769        .get("Networks")
770        .and_then(|n| n.as_object())
771        .map(|map| {
772            map.iter()
773                .map(|(name, cfg)| NetworkInfo {
774                    name: name.clone(),
775                    ip_address: cfg
776                        .get("IPAddress")
777                        .and_then(|v| v.as_str())
778                        .unwrap_or("")
779                        .to_string(),
780                })
781                .collect::<Vec<_>>()
782        })
783        .unwrap_or_default();
784
785    let host_config = &entry["HostConfig"];
786
787    let image_digest = entry["Image"]
788        .as_str()
789        .filter(|s| !s.is_empty())
790        .map(|s| s.to_string());
791    let restart_policy = host_config
792        .get("RestartPolicy")
793        .and_then(|p| p.get("Name"))
794        .and_then(|s| s.as_str())
795        .filter(|s| !s.is_empty() && *s != "no")
796        .map(|s| s.to_string());
797    let user = config["User"]
798        .as_str()
799        .filter(|s| !s.is_empty())
800        .map(|s| s.to_string());
801    let privileged = host_config["Privileged"].as_bool().unwrap_or(false);
802    let readonly_rootfs = host_config["ReadonlyRootfs"].as_bool().unwrap_or(false);
803    let apparmor_profile = host_config["AppArmorProfile"]
804        .as_str()
805        .or_else(|| entry["AppArmorProfile"].as_str())
806        .filter(|s| !s.is_empty())
807        .map(|s| s.to_string());
808    let seccomp_profile = host_config["SecurityOpt"].as_array().and_then(|arr| {
809        arr.iter()
810            .filter_map(|v| v.as_str())
811            .find_map(|s| s.strip_prefix("seccomp=").map(|v| v.to_string()))
812    });
813    let cap_add = host_config["CapAdd"]
814        .as_array()
815        .map(|arr| {
816            arr.iter()
817                .filter_map(|v| v.as_str().map(|s| s.to_string()))
818                .collect()
819        })
820        .unwrap_or_default();
821    let cap_drop = host_config["CapDrop"]
822        .as_array()
823        .map(|arr| {
824            arr.iter()
825                .filter_map(|v| v.as_str().map(|s| s.to_string()))
826                .collect()
827        })
828        .unwrap_or_default();
829    let mounts = entry["Mounts"]
830        .as_array()
831        .map(|arr| {
832            arr.iter()
833                .map(|m| MountInfo {
834                    source: m["Source"].as_str().unwrap_or("").to_string(),
835                    destination: m["Destination"].as_str().unwrap_or("").to_string(),
836                    read_only: !m["RW"].as_bool().unwrap_or(true),
837                })
838                .collect()
839        })
840        .unwrap_or_default();
841    let labels = config.get("Labels").and_then(|l| l.as_object());
842    let label = |key: &str| {
843        labels
844            .and_then(|l| l.get(key))
845            .and_then(|v| v.as_str())
846            .filter(|s| !s.is_empty())
847            .map(|s| s.to_string())
848    };
849    let compose_project = label("com.docker.compose.project");
850    let compose_service = label("com.docker.compose.service");
851    let image_version = label("org.opencontainers.image.version");
852    let image_revision = label("org.opencontainers.image.revision");
853    let image_source = label("org.opencontainers.image.source");
854
855    let created_at = entry["Created"].as_str().unwrap_or("").to_string();
856    // State.Pid is `0` when the container is not running. Drop the zero so
857    // the UI does not render a misleading "pid 0" row for exited rows.
858    let pid = state["Pid"].as_u64().filter(|n| *n > 0).map(|n| n as u32);
859    let hostname = config["Hostname"]
860        .as_str()
861        .filter(|s| !s.is_empty())
862        .map(|s| s.to_string());
863    let working_dir = config["WorkingDir"]
864        .as_str()
865        .filter(|s| !s.is_empty())
866        .map(|s| s.to_string());
867    let stop_signal = config["StopSignal"]
868        .as_str()
869        .filter(|s| !s.is_empty())
870        .map(|s| s.to_string());
871    let stop_timeout = config["StopTimeout"].as_u64().map(|n| n as u32);
872
873    let network_mode = host_config["NetworkMode"]
874        .as_str()
875        .filter(|s| !s.is_empty() && *s != "default")
876        .map(|s| s.to_string());
877    // HostConfig.Memory is bytes, 0 = unlimited (drop). Same for NanoCpus.
878    let memory_limit = host_config["Memory"].as_u64().filter(|n| *n > 0);
879    let cpu_limit_nanos = host_config["NanoCpus"].as_u64().filter(|n| *n > 0);
880    // PidsLimit is i64. 0 or -1 means unlimited; drop both.
881    let pids_limit = host_config["PidsLimit"].as_i64().filter(|n| *n > 0);
882    // LogConfig.Type defaults to "json-file" on docker. Always carry it
883    // so the renderer can decide whether to surface "Logs" only when
884    // non-default.
885    let log_driver = host_config
886        .get("LogConfig")
887        .and_then(|l| l.get("Type"))
888        .and_then(|v| v.as_str())
889        .filter(|s| !s.is_empty())
890        .map(|s| s.to_string());
891
892    let healthcheck = config.get("Healthcheck");
893    let health_test = healthcheck
894        .and_then(|h| h.get("Test"))
895        .and_then(|t| t.as_array())
896        .map(|arr| {
897            arr.iter()
898                .filter_map(|v| v.as_str().map(|s| s.to_string()))
899                .collect::<Vec<_>>()
900        })
901        .filter(|v| !v.is_empty());
902    let health_interval_ns = healthcheck
903        .and_then(|h| h.get("Interval"))
904        .and_then(|v| v.as_u64())
905        .filter(|n| *n > 0);
906    let health_failing_streak = state
907        .get("Health")
908        .and_then(|h| h.get("FailingStreak"))
909        .and_then(|v| v.as_u64())
910        .map(|n| n as u32);
911
912    Ok(ContainerInspect {
913        exit_code,
914        oom_killed,
915        started_at,
916        finished_at,
917        created_at,
918        health,
919        restart_count,
920        command,
921        entrypoint,
922        env_count,
923        mount_count,
924        networks,
925        image_digest,
926        restart_policy,
927        user,
928        privileged,
929        readonly_rootfs,
930        apparmor_profile,
931        seccomp_profile,
932        cap_add,
933        cap_drop,
934        mounts,
935        compose_project,
936        compose_service,
937        pid,
938        stop_signal,
939        stop_timeout,
940        image_version,
941        image_revision,
942        image_source,
943        working_dir,
944        hostname,
945        memory_limit,
946        cpu_limit_nanos,
947        pids_limit,
948        log_driver,
949        network_mode,
950        health_test,
951        health_interval_ns,
952        health_failing_streak,
953    })
954}
955
956/// Parse a Docker `Up …` status string into a compact uptime label.
957/// Returns `None` for any non-running state (Exited, Created, Restarting,
958/// Paused without an `Up` prefix, empty). Cells render `<1m` for
959/// sub-minute uptimes, `1m` / `5m` / `12h` / `5w` / `3mo` / `2y` otherwise.
960/// Format follows Docker's `units.HumanDuration`.
961pub fn parse_uptime_from_status(s: &str) -> Option<String> {
962    let body = s.strip_prefix("Up ")?;
963    let body = body.split('(').next()?.trim();
964    if body == "Less than a second" {
965        return Some("<1m".to_string());
966    }
967    if body == "About a minute" {
968        return Some("1m".to_string());
969    }
970    if body == "About an hour" {
971        return Some("1h".to_string());
972    }
973    let mut parts = body.split_whitespace();
974    let count: u64 = parts.next()?.parse().ok()?;
975    let unit = parts.next()?;
976    let suffix = match unit {
977        "second" | "seconds" => return Some("<1m".to_string()),
978        "minute" | "minutes" => "m",
979        "hour" | "hours" => "h",
980        "day" | "days" => "d",
981        "week" | "weeks" => "w",
982        "month" | "months" => "mo",
983        "year" | "years" => "y",
984        _ => return None,
985    };
986    Some(format!("{count}{suffix}"))
987}
988
989/// Synchronously fetch + parse `container inspect`. Validates the
990/// container ID before issuing the SSH call.
991pub fn fetch_container_inspect(
992    ctx: &SshContext<'_>,
993    runtime: ContainerRuntime,
994    container_id: &str,
995) -> Result<ContainerInspect, String> {
996    validate_container_id(container_id)?;
997    let command = container_inspect_command(runtime, container_id);
998    let result = crate::snippet::run_snippet_ctx(ctx, &command, true);
999    match result {
1000        Ok(r) if r.status.success() => parse_container_inspect(&r.stdout),
1001        Ok(r) => Err(crate::messages::container_command_failed(
1002            r.status.code().unwrap_or(1),
1003        )),
1004        Err(e) => Err(e.to_string()),
1005    }
1006}
1007
1008/// Spawn a background thread to run `container inspect`. Mirrors the
1009/// `spawn_container_listing` pattern so the call site looks identical.
1010pub fn spawn_container_inspect_listing<F>(
1011    ctx: OwnedSshContext,
1012    runtime: ContainerRuntime,
1013    container_id: String,
1014    send: F,
1015) where
1016    F: FnOnce(String, String, Result<ContainerInspect, String>) + Send + 'static,
1017{
1018    std::thread::spawn(move || {
1019        let result = fetch_container_inspect(&ctx.borrow(), runtime, &container_id);
1020        send(ctx.alias, container_id, result);
1021    });
1022}
1023
1024/// Build the `<runtime> logs --tail <n> <id>` command. The
1025/// `--tail` cap is enforced server-side so the SSH stream stays
1026/// bounded even on a noisy container.
1027pub(crate) fn container_logs_command(
1028    runtime: ContainerRuntime,
1029    container_id: &str,
1030    tail: usize,
1031) -> String {
1032    format!("{} logs --tail {} {}", runtime.as_str(), tail, container_id)
1033}
1034
1035/// Synchronously fetch logs and split into lines. Returns the raw
1036/// captured stdout split on `\n` so the renderer does not have to
1037/// re-parse. Empty trailing lines are dropped.
1038pub fn fetch_container_logs(
1039    ctx: &SshContext<'_>,
1040    runtime: ContainerRuntime,
1041    container_id: &str,
1042    tail: usize,
1043) -> Result<Vec<String>, String> {
1044    validate_container_id(container_id)?;
1045    let command = container_logs_command(runtime, container_id, tail);
1046    let result = crate::snippet::run_snippet_ctx(ctx, &command, true);
1047    match result {
1048        Ok(r) if r.status.success() => Ok(parse_log_output(&r.stdout, &r.stderr)),
1049        Ok(r) => Err(crate::messages::container_command_failed(
1050            r.status.code().unwrap_or(1),
1051        )),
1052        Err(e) => Err(e.to_string()),
1053    }
1054}
1055
1056/// Merge stdout (app logs) and stderr (errors) into a single chronological
1057/// stream. Many container runtimes split levels across the two streams;
1058/// re-interleaving them is closer to what `docker logs` shows on a TTY.
1059/// Trailing blank lines are stripped from each stream before merging so a
1060/// stdout block that ends in a newline does not introduce a phantom empty
1061/// row between the two streams.
1062pub(crate) fn parse_log_output(stdout: &str, stderr: &str) -> Vec<String> {
1063    let mut lines: Vec<String> = stdout.lines().map(|s| s.to_string()).collect();
1064    while lines.last().map(|s| s.is_empty()).unwrap_or(false) {
1065        lines.pop();
1066    }
1067    for s in stderr.lines() {
1068        lines.push(s.to_string());
1069    }
1070    while lines.last().map(|s| s.is_empty()).unwrap_or(false) {
1071        lines.pop();
1072    }
1073    lines
1074}
1075
1076/// Spawn a background thread to run `container logs`. Same shape as
1077/// `spawn_container_inspect_listing`. In demo mode the SSH call is
1078/// short-circuited with a deterministic synthetic log stream so the
1079/// logs viewer (and its `/` search) is exercisable without a remote.
1080pub fn spawn_container_logs_fetch<F>(
1081    ctx: OwnedSshContext,
1082    runtime: ContainerRuntime,
1083    container_id: String,
1084    container_name: String,
1085    tail: usize,
1086    send: F,
1087) where
1088    F: FnOnce(String, String, String, Result<Vec<String>, String>) + Send + 'static,
1089{
1090    if crate::demo_flag::is_demo() {
1091        let lines = demo_log_lines(&container_name, tail);
1092        log::debug!(
1093            "[purple] container_logs_fetch: demo short-circuit alias={} id={} lines={}",
1094            ctx.alias,
1095            container_id,
1096            lines.len()
1097        );
1098        send(ctx.alias, container_id, container_name, Ok(lines));
1099        return;
1100    }
1101    std::thread::spawn(move || {
1102        let result = fetch_container_logs(&ctx.borrow(), runtime, &container_id, tail);
1103        send(ctx.alias, container_id, container_name, result);
1104    });
1105}
1106
1107/// Generate a deterministic stream of fake log lines for demo mode.
1108/// Mixes INFO / WARN / ERROR / DEBUG with realistic-looking content
1109/// (HTTP requests, DB pings, retries, timeouts) so the user can
1110/// usefully press `/` and find matches under `--demo`. Anchored to
1111/// `demo_flag::now_secs()` so timestamps stay stable across renders.
1112pub(crate) fn demo_log_lines(container_name: &str, tail: usize) -> Vec<String> {
1113    use std::time::{Duration, UNIX_EPOCH};
1114    // Cheap hash to fan out per-container variation without bringing
1115    // `rand` into the binary.
1116    let seed: u32 = container_name
1117        .bytes()
1118        .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32));
1119
1120    // Templates rotate every line. Index 0 is the freshest log line.
1121    let templates: &[&str] = &[
1122        "INFO  [{}] handled GET /api/v1/health 200 in 14ms",
1123        "INFO  [{}] handled POST /api/v1/orders 201 in 38ms (user_id={user})",
1124        "DEBUG [{}] cache hit key=session:{user} ttl=3600",
1125        "INFO  [{}] handled GET /api/v1/users/{user} 200 in 11ms",
1126        "WARN  [{}] slow query detected duration=812ms statement=SELECT FROM orders",
1127        "INFO  [{}] connection pool size=12 idle=8 in_use=4",
1128        "DEBUG [{}] flushing metrics batch size=64",
1129        "INFO  [{}] handled GET /api/v1/inventory 200 in 22ms",
1130        "ERROR [{}] upstream timeout after 5000ms target=payments retry=1",
1131        "WARN  [{}] retrying request attempt=2 backoff=250ms",
1132        "INFO  [{}] handled POST /api/v1/login 200 in 31ms",
1133        "DEBUG [{}] gc cycle reclaimed=42MB took=18ms",
1134        "INFO  [{}] heartbeat ok rss=128MB cpu=4%",
1135        "ERROR [{}] failed to acquire lock resource=cache_warmer waiter=3",
1136        "INFO  [{}] handled DELETE /api/v1/sessions/{user} 204 in 9ms",
1137        "WARN  [{}] disk usage at 78% mount=/data threshold=80%",
1138        "INFO  [{}] handled GET /api/v1/search?q=widget 200 in 47ms",
1139        "DEBUG [{}] websocket ping rtt=12ms",
1140    ];
1141
1142    // Always use `demo_flag::now_secs()` even outside demo mode: the
1143    // helper's OnceLock caches the first wallclock value, so repeated
1144    // calls within a process return the same instant. Branching on
1145    // `is_demo()` would let tests cross a second boundary and flake.
1146    let now = crate::demo_flag::now_secs();
1147
1148    // Map each line to a timestamp working backwards from now. One log
1149    // every 3 seconds keeps the time range realistic for a 200-line tail.
1150    let mut lines = Vec::with_capacity(tail);
1151    for i in 0..tail {
1152        let template = templates[(i + seed as usize) % templates.len()];
1153        let user = 1000 + ((seed as usize + i * 7) % 50);
1154        let secs_back = (i as u64) * 3;
1155        let line_time = UNIX_EPOCH + Duration::from_secs(now.saturating_sub(secs_back));
1156        let ts = format_demo_timestamp(line_time);
1157        let body = template
1158            .replace("{}", container_name)
1159            .replace("{user}", &user.to_string());
1160        lines.push(format!("{} {}", ts, body));
1161    }
1162    // Render flush-top with the newest line at the bottom of the
1163    // viewport, matching real `docker logs --tail` output.
1164    lines.reverse();
1165    lines
1166}
1167
1168fn format_demo_timestamp(t: std::time::SystemTime) -> String {
1169    use std::time::UNIX_EPOCH;
1170    let secs = t
1171        .duration_since(UNIX_EPOCH)
1172        .map(|d| d.as_secs())
1173        .unwrap_or(0);
1174    // Fast UTC breakdown without dragging in chrono. Good enough for a
1175    // demo timestamp where leap seconds / DST are irrelevant.
1176    let days_since_epoch = (secs / 86_400) as i64;
1177    let seconds_in_day = (secs % 86_400) as u32;
1178    let h = seconds_in_day / 3600;
1179    let m = (seconds_in_day % 3600) / 60;
1180    let s = seconds_in_day % 60;
1181    let (y, mo, d) = civil_from_days(days_since_epoch);
1182    format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}", y, mo, d, h, m, s)
1183}
1184
1185/// Convert days-since-1970-01-01 to (year, month, day). Howard Hinnant's
1186/// civil_from_days algorithm — proleptic Gregorian, 1970 = day 0.
1187fn civil_from_days(z: i64) -> (i32, u32, u32) {
1188    let z = z + 719_468;
1189    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
1190    let doe = (z - era * 146_097) as u64;
1191    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1192    let y = yoe as i64 + era * 400;
1193    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1194    let mp = (5 * doy + 2) / 153;
1195    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
1196    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
1197    let y = if m <= 2 { y + 1 } else { y };
1198    (y as i32, m, d)
1199}
1200
1201// ---------------------------------------------------------------------------
1202// JSON lines cache
1203// ---------------------------------------------------------------------------
1204
1205/// A cached container listing for a single host. `engine_version` is the
1206/// daemon's `Server.Version` captured during the last refresh, surfaced in
1207/// the host detail panel; `None` means the version sub-call did not return
1208/// or the cache was written by an older purple build.
1209#[derive(Debug, Clone)]
1210pub struct ContainerCacheEntry {
1211    pub timestamp: u64,
1212    pub runtime: ContainerRuntime,
1213    pub engine_version: Option<String>,
1214    pub containers: Vec<ContainerInfo>,
1215}
1216
1217/// Serde helper for a single JSON line in the cache file. `engine_version`
1218/// uses `serde(default)` so cache files written before this field existed
1219/// still deserialize cleanly.
1220#[derive(Serialize, Deserialize)]
1221struct CacheLine {
1222    alias: String,
1223    timestamp: u64,
1224    runtime: ContainerRuntime,
1225    #[serde(default, skip_serializing_if = "Option::is_none")]
1226    engine_version: Option<String>,
1227    containers: Vec<ContainerInfo>,
1228}
1229
1230fn cache_path(paths: Option<&crate::runtime::env::Paths>) -> Option<std::path::PathBuf> {
1231    paths.map(crate::runtime::env::Paths::container_cache)
1232}
1233
1234/// Load container cache from `~/.purple/container_cache.jsonl`.
1235/// Malformed lines are silently ignored. Duplicate aliases: last-write-wins.
1236pub fn load_container_cache(
1237    paths: Option<&crate::runtime::env::Paths>,
1238) -> HashMap<String, ContainerCacheEntry> {
1239    let mut map = HashMap::new();
1240    let Some(path) = cache_path(paths) else {
1241        return map;
1242    };
1243    let Ok(content) = std::fs::read_to_string(&path) else {
1244        return map;
1245    };
1246    for line in content.lines() {
1247        let trimmed = line.trim();
1248        if trimmed.is_empty() {
1249            continue;
1250        }
1251        if let Ok(entry) = serde_json::from_str::<CacheLine>(trimmed) {
1252            map.insert(
1253                entry.alias,
1254                ContainerCacheEntry {
1255                    timestamp: entry.timestamp,
1256                    runtime: entry.runtime,
1257                    engine_version: entry.engine_version,
1258                    containers: entry.containers,
1259                },
1260            );
1261        }
1262    }
1263    map
1264}
1265
1266/// Parse container cache from JSONL content string (for demo/test use).
1267pub fn parse_container_cache_content(content: &str) -> HashMap<String, ContainerCacheEntry> {
1268    let mut map = HashMap::new();
1269    for line in content.lines() {
1270        let trimmed = line.trim();
1271        if trimmed.is_empty() {
1272            continue;
1273        }
1274        if let Ok(entry) = serde_json::from_str::<CacheLine>(trimmed) {
1275            map.insert(
1276                entry.alias,
1277                ContainerCacheEntry {
1278                    timestamp: entry.timestamp,
1279                    runtime: entry.runtime,
1280                    engine_version: entry.engine_version,
1281                    containers: entry.containers,
1282                },
1283            );
1284        }
1285    }
1286    map
1287}
1288
1289/// Save container cache to `~/.purple/container_cache.jsonl` via atomic write.
1290pub fn save_container_cache(
1291    paths: Option<&crate::runtime::env::Paths>,
1292    cache: &HashMap<String, ContainerCacheEntry>,
1293) {
1294    if crate::demo_flag::is_demo() {
1295        return;
1296    }
1297    let Some(path) = cache_path(paths) else {
1298        return;
1299    };
1300    let mut lines = Vec::with_capacity(cache.len());
1301    for (alias, entry) in cache {
1302        let line = CacheLine {
1303            alias: alias.clone(),
1304            timestamp: entry.timestamp,
1305            runtime: entry.runtime,
1306            engine_version: entry.engine_version.clone(),
1307            containers: entry.containers.clone(),
1308        };
1309        if let Ok(s) = serde_json::to_string(&line) {
1310            lines.push(s);
1311        }
1312    }
1313    let content = lines.join("\n");
1314    log::debug!(
1315        "[purple] save_container_cache: {} host entries, {} bytes -> {}",
1316        cache.len(),
1317        content.len(),
1318        path.display()
1319    );
1320    if let Err(e) = crate::fs_util::atomic_write(&path, content.as_bytes()) {
1321        log::warn!(
1322            "[config] Failed to write container cache {}: {e}",
1323            path.display()
1324        );
1325    }
1326}
1327
1328// ---------------------------------------------------------------------------
1329// String truncation
1330// ---------------------------------------------------------------------------
1331
1332/// Truncate a string to at most `max` characters. Appends ".." if truncated.
1333pub fn truncate_str(s: &str, max: usize) -> String {
1334    let count = s.chars().count();
1335    if count <= max {
1336        s.to_string()
1337    } else {
1338        let cut = max.saturating_sub(2);
1339        let end = s.char_indices().nth(cut).map(|(i, _)| i).unwrap_or(s.len());
1340        format!("{}..", &s[..end])
1341    }
1342}
1343
1344// ---------------------------------------------------------------------------
1345// Relative time
1346// ---------------------------------------------------------------------------
1347
1348/// Format a duration in seconds as a compact label (`12s`, `5m`,
1349/// `2h`, `3d`). Used for the in-border staleness badge where width
1350/// is precious and the surrounding label (`synced`) already says
1351/// "ago" without the suffix.
1352pub fn format_uptime_short(seconds: u64) -> String {
1353    if seconds < 60 {
1354        format!("{seconds}s")
1355    } else if seconds < 3600 {
1356        format!("{}m", seconds / 60)
1357    } else if seconds < 86400 {
1358        format!("{}h", seconds / 3600)
1359    } else {
1360        format!("{}d", seconds / 86400)
1361    }
1362}
1363
1364/// Format a Unix timestamp as a human-readable relative time string.
1365/// Honours `demo_flag::now_secs()` when demo mode is active so visual
1366/// regression goldens stay byte-stable across long-running test
1367/// processes (same pattern as `history::format_time_ago`).
1368pub fn format_relative_time(timestamp: u64) -> String {
1369    let now = if crate::demo_flag::is_demo() {
1370        crate::demo_flag::now_secs()
1371    } else {
1372        SystemTime::now()
1373            .duration_since(UNIX_EPOCH)
1374            .unwrap_or_default()
1375            .as_secs()
1376    };
1377    let diff = now.saturating_sub(timestamp);
1378    if diff < 60 {
1379        "just now".to_string()
1380    } else if diff < 3600 {
1381        format!("{}m ago", diff / 60)
1382    } else if diff < 86400 {
1383        format!("{}h ago", diff / 3600)
1384    } else {
1385        format!("{}d ago", diff / 86400)
1386    }
1387}
1388
1389// ---------------------------------------------------------------------------
1390// Tests
1391// ---------------------------------------------------------------------------
1392
1393#[cfg(test)]
1394#[path = "containers_tests.rs"]
1395mod tests;