Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

26.4 KB
Raw Blame
//! Management of the bundled macrod daemon: the local agent runtime that
//! lets users run coding agents on this machine.
//!
//! The desktop app ships the `macrod` binary next to its own executable and
//! supervises it as a child process in `macrod service` mode. That mode
//! reports state changes as one JSON object per line on stdout; this module
//! folds those lines into a [`MacrodStatus`] snapshot, re-emits every change
//! to the webview as a `macrod-status` event, and exposes commands to detect
//! installed agents, start or stop the daemon, and read the snapshot.
//!
//! Once started, the daemon is kept up: an unexpected exit (a crash, a lost
//! connection, an expired pairing) restarts it with backoff until the user
//! stops it, and app launch resumes any configured daemon the user has not
//! stopped.
//!
//! GUI apps on macOS inherit launchd's minimal environment, where
//! user-installed CLIs (`claude`, `codex`, `npm`) and the credentials and
//! config their shells export are invisible. Every macrod invocation runs with
//! the user's interactive login-shell environment, so detection and agent
//! authentication match what a terminal would see.

use std::path::PathBuf;
use std::process::Stdio;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;

use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Emitter, Manager};
use tokio::io::AsyncBufReadExt as _;

/// The webview event carrying each [`MacrodStatus`] change.
const STATUS_EVENT: &str = "macrod-status";

/// The first restart delay after an unexpected exit; doubles per consecutive
/// failure up to [`RESTART_MAX_DELAY`].
const RESTART_BASE_DELAY: Duration = Duration::from_secs(1);
const RESTART_MAX_DELAY: Duration = Duration::from_secs(60);

/// How long to wait before restart attempt `attempt` (1-based).
fn restart_delay(attempt: u32) -> Duration {
    RESTART_BASE_DELAY
        .saturating_mul(1 << attempt.saturating_sub(1).min(6))
        .min(RESTART_MAX_DELAY)
}

/// Where the daemon lifecycle currently stands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum MacrodPhase {
    Stopped,
    Starting,
    InstallingAdapter,
    Pairing,
    Running,
    Error,
}

impl Default for MacrodPhase {
    fn default() -> Self {
        Self::Stopped
    }
}

/// The daemon state snapshot the frontend renders from.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct MacrodStatus {
    pub(crate) phase: MacrodPhase,
    /// Agent preset id from the service config, e.g. `claude-code`.
    pub(crate) agent_id: Option<String>,
    /// Human-readable agent name from the service config.
    pub(crate) agent_name: Option<String>,
    /// Workspace directory sessions run in.
    pub(crate) workspace: Option<String>,
    /// Open pairing code awaiting approval, `XXXX-XXXX`.
    pub(crate) pairing_code: Option<String>,
    /// When the open pairing expires (RFC 3339).
    pub(crate) pairing_expires_at: Option<String>,
    /// The registered harness once paired.
    pub(crate) harness_id: Option<String>,
    /// The last fatal error, kept until the next start.
    pub(crate) last_error: Option<String>,
}

impl MacrodStatus {
    /// Fold one service event line into this snapshot.
    fn apply(&mut self, event: &serde_json::Value) {
        let text = |key: &str| {
            event
                .get(key)
                .and_then(serde_json::Value::as_str)
                .map(str::to_owned)
        };
        match event.get("event").and_then(serde_json::Value::as_str) {
            Some("config") => {
                self.agent_id = text("agent_id");
                self.agent_name = text("agent_name");
                self.workspace = text("workspace");
            }
            Some("installing_adapter") => self.phase = MacrodPhase::InstallingAdapter,
            Some("adapter_installed") => self.phase = MacrodPhase::Starting,
            Some("pairing") => {
                self.phase = MacrodPhase::Pairing;
                self.pairing_code = text("code");
                self.pairing_expires_at = text("expires_at");
            }
            Some("paired") => {
                self.pairing_code = None;
                self.pairing_expires_at = None;
                self.harness_id = text("harness_id");
            }
            Some("running") => {
                self.phase = MacrodPhase::Running;
                self.harness_id = text("harness_id");
            }
            Some("fatal") => {
                self.phase = MacrodPhase::Error;
                self.last_error = text("message");
            }
            _ => {}
        }
    }
}

