eclipse-cli 0.13.4

Command-line interface for eclipse
//! `/bg`: start a run that outlives the prompt, and the process that does the work.
//!
//! The registry itself — the file format, the pid rule, what a row says — is
//! [`eclipse_core::tasks`]. What lives here is the one thing the CLI can do and the core cannot:
//! spawn a second `eclipse`, with the same config, profile and tool policy as the prompt it was
//! started at, detached from this terminal so a `Ctrl-C` here does not kill it.
//!
//! Three properties are load-bearing:
//!
//! - **Detached, not backgrounded.** `setsid` puts the child in its own session with no
//!   controlling terminal, so the shell's `SIGINT`, a closed window and a `Ctrl-C` at the composer
//!   all leave it alone. A run that dies with the prompt it was launched from is not a run that
//!   outlives the prompt.
//! - **Its own session id, chosen here.** The parent picks the id and tells the child to use it
//!   (`-s <id> --task <id>`), so the answer `/bg` prints is the id `/tasks` will show, and the
//!   registry has a row before the child has finished starting.
//! - **Inherited exactly.** Config path, profile, route, model, `--yes` and `--no-mcp` are passed
//!   through as flags rather than left to the environment, because "same workspace, same policy" is
//!   the promise `/bg` makes.

use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use eclipse_core::session::SessionStore;
use eclipse_core::tasks::{Registry, Task};

/// Everything a background run inherits from the prompt it was started at.
#[derive(Debug, Clone)]
pub struct Spawner {
    /// The binary to run. `current_exe` in practice: the same build answers.
    pub exe: PathBuf,
    pub config: Option<PathBuf>,
    pub profile: Option<String>,
    pub route: Option<String>,
    /// The `--model` this session was started with. A front end that can switch models passes
    /// the one in use instead; this is the fallback for a front end that cannot.
    pub model: Option<String>,
    pub no_mcp: bool,
    /// The composer's `/yolo` switch, read when a task is spawned rather than when the session
    /// started: a background task inherits the mode of the session that typed `/bg`, including a
    /// `/yolo off` typed since. Passed down as `--yes`, because a background run has nobody to
    /// ask, so an unanswered gate parks it.
    pub yes: crate::yolo::Yolo,
    pub registry: Registry,
    pub sessions: PathBuf,
}

