Skip to main content

visdom_cli/
launch.rs

1//! Handing the terminal over to the agent.
2
3use std::path::Path;
4use std::process::Command;
5
6use tracevault_cli::agent::Agent;
7
8use crate::config::agent_config_key;
9
10/// What to tell the user when the agent's executable cannot be started.
11pub fn launch_error_message(
12    program: &str,
13    error: &std::io::Error,
14    agent: Agent,
15    user_config: &Path,
16) -> String {
17    format!(
18        "visdom: cannot start {program}: {error} (set agents.{} in {} to use another executable)",
19        agent_config_key(agent),
20        user_config.display()
21    )
22}
23
24/// Replace this process with the agent, so the terminal, signals and exit
25/// code are the agent's. Returns only by exiting: 127 when the executable
26/// cannot be started.
27pub fn exec_agent(mut cmd: Command, agent: Agent, user_config: &Path) -> ! {
28    let program = cmd.get_program().to_string_lossy().into_owned();
29    let error = replace_process(&mut cmd);
30    eprintln!(
31        "{}",
32        launch_error_message(&program, &error, agent, user_config)
33    );
34    std::process::exit(127)
35}
36
37#[cfg(unix)]
38fn replace_process(cmd: &mut Command) -> std::io::Error {
39    use std::os::unix::process::CommandExt;
40    cmd.exec()
41}
42
43/// Without `exec`: run the agent as a child and exit with its status.
44#[cfg(not(unix))]
45fn replace_process(cmd: &mut Command) -> std::io::Error {
46    match cmd.status() {
47        Ok(status) => std::process::exit(status.code().unwrap_or(1)),
48        Err(e) => e,
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn launch_error_names_the_program_and_the_config_key() {
58        let error = std::io::Error::new(std::io::ErrorKind::NotFound, "No such file");
59        let message = launch_error_message(
60            "claude",
61            &error,
62            Agent::ClaudeCode,
63            Path::new("/home/u/.config/visdom/config.toml"),
64        );
65        assert!(
66            message.contains("cannot start claude: No such file"),
67            "{message}"
68        );
69        assert!(message.contains("agents.claude_code"), "{message}");
70        assert!(
71            message.contains("/home/u/.config/visdom/config.toml"),
72            "{message}"
73        );
74        let message = launch_error_message("codex", &error, Agent::Codex, Path::new("/c"));
75        assert!(message.contains("agents.codex"), "{message}");
76    }
77}