/// The supervised daemon, managed as Tauri state.
#[derive(Default)]
pub(crate) struct MacrodState {
    inner: Arc<Mutex<Inner>>,
}

#[derive(Default)]
struct Inner {
    /// The live child; `None` once it exited or was stopped.
    child: Option<tokio::process::Child>,
    status: MacrodStatus,
    /// Increments per start so a stale reader task cannot clobber a newer run.
    generation: u64,
    /// Whether the daemon should be up: set by a start, cleared by a stop.
    /// An exit while this is set is unexpected and triggers a restart.
    wanted: bool,
    /// Consecutive restarts without reaching `running`, for backoff.
    restarts: u32,
}

fn emit_status(app: &AppHandle, status: &MacrodStatus) {
    if let Err(error) = app.emit(STATUS_EVENT, status) {
        tracing::warn!(?error, "failed to emit macrod status");
    }
}

/// Brackets the shell's `env` output, so rc-file banners are never parsed.
#[cfg(any(unix, test))]
const ENV_START: &str = "__MACRO_SHELL_ENV_START__";
#[cfg(any(unix, test))]
const ENV_END: &str = "__MACRO_SHELL_ENV_END__";

/// How long an interactive login shell may take to print its environment.
#[cfg(unix)]
const SHELL_ENV_TIMEOUT: Duration = Duration::from_secs(5);

/// Shell bookkeeping that describes the probe shell, not the user's setup.
const SHELL_ONLY_VARS: [&str; 5] = ["_", "SHLVL", "PWD", "OLDPWD", "PATH"];

/// The environment of the user's interactive login shell, resolved once:
/// what a terminal sees, including variables exported from `.zshrc` or
/// `.bashrc` that a non-interactive login shell skips. Agents read their
/// credentials and config from there (`CLAUDE_CODE_OAUTH_TOKEN`,
/// `CLAUDE_CONFIG_DIR`, `ANTHROPIC_API_KEY`, ...); without them Claude Code
/// falls back to stale stored credentials and fails to authenticate. Empty
/// when it cannot be read (non-unix, odd shells, a hung rc file).
fn login_shell_env() -> &'static [(String, String)] {
    static RESOLVED: OnceLock<Vec<(String, String)>> = OnceLock::new();
    RESOLVED.get_or_init(|| {
        #[cfg(unix)]
        {
            read_login_shell_env().unwrap_or_default()
        }
        #[cfg(not(unix))]
        {
            Vec::new()
        }
    })
}

#[cfg(unix)]
fn read_login_shell_env() -> Option<Vec<(String, String)>> {
    use std::io::Read as _;

    let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_owned());
    // `env` output is shell-agnostic (fish would join "$PATH" with spaces).
    let script = format!("echo {ENV_START}; env; echo {ENV_END}");
    let mut child = std::process::Command::new(&shell)
        .args(["-i", "-l", "-c", &script])
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .ok()?;
    let mut stdout = child.stdout.take()?;
    let reader = std::thread::spawn(move || {
        let mut bytes = Vec::new();
        let _ = stdout.read_to_end(&mut bytes);
        bytes
    });
    let deadline = std::time::Instant::now() + SHELL_ENV_TIMEOUT;
    loop {
        match child.try_wait() {
            Ok(Some(_)) => break,
            Ok(None) if std::time::Instant::now() < deadline => {
                std::thread::sleep(Duration::from_millis(20));
            }
            _ => {
                tracing::warn!(shell, "login shell environment timed out");
                let _ = child.kill();
                let _ = child.wait();
                return None;
            }
        }
    }
    let bytes = reader.join().ok()?;
    let vars = parse_shell_env(&String::from_utf8_lossy(&bytes));
    (!vars.is_empty()).then_some(vars)
}