impl Spawner {
    /// Start `prompt` in a detached run and return the session id it will use.
    ///
    /// The id is chosen before the spawn so it can be printed, and the registry entry is written
    /// by the parent: a task that is invisible for its first hundred milliseconds is one somebody
    /// will ask about twice.
    pub fn spawn(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<String> {
        let prompt = prompt.trim();
        if prompt.is_empty() {
            anyhow::bail!("`/bg` needs a prompt: `/bg <what to do>`");
        }
        let id = SessionStore::new(self.sessions.clone()).new_id();
        std::fs::create_dir_all(self.registry.dir()).map_err(|e| {
            anyhow::anyhow!(
                "cannot create {} ({e}): `/bg` needs somewhere to write what it started",
                self.registry.dir().display()
            )
        })?;
        // The child's own stdout and stderr, beside its registry entry. A detached process whose
        // failure only ever existed on a terminal that is gone is a failure nobody can read.
        let log = std::fs::File::create(self.registry.log_path(&id)).map_err(|e| {
            anyhow::anyhow!(
                "cannot write {} ({e})",
                self.registry.log_path(&id).display()
            )
        })?;
        let mut cmd = Command::new(&self.exe);
        if let Some(path) = &self.config {
            cmd.arg("--config").arg(path);
        }
        if let Some(profile) = &self.profile {
            cmd.arg("--profile").arg(profile);
        }
        if let Some(route) = &self.route {
            cmd.arg("--route").arg(route);
        }
        if self.no_mcp {
            cmd.arg("--no-mcp");
        }
        if self.yes.on() {
            cmd.arg("--yes");
        }
        let model = model.or(self.model.as_deref());
        if let Some(model) = model.map(str::trim).filter(|m| !m.is_empty()) {
            cmd.arg("--model").arg(model);
        }
        // `--` before the prompt: a question that begins with a dash is a question, not a flag.
        cmd.arg("run").arg("-s").arg(&id);
        // What makes this child a task rather than an orphan: it announces itself in the registry
        // and writes how it ended.
        cmd.arg("--task").arg(&id);
        cmd.arg("--").arg(prompt);
        cmd.stdin(Stdio::null())
            .stdout(Stdio::from(log.try_clone()?))
            .stderr(Stdio::from(log));
        detach(&mut cmd);
        let mut child = cmd
            .spawn()
            .map_err(|e| anyhow::anyhow!("cannot start {} ({e})", self.exe.display()))?;
        let task = Task::spawned(&id, child.id(), prompt);
        if let Err(e) = self.registry.write(&task) {
            // No registry entry means no `/tasks` row and no honest state for a process that is
            // already running: stop it rather than leave a run nobody can find.
            let _ = child.kill();
            let _ = child.wait();
            return Err(anyhow::anyhow!(
                "the task was started but could not be registered ({}); it was stopped",
                e
            ));
        }
        Ok(id)
    }
}

/// Put the child in its own session, with no controlling terminal.
#[cfg(unix)]
fn detach(cmd: &mut Command) {
    use std::os::unix::process::CommandExt;
    // SAFETY: `setsid` touches nothing but the child, has no preconditions, and runs between
    // fork and exec where no other thread of ours can observe it.
    unsafe {
        cmd.pre_exec(|| {
            if libc::setsid() == -1 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(())
        });
    }
}

#[cfg(not(unix))]
fn detach(_cmd: &mut Command) {}

/// Where the running binary is: the same build, from the same place, so a `/bg` inherits a
/// version rather than a `PATH` entry.
pub fn this_binary() -> PathBuf {
    std::env::current_exe().unwrap_or_else(|_| PathBuf::from("eclipse"))
}

/// A task chosen from a list by the word someone typed: a number from 1, a full id, or a prefix
/// of one. `None` means nothing matched, which the caller says out loud.
///
/// A number that names a row *is* a row; anything else — including a number too large for the
/// list, which is what a session id beginning with digits looks like — is matched as an id.
pub fn choose(tasks: &[Task], word: &str) -> Option<Task> {
    let word = word.trim();
    if word.is_empty() {
        return None;
    }
    if let Some(row) = word
        .parse::<usize>()
        .ok()
        .and_then(|n| n.checked_sub(1))
        .and_then(|i| tasks.get(i))
    {
        return Some(row.clone());
    }
    let exact = tasks.iter().find(|t| t.session == word);
    if exact.is_some() {
        return exact.cloned();
    }
    let mut hits = tasks.iter().filter(|t| t.session.starts_with(word));
    let first = hits.next()?;
    // An ambiguous prefix is not a choice: two tasks that start alike must not be guessed between.
    if hits.next().is_some() {
        return None;
    }
    Some(first.clone())
}

/// A run that is a task: the entry it keeps up to date, and the handle a signal reaches.
///
/// `--task <id>` is the whole of "this process is a background run". It is set by `/bg`, which
/// chose the id and printed it, so the child does not have to invent one or announce itself.
pub struct TaskRun {
    pub tracker: eclipse_core::tasks::Tracker,
    /// Shared with the run loop: `SIGTERM` cancels this, and the loop stops at its next boundary
    /// exactly as it would after `^C`.
    pub cancel: eclipse_core::cancel::Cancel,
}

impl TaskRun {
    /// Announce the run in the registry, and hand back what keeps it honest.
    ///
    /// A registry that cannot be written does not stop the run: the entry is how the run is
    /// *found*, and a run that works but cannot be listed is better than a run that refused to
    /// start. The parent has already written a `starting` row for the same id.
    pub fn begin(state_dir: &Path, id: &str, prompt: &str) -> anyhow::Result<TaskRun> {
        eclipse_core::session::validate_id(id)
            .map_err(|e| anyhow::anyhow!("`--task` needs a session id: {e}"))?;
        let registry = Registry::new(state_dir);
        let run = TaskRun {
            tracker: eclipse_core::tasks::Tracker::new(registry.clone(), id),
            cancel: eclipse_core::cancel::Cancel::new(),
        };
        // Before the entry says `running`: a `kill` that arrives while `/tasks` already shows the
        // task has to be caught, or the row would sit at `running` behind a process that is gone.
        run.follow_signals();
        let _ = registry.write(&Task::begun(id, prompt));
        Ok(run)
    }

