codex.rs

  1use std::rc::Rc;
  2use std::sync::Arc;
  3use std::{any::Any, path::Path};
  4
  5use acp_thread::AgentConnection;
  6use agent_client_protocol as acp;
  7use anyhow::{Context as _, Result};
  8use collections::HashSet;
  9use fs::Fs;
 10use gpui::{App, AppContext as _, SharedString, Task};
 11use project::agent_server_store::{AllAgentServersSettings, CODEX_NAME};
 12use settings::{SettingsStore, update_settings_file};
 13
 14use crate::{AgentServer, AgentServerDelegate, load_proxy_env};
 15
 16#[derive(Clone)]
 17pub struct Codex;
 18
 19#[cfg(test)]
 20pub(crate) mod tests {
 21    use super::*;
 22
 23    crate::common_e2e_tests!(async |_, _, _| Codex, allow_option_id = "proceed_once");
 24}
 25
 26impl AgentServer for Codex {
 27    fn name(&self) -> SharedString {
 28        "Codex".into()
 29    }
 30
 31    fn logo(&self) -> ui::IconName {
 32        ui::IconName::AiOpenAi
 33    }
 34
 35    fn default_mode(&self, cx: &mut App) -> Option<acp::SessionModeId> {
 36        let settings = cx.read_global(|settings: &SettingsStore, _| {
 37            settings.get::<AllAgentServersSettings>(None).codex.clone()
 38        });
 39
 40        settings
 41            .as_ref()
 42            .and_then(|s| s.default_mode.clone().map(acp::SessionModeId::new))
 43    }
 44
 45    fn set_default_mode(&self, mode_id: Option<acp::SessionModeId>, fs: Arc<dyn Fs>, cx: &mut App) {
 46        update_settings_file(fs, cx, |settings, _| {
 47            settings
 48                .agent_servers
 49                .get_or_insert_default()
 50                .codex
 51                .get_or_insert_default()
 52                .default_mode = mode_id.map(|m| m.to_string())
 53        });
 54    }
 55
 56    fn default_model(&self, cx: &mut App) -> Option<acp::ModelId> {
 57        let settings = cx.read_global(|settings: &SettingsStore, _| {
 58            settings.get::<AllAgentServersSettings>(None).codex.clone()
 59        });
 60
 61        settings
 62            .as_ref()
 63            .and_then(|s| s.default_model.clone().map(acp::ModelId::new))
 64    }
 65
 66    fn set_default_model(&self, model_id: Option<acp::ModelId>, fs: Arc<dyn Fs>, cx: &mut App) {
 67        update_settings_file(fs, cx, |settings, _| {
 68            settings
 69                .agent_servers
 70                .get_or_insert_default()
 71                .codex
 72                .get_or_insert_default()
 73                .default_model = model_id.map(|m| m.to_string())
 74        });
 75    }
 76
 77    fn favorite_model_ids(&self, cx: &mut App) -> HashSet<acp::ModelId> {
 78        let settings = cx.read_global(|settings: &SettingsStore, _| {
 79            settings.get::<AllAgentServersSettings>(None).codex.clone()
 80        });
 81
 82        settings
 83            .as_ref()
 84            .map(|s| {
 85                s.favorite_models
 86                    .iter()
 87                    .map(|id| acp::ModelId::new(id.clone()))
 88                    .collect()
 89            })
 90            .unwrap_or_default()
 91    }
 92
 93    fn toggle_favorite_model(
 94        &self,
 95        model_id: acp::ModelId,
 96        should_be_favorite: bool,
 97        fs: Arc<dyn Fs>,
 98        cx: &App,
 99    ) {
100        update_settings_file(fs, cx, move |settings, _| {
101            let favorite_models = &mut settings
102                .agent_servers
103                .get_or_insert_default()
104                .codex
105                .get_or_insert_default()
106                .favorite_models;
107
108            let model_id_str = model_id.to_string();
109            if should_be_favorite {
110                if !favorite_models.contains(&model_id_str) {
111                    favorite_models.push(model_id_str);
112                }
113            } else {
114                favorite_models.retain(|id| id != &model_id_str);
115            }
116        });
117    }
118
119    fn connect(
120        &self,
121        root_dir: Option<&Path>,
122        delegate: AgentServerDelegate,
123        cx: &mut App,
124    ) -> Task<Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
125        let name = self.name();
126        let root_dir = root_dir.map(|root_dir| root_dir.to_string_lossy().into_owned());
127        let is_remote = delegate.project.read(cx).is_via_remote_server();
128        let store = delegate.store.downgrade();
129        let extra_env = load_proxy_env(cx);
130        let default_mode = self.default_mode(cx);
131        let default_model = self.default_model(cx);
132
133        cx.spawn(async move |cx| {
134            let (command, root_dir, login) = store
135                .update(cx, |store, cx| {
136                    let agent = store
137                        .get_external_agent(&CODEX_NAME.into())
138                        .context("Codex is not registered")?;
139                    anyhow::Ok(agent.get_command(
140                        root_dir.as_deref(),
141                        extra_env,
142                        delegate.status_tx,
143                        delegate.new_version_available,
144                        &mut cx.to_async(),
145                    ))
146                })??
147                .await?;
148
149            let connection = crate::acp::connect(
150                name,
151                command,
152                root_dir.as_ref(),
153                default_mode,
154                default_model,
155                is_remote,
156                cx,
157            )
158            .await?;
159            Ok((connection, login))
160        })
161    }
162
163    fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
164        self
165    }
166}