/// Parse `env` output between the markers. A line that does not start a
/// `NAME=` assignment continues the previous value (a multi-line variable).
#[cfg(any(unix, test))]
fn parse_shell_env(output: &str) -> Vec<(String, String)> {
    let Some((_, rest)) = output.split_once(&format!("{ENV_START}\n")) else {
        return Vec::new();
    };
    let Some((body, _)) = rest.rsplit_once(ENV_END) else {
        return Vec::new();
    };
    let mut vars: Vec<(String, String)> = Vec::new();
    for line in body.lines() {
        // bash prints exported functions as `BASH_FUNC_name%%=() {`; they
        // start an entry (so their body lines don't join the previous
        // variable) that is dropped below.
        let assignment = line.split_once('=').filter(|(name, _)| {
            let name = name
                .strip_prefix("BASH_FUNC_")
                .and_then(|function| function.strip_suffix("%%"))
                .unwrap_or(name);
            !name.is_empty()
                && !name.starts_with(|c: char| c.is_ascii_digit())
                && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
        });
        match (assignment, vars.last_mut()) {
            (Some((name, value)), _) => vars.push((name.to_owned(), value.to_owned())),
            (None, Some((_, value))) => {
                value.push('\n');
                value.push_str(line);
            }
            (None, None) => {}
        }
    }
    vars.retain(|(name, _)| !name.starts_with("BASH_FUNC_"));
    vars
}

/// The user's login-shell `PATH`, when the shell environment was read.
fn login_shell_path() -> Option<&'static str> {
    login_shell_env()
        .iter()
        .rev()
        .find(|(name, _)| name == "PATH")
        .map(|(_, path)| path.as_str())
        .filter(|path| !path.is_empty())
}

/// The `PATH` macrod runs with: login shell first, then this process's own,
/// then well-known install locations, deduplicated in order.
fn macrod_path_env() -> String {
    let mut directories: Vec<String> = Vec::new();
    let mut push = |value: &str| {
        for directory in std::env::split_paths(value) {
            let directory = directory.to_string_lossy().into_owned();
            if !directory.is_empty() && !directories.contains(&directory) {
                directories.push(directory);
            }
        }
    };
    if let Some(path) = login_shell_path() {
        push(path);
    }
    if let Ok(path) = std::env::var("PATH") {
        push(&path);
    }
    if let Ok(home) = std::env::var("HOME") {
        for suffix in [".local/bin", ".bun/bin", ".volta/bin", ".cargo/bin"] {
            push(&format!("{home}/{suffix}"));
        }
    }
    for directory in ["/opt/homebrew/bin", "/usr/local/bin"] {
        push(directory);
    }
    directories.join(if cfg!(windows) { ";" } else { ":" })
}

/// Locate the macrod binary: an explicit override, the bundled copy next to
/// this executable, the resource directory, then the development `PATH`.
fn macrod_binary(app: &AppHandle) -> Option<PathBuf> {
    let name = if cfg!(windows) {
        "macrod.exe"
    } else {
        "macrod"
    };
    if let Ok(path) = std::env::var("MACROD_PATH") {
        let path = PathBuf::from(path);
        if path.is_file() {
            return Some(path);
        }
    }
    if let Some(path) = std::env::current_exe()
        .ok()
        .and_then(|exe| Some(exe.parent()?.join(name)))
        .filter(|path| path.is_file())
    {
        return Some(path);
    }
    if let Some(path) = app
        .path()
        .resource_dir()
        .ok()
        .map(|resources| resources.join(name))
        .filter(|path| path.is_file())
    {
        return Some(path);
    }
    std::env::split_paths(&macrod_path_env())
        .map(|directory| directory.join(name))
        .find(|path| path.is_file())
}

fn macrod_command(app: &AppHandle) -> Result<tokio::process::Command, String> {
    let binary =
        macrod_binary(app).ok_or_else(|| "macrod is not bundled with this build".to_owned())?;
    let mut command = tokio::process::Command::new(binary);
    command.envs(
        login_shell_env()
            .iter()
            .filter(|(name, _)| !SHELL_ONLY_VARS.contains(&name.as_str()))
            .map(|(name, value)| (name.as_str(), value.as_str())),
    );
    command.env("PATH", macrod_path_env());
    if crate::AppEnvironment::current() == crate::AppEnvironment::Development {
        // A config created by this daemon must target the dev deployment,
        // like the webview it pairs with.
        command.env("DEV_MODE", "1");
    }
    #[cfg(windows)]
    {
        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
        command.creation_flags(CREATE_NO_WINDOW);
    }
    Ok(command)
}