    /// Stop when this process is asked to stop.
    ///
    /// A detached run has no terminal, so `SIGINT` is not the signal it gets: `kill` sends
    /// `SIGTERM`. Cancelling rather than exiting immediately is what keeps the session's record —
    /// what was written stays written, and the entry says `stopped` instead of vanishing.
    #[cfg(unix)]
    pub fn follow_signals(&self) {
        use tokio::signal::unix::{signal, SignalKind};
        // `#432`: `tokio::spawn` does not promise the handler exists when this returns — the future
        // is polled later, so a `kill` landing in that window takes the default action and kills the
        // run outright, leaving the entry at `running` behind a dead pid. `signal()` registers the
        // handler eagerly (`signal_enable` before it returns), so the install goes here and only the
        // wait is spawned.
        let Ok(mut term) = signal(SignalKind::terminate()) else {
            return;
        };
        let cancel = self.cancel.clone();
        tokio::spawn(async move {
            term.recv().await;
            cancel.cancel();
        });
    }

    #[cfg(not(unix))]
    pub fn follow_signals(&self) {}
}

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

    fn task(id: &str) -> Task {
        let mut t = Task::spawned(id, std::process::id(), "a question");
        t.state = State::Done;
        t
    }

    #[test]
    fn a_number_a_full_id_and_an_unambiguous_prefix_all_choose_the_same_row() {
        let tasks = vec![task("100-1-0"), task("200-2-0")];
        assert_eq!(
            choose(&tasks, "2").map(|t| t.session),
            Some("200-2-0".into())
        );
        assert_eq!(
            choose(&tasks, "100-1-0").map(|t| t.session),
            Some("100-1-0".into())
        );
        assert_eq!(
            choose(&tasks, "200").map(|t| t.session),
            Some("200-2-0".into())
        );
        assert_eq!(choose(&tasks, "0"), None, "counting starts at one");
        assert_eq!(choose(&tasks, "3"), None);
        // A number too big for the list is not a row: it is matched as an id, which is what a
        // session id starting with digits looks like.
        assert_eq!(
            choose(&tasks, "200-2").map(|t| t.session),
            Some("200-2-0".into())
        );
        assert_eq!(choose(&tasks, "9"), None);
        assert_eq!(choose(&tasks, ""), None);
        // Two rows that begin alike are not guessed between.
        assert_eq!(choose(&[task("1-1-0"), task("1-2-0")], "1-"), None);
    }

    #[test]
    fn an_empty_prompt_is_refused_before_anything_is_spawned() {
        let dir = tempfile::tempdir().unwrap();
        let spawner = Spawner {
            exe: PathBuf::from("/nonexistent/eclipse"),
            config: None,
            profile: None,
            route: None,
            model: None,
            no_mcp: false,
            yes: crate::yolo::Yolo::new(false),
            registry: Registry::new(dir.path()),
            sessions: dir.path().join("sessions"),
        };
        let err = spawner.spawn("   ", None).unwrap_err().to_string();
        assert!(err.contains("/bg"), "{err}");
        assert!(err.contains("needs a prompt"), "{err}");
        assert!(
            spawner.registry.list().is_empty(),
            "nothing was started, so nothing was registered"
        );
    }

    /// A spawn whose binary does not exist fails as a sentence, not as a panic, and leaves no
    /// registry entry behind.
    #[test]
    fn a_spawn_that_cannot_start_says_so_and_registers_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let spawner = Spawner {
            exe: PathBuf::from("/nonexistent/eclipse"),
            config: None,
            profile: None,
            route: None,
            model: None,
            no_mcp: false,
            yes: crate::yolo::Yolo::new(false),
            registry: Registry::new(dir.path()),
            sessions: dir.path().join("sessions"),
        };
        let err = spawner.spawn("do the thing", None).unwrap_err().to_string();
        assert!(err.contains("cannot start"), "{err}");
        assert!(spawner.registry.list().is_empty(), "{err}");
    }
}