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 lower.contains("permission denied") || lower.contains("got permission denied") {
483        crate::messages::CONTAINER_PERMISSION_DENIED.to_string()
484    } else if lower.contains("cannot connect to the docker daemon")
485        || lower.contains("cannot connect to podman")
486    {
487        crate::messages::CONTAINER_DAEMON_NOT_RUNNING.to_string()
488    } else if lower.contains("connection refused") {
489        crate::messages::CONTAINER_CONNECTION_REFUSED.to_string()
490    } else if lower.contains("no route to host") || lower.contains("network is unreachable") {
491        crate::messages::CONTAINER_HOST_UNREACHABLE.to_string()
492    } else {
493        crate::messages::container_command_failed(code.unwrap_or(1))
494    }
495}
496
497/// Fetch container list synchronously via SSH.
498/// Follows the `fetch_remote_listing` pattern.
499pub fn fetch_containers(
500    ctx: &SshContext<'_>,
501    cached_runtime: Option<ContainerRuntime>,
502) -> Result<ContainerListing, ContainerError> {
503    let command = container_list_command(cached_runtime);
504    let result = crate::snippet::run_snippet_ctx(ctx, &command, true);
505    let alias = ctx.alias;
506    match result {
507        Ok(r) if r.status.success() => {
508            parse_container_output(&r.stdout, cached_runtime).map_err(|e| {
509                error!("[external] Container list parse failed: alias={alias}: {e}");
510                ContainerError {
511                    runtime: cached_runtime,
512                    message: e,
513                }
514            })
515        }
516        Ok(r) => {
517            let stderr = r.stderr.trim().to_string();
518            let msg = friendly_container_error(&stderr, r.status.code());
519            // A non-zero remote exit (docker missing, daemon down, ...) is a
520            // routine remote status, not an ssh connection failure: keep it out
521            // of the error level.
522            log::log!(
523                crate::connection::remote_exit_log_level(r.status.code().unwrap_or(-1)),
524                "[external] Container fetch failed: alias={alias}: {msg}"
525            );
526            Err(ContainerError {
527                runtime: cached_runtime,
528                message: msg,
529            })
530        }
531        Err(e) => {
532            error!("[external] Container fetch failed: alias={alias}: {e}");
533            Err(ContainerError {
534                runtime: cached_runtime,
535                message: e.to_string(),
536            })
537        }
538    }
539}
540
541/// Spawn a background thread to fetch container listings.
542/// Follows the `spawn_remote_listing` pattern.
543pub fn spawn_container_listing<F>(
544    ctx: OwnedSshContext,
545    cached_runtime: Option<ContainerRuntime>,
546    send: F,
547) where
548    F: FnOnce(String, Result<ContainerListing, ContainerError>) + Send + 'static,
549{
550    std::thread::spawn(move || {
551        let result = fetch_containers(&ctx.borrow(), cached_runtime);
552        send(ctx.alias, result);
553    });
554}
555
556/// Spawn a background thread to perform a container action (start/stop/restart).
557/// Validates the container ID before executing.
558pub fn spawn_container_action<F>(
559    ctx: OwnedSshContext,
560    runtime: ContainerRuntime,
561    action: ContainerAction,
562    container_id: String,
563    send: F,
564) where
565    F: FnOnce(String, ContainerAction, Result<(), String>) + Send + 'static,
566{
567    std::thread::spawn(move || {
568        if let Err(e) = validate_container_id(&container_id) {
569            log::debug!(
570                "[purple] container action {} blocked on alias={}: invalid container_id: {}",
571                action.as_str(),
572                ctx.alias,
573                e
574            );
575            send(ctx.alias, action, Err(e));
576            return;
577        }
578        let alias = &ctx.alias;
579        info!(
580            "[external] Container action: {} container={container_id} alias={alias}",
581            action.as_str()
582        );
583        let command = container_action_command(runtime, action, &container_id);
584        let result = crate::snippet::run_snippet_ctx(&ctx.borrow(), &command, true);
585        match result {
586            Ok(r) if r.status.success() => send(ctx.alias, action, Ok(())),
587            Ok(r) => {
588                let err = friendly_container_error(r.stderr.trim(), r.status.code());
589                // Routine remote exit (already stopped, no such container, ...)
590                // stays out of the error level; only an ssh transport failure
591                // (255) is a genuine connection error.
592                log::log!(
593                    crate::connection::remote_exit_log_level(r.status.code().unwrap_or(-1)),
594                    "[external] Container {} failed: alias={alias} container={container_id}: {err}",
595                    action.as_str()
596                );
597                send(ctx.alias, action, Err(err));
598            }
599            Err(e) => {
600                error!(
601                    "[external] Container {} failed: alias={alias} container={container_id}: {e}",
602                    action.as_str()
603                );
604                send(ctx.alias, action, Err(e.to_string()));
605            }
606        }
607    });
608}
609
610// ---------------------------------------------------------------------------
611// ContainerInspect: subset of `docker inspect` output we surface in the UI
612// ---------------------------------------------------------------------------
613
614/// Parsed subset of `docker inspect <id>` (or `podman inspect`). Only the
615/// fields purple's container detail panel renders are extracted; the rest
616/// of the JSON document is discarded so cache size stays bounded.
617#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
618pub struct ContainerInspect {
619    pub exit_code: i32,
620    pub oom_killed: bool,
621    pub started_at: String,
622    pub finished_at: String,
623    pub created_at: String,
624    /// `Some("healthy" | "unhealthy" | "starting")` when the image defines
625    /// a HEALTHCHECK. `None` when no healthcheck is configured.
626    pub health: Option<String>,
627    pub restart_count: u32,
628    pub command: Option<Vec<String>>,
629    pub entrypoint: Option<Vec<String>>,
630    pub env_count: usize,
631    pub mount_count: usize,
632    pub networks: Vec<NetworkInfo>,
633    // Audit-relevant fields surfaced in the right-side detail panel.
634    pub image_digest: Option<String>,
635    pub restart_policy: Option<String>,
636    pub user: Option<String>,
637    pub privileged: bool,
638    pub readonly_rootfs: bool,
639    pub apparmor_profile: Option<String>,
640    pub seccomp_profile: Option<String>,
641    pub cap_add: Vec<String>,
642    pub cap_drop: Vec<String>,
643    pub mounts: Vec<MountInfo>,
644    pub compose_project: Option<String>,
645    pub compose_service: Option<String>,
646    // Lifecycle / runtime details surfaced in the LIFECYCLE card.
647    pub pid: Option<u32>,
648    pub stop_signal: Option<String>,
649    pub stop_timeout: Option<u32>,
650    // App identity from OCI image labels (visible in APP card).
651    pub image_version: Option<String>,
652    pub image_revision: Option<String>,
653    pub image_source: Option<String>,
654    pub working_dir: Option<String>,
655    pub hostname: Option<String>,
656    // Resource constraints (RESOURCES card). 0 / None means unlimited.
657    pub memory_limit: Option<u64>,
658    pub cpu_limit_nanos: Option<u64>,
659    pub pids_limit: Option<i64>,
660    pub log_driver: Option<String>,
661    // Network mode (NETWORK card): bridge / host / none / container:xyz.
662    pub network_mode: Option<String>,
663    // Healthcheck definition + recent stats (HEALTH card when present).
664    pub health_test: Option<Vec<String>>,
665    pub health_interval_ns: Option<u64>,
666    pub health_failing_streak: Option<u32>,
667}
668
669#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
670pub struct NetworkInfo {
671    pub name: String,
672    pub ip_address: String,
673}
674
675#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
676pub struct MountInfo {
677    pub source: String,
678    pub destination: String,
679    pub read_only: bool,
680}
681
682/// Build the SSH command string for inspecting a single container.
683///
684/// Callers MUST validate `container_id` with `validate_container_id` before
685/// reaching this builder. Restricted to crate visibility so a future caller
686/// outside this crate cannot accidentally skip the guard.
687pub(crate) fn container_inspect_command(runtime: ContainerRuntime, container_id: &str) -> String {
688    format!("{} inspect {}", runtime.as_str(), container_id)
689}
690
691/// Translate a non-zero docker/podman exit code into a short
692/// human-readable hint. Returns `None` for codes without a well-known
693/// meaning so the UI can fall back to the bare number. Exit 0 has no
694/// entry because the detail panel only annotates failed exits.
695/// Sources: docker docs + Linux signal table.
696pub fn exit_code_meaning(code: i32) -> Option<&'static str> {
697    match code {
698        1 => Some("application error"),
699        125 => Some("docker run failed"),
700        126 => Some("command not executable"),
701        127 => Some("command not found"),
702        130 => Some("interrupted (SIGINT)"),
703        137 => Some("killed (SIGKILL / OOM)"),
704        139 => Some("segfault (SIGSEGV)"),
705        143 => Some("terminated (SIGTERM)"),
706        _ => None,
707    }
708}
709
710/// Parse `docker inspect <id>` stdout into `ContainerInspect`. The command
711/// always returns a JSON array; we take the first element. Missing fields
712/// degrade to defaults rather than fail so a partial response still
713/// renders something useful.
714pub fn parse_container_inspect(output: &str) -> Result<ContainerInspect, String> {
715    let trimmed = output.trim();
716    if trimmed.is_empty() {
717        return Err(crate::messages::CONTAINER_INSPECT_EMPTY.to_string());
718    }
719    let value: serde_json::Value = serde_json::from_str(trimmed)
720        .map_err(|e| crate::messages::container_inspect_parse_failed(&e.to_string()))?;
721    let entry = value
722        .as_array()
723        .and_then(|a| a.first())
724        .ok_or_else(|| crate::messages::CONTAINER_INSPECT_EMPTY.to_string())?;
725
726    let state = &entry["State"];
727    let config = &entry["Config"];
728    let network_settings = &entry["NetworkSettings"];
729
730    let exit_code = state["ExitCode"].as_i64().unwrap_or(0) as i32;
731    // Podman 5.x and docker both emit `OOMKilled`. Podman 3.x (still the
732    // packaged default on Ubuntu 22.04 LTS) emits `OomKilled`. Try both so
733    // OOM-killed containers surface in the ATTENTION card regardless of
734    // remote runtime version.
735    let oom_killed = state["OOMKilled"]
736        .as_bool()
737        .or_else(|| state["OomKilled"].as_bool())
738        .unwrap_or(false);
739    let started_at = state["StartedAt"].as_str().unwrap_or("").to_string();
740    let finished_at = state["FinishedAt"].as_str().unwrap_or("").to_string();
741    let health = state
742        .get("Health")
743        .and_then(|h| h.get("Status"))
744        .and_then(|s| s.as_str())
745        .map(|s| s.to_string());
746    let restart_count = entry["RestartCount"].as_u64().unwrap_or(0) as u32;
747
748    let command = config["Cmd"].as_array().map(|arr| {
749        arr.iter()
750            .filter_map(|v| v.as_str().map(|s| s.to_string()))
751            .collect()
752    });
753    let entrypoint = config["Entrypoint"].as_array().map(|arr| {
754        arr.iter()
755            .filter_map(|v| v.as_str().map(|s| s.to_string()))
756            .collect()
757    });
758    let env_count = config["Env"].as_array().map(|arr| arr.len()).unwrap_or(0);
759    let mount_count = entry["Mounts"].as_array().map(|arr| arr.len()).unwrap_or(0);
760
761    let networks = network_settings
762        .get("Networks")
763        .and_then(|n| n.as_object())
764        .map(|map| {
765            map.iter()
766                .map(|(name, cfg)| NetworkInfo {
767                    name: name.clone(),
768                    ip_address: cfg
769                        .get("IPAddress")
770                        .and_then(|v| v.as_str())
771                        .unwrap_or("")
772                        .to_string(),
773                })
774                .collect::<Vec<_>>()
775        })
776        .unwrap_or_default();
777
778    let host_config = &entry["HostConfig"];
779
780    let image_digest = entry["Image"]
781        .as_str()
782        .filter(|s| !s.is_empty())
783        .map(|s| s.to_string());
784    let restart_policy = host_config
785        .get("RestartPolicy")
786        .and_then(|p| p.get("Name"))
787        .and_then(|s| s.as_str())
788        .filter(|s| !s.is_empty() && *s != "no")
789        .map(|s| s.to_string());
790    let user = config["User"]
791        .as_str()
792        .filter(|s| !s.is_empty())
793        .map(|s| s.to_string());
794    let privileged = host_config["Privileged"].as_bool().unwrap_or(false);
795    let readonly_rootfs = host_config["ReadonlyRootfs"].as_bool().unwrap_or(false);
796    let apparmor_profile = host_config["AppArmorProfile"]
797        .as_str()
798        .or_else(|| entry["AppArmorProfile"].as_str())
799        .filter(|s| !s.is_empty())
800        .map(|s| s.to_string());
801    let seccomp_profile = host_config["SecurityOpt"].as_array().and_then(|arr| {
802        arr.iter()
803            .filter_map(|v| v.as_str())
804            .find_map(|s| s.strip_prefix("seccomp=").map(|v| v.to_string()))
805    });
806    let cap_add = host_config["CapAdd"]
807        .as_array()
808        .map(|arr| {
809            arr.iter()
810                .filter_map(|v| v.as_str().map(|s| s.to_string()))
811                .collect()
812        })
813        .unwrap_or_default();
814    let cap_drop = host_config["CapDrop"]
815        .as_array()
816        .map(|arr| {
817            arr.iter()
818                .filter_map(|v| v.as_str().map(|s| s.to_string()))
819                .collect()
820        })
821        .unwrap_or_default();
822    let mounts = entry["Mounts"]
823        .as_array()
824        .map(|arr| {
825            arr.iter()
826                .map(|m| MountInfo {
827                    source: m["Source"].as_str().unwrap_or("").to_string(),
828                    destination: m["Destination"].as_str().unwrap_or("").to_string(),
829                    read_only: !m["RW"].as_bool().unwrap_or(true),
830                })
831                .collect()
832        })
833        .unwrap_or_default();
834    let labels = config.get("Labels").and_then(|l| l.as_object());
835    let label = |key: &str| {
836        labels
837            .and_then(|l| l.get(key))
838            .and_then(|v| v.as_str())
839            .filter(|s| !s.is_empty())
840            .map(|s| s.to_string())
841    };
842    let compose_project = label("com.docker.compose.project");
843    let compose_service = label("com.docker.compose.service");
844    let image_version = label("org.opencontainers.image.version");
845    let image_revision = label("org.opencontainers.image.revision");
846    let image_source = label("org.opencontainers.image.source");
847
848    let created_at = entry["Created"].as_str().unwrap_or("").to_string();
849    // State.Pid is `0` when the container is not running. Drop the zero so
850    // the UI does not render a misleading "pid 0" row for exited rows.
851    let pid = state["Pid"].as_u64().filter(|n| *n > 0).map(|n| n as u32);
852    let hostname = config["Hostname"]
853        .as_str()
854        .filter(|s| !s.is_empty())
855        .map(|s| s.to_string());
856    let working_dir = config["WorkingDir"]
857        .as_str()
858        .filter(|s| !s.is_empty())
859        .map(|s| s.to_string());
860    let stop_signal = config["StopSignal"]
861        .as_str()
862        .filter(|s| !s.is_empty())
863        .map(|s| s.to_string());
864    let stop_timeout = config["StopTimeout"].as_u64().map(|n| n as u32);
865
866    let network_mode = host_config["NetworkMode"]
867        .as_str()
868        .filter(|s| !s.is_empty() && *s != "default")
869        .map(|s| s.to_string());
870    // HostConfig.Memory is bytes, 0 = unlimited (drop). Same for NanoCpus.
871    let memory_limit = host_config["Memory"].as_u64().filter(|n| *n > 0);
872    let cpu_limit_nanos = host_config["NanoCpus"].as_u64().filter(|n| *n > 0);
873    // PidsLimit is i64. 0 or -1 means unlimited; drop both.
874    let pids_limit = host_config["PidsLimit"].as_i64().filter(|n| *n > 0);
875    // LogConfig.Type defaults to "json-file" on docker. Always carry it
876    // so the renderer can decide whether to surface "Logs" only when
877    // non-default.
878    let log_driver = host_config
879        .get("LogConfig")
880        .and_then(|l| l.get("Type"))
881        .and_then(|v| v.as_str())
882        .filter(|s| !s.is_empty())
883        .map(|s| s.to_string());
884
885    let healthcheck = config.get("Healthcheck");
886    let health_test = healthcheck
887        .and_then(|h| h.get("Test"))
888        .and_then(|t| t.as_array())
889        .map(|arr| {
890            arr.iter()
891                .filter_map(|v| v.as_str().map(|s| s.to_string()))
892                .collect::<Vec<_>>()
893        })
894        .filter(|v| !v.is_empty());
895    let health_interval_ns = healthcheck
896        .and_then(|h| h.get("Interval"))
897        .and_then(|v| v.as_u64())
898        .filter(|n| *n > 0);
899    let health_failing_streak = state
900        .get("Health")
901        .and_then(|h| h.get("FailingStreak"))
902        .and_then(|v| v.as_u64())
903        .map(|n| n as u32);
904
905    Ok(ContainerInspect {
906        exit_code,
907        oom_killed,
908        started_at,
909        finished_at,
910        created_at,
911        health,
912        restart_count,
913        command,
914        entrypoint,
915        env_count,
916        mount_count,
917        networks,
918        image_digest,
919        restart_policy,
920        user,
921        privileged,
922        readonly_rootfs,
923        apparmor_profile,
924        seccomp_profile,
925        cap_add,
926        cap_drop,
927        mounts,
928        compose_project,
929        compose_service,
930        pid,
931        stop_signal,
932        stop_timeout,
933        image_version,
934        image_revision,
935        image_source,
936        working_dir,
937        hostname,
938        memory_limit,
939        cpu_limit_nanos,
940        pids_limit,
941        log_driver,
942        network_mode,
943        health_test,
944        health_interval_ns,
945        health_failing_streak,
946    })
947}
948
949/// Parse a Docker `Up …` status string into a compact uptime label.
950/// Returns `None` for any non-running state (Exited, Created, Restarting,
951/// Paused without an `Up` prefix, empty). Cells render `<1m` for
952/// sub-minute uptimes, `1m` / `5m` / `12h` / `5w` / `3mo` / `2y` otherwise.
953/// Format follows Docker's `units.HumanDuration`.
954pub fn parse_uptime_from_status(s: &str) -> Option<String> {
955    let body = s.strip_prefix("Up ")?;
956    let body = body.split('(').next()?.trim();
957    if body == "Less than a second" {
958        return Some("<1m".to_string());
959    }
960    if body == "About a minute" {
961        return Some("1m".to_string());
962    }
963    if body == "About an hour" {
964        return Some("1h".to_string());
965    }
966    let mut parts = body.split_whitespace();
967    let count: u64 = parts.next()?.parse().ok()?;
968    let unit = parts.next()?;
969    let suffix = match unit {
970        "second" | "seconds" => return Some("<1m".to_string()),
971        "minute" | "minutes" => "m",
972        "hour" | "hours" => "h",
973        "day" | "days" => "d",
974        "week" | "weeks" => "w",
975        "month" | "months" => "mo",
976        "year" | "years" => "y",
977        _ => return None,
978    };
979    Some(format!("{count}{suffix}"))
980}
981
982/// Synchronously fetch + parse `container inspect`. Validates the
983/// container ID before issuing the SSH call.
984pub fn fetch_container_inspect(
985    ctx: &SshContext<'_>,
986    runtime: ContainerRuntime,
987    container_id: &str,
988) -> Result<ContainerInspect, String> {
989    validate_container_id(container_id)?;
990    let command = container_inspect_command(runtime, container_id);
991    let result = crate::snippet::run_snippet_ctx(ctx, &command, true);
992    match result {
993        Ok(r) if r.status.success() => parse_container_inspect(&r.stdout),
994        Ok(r) => Err(crate::messages::container_command_failed(
995            r.status.code().unwrap_or(1),
996        )),
997        Err(e) => Err(e.to_string()),
998    }
999}
1000
1001/// Spawn a background thread to run `container inspect`. Mirrors the
1002/// `spawn_container_listing` pattern so the call site looks identical.
1003pub fn spawn_container_inspect_listing<F>(
1004    ctx: OwnedSshContext,
1005    runtime: ContainerRuntime,
1006    container_id: String,
1007    send: F,
1008) where
1009    F: FnOnce(String, String, Result<ContainerInspect, String>) + Send + 'static,
1010{
1011    std::thread::spawn(move || {
1012        let result = fetch_container_inspect(&ctx.borrow(), runtime, &container_id);
1013        send(ctx.alias, container_id, result);
1014    });
1015}
1016
1017/// Build the `<runtime> logs --tail <n> <id>` command. The
1018/// `--tail` cap is enforced server-side so the SSH stream stays
1019/// bounded even on a noisy container.
1020pub(crate) fn container_logs_command(
1021    runtime: ContainerRuntime,
1022    container_id: &str,
1023    tail: usize,
1024) -> String {
1025    format!("{} logs --tail {} {}", runtime.as_str(), tail, container_id)
1026}
1027
1028/// Synchronously fetch logs and split into lines. Returns the raw
1029/// captured stdout split on `\n` so the renderer does not have to
1030/// re-parse. Empty trailing lines are dropped.
1031pub fn fetch_container_logs(
1032    ctx: &SshContext<'_>,
1033    runtime: ContainerRuntime,
1034    container_id: &str,
1035    tail: usize,
1036) -> Result<Vec<String>, String> {
1037    validate_container_id(container_id)?;
1038    let command = container_logs_command(runtime, container_id, tail);
1039    let result = crate::snippet::run_snippet_ctx(ctx, &command, true);
1040    match result {
1041        Ok(r) if r.status.success() => Ok(parse_log_output(&r.stdout, &r.stderr)),
1042        Ok(r) => Err(crate::messages::container_command_failed(
1043            r.status.code().unwrap_or(1),
1044        )),
1045        Err(e) => Err(e.to_string()),
1046    }
1047}
1048
1049/// Merge stdout (app logs) and stderr (errors) into a single chronological
1050/// stream. Many container runtimes split levels across the two streams;
1051/// re-interleaving them is closer to what `docker logs` shows on a TTY.
1052/// Trailing blank lines are stripped from each stream before merging so a
1053/// stdout block that ends in a newline does not introduce a phantom empty
1054/// row between the two streams.
1055pub(crate) fn parse_log_output(stdout: &str, stderr: &str) -> Vec<String> {
1056    let mut lines: Vec<String> = stdout.lines().map(|s| s.to_string()).collect();
1057    while lines.last().map(|s| s.is_empty()).unwrap_or(false) {
1058        lines.pop();
1059    }
1060    for s in stderr.lines() {
1061        lines.push(s.to_string());
1062    }
1063    while lines.last().map(|s| s.is_empty()).unwrap_or(false) {
1064        lines.pop();
1065    }
1066    lines
1067}
1068
1069/// Spawn a background thread to run `container logs`. Same shape as
1070/// `spawn_container_inspect_listing`. In demo mode the SSH call is
1071/// short-circuited with a deterministic synthetic log stream so the
1072/// logs viewer (and its `/` search) is exercisable without a remote.
1073pub fn spawn_container_logs_fetch<F>(
1074    ctx: OwnedSshContext,
1075    runtime: ContainerRuntime,
1076    container_id: String,
1077    container_name: String,
1078    tail: usize,
1079    send: F,
1080) where
1081    F: FnOnce(String, String, String, Result<Vec<String>, String>) + Send + 'static,
1082{
1083    if crate::demo_flag::is_demo() {
1084        let lines = demo_log_lines(&container_name, tail);
1085        log::debug!(
1086            "[purple] container_logs_fetch: demo short-circuit alias={} id={} lines={}",
1087            ctx.alias,
1088            container_id,
1089            lines.len()
1090        );
1091        send(ctx.alias, container_id, container_name, Ok(lines));
1092        return;
1093    }
1094    std::thread::spawn(move || {
1095        let result = fetch_container_logs(&ctx.borrow(), runtime, &container_id, tail);
1096        send(ctx.alias, container_id, container_name, result);
1097    });
1098}
1099
1100/// Generate a deterministic stream of fake log lines for demo mode.
1101/// Mixes INFO / WARN / ERROR / DEBUG with realistic-looking content
1102/// (HTTP requests, DB pings, retries, timeouts) so the user can
1103/// usefully press `/` and find matches under `--demo`. Anchored to
1104/// `demo_flag::now_secs()` so timestamps stay stable across renders.
1105pub(crate) fn demo_log_lines(container_name: &str, tail: usize) -> Vec<String> {
1106    use std::time::{Duration, UNIX_EPOCH};
1107    // Cheap hash to fan out per-container variation without bringing
1108    // `rand` into the binary.
1109    let seed: u32 = container_name
1110        .bytes()
1111        .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32));
1112
1113    // Templates rotate every line. Index 0 is the freshest log line.
1114    let templates: &[&str] = &[
1115        "INFO  [{}] handled GET /api/v1/health 200 in 14ms",
1116        "INFO  [{}] handled POST /api/v1/orders 201 in 38ms (user_id={user})",
1117        "DEBUG [{}] cache hit key=session:{user} ttl=3600",
1118        "INFO  [{}] handled GET /api/v1/users/{user} 200 in 11ms",
1119        "WARN  [{}] slow query detected duration=812ms statement=SELECT FROM orders",
1120        "INFO  [{}] connection pool size=12 idle=8 in_use=4",
1121        "DEBUG [{}] flushing metrics batch size=64",
1122        "INFO  [{}] handled GET /api/v1/inventory 200 in 22ms",
1123        "ERROR [{}] upstream timeout after 5000ms target=payments retry=1",
1124        "WARN  [{}] retrying request attempt=2 backoff=250ms",
1125        "INFO  [{}] handled POST /api/v1/login 200 in 31ms",
1126        "DEBUG [{}] gc cycle reclaimed=42MB took=18ms",
1127        "INFO  [{}] heartbeat ok rss=128MB cpu=4%",
1128        "ERROR [{}] failed to acquire lock resource=cache_warmer waiter=3",
1129        "INFO  [{}] handled DELETE /api/v1/sessions/{user} 204 in 9ms",
1130        "WARN  [{}] disk usage at 78% mount=/data threshold=80%",
1131        "INFO  [{}] handled GET /api/v1/search?q=widget 200 in 47ms",
1132        "DEBUG [{}] websocket ping rtt=12ms",
1133    ];
1134
1135    // Always use `demo_flag::now_secs()` even outside demo mode: the
1136    // helper's OnceLock caches the first wallclock value, so repeated
1137    // calls within a process return the same instant. Branching on
1138    // `is_demo()` would let tests cross a second boundary and flake.
1139    let now = crate::demo_flag::now_secs();
1140
1141    // Map each line to a timestamp working backwards from now. One log
1142    // every 3 seconds keeps the time range realistic for a 200-line tail.
1143    let mut lines = Vec::with_capacity(tail);
1144    for i in 0..tail {
1145        let template = templates[(i + seed as usize) % templates.len()];
1146        let user = 1000 + ((seed as usize + i * 7) % 50);
1147        let secs_back = (i as u64) * 3;
1148        let line_time = UNIX_EPOCH + Duration::from_secs(now.saturating_sub(secs_back));
1149        let ts = format_demo_timestamp(line_time);
1150        let body = template
1151            .replace("{}", container_name)
1152            .replace("{user}", &user.to_string());
1153        lines.push(format!("{} {}", ts, body));
1154    }
1155    // Render flush-top with the newest line at the bottom of the
1156    // viewport, matching real `docker logs --tail` output.
1157    lines.reverse();
1158    lines
1159}
1160
1161fn format_demo_timestamp(t: std::time::SystemTime) -> String {
1162    use std::time::UNIX_EPOCH;
1163    let secs = t
1164        .duration_since(UNIX_EPOCH)
1165        .map(|d| d.as_secs())
1166        .unwrap_or(0);
1167    // Fast UTC breakdown without dragging in chrono. Good enough for a
1168    // demo timestamp where leap seconds / DST are irrelevant.
1169    let days_since_epoch = (secs / 86_400) as i64;
1170    let seconds_in_day = (secs % 86_400) as u32;
1171    let h = seconds_in_day / 3600;
1172    let m = (seconds_in_day % 3600) / 60;
1173    let s = seconds_in_day % 60;
1174    let (y, mo, d) = civil_from_days(days_since_epoch);
1175    format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}", y, mo, d, h, m, s)
1176}
1177
1178/// Convert days-since-1970-01-01 to (year, month, day). Howard Hinnant's
1179/// civil_from_days algorithm — proleptic Gregorian, 1970 = day 0.
1180fn civil_from_days(z: i64) -> (i32, u32, u32) {
1181    let z = z + 719_468;
1182    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
1183    let doe = (z - era * 146_097) as u64;
1184    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1185    let y = yoe as i64 + era * 400;
1186    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1187    let mp = (5 * doy + 2) / 153;
1188    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
1189    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
1190    let y = if m <= 2 { y + 1 } else { y };
1191    (y as i32, m, d)
1192}
1193
1194// ---------------------------------------------------------------------------
1195// JSON lines cache
1196// ---------------------------------------------------------------------------
1197
1198/// A cached container listing for a single host. `engine_version` is the
1199/// daemon's `Server.Version` captured during the last refresh, surfaced in
1200/// the host detail panel; `None` means the version sub-call did not return
1201/// or the cache was written by an older purple build.
1202#[derive(Debug, Clone)]
1203pub struct ContainerCacheEntry {
1204    pub timestamp: u64,
1205    pub runtime: ContainerRuntime,
1206    pub engine_version: Option<String>,
1207    pub containers: Vec<ContainerInfo>,
1208}
1209
1210/// Serde helper for a single JSON line in the cache file. `engine_version`
1211/// uses `serde(default)` so cache files written before this field existed
1212/// still deserialize cleanly.
1213#[derive(Serialize, Deserialize)]
1214struct CacheLine {
1215    alias: String,
1216    timestamp: u64,
1217    runtime: ContainerRuntime,
1218    #[serde(default, skip_serializing_if = "Option::is_none")]
1219    engine_version: Option<String>,
1220    containers: Vec<ContainerInfo>,
1221}
1222
1223fn cache_path(paths: Option<&crate::runtime::env::Paths>) -> Option<std::path::PathBuf> {
1224    paths.map(crate::runtime::env::Paths::container_cache)
1225}
1226
1227/// Load container cache from `~/.purple/container_cache.jsonl`.
1228/// Malformed lines are silently ignored. Duplicate aliases: last-write-wins.
1229pub fn load_container_cache(
1230    paths: Option<&crate::runtime::env::Paths>,
1231) -> HashMap<String, ContainerCacheEntry> {
1232    let mut map = HashMap::new();
1233    let Some(path) = cache_path(paths) else {
1234        return map;
1235    };
1236    let Ok(content) = std::fs::read_to_string(&path) else {
1237        return map;
1238    };
1239    for line in content.lines() {
1240        let trimmed = line.trim();
1241        if trimmed.is_empty() {
1242            continue;
1243        }
1244        if let Ok(entry) = serde_json::from_str::<CacheLine>(trimmed) {
1245            map.insert(
1246                entry.alias,
1247                ContainerCacheEntry {
1248                    timestamp: entry.timestamp,
1249                    runtime: entry.runtime,
1250                    engine_version: entry.engine_version,
1251                    containers: entry.containers,
1252                },
1253            );
1254        }
1255    }
1256    map
1257}
1258
1259/// Parse container cache from JSONL content string (for demo/test use).
1260pub fn parse_container_cache_content(content: &str) -> HashMap<String, ContainerCacheEntry> {
1261    let mut map = HashMap::new();
1262    for line in content.lines() {
1263        let trimmed = line.trim();
1264        if trimmed.is_empty() {
1265            continue;
1266        }
1267        if let Ok(entry) = serde_json::from_str::<CacheLine>(trimmed) {
1268            map.insert(
1269                entry.alias,
1270                ContainerCacheEntry {
1271                    timestamp: entry.timestamp,
1272                    runtime: entry.runtime,
1273                    engine_version: entry.engine_version,
1274                    containers: entry.containers,
1275                },
1276            );
1277        }
1278    }
1279    map
1280}
1281
1282/// Save container cache to `~/.purple/container_cache.jsonl` via atomic write.
1283pub fn save_container_cache(
1284    paths: Option<&crate::runtime::env::Paths>,
1285    cache: &HashMap<String, ContainerCacheEntry>,
1286) {
1287    if crate::demo_flag::is_demo() {
1288        return;
1289    }
1290    let Some(path) = cache_path(paths) else {
1291        return;
1292    };
1293    let mut lines = Vec::with_capacity(cache.len());
1294    for (alias, entry) in cache {
1295        let line = CacheLine {
1296            alias: alias.clone(),
1297            timestamp: entry.timestamp,
1298            runtime: entry.runtime,
1299            engine_version: entry.engine_version.clone(),
1300            containers: entry.containers.clone(),
1301        };
1302        if let Ok(s) = serde_json::to_string(&line) {
1303            lines.push(s);
1304        }
1305    }
1306    let content = lines.join("\n");
1307    log::debug!(
1308        "[purple] save_container_cache: {} host entries, {} bytes -> {}",
1309        cache.len(),
1310        content.len(),
1311        path.display()
1312    );
1313    if let Err(e) = crate::fs_util::atomic_write(&path, content.as_bytes()) {
1314        log::warn!(
1315            "[config] Failed to write container cache {}: {e}",
1316            path.display()
1317        );
1318    }
1319}
1320
1321// ---------------------------------------------------------------------------
1322// String truncation
1323// ---------------------------------------------------------------------------
1324
1325/// Truncate a string to at most `max` characters. Appends ".." if truncated.
1326pub fn truncate_str(s: &str, max: usize) -> String {
1327    let count = s.chars().count();
1328    if count <= max {
1329        s.to_string()
1330    } else {
1331        let cut = max.saturating_sub(2);
1332        let end = s.char_indices().nth(cut).map(|(i, _)| i).unwrap_or(s.len());
1333        format!("{}..", &s[..end])
1334    }
1335}
1336
1337// ---------------------------------------------------------------------------
1338// Relative time
1339// ---------------------------------------------------------------------------
1340
1341/// Format a duration in seconds as a compact label (`12s`, `5m`,
1342/// `2h`, `3d`). Used for the in-border staleness badge where width
1343/// is precious and the surrounding label (`synced`) already says
1344/// "ago" without the suffix.
1345pub fn format_uptime_short(seconds: u64) -> String {
1346    if seconds < 60 {
1347        format!("{seconds}s")
1348    } else if seconds < 3600 {
1349        format!("{}m", seconds / 60)
1350    } else if seconds < 86400 {
1351        format!("{}h", seconds / 3600)
1352    } else {
1353        format!("{}d", seconds / 86400)
1354    }
1355}
1356
1357/// Format a Unix timestamp as a human-readable relative time string.
1358/// Honours `demo_flag::now_secs()` when demo mode is active so visual
1359/// regression goldens stay byte-stable across long-running test
1360/// processes (same pattern as `history::format_time_ago`).
1361pub fn format_relative_time(timestamp: u64) -> String {
1362    let now = if crate::demo_flag::is_demo() {
1363        crate::demo_flag::now_secs()
1364    } else {
1365        SystemTime::now()
1366            .duration_since(UNIX_EPOCH)
1367            .unwrap_or_default()
1368            .as_secs()
1369    };
1370    let diff = now.saturating_sub(timestamp);
1371    if diff < 60 {
1372        "just now".to_string()
1373    } else if diff < 3600 {
1374        format!("{}m ago", diff / 60)
1375    } else if diff < 86400 {
1376        format!("{}h ago", diff / 3600)
1377    } else {
1378        format!("{}d ago", diff / 86400)
1379    }
1380}
1381
1382// ---------------------------------------------------------------------------
1383// Tests
1384// ---------------------------------------------------------------------------
1385
1386#[cfg(test)]
1387#[path = "containers_tests.rs"]
1388mod tests;