/// Run a one-shot macrod query and parse its stdout as JSON.
async fn macrod_query(app: &AppHandle, args: &[&str]) -> Result<serde_json::Value, String> {
    let output = macrod_command(app)?
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true)
        .output()
        .await
        .map_err(|error| format!("could not run macrod: {error}"))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!(
            "macrod {} failed: {}",
            args.join(" "),
            stderr.trim().lines().last().unwrap_or("no output")
        ));
    }
    serde_json::from_slice(&output.stdout)
        .map_err(|error| format!("macrod {} returned invalid JSON: {error}", args.join(" ")))
}

/// Whether this build can run a local agent runtime, and the daemon facts the
/// setup flow pre-fills from.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct MacrodSupport {
    /// Whether the bundled daemon exists on this platform and build.
    supported: bool,
    /// Suggested workspace directory for a first-time setup.
    default_workspace: Option<String>,
}

#[tauri::command]
pub(crate) fn macrod_support(app: AppHandle) -> MacrodSupport {
    let supported = macrod_binary(&app).is_some();
    let default_workspace = app
        .path()
        .home_dir()
        .ok()
        .map(|home| home.join("Macro").to_string_lossy().into_owned());
    MacrodSupport {
        supported,
        default_workspace,
    }
}

/// The ACP agents installed on this machine, from `macrod detect-agents`.
#[tauri::command]
pub(crate) async fn macrod_detect_agents(app: AppHandle) -> Result<serde_json::Value, String> {
    macrod_query(&app, &["detect-agents"]).await
}

/// The service config's state, from `macrod inspect`.
#[tauri::command]
pub(crate) async fn macrod_inspect(app: AppHandle) -> Result<serde_json::Value, String> {
    macrod_query(&app, &["inspect"]).await
}

/// Setup choices for a first-time (or re-) configuration. All optional: a
/// plain restart of an already configured daemon passes none of them. The
/// runtime's name, ownership, and permission bypass are set on the web, not
/// here; fields an older web bundle still sends are ignored.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct MacrodStartOptions {
    agent: Option<String>,
    workspace: Option<String>,
}

/// Start (or restart) the supervised daemon and remember to auto-start it on
/// the next app launch.
#[tauri::command]
pub(crate) async fn macrod_start(
    app: AppHandle,
    state: tauri::State<'_, MacrodState>,
    options: MacrodStartOptions,
) -> Result<MacrodStatus, String> {
    stop_child(&state.inner).await;
    {
        let mut inner = state.inner.lock().expect("macrod state lock");
        inner.wanted = true;
        inner.restarts = 0;
    }
    set_autostart(&app, true);
    let status =
        launch(&app, &state.inner, &options, None)?.expect("an unconditional launch always spawns");
    emit_status(&app, &status);
    Ok(status)
}

/// Spawn `macrod service` and attach its readers. With `resume`, this is a
/// supervisor restart after that generation exited: it spawns nothing
/// (returns `None`) when a start or stop has happened since.
fn launch(
    app: &AppHandle,
    state: &Arc<Mutex<Inner>>,
    options: &MacrodStartOptions,
    resume: Option<u64>,
) -> Result<Option<MacrodStatus>, String> {
    let mut command = macrod_command(app)?;
    command.arg("service");
    if let Some(agent) = &options.agent {
        command.args(["--agent", agent]);
    }
    if let Some(workspace) = &options.workspace {
        command.args(["--workspace", workspace]);
    }
    command
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true);

    // Spawn under the lock so a concurrent start or stop cannot interleave
    // with a supervisor restart.
    let mut inner = state.lock().expect("macrod state lock");
    if resume.is_some_and(|generation| inner.generation != generation || !inner.wanted) {
        return Ok(None);
    }
    let mut child = command
        .spawn()
        .map_err(|error| format!("could not start macrod: {error}"))?;
    let stdout = child
        .stdout
        .take()
        .ok_or_else(|| "macrod started without stdout".to_owned())?;
    if let Some(stderr) = child.stderr.take() {
        tauri::async_runtime::spawn(async move {
            let mut lines = tokio::io::BufReader::new(stderr).lines();
            while let Ok(Some(line)) = lines.next_line().await {
                tracing::debug!(target: "macrod", "{line}");
            }
        });
    }
    inner.child = Some(child);
    inner.generation += 1;
    inner.status = MacrodStatus {
        phase: MacrodPhase::Starting,
        ..MacrodStatus::default()
    };
    tauri::async_runtime::spawn(read_events(
        app.clone(),
        state.clone(),
        inner.generation,
        stdout,
    ));
    Ok(Some(inner.status.clone()))
}

