Skip to main content

lean_ctx/core/intelligence_runtime/
cockpit.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The Cockpit web UI: a free, separately licensed, signed package kind.
3//!
4//! It travels through the runtime channel like the Intelligence Runtime and
5//! is authenticated just as strictly (manifest, signature, archive, catalog
6//! and delegation), but it is never licence-bound, lives in its own store
7//! (`cockpit-runtime[-production]`) with its own activation record, and is
8//! re-authenticated as a Cockpit on every start.
9//!
10//! One Cockpit per Engine dashboard process. It is started from a private
11//! copy of the authenticated bytes with a cleared environment and receives
12//! one JSON line on stdin (the start contract `leanctx.cockpit-start/v1`).
13//! It binds 127.0.0.1:0 and names its port as the first stdout line,
14//! `{"listening":<port>}`. The supervisor keeps stdin open for the Engine's
15//! lifetime; the Cockpit ends at stdin EOF, at the latest when this process
16//! ends. A crash is restarted on the next request after a bounded backoff.
17//! No token is ever logged.
18
19use std::io::{BufRead, BufReader, Read, Write};
20use std::path::{Path, PathBuf};
21use std::process::{Child, ChildStdin, Command, Stdio};
22use std::sync::{Mutex, PoisonError, mpsc};
23use std::time::{Duration, Instant};
24
25use serde::{Deserialize, Serialize};
26
27use super::{InstallError, Result, RuntimeKind, VerifiedPackage, bootstrap, install};
28
29/// The activation record in the Cockpit store: which installed package the
30/// dashboard starts, under which artifact key, and whether it is enabled.
31const ACTIVATION: &str = "activation.json";
32/// The name of the private copy the Cockpit runs as.
33const EXECUTABLE: &str = if cfg!(windows) {
34    "leanctx-cockpit.exe"
35} else {
36    "leanctx-cockpit"
37};
38/// How long a start may take to name its port.
39const HANDSHAKE: Duration = Duration::from_secs(10);
40/// How long a Cockpit may take to end after its stdin closed.
41const EXIT_GRACE: Duration = Duration::from_secs(2);
42/// Waits before the first, second and every further restart after a
43/// failure in a row. A Cockpit that ran for `STABLE` ends the row.
44const RESTART_BACKOFF: [Duration; 3] = [
45    Duration::from_secs(1),
46    Duration::from_secs(5),
47    Duration::from_secs(30),
48];
49const STABLE: Duration = Duration::from_mins(1);
50/// The port line is short; anything longer is not the start contract.
51const MAX_PORT_LINE: u64 = 256;
52
53/// What the dashboard knows about itself when it asks for the Cockpit.
54pub struct CockpitLaunch {
55    /// The port of the Engine dashboard on 127.0.0.1.
56    pub engine_port: u16,
57    /// The dashboard bearer token the Cockpit uses to call the Engine.
58    pub engine_token: String,
59    pub project_root: PathBuf,
60}
61
62/// Where the running Cockpit listens, and the token the dashboard's proxy
63/// presents to it.
64#[derive(Clone, PartialEq, Eq)]
65pub struct CockpitEndpoint {
66    pub port: u16,
67    /// 32 random bytes, lowercase hex.
68    pub cockpit_token: String,
69}
70
71impl std::fmt::Debug for CockpitEndpoint {
72    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        formatter
74            .debug_struct("CockpitEndpoint")
75            .field("port", &self.port)
76            .field("cockpit_token", &"<redacted>")
77            .finish()
78    }
79}
80
81/// Why no Cockpit is available; the dashboard shows the matching fallback.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum CockpitUnavailable {
84    /// No Cockpit is installed and activated in this host's Cockpit store.
85    NotInstalled,
86    /// The activation or the installed package did not authenticate.
87    VerificationFailed,
88    /// The authenticated Cockpit did not start, did not name its port in
89    /// time, or crashed and waits for its restart.
90    StartFailed,
91    /// The Cockpit is installed and was deactivated.
92    Disabled,
93    /// A source build: no Cockpit channel is compiled in and none is
94    /// installed. The Cockpit ships with the official installs.
95    SourceBuild,
96    /// The install could not download the Cockpit: a network error or a
97    /// timeout. Nothing was installed; a retry or a local bundle helps.
98    DownloadFailed,
99}
100
101impl CockpitUnavailable {
102    pub const fn as_str(self) -> &'static str {
103        match self {
104            Self::NotInstalled => "not_installed",
105            Self::VerificationFailed => "verification_failed",
106            Self::StartFailed => "start_failed",
107            Self::Disabled => "disabled",
108            Self::SourceBuild => "source_build",
109            Self::DownloadFailed => "download_failed",
110        }
111    }
112
113    /// One line for a user who opens the Cockpit while it cannot be served:
114    /// the reason and the one action that helps. The terminal alternative is
115    /// added once by the caller (CLI line, unavailable page), never here.
116    pub const fn message(self) -> &'static str {
117        match self {
118            Self::NotInstalled => {
119                "The Cockpit is not installed. Install it with: lean-ctx cockpit install"
120            }
121            Self::VerificationFailed => {
122                "The installed Cockpit did not verify and was not started. Reinstall it with: lean-ctx cockpit install"
123            }
124            Self::StartFailed => {
125                "The Cockpit is installed but did not start. See why: lean-ctx cockpit --foreground (it logs the cause)"
126            }
127            Self::Disabled => {
128                "The Cockpit is deactivated. Activate it again with: lean-ctx cockpit install"
129            }
130            Self::SourceBuild => {
131                "Source build: the Cockpit ships with official installs (install.sh, Homebrew, npm, AUR)"
132            }
133            Self::DownloadFailed => {
134                "The Cockpit download failed (network error or timeout). Try again with: lean-ctx cockpit install, or install a local bundle with: lean-ctx cockpit install --from <bundle>"
135            }
136        }
137    }
138}
139
140/// The five files of a Cockpit bundle and their size bounds.
141const BUNDLE_FILES: [(&str, usize); 5] = [
142    ("channel.json", 65_536),
143    ("channel.sig", 64),
144    ("manifest.json", 65_536),
145    ("manifest.sig", 64),
146    ("archive.tar.gz", super::manifest::MAX_ARCHIVE),
147];
148
149/// A bundle: a directory holding [`BUNDLE_FILES`], or a `.tar.gz` holding
150/// them directly or in one top-level directory. Nothing else is read.
151fn read_bundle(path: &Path) -> Result<super::catalog::Bundle> {
152    let mut files: [Option<Vec<u8>>; 5] = Default::default();
153    if std::fs::symlink_metadata(path)?.is_dir() {
154        for (slot, (name, limit)) in files.iter_mut().zip(BUNDLE_FILES) {
155            *slot = Some(super::read_regular(&path.join(name), limit)?);
156        }
157    } else {
158        let packed = super::read_regular(path, super::manifest::MAX_ARCHIVE + (1 << 20))?;
159        let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(packed.as_slice()));
160        for entry in archive.entries().map_err(|_| InstallError::Archive)? {
161            let entry = entry.map_err(|_| InstallError::Archive)?;
162            let kind = entry.header().entry_type();
163            if kind.is_dir() {
164                continue;
165            }
166            let entry_path = entry
167                .path()
168                .map_err(|_| InstallError::Archive)?
169                .into_owned();
170            let parts: Vec<_> = entry_path.components().collect();
171            if !kind.is_file()
172                || parts.len() > 2
173                || parts
174                    .iter()
175                    .any(|part| !matches!(part, std::path::Component::Normal(_)))
176            {
177                return Err(InstallError::Archive);
178            }
179            let name = entry_path.file_name().and_then(|name| name.to_str());
180            let Some(index) = BUNDLE_FILES
181                .iter()
182                .position(|(known, _)| Some(*known) == name)
183            else {
184                return Err(InstallError::Archive);
185            };
186            let limit = BUNDLE_FILES[index].1;
187            let mut bytes = Vec::new();
188            entry
189                .take(limit as u64 + 1)
190                .read_to_end(&mut bytes)
191                .map_err(|_| InstallError::Archive)?;
192            if bytes.len() > limit || files[index].replace(bytes).is_some() {
193                return Err(InstallError::Archive);
194            }
195        }
196    }
197    let [
198        Some(catalog),
199        Some(catalog_signature),
200        Some(manifest),
201        Some(signature),
202        Some(archive),
203    ] = files
204    else {
205        return Err(InstallError::Archive);
206    };
207    Ok(super::catalog::Bundle {
208        catalog,
209        catalog_signature,
210        archive,
211        manifest,
212        signature,
213    })
214}
215
216/// Verify `bundle` against this host's compiled-in Cockpit channel root,
217/// install it and activate it. No network. An older channel sequence than
218/// the active one installs only with `downgrade`.
219fn import(bundle: &super::catalog::Bundle, downgrade: bool) -> Result<serde_json::Value> {
220    let channel = bootstrap::cockpit_channel()?.ok_or(InstallError::Policy)?;
221    let root = bootstrap::cockpit_root()?;
222    install::prepare_parent_chain(root.parent().ok_or(InstallError::Directory)?)?;
223    let _guard = install::configuration_guard(&root)?;
224    let expected = install::active_manifest(&root)?;
225    let installation = super::catalog::import_kind(
226        RuntimeKind::Cockpit,
227        bundle,
228        &channel.key,
229        &root,
230        &expected,
231        downgrade,
232    )?;
233    activate_installation(&root, &installation, "bundle")
234}
235
236/// `lean-ctx cockpit install --from <dir|file.tar.gz> [--allow-downgrade]`.
237pub(crate) fn install_from(path: &Path, downgrade: bool) -> Result<serde_json::Value> {
238    import(&read_bundle(path)?, downgrade)
239}
240
241/// The `--from` form of `lean-ctx cockpit install` (`args` follow
242/// `install`); `false` when the arguments do not name one, so the caller
243/// installs from the channel. Exits non-zero on failure.
244pub fn install_from_cli(args: &[String]) -> bool {
245    if args.is_empty() {
246        return false;
247    }
248    let downgrade = args.iter().any(|arg| arg == "--allow-downgrade");
249    let rest: Vec<&str> = args
250        .iter()
251        .map(String::as_str)
252        .filter(|arg| *arg != "--allow-downgrade")
253        .collect();
254    let path = match rest.as_slice() {
255        ["--from", path] => *path,
256        [flag] if flag.starts_with("--from=") => &flag["--from=".len()..],
257        _ => {
258            eprintln!(
259                "Usage: lean-ctx cockpit install [--from <dir|file.tar.gz> [--allow-downgrade]]"
260            );
261            std::process::exit(2);
262        }
263    };
264    match install_from(Path::new(path), downgrade) {
265        Ok(result) => {
266            println!(
267                "{}",
268                serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string())
269            );
270            println!("Open it with: lean-ctx cockpit");
271        }
272        Err(InstallError::Downgrade) => {
273            eprintln!(
274                "lean-ctx cockpit install --from: this bundle is older than the active Cockpit; \
275                 add --allow-downgrade to install it"
276            );
277            std::process::exit(1);
278        }
279        Err(error) => {
280            eprintln!("lean-ctx cockpit install --from: the bundle was not installed ({error:?})");
281            std::process::exit(1);
282        }
283    }
284    true
285}
286
287/// The Cockpit bundle an official install ships beside the Engine.
288fn bundled_dir() -> Option<PathBuf> {
289    let exe = std::env::current_exe().ok()?.canonicalize().ok()?;
290    let prefix = exe.parent()?.parent()?;
291    ["share", "libexec"]
292        .iter()
293        .map(|place| prefix.join(place).join("lean-ctx").join("cockpit"))
294        .find(|dir| dir.join("manifest.json").is_file())
295}
296
297/// Import the shipped Cockpit when none is active or it ships a different
298/// package; one older than the active install (by channel sequence) is left
299/// alone. Never fails a start.
300fn import_bundled() {
301    let Some(dir) = bundled_dir() else {
302        return;
303    };
304    let Ok(manifest) = super::read_regular(&dir.join("manifest.json"), 65_536) else {
305        return;
306    };
307    let shipped = super::sha256(&manifest);
308    let active = bootstrap::cockpit_root()
309        .ok()
310        .and_then(|root| read_activation(&root).ok().flatten());
311    // The shipped package is active, or the user deactivated the Cockpit
312    // and keeps it deactivated.
313    if active
314        .as_ref()
315        .is_some_and(|active| !active.enabled || active.manifest_sha256 == shipped)
316    {
317        return;
318    }
319    match read_bundle(&dir).and_then(|bundle| import(&bundle, false)) {
320        Ok(_) => tracing::info!("imported the bundled cockpit"),
321        Err(InstallError::Downgrade) => {
322            tracing::info!("bundled cockpit is older than the active one; kept the active one");
323        }
324        Err(error) => tracing::debug!("bundled cockpit not imported: {error:?}"),
325    }
326}
327
328#[derive(Serialize, Deserialize)]
329#[serde(deny_unknown_fields)]
330struct Activation {
331    schema_version: u32,
332    enabled: bool,
333    manifest_sha256: String,
334    trust_key_hex: String,
335}
336
337fn read_activation(root: &Path) -> Result<Option<Activation>> {
338    let path = root.join(ACTIVATION);
339    if !path.try_exists()? {
340        return Ok(None);
341    }
342    let activation: Activation = serde_json::from_slice(&super::read_regular(&path, 4096)?)
343        .map_err(|_| InstallError::State)?;
344    if activation.schema_version != 1
345        || !super::is_digest(&activation.manifest_sha256, 64)
346        || !super::is_digest(&activation.trust_key_hex, 64)
347    {
348        return Err(InstallError::State);
349    }
350    Ok(Some(activation))
351}
352
353/// The caller holds the store's configuration guard.
354fn write_activation(root: &Path, activation: &Activation) -> Result<()> {
355    let bytes = serde_json::to_vec_pretty(activation).map_err(|_| InstallError::State)?;
356    crate::core::updater::atomic_write_bytes(&root.join(ACTIVATION), &bytes)
357        .map_err(|_| InstallError::Commit)
358}
359
360/// Authenticate the selected package as a Cockpit and record it as the one
361/// the dashboard starts. The caller holds the store's configuration guard.
362fn activate_locked(root: &Path, selected: &str, key_hex: &str) -> Result<serde_json::Value> {
363    let key = super::trust_key(key_hex)?;
364    let package = install::verified_active_kind(RuntimeKind::Cockpit, root, selected, &key)?;
365    write_activation(
366        root,
367        &Activation {
368            schema_version: 1,
369            enabled: true,
370            manifest_sha256: selected.to_owned(),
371            trust_key_hex: key_hex.to_owned(),
372        },
373    )?;
374    Ok(serde_json::json!({"status": "activated", "kind": "cockpit",
375        "receipt": package.receipt, "runtime_started": false, "release_approved": false}))
376}
377
378/// The activated Cockpit of this host, authenticated now.
379fn authenticated() -> std::result::Result<(PathBuf, VerifiedPackage), CockpitUnavailable> {
380    let root = bootstrap::cockpit_root().map_err(|_| CockpitUnavailable::NotInstalled)?;
381    let activation = match read_activation(&root) {
382        Ok(Some(activation)) => activation,
383        Ok(None) => return Err(CockpitUnavailable::NotInstalled),
384        Err(_) => return Err(CockpitUnavailable::VerificationFailed),
385    };
386    if !activation.enabled {
387        return Err(CockpitUnavailable::Disabled);
388    }
389    let package = super::trust_key(&activation.trust_key_hex)
390        .and_then(|key| {
391            install::verified_active_kind(
392                RuntimeKind::Cockpit,
393                &root,
394                &activation.manifest_sha256,
395                &key,
396            )
397        })
398        .map_err(|_| CockpitUnavailable::VerificationFailed)?;
399    Ok((root, package))
400}
401
402/// Download, verify, install and activate the Cockpit from this host's
403/// bundled Cockpit channel. `staging`, when given, must name that channel's
404/// track. Network access happens only here, on an explicit request.
405fn install_configured(staging: Option<bool>) -> Result<serde_json::Value> {
406    let channel = bootstrap::cockpit_channel()?.ok_or(InstallError::Policy)?;
407    if staging.is_some_and(|staging| staging != channel.staging) {
408        return Err(InstallError::Usage);
409    }
410    let root = bootstrap::cockpit_root()?;
411    install::prepare_parent_chain(root.parent().ok_or(InstallError::Directory)?)?;
412    let _guard = install::configuration_guard(&root)?;
413    let expected = install::active_manifest(&root)?;
414    let installation = super::catalog::sync_kind(
415        RuntimeKind::Cockpit,
416        channel.urls,
417        &channel.key,
418        &root,
419        &expected,
420        super::catalog::Companions::Inline,
421    )?;
422    activate_installation(&root, &installation, "channel")
423}
424
425/// Activate what an install selected. The caller holds the store's
426/// configuration guard.
427fn activate_installation(
428    root: &Path,
429    installation: &serde_json::Value,
430    source: &str,
431) -> Result<serde_json::Value> {
432    let selected = installation["receipt"]["manifest_sha256"]
433        .as_str()
434        .ok_or(InstallError::State)?;
435    let key = installation["artifact_key_hex"]
436        .as_str()
437        .ok_or(InstallError::State)?;
438    let activation = activate_locked(root, selected, key)?;
439    retire();
440    Ok(
441        serde_json::json!({"status": "installed_and_activated", "kind": "cockpit", "source": source,
442        "installation": installation, "activation": activation, "release_approved": false}),
443    )
444}
445
446/// Install-on-demand for `lean-ctx cockpit`: the same path as
447/// `setup runtime sync-configured --kind cockpit`. The caller has the
448/// user's request to install; this downloads from the bundled channel.
449pub fn install_cockpit() -> std::result::Result<serde_json::Value, CockpitUnavailable> {
450    install_configured(None).map_err(|error| install_failure(&error))
451}
452
453/// What a failed install-on-demand tells the user.
454fn install_failure(error: &InstallError) -> CockpitUnavailable {
455    match error {
456        InstallError::Manifest
457        | InstallError::ChannelExpired
458        | InstallError::ChannelMismatch
459        | InstallError::PlatformUnavailable
460        | InstallError::Signature
461        | InstallError::Archive
462        | InstallError::Size
463        | InstallError::State
464        | InstallError::Downgrade => CockpitUnavailable::VerificationFailed,
465        // #2270: a failed download is not "not installed"; that line named
466        // the very command that had just failed.
467        InstallError::Download => CockpitUnavailable::DownloadFailed,
468        _ => CockpitUnavailable::NotInstalled,
469    }
470}
471
472/// Whether a Cockpit could be started now, decided exactly as a start
473/// decides it (shipped bundle imported first, then authenticated), without
474/// starting one and without network. Lets a command fall back to its
475/// terminal report before it opens a browser on the install page.
476pub fn availability() -> std::result::Result<(), CockpitUnavailable> {
477    import_bundled();
478    match authenticated() {
479        Ok(_) => Ok(()),
480        Err(CockpitUnavailable::NotInstalled)
481            if bootstrap::cockpit_channel().ok().flatten().is_none() =>
482        {
483            Err(CockpitUnavailable::SourceBuild)
484        }
485        Err(reason) => Err(reason),
486    }
487}
488
489/// `LEAN_CTX_NO_COCKPIT=1` (as for install.sh) keeps every automatic install off.
490fn installs_opted_out() -> bool {
491    std::env::var_os("LEAN_CTX_NO_COCKPIT").is_some_and(|value| !value.is_empty() && value != "0")
492}
493
494/// `availability`, but a missing Cockpit of an official build is installed
495/// first: the person asked to open it, and the Cockpit ships with LeanCTX.
496pub fn available_or_installed() -> std::result::Result<(), CockpitUnavailable> {
497    match availability() {
498        Err(CockpitUnavailable::NotInstalled) if !installs_opted_out() => {
499            eprintln!(
500                "Installing the LeanCTX Cockpit (signed, free) from the LeanCTX runtime channel…"
501            );
502            install_cockpit()?;
503            availability()
504        }
505        other => other,
506    }
507}
508
509/// After a failed automatic install, the next automatic attempt waits a day.
510const AUTO_RETRY: Duration = Duration::from_hours(24);
511
512fn auto_attempt_marker() -> Option<PathBuf> {
513    crate::core::data_dir::resolve_data_dir()
514        .ok()
515        .map(|dir| dir.join("cockpit-auto-install.failed"))
516}
517
518/// Whether a failed attempt recorded at `failed_at` still blocks one at `now`.
519fn retry_blocked(failed_at: Option<std::time::SystemTime>, now: std::time::SystemTime) -> bool {
520    failed_at
521        .and_then(|failed_at| now.duration_since(failed_at).ok())
522        .is_some_and(|elapsed| elapsed < AUTO_RETRY)
523}
524
525/// Install the Cockpit without being asked when an official build has none:
526/// after an update from a release without it, or an install path that ships
527/// only the Engine, nobody has to run a command. Only when none is installed
528/// (a deactivated Cockpit stays deactivated), outside CI, and after a failure
529/// at most once a day unless `retry_now`. Returns whether it installed one.
530pub(crate) fn install_if_missing(retry_now: bool) -> bool {
531    if installs_opted_out()
532        || crate::core::telemetry_consent::ci_detected(crate::core::host_env::var)
533    {
534        return false;
535    }
536    if !matches!(availability(), Err(CockpitUnavailable::NotInstalled)) {
537        return false;
538    }
539    let marker = auto_attempt_marker();
540    let failed_at = marker
541        .as_deref()
542        .and_then(|path| std::fs::metadata(path).ok())
543        .and_then(|metadata| metadata.modified().ok());
544    if !retry_now && retry_blocked(failed_at, std::time::SystemTime::now()) {
545        return false;
546    }
547    match install_cockpit() {
548        Ok(_) => {
549            if let Some(path) = &marker {
550                let _ = std::fs::remove_file(path);
551            }
552            tracing::info!("installed the cockpit automatically");
553            true
554        }
555        Err(reason) => {
556            if let Some(path) = &marker {
557                let _ = std::fs::write(path, reason.as_str());
558            }
559            tracing::debug!("automatic cockpit install failed: {}", reason.as_str());
560            false
561        }
562    }
563}
564
565/// `install_if_missing` on its own thread: an MCP or daemon start never waits
566/// for the download.
567pub fn install_if_missing_in_background() {
568    let _ = std::thread::Builder::new()
569        .name("cockpit-install".into())
570        .spawn(|| {
571            install_if_missing(false);
572        });
573}
574
575/// What `setup runtime status --kind cockpit` reports; starts nothing and
576/// uses no network.
577pub(crate) fn status() -> serde_json::Value {
578    let (status, version) = match authenticated() {
579        Ok((_, package)) => ("installed", Some(package.receipt.version)),
580        Err(reason) => (reason.as_str(), None),
581    };
582    let channel = bootstrap::cockpit_channel().ok().flatten();
583    serde_json::json!({"schema_version": 1, "kind": "cockpit", "status": status,
584        "version": version, "channel_available": channel.is_some(),
585        "staging": channel.map(|channel| channel.staging),
586        "runtime_started": false, "release_approved": false})
587}
588
589fn deactivate() -> Result<serde_json::Value> {
590    let root = bootstrap::cockpit_root()?;
591    if !root.try_exists()? {
592        return Ok(serde_json::json!({"status": "not_installed", "kind": "cockpit"}));
593    }
594    let _guard = install::configuration_guard(&root)?;
595    let Some(mut activation) = read_activation(&root)? else {
596        return Ok(serde_json::json!({"status": "not_installed", "kind": "cockpit"}));
597    };
598    activation.enabled = false;
599    write_activation(&root, &activation)?;
600    retire();
601    Ok(serde_json::json!({"status": "disabled", "kind": "cockpit", "release_approved": false}))
602}
603
604/// `lean-ctx setup runtime <operation> --kind cockpit`: the Cockpit's own
605/// `status`, `sync-configured`, `activate` and `deactivate`. Package
606/// operations (`verify`, `install`, `download`, `sync`) run the shared path.
607pub(super) fn run_cli(
608    operation: &str,
609    staging: bool,
610    accepted: bool,
611    flags: &std::collections::BTreeMap<&str, &str>,
612) -> Result<serde_json::Value> {
613    match operation {
614        "status" if flags.is_empty() => Ok(status()),
615        "deactivate" if flags.is_empty() => deactivate(),
616        "sync-configured" if flags.is_empty() && accepted => install_configured(Some(staging)),
617        // Explicit staging activation of a package installed with
618        // `install --staging --kind cockpit` into this host's Cockpit store.
619        "activate" if staging && accepted && flags.len() == 4 => {
620            let get = |name| flags.get(name).copied().ok_or(InstallError::Usage);
621            let root = Path::new(get("--root")?);
622            let selected = get("--manifest-sha256")?;
623            if get("--expected-active")? != selected
624                || root != bootstrap::cockpit_root()?
625                || bootstrap::production_key(root)?.is_some()
626            {
627                return Err(InstallError::Usage);
628            }
629            let _guard = install::configuration_guard(root)?;
630            let result = activate_locked(root, selected, get("--trust-key-hex")?)?;
631            retire();
632            Ok(result)
633        }
634        _ => Err(InstallError::Usage),
635    }
636}
637
638/// The commit budget of a Windows Cockpit in MiB when
639/// `LEAN_CTX_COCKPIT_MEMORY_MB` does not set one (#2252).
640#[cfg(any(windows, test))]
641const MEMORY_BUDGET_DEFAULT_MIB: u64 = 4096;
642/// The smallest budget a setting may choose.
643#[cfg(any(windows, test))]
644const MEMORY_BUDGET_MIN_MIB: u64 = 256;
645/// How many bytes of the Cockpit's stderr are kept for an exit report.
646const STDERR_TAIL: usize = 4096;
647/// How long an exit report waits for the rest of the Cockpit's stderr.
648const STDERR_SETTLE: Duration = Duration::from_millis(500);
649
650/// The Cockpit's memory budget in bytes: `LEAN_CTX_COCKPIT_MEMORY_MB`, at
651/// least `MEMORY_BUDGET_MIN_MIB`; `0` turns it off, and anything that is not
652/// a number keeps the default.
653#[cfg(any(windows, test))]
654fn memory_budget(setting: Option<&str>) -> Option<u64> {
655    let mib = match setting.map(str::trim) {
656        Some("0") => return None,
657        Some(value) => value
658            .parse::<u64>()
659            .map_or(MEMORY_BUDGET_DEFAULT_MIB, |mib| {
660                mib.max(MEMORY_BUDGET_MIN_MIB)
661            }),
662        None => MEMORY_BUDGET_DEFAULT_MIB,
663    };
664    Some(mib.saturating_mul(1024 * 1024))
665}
666
667/// The end of what the Cockpit wrote to stderr.
668#[derive(Default)]
669struct StderrTail {
670    bytes: Vec<u8>,
671    /// Bytes were dropped from the front: the first line is partial.
672    cut: bool,
673}
674
675/// Append `chunk` to `tail` and keep only its last `cap` bytes.
676fn keep_tail(tail: &mut StderrTail, chunk: &[u8], cap: usize) {
677    tail.bytes.extend_from_slice(chunk);
678    if tail.bytes.len() > cap {
679        tail.bytes.drain(..tail.bytes.len() - cap);
680        tail.cut = true;
681    }
682}
683
684/// The shortest piece of a token that is redacted at an edge of the report.
685const MIN_SECRET_FRAGMENT: usize = 4;
686
687/// The kept stderr as loggable text. Only whole lines are shown: a first
688/// line cut by the bound (`cut`) and a last line still being written
689/// (`open_end`) are dropped, so no token is shown in part. The session's own
690/// tokens, any piece of them left at an edge, and anything credential-shaped
691/// are redacted; control characters other than line breaks and tabs are
692/// dropped.
693fn stderr_report(tail: &[u8], cut: bool, open_end: bool, secrets: &[String]) -> String {
694    let mut text = String::from_utf8_lossy(tail).into_owned();
695    if cut {
696        text = text
697            .split_once('\n')
698            .map_or_else(String::new, |(_, rest)| rest.to_owned());
699    }
700    if open_end {
701        text.truncate(text.rfind('\n').map_or(0, |end| end + 1));
702    }
703    for secret in secrets.iter().filter(|secret| !secret.is_empty()) {
704        text = text.replace(secret.as_str(), "[REDACTED:token]");
705        for len in (MIN_SECRET_FRAGMENT..secret.len()).rev() {
706            let (Some(head), Some(rest)) = (secret.get(..len), secret.get(secret.len() - len..))
707            else {
708                continue;
709            };
710            if let Some(kept) = text.strip_prefix(rest) {
711                text = format!("[REDACTED:token]{kept}");
712            }
713            if let Some(kept) = text.strip_suffix(head) {
714                text = format!("{kept}[REDACTED:token]");
715            }
716        }
717    }
718    crate::core::redaction::redact_text(&text)
719        .chars()
720        .filter(|c| !c.is_control() || matches!(c, '\n' | '\t'))
721        .collect::<String>()
722        .trim()
723        .to_owned()
724}
725
726/// A Windows job that holds the Cockpit: its committed memory is capped, and
727/// closing the job ends whatever still runs in it (#2252).
728#[cfg(windows)]
729struct MemoryJob {
730    handle: windows_sys::Win32::Foundation::HANDLE,
731    limit: u64,
732}
733
734#[cfg(windows)]
735impl MemoryJob {
736    fn assign(child: &Child, limit: Option<u64>) -> std::io::Result<Self> {
737        use std::os::windows::io::AsRawHandle;
738        use windows_sys::Win32::System::JobObjects::{
739            AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
740            JOB_OBJECT_LIMIT_PROCESS_MEMORY, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
741            JobObjectExtendedLimitInformation, SetInformationJobObject,
742        };
743        // SAFETY: null attributes and name create a private job owned by Self.
744        let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
745        if handle.is_null() {
746            return Err(std::io::Error::last_os_error());
747        }
748        let job = Self {
749            handle,
750            limit: limit.unwrap_or(0),
751        };
752        let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
753        limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
754        if let Some(limit) = limit {
755            limits.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_PROCESS_MEMORY;
756            limits.ProcessMemoryLimit = usize::try_from(limit).unwrap_or(usize::MAX);
757        }
758        // SAFETY: limits has the exact structure and size this class requires.
759        let configured = unsafe {
760            SetInformationJobObject(
761                job.handle,
762                JobObjectExtendedLimitInformation,
763                std::ptr::from_ref(&limits).cast(),
764                std::mem::size_of_val(&limits) as u32,
765            )
766        };
767        if configured == 0 {
768            return Err(std::io::Error::last_os_error());
769        }
770        // SAFETY: Child owns a live handle to the process it started.
771        let assigned =
772            unsafe { AssignProcessToJobObject(job.handle, child.as_raw_handle().cast()) };
773        if assigned == 0 {
774            return Err(std::io::Error::last_os_error());
775        }
776        Ok(job)
777    }
778
779    /// The most memory the Cockpit has committed so far, in bytes.
780    fn peak(&self) -> Option<u64> {
781        use windows_sys::Win32::System::JobObjects::{
782            JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
783            QueryInformationJobObject,
784        };
785        let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
786        // SAFETY: limits is writable for the exact size this class requires.
787        let queried = unsafe {
788            QueryInformationJobObject(
789                self.handle,
790                JobObjectExtendedLimitInformation,
791                std::ptr::from_mut(&mut limits).cast(),
792                std::mem::size_of_val(&limits) as u32,
793                std::ptr::null_mut(),
794            )
795        };
796        (queried != 0).then_some(limits.PeakProcessMemoryUsed as u64)
797    }
798}
799
800// SAFETY: a job handle is a kernel object handle, valid from any thread; the
801// supervisor's static state moves the running Cockpit between threads.
802#[cfg(windows)]
803unsafe impl Send for MemoryJob {}
804
805#[cfg(windows)]
806impl Drop for MemoryJob {
807    fn drop(&mut self) {
808        // SAFETY: this instance exclusively owns the CreateJobObjectW handle.
809        unsafe {
810            windows_sys::Win32::Foundation::CloseHandle(self.handle);
811        }
812    }
813}
814
815/// One started Cockpit process: its stdin stays open while it runs.
816pub(super) struct Process {
817    child: Child,
818    stdin: Option<ChildStdin>,
819    port: u16,
820    /// The last `STDERR_TAIL` bytes the Cockpit wrote to stderr; only ever
821    /// logged redacted, in an exit report.
822    stderr: std::sync::Arc<Mutex<StderrTail>>,
823    stderr_reader: Option<std::thread::JoinHandle<()>>,
824    /// The tokens of this start, redacted from every exit report.
825    secrets: Vec<String>,
826    /// True once `stop` had to kill the Cockpit: its failed exit status is
827    /// then the supervisor's doing, not a crash or a failed allocation.
828    killed: bool,
829    /// Declared after `child`: dropped once the Cockpit was stopped, and then
830    /// ends anything left in its job.
831    #[cfg(windows)]
832    job: Option<MemoryJob>,
833}
834
835impl Process {
836    /// Why the exited Cockpit ended, for the log: its exit status, on Windows
837    /// its peak memory against the budget, and the redacted end of its
838    /// stderr.
839    fn exit_report(&mut self) -> String {
840        let (status, failed) = match self.child.try_wait() {
841            Ok(Some(status)) => (status.to_string(), !status.success()),
842            _ => ("still running".to_owned(), false),
843        };
844        let mut report = format!("status {status}");
845        if self.killed {
846            report.push_str(" (stopped by the supervisor)");
847        }
848        #[cfg(windows)]
849        if let Some(job) = &self.job {
850            if let Some(peak) = job.peak() {
851                let mib = |bytes: u64| bytes / (1024 * 1024);
852                if job.limit > 0 {
853                    report.push_str(&format!(
854                        ", peak memory {} MiB of its {} MiB budget",
855                        mib(peak),
856                        mib(job.limit)
857                    ));
858                    if peak.saturating_add(16 * 1024 * 1024) >= job.limit {
859                        report.push_str(
860                            " (it reached the budget; raise it with LEAN_CTX_COCKPIT_MEMORY_MB)",
861                        );
862                    } else if failed && !self.killed {
863                        // One allocation beyond the budget fails without
864                        // raising the peak.
865                        report.push_str(
866                            " (an allocation beyond the budget may have failed; raise it with LEAN_CTX_COCKPIT_MEMORY_MB)",
867                        );
868                    }
869                } else {
870                    report.push_str(&format!(", peak memory {} MiB", mib(peak)));
871                }
872            }
873        }
874        #[cfg(not(windows))]
875        let _ = failed;
876        let mut open_end = false;
877        if let Some(reader) = self.stderr_reader.take() {
878            let settle = Instant::now() + STDERR_SETTLE;
879            while !reader.is_finished() && Instant::now() < settle {
880                std::thread::sleep(Duration::from_millis(10));
881            }
882            if reader.is_finished() {
883                let _ = reader.join();
884            } else {
885                // Still read, e.g. while a descendant holds the pipe: the last
886                // line may be incomplete.
887                open_end = true;
888            }
889        }
890        let tail = self.stderr.lock().unwrap_or_else(PoisonError::into_inner);
891        let stderr = stderr_report(&tail.bytes, tail.cut, open_end, &self.secrets);
892        if !stderr.is_empty() {
893            report.push_str(&format!(
894                "; last stderr (redacted, at most {STDERR_TAIL} bytes):\n{stderr}"
895            ));
896        }
897        report
898    }
899
900    /// Close stdin, give the Cockpit `grace` to end, then kill and collect
901    /// it. True when it ended by itself. Repeated calls do nothing.
902    pub(super) fn stop(&mut self, grace: Duration) -> bool {
903        drop(self.stdin.take());
904        let deadline = Instant::now() + grace;
905        loop {
906            match self.child.try_wait() {
907                Ok(Some(_)) => return true,
908                Ok(None) if Instant::now() < deadline => {
909                    std::thread::sleep(Duration::from_millis(20));
910                }
911                _ => {
912                    let _ = self.child.kill();
913                    let _ = self.child.wait();
914                    self.killed = true;
915                    return false;
916                }
917            }
918        }
919    }
920
921    fn running(&mut self) -> bool {
922        matches!(self.child.try_wait(), Ok(None))
923    }
924}
925
926impl Drop for Process {
927    fn drop(&mut self) {
928        self.stop(EXIT_GRACE);
929    }
930}
931
932/// Spawn `command`, hand it the start line and read its port within
933/// `deadline`. A start that does not name its port in time is killed.
934pub(super) fn handshake(
935    mut command: Command,
936    start: &[u8],
937    secrets: Vec<String>,
938    deadline: Duration,
939) -> std::result::Result<Process, CockpitUnavailable> {
940    command
941        .stdin(Stdio::piped())
942        .stdout(Stdio::piped())
943        // Kept as a bounded tail and only logged redacted: it could repeat a
944        // token (#2252).
945        .stderr(Stdio::piped());
946    let child = command.spawn().map_err(|error| {
947        tracing::warn!("cockpit not started: the process could not be spawned: {error}");
948        CockpitUnavailable::StartFailed
949    })?;
950    #[cfg(windows)]
951    let job = {
952        let budget = memory_budget(std::env::var("LEAN_CTX_COCKPIT_MEMORY_MB").ok().as_deref());
953        match MemoryJob::assign(&child, budget) {
954            Ok(job) => Some(job),
955            Err(error) => {
956                tracing::warn!(
957                    "cockpit runs without its memory budget, the job could not be set up: {error}"
958                );
959                None
960            }
961        }
962    };
963    let mut process = Process {
964        child,
965        stdin: None,
966        port: 0,
967        stderr: std::sync::Arc::default(),
968        stderr_reader: None,
969        secrets,
970        killed: false,
971        #[cfg(windows)]
972        job,
973    };
974    if let Some(mut stderr) = process.child.stderr.take() {
975        let tail = std::sync::Arc::clone(&process.stderr);
976        process.stderr_reader = std::thread::Builder::new()
977            .name("cockpit-stderr".to_owned())
978            .spawn(move || {
979                let mut chunk = [0_u8; 1024];
980                while let Ok(read @ 1..) = stderr.read(&mut chunk) {
981                    let mut tail = tail.lock().unwrap_or_else(PoisonError::into_inner);
982                    keep_tail(&mut tail, &chunk[..read], STDERR_TAIL);
983                }
984            })
985            .ok();
986    }
987    let (Some(mut stdin), Some(stdout)) = (process.child.stdin.take(), process.child.stdout.take())
988    else {
989        process.stop(Duration::ZERO);
990        return Err(CockpitUnavailable::StartFailed);
991    };
992    if stdin.write_all(start).and_then(|()| stdin.flush()).is_err() {
993        process.stop(Duration::ZERO);
994        return Err(CockpitUnavailable::StartFailed);
995    }
996    process.stdin = Some(stdin);
997    let (sender, receiver) = mpsc::sync_channel(1);
998    let reader = std::thread::Builder::new()
999        .name("cockpit-output".to_owned())
1000        .spawn(move || {
1001            let mut output = BufReader::new(stdout);
1002            let mut line = Vec::new();
1003            let read = (&mut output)
1004                .take(MAX_PORT_LINE)
1005                .read_until(b'\n', &mut line);
1006            let _ = sender.send(read.ok().map(|_| line));
1007            // Drained to its end, so the Cockpit never blocks on a full pipe.
1008            let _ = std::io::copy(&mut output, &mut std::io::sink());
1009        });
1010    let port = reader
1011        .ok()
1012        .and_then(|_| receiver.recv_timeout(deadline).ok().flatten())
1013        .and_then(|line| listening(&line));
1014    if let Some(port) = port {
1015        process.port = port;
1016        Ok(process)
1017    } else {
1018        let exited = process.child.try_wait().ok().flatten().is_some();
1019        process.stop(Duration::ZERO);
1020        let report = process.exit_report();
1021        if exited {
1022            tracing::warn!(
1023                "cockpit not started: it exited before naming its loopback port: {report}"
1024            );
1025        } else {
1026            tracing::warn!(
1027                "cockpit not started: it did not name its loopback port within {} s: {report}",
1028                deadline.as_secs()
1029            );
1030        }
1031        Err(CockpitUnavailable::StartFailed)
1032    }
1033}
1034
1035/// The port of a terminated `{"listening":<port>}` line.
1036fn listening(line: &[u8]) -> Option<u16> {
1037    #[derive(Deserialize)]
1038    #[serde(deny_unknown_fields)]
1039    struct Listening {
1040        listening: u16,
1041    }
1042    if line.last() != Some(&b'\n') {
1043        return None;
1044    }
1045    serde_json::from_slice::<Listening>(line)
1046        .ok()
1047        .map(|listening| listening.listening)
1048        .filter(|port| *port != 0)
1049}
1050
1051struct Running {
1052    process: Process,
1053    /// The private directory the authenticated binary runs from.
1054    prepared: Option<super::health::Prepared>,
1055    cockpit_token: String,
1056    launch: [u8; 32],
1057    started: Instant,
1058}
1059
1060impl Drop for Running {
1061    fn drop(&mut self) {
1062        self.process.stop(EXIT_GRACE);
1063        if let Some(prepared) = self.prepared.take() {
1064            let _ = prepared.close();
1065        }
1066    }
1067}
1068
1069struct State {
1070    running: Option<Running>,
1071    /// Failures in a row.
1072    failures: usize,
1073    retry_at: Option<Instant>,
1074    last_failure: CockpitUnavailable,
1075}
1076
1077static STATE: Mutex<State> = Mutex::new(State {
1078    running: None,
1079    failures: 0,
1080    retry_at: None,
1081    last_failure: CockpitUnavailable::StartFailed,
1082});
1083
1084fn launch_key(launch: &CockpitLaunch) -> [u8; 32] {
1085    let mut hasher = blake3::Hasher::new();
1086    hasher.update(&launch.engine_port.to_le_bytes());
1087    hasher.update(&(launch.engine_token.len() as u64).to_le_bytes());
1088    hasher.update(launch.engine_token.as_bytes());
1089    hasher.update(launch.project_root.as_os_str().as_encoded_bytes());
1090    *hasher.finalize().as_bytes()
1091}
1092
1093/// The running Cockpit of this process, started when none runs. Holds the
1094/// supervisor lock across a start, so concurrent callers share one start.
1095pub fn cockpit_endpoint(
1096    launch: &CockpitLaunch,
1097) -> std::result::Result<CockpitEndpoint, CockpitUnavailable> {
1098    let key = launch_key(launch);
1099    let mut state = STATE.lock().unwrap_or_else(PoisonError::into_inner);
1100    let now = Instant::now();
1101    if let Some(running) = state.running.as_mut() {
1102        if running.process.running() {
1103            if running.launch == key {
1104                return Ok(CockpitEndpoint {
1105                    port: running.process.port,
1106                    cockpit_token: running.cockpit_token.clone(),
1107                });
1108            }
1109            // Started for another dashboard: replaced, nothing failed.
1110            state.running = None;
1111        } else {
1112            let stable = running.started.elapsed() >= STABLE;
1113            let report = running.process.exit_report();
1114            state.running = None;
1115            if stable {
1116                state.failures = 0;
1117            }
1118            tracing::warn!("cockpit exited ({report}); restarting after backoff");
1119            fail(&mut state, CockpitUnavailable::StartFailed, now);
1120        }
1121    }
1122    if state.retry_at.is_some_and(|at| now < at) {
1123        return Err(state.last_failure);
1124    }
1125    match start(launch, key) {
1126        Ok(running) => {
1127            let endpoint = CockpitEndpoint {
1128                port: running.process.port,
1129                cockpit_token: running.cockpit_token.clone(),
1130            };
1131            state.retry_at = None;
1132            state.running = Some(running);
1133            Ok(endpoint)
1134        }
1135        // Nothing to retry: the user installs or activates it.
1136        Err(
1137            reason @ (CockpitUnavailable::NotInstalled
1138            | CockpitUnavailable::Disabled
1139            | CockpitUnavailable::SourceBuild),
1140        ) => Err(reason),
1141        Err(reason) => {
1142            tracing::warn!("cockpit not started: {}", reason.as_str());
1143            fail(&mut state, reason, now);
1144            Err(reason)
1145        }
1146    }
1147}
1148
1149fn fail(state: &mut State, reason: CockpitUnavailable, now: Instant) {
1150    let wait = RESTART_BACKOFF[state.failures.min(RESTART_BACKOFF.len() - 1)];
1151    state.failures = state.failures.saturating_add(1);
1152    state.retry_at = Some(now + wait);
1153    state.last_failure = reason;
1154}
1155
1156/// Stop this process's Cockpit, if any; the next request starts the
1157/// currently activated package without waiting for a backoff.
1158pub fn retire() {
1159    let mut state = STATE.lock().unwrap_or_else(PoisonError::into_inner);
1160    state.running = None;
1161    state.failures = 0;
1162    state.retry_at = None;
1163}
1164
1165fn start(
1166    launch: &CockpitLaunch,
1167    key: [u8; 32],
1168) -> std::result::Result<Running, CockpitUnavailable> {
1169    import_bundled();
1170    let (root, package) = match authenticated() {
1171        Err(CockpitUnavailable::NotInstalled)
1172            if bootstrap::cockpit_channel().ok().flatten().is_none() =>
1173        {
1174            return Err(CockpitUnavailable::SourceBuild);
1175        }
1176        other => other?,
1177    };
1178    let mut token = [0_u8; 32];
1179    getrandom::fill(&mut token).map_err(|_| CockpitUnavailable::StartFailed)?;
1180    let cockpit_token = hex::encode(token);
1181    let start_line = start_line(launch, &cockpit_token).ok_or(CockpitUnavailable::StartFailed)?;
1182    let (prepared, command) = super::health::prepare_binary(&package.binary, &root, EXECUTABLE)
1183        .map_err(|error| {
1184            tracing::warn!("cockpit not started: its private copy was not prepared ({error:?})");
1185            CockpitUnavailable::StartFailed
1186        })?;
1187    match handshake(
1188        command,
1189        &start_line,
1190        vec![cockpit_token.clone(), launch.engine_token.clone()],
1191        HANDSHAKE,
1192    ) {
1193        Ok(process) => Ok(Running {
1194            process,
1195            prepared: Some(prepared),
1196            cockpit_token,
1197            launch: key,
1198            started: Instant::now(),
1199        }),
1200        Err(reason) => {
1201            let _ = prepared.close();
1202            Err(reason)
1203        }
1204    }
1205}
1206
1207/// The one start line of contract `leanctx.cockpit-start/v1`.
1208fn start_line(launch: &CockpitLaunch, cockpit_token: &str) -> Option<Vec<u8>> {
1209    let engine_exe = std::env::current_exe().ok()?;
1210    // The Cockpit runs with a cleared environment: these absolute paths,
1211    // resolved exactly as the Engine resolves them, are how it finds them.
1212    let data_dir = crate::core::data_dir::resolve_data_dir().ok()?;
1213    let state_dir = crate::core::paths::state_dir().ok()?;
1214    if !data_dir.is_absolute() || !state_dir.is_absolute() {
1215        return None;
1216    }
1217    // Optional: the host session logs it reads live under the user's home.
1218    let home_dir = dirs::home_dir()
1219        .filter(|home| home.is_absolute())
1220        .and_then(|home| home.to_str().map(str::to_owned));
1221    // Optional: Engine stores it reads (e.g. path_mode_memory.json) live here.
1222    let cache_dir = crate::core::paths::cache_dir()
1223        .ok()
1224        .filter(|cache| cache.is_absolute())
1225        .and_then(|cache| cache.to_str().map(str::to_owned));
1226    // Optional: where the Engine reads its config, and the PATH its own CLI
1227    // calls (`gh`, `git`) resolve against.
1228    let config_dir = crate::core::paths::config_dir_read_only()
1229        .ok()
1230        .filter(|config| config.is_absolute())
1231        .and_then(|config| config.to_str().map(str::to_owned));
1232    let search_path = std::env::var("PATH").ok();
1233    let mut line = serde_json::to_vec(&serde_json::json!({
1234        "home_dir": home_dir,
1235        "engine_cache_dir": cache_dir,
1236        "engine_config_dir": config_dir,
1237        "search_path": search_path,
1238        "cockpit_token": cockpit_token,
1239        "engine_url": format!("http://127.0.0.1:{}", launch.engine_port),
1240        "engine_token": launch.engine_token,
1241        "engine_exe": engine_exe.to_str()?,
1242        "project_root": launch.project_root.to_str()?,
1243        "data_dir": data_dir.to_str()?,
1244        "engine_state_dir": state_dir.to_str()?,
1245        "engine_version": env!("CARGO_PKG_VERSION"),
1246    }))
1247    .ok()?;
1248    line.push(b'\n');
1249    Some(line)
1250}
1251
1252#[cfg(all(test, unix))]
1253#[path = "cockpit_tests.rs"]
1254mod tests;
1255
1256#[cfg(all(test, windows))]
1257mod windows_tests {
1258    use super::*;
1259
1260    #[test]
1261    fn the_memory_job_reports_its_peak_and_ends_the_cockpit_when_closed() {
1262        let mut child = Command::new("cmd")
1263            .args(["/C", "ping -n 30 127.0.0.1 >NUL"])
1264            .stdout(Stdio::null())
1265            .spawn()
1266            .unwrap();
1267        let job = MemoryJob::assign(&child, memory_budget(Some("256"))).unwrap();
1268        assert_eq!(job.limit, 256 * 1024 * 1024);
1269        assert!(job.peak().is_some_and(|peak| peak > 0));
1270        assert!(child.try_wait().unwrap().is_none());
1271        drop(job);
1272        let deadline = Instant::now() + Duration::from_secs(10);
1273        while child.try_wait().unwrap().is_none() {
1274            assert!(Instant::now() < deadline, "closing the job ends the child");
1275            std::thread::sleep(Duration::from_millis(20));
1276        }
1277    }
1278}