/// Restart the daemon once the backoff for this failure elapses, unless a
/// start or stop superseded `generation` meanwhile. A spawn failure counts as
/// another failure and schedules the next attempt.
fn schedule_restart(app: AppHandle, state: Arc<Mutex<Inner>>, generation: u64) {
    let attempt = {
        let mut inner = state.lock().expect("macrod state lock");
        inner.restarts += 1;
        inner.restarts
    };
    let delay = restart_delay(attempt);
    tracing::warn!(target: "macrod", attempt, ?delay, "macrod exited unexpectedly; restarting");
    tauri::async_runtime::spawn(async move {
        tokio::time::sleep(delay).await;
        match launch(
            &app,
            &state,
            &MacrodStartOptions::default(),
            Some(generation),
        ) {
            Ok(Some(status)) => emit_status(&app, &status),
            Ok(None) => {}
            Err(error) => {
                tracing::warn!(target: "macrod", "macrod restart failed: {error}");
                let status = {
                    let mut inner = state.lock().expect("macrod state lock");
                    if inner.generation != generation || !inner.wanted {
                        return;
                    }
                    inner.status.phase = MacrodPhase::Error;
                    inner.status.last_error = Some(error);
                    inner.status.clone()
                };
                emit_status(&app, &status);
                schedule_restart(app, state, generation);
            }
        }
    });
}

/// Fold the service's stdout into the snapshot until it closes.
async fn read_events(
    app: AppHandle,
    inner: Arc<Mutex<Inner>>,
    generation: u64,
    stdout: tokio::process::ChildStdout,
) {
    let mut lines = tokio::io::BufReader::new(stdout).lines();
    while let Ok(Some(line)) = lines.next_line().await {
        let Ok(event) = serde_json::from_str::<serde_json::Value>(&line) else {
            tracing::warn!(target: "macrod", "unparseable service event: {line}");
            continue;
        };
        let status = {
            let mut inner = inner.lock().expect("macrod state lock");
            if inner.generation != generation {
                return;
            }
            inner.status.apply(&event);
            if inner.status.phase == MacrodPhase::Running {
                inner.restarts = 0;
            }
            inner.status.clone()
        };
        emit_status(&app, &status);
    }
    // stdout closed: the daemon exited. Keep an error phase so the user sees
    // why; otherwise show it as starting again, or stopped when unwanted.
    let (status, restart) = {
        let mut inner = inner.lock().expect("macrod state lock");
        if inner.generation != generation {
            return;
        }
        inner.child = None;
        if inner.status.phase != MacrodPhase::Error {
            inner.status.phase = if inner.wanted {
                MacrodPhase::Starting
            } else {
                MacrodPhase::Stopped
            };
        }
        (inner.status.clone(), inner.wanted)
    };
    emit_status(&app, &status);
    if restart {
        schedule_restart(app, inner, generation);
    }
}

/// Stop the supervised daemon and stop auto-starting it.
#[tauri::command]
pub(crate) async fn macrod_stop(
    app: AppHandle,
    state: tauri::State<'_, MacrodState>,
) -> Result<MacrodStatus, String> {
    set_autostart(&app, false);
    state.inner.lock().expect("macrod state lock").wanted = false;
    stop_child(&state.inner).await;
    let status = {
        let mut inner = state.inner.lock().expect("macrod state lock");
        inner.status = MacrodStatus::default();
        inner.status.clone()
    };
    emit_status(&app, &status);
    Ok(status)
}

/// The current snapshot, for a webview that (re)mounted after events fired.
#[tauri::command]
pub(crate) fn macrod_status(state: tauri::State<'_, MacrodState>) -> MacrodStatus {
    state
        .inner
        .lock()
        .expect("macrod state lock")
        .status
        .clone()
}

/// Kill the child synchronously; the app is exiting and cannot await.
pub(crate) fn kill_now(state: &MacrodState) {
    let child = {
        let mut inner = state.inner.lock().expect("macrod state lock");
        inner.wanted = false;
        inner.generation += 1;
        inner.child.take()
    };
    if let Some(mut child) = child {
        let _ = child.start_kill();
    }
}

/// Kill the child, invalidating any reader still attached to it.
async fn stop_child(inner: &Arc<Mutex<Inner>>) {
    let child = {
        let mut inner = inner.lock().expect("macrod state lock");
        inner.generation += 1;
        inner.child.take()
    };
    if let Some(mut child) = child {
        // Closing stdin asks the service to shut down on its own; the kill is
        // the backstop for a wedged process.
        child.stdin.take();
        match tokio::time::timeout(std::time::Duration::from_secs(3), child.wait()).await {
            Ok(_) => {}
            Err(_) => {
                let _ = child.start_kill();
                let _ = child.wait().await;
            }
        }
    }
}

/// Where the auto-start marker lives: a tiny JSON file in the app's config
/// directory, read before the webview exists.
fn autostart_marker(app: &AppHandle) -> Option<PathBuf> {
    app.path()
        .app_config_dir()
        .ok()
        .map(|directory| directory.join("macrod.json"))
}

#[derive(Debug, Default, Serialize, Deserialize)]
struct AutostartMarker {
    autostart: bool,
}

fn set_autostart(app: &AppHandle, autostart: bool) {
    let Some(path) = autostart_marker(app) else {
        return;
    };
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let marker = AutostartMarker { autostart };
    if let Err(error) = std::fs::write(
        &path,
        serde_json::to_vec(&marker).expect("marker is plain data"),
    ) {
        tracing::warn!(?error, "failed to persist macrod autostart marker");
    }
}

/// Whether the user explicitly stopped the daemon. Only a stop opts out of
/// auto-start; a missing or unreadable marker does not.
fn stopped_by_user(app: &AppHandle) -> bool {
    autostart_marker(app)
        .and_then(|path| std::fs::read(path).ok())
        .and_then(|raw| serde_json::from_slice::<AutostartMarker>(&raw).ok())
        .is_some_and(|marker| !marker.autostart)
}

/// At app launch: resume the daemon whenever a config exists and the user has
/// not stopped it, so agents are reachable without opening settings. A config
/// whose credential lapsed re-pairs, and the webview approves the new code.
pub(crate) fn autostart(app: &AppHandle) {
    let app = app.clone();
    tauri::async_runtime::spawn(async move {
        if stopped_by_user(&app) || macrod_binary(&app).is_none() {
            return;
        }
        let configured = match macrod_query(&app, &["inspect"]).await {
            Ok(inspection) => inspection
                .get("exists")
                .and_then(serde_json::Value::as_bool)
                .unwrap_or(false),
            Err(error) => {
                tracing::warn!(target: "macrod", "autostart inspect failed: {error}");
                false
            }
        };
        if !configured {
            return;
        }
        let state = app.state::<MacrodState>();
        if let Err(error) = macrod_start(app.clone(), state, MacrodStartOptions::default()).await {
            tracing::warn!(target: "macrod", "autostart failed: {error}");
        }
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn restart_delay_doubles_up_to_the_cap() {
        let seconds: Vec<u64> = (1..=9).map(|n| restart_delay(n).as_secs()).collect();
        assert_eq!(seconds, [1, 2, 4, 8, 16, 32, 60, 60, 60]);
        assert_eq!(restart_delay(u32::MAX), RESTART_MAX_DELAY);
    }

    #[test]
    fn shell_env_skips_banners_and_keeps_multiline_values() {
        let output = format!(
            "Welcome! PATH=/banner\n{ENV_START}\nPATH=/usr/bin:/bin\n\
             CLAUDE_CODE_OAUTH_TOKEN=token\nNOTE=line one\nline two\n\
             BASH_FUNC_greet%%=() {{  echo hi\n}}\nEMPTY=\n{ENV_END}\nbye\n"
        );
        assert_eq!(
            parse_shell_env(&output),
            [
                ("PATH".to_owned(), "/usr/bin:/bin".to_owned()),
                ("CLAUDE_CODE_OAUTH_TOKEN".to_owned(), "token".to_owned()),
                ("NOTE".to_owned(), "line one\nline two".to_owned()),
                ("EMPTY".to_owned(), String::new()),
            ]
        );
    }

    #[test]
    fn shell_env_without_markers_is_empty() {
        assert!(parse_shell_env("PATH=/usr/bin\n").is_empty());
    }
}