agent.rs

   1mod db;
   2mod edit_agent;
   3mod history_store;
   4mod legacy_thread;
   5mod native_agent_server;
   6pub mod outline;
   7mod templates;
   8#[cfg(test)]
   9mod tests;
  10mod thread;
  11mod tools;
  12
  13use context_server::ContextServerId;
  14pub use db::*;
  15pub use history_store::*;
  16pub use native_agent_server::NativeAgentServer;
  17pub use templates::*;
  18pub use thread::*;
  19pub use tools::*;
  20
  21use acp_thread::{AcpThread, AgentModelSelector, UserMessageId};
  22use agent_client_protocol as acp;
  23use anyhow::{Context as _, Result, anyhow};
  24use chrono::{DateTime, Utc};
  25use collections::{HashMap, HashSet, IndexMap};
  26use fs::Fs;
  27use futures::channel::{mpsc, oneshot};
  28use futures::future::Shared;
  29use futures::{StreamExt, future};
  30use gpui::{
  31    App, AppContext, AsyncApp, Context, Entity, SharedString, Subscription, Task, WeakEntity,
  32};
  33use language_model::{IconOrSvg, LanguageModel, LanguageModelProvider, LanguageModelRegistry};
  34use project::{Project, ProjectItem, ProjectPath, Worktree};
  35use prompt_store::{
  36    ProjectContext, PromptStore, RULES_FILE_NAMES, RulesFileContext, UserRulesContext,
  37    WorktreeContext,
  38};
  39use serde::{Deserialize, Serialize};
  40use settings::{LanguageModelSelection, update_settings_file};
  41use std::any::Any;
  42use std::path::{Path, PathBuf};
  43use std::rc::Rc;
  44use std::sync::Arc;
  45use util::ResultExt;
  46use util::rel_path::RelPath;
  47
  48#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  49pub struct ProjectSnapshot {
  50    pub worktree_snapshots: Vec<project::telemetry_snapshot::TelemetryWorktreeSnapshot>,
  51    pub timestamp: DateTime<Utc>,
  52}
  53
  54pub struct RulesLoadingError {
  55    pub message: SharedString,
  56}
  57
  58/// Holds both the internal Thread and the AcpThread for a session
  59struct Session {
  60    /// The internal thread that processes messages
  61    thread: Entity<Thread>,
  62    /// The ACP thread that handles protocol communication
  63    acp_thread: WeakEntity<acp_thread::AcpThread>,
  64    pending_save: Task<()>,
  65    _subscriptions: Vec<Subscription>,
  66}
  67
  68pub struct LanguageModels {
  69    /// Access language model by ID
  70    models: HashMap<acp::ModelId, Arc<dyn LanguageModel>>,
  71    /// Cached list for returning language model information
  72    model_list: acp_thread::AgentModelList,
  73    refresh_models_rx: watch::Receiver<()>,
  74    refresh_models_tx: watch::Sender<()>,
  75    _authenticate_all_providers_task: Task<()>,
  76}
  77
  78impl LanguageModels {
  79    fn new(cx: &mut App) -> Self {
  80        let (refresh_models_tx, refresh_models_rx) = watch::channel(());
  81
  82        let mut this = Self {
  83            models: HashMap::default(),
  84            model_list: acp_thread::AgentModelList::Grouped(IndexMap::default()),
  85            refresh_models_rx,
  86            refresh_models_tx,
  87            _authenticate_all_providers_task: Self::authenticate_all_language_model_providers(cx),
  88        };
  89        this.refresh_list(cx);
  90        this
  91    }
  92
  93    fn refresh_list(&mut self, cx: &App) {
  94        let providers = LanguageModelRegistry::global(cx)
  95            .read(cx)
  96            .visible_providers()
  97            .into_iter()
  98            .filter(|provider| provider.is_authenticated(cx))
  99            .collect::<Vec<_>>();
 100
 101        let mut language_model_list = IndexMap::default();
 102        let mut recommended_models = HashSet::default();
 103
 104        let mut recommended = Vec::new();
 105        for provider in &providers {
 106            for model in provider.recommended_models(cx) {
 107                recommended_models.insert((model.provider_id(), model.id()));
 108                recommended.push(Self::map_language_model_to_info(&model, provider));
 109            }
 110        }
 111        if !recommended.is_empty() {
 112            language_model_list.insert(
 113                acp_thread::AgentModelGroupName("Recommended".into()),
 114                recommended,
 115            );
 116        }
 117
 118        let mut models = HashMap::default();
 119        for provider in providers {
 120            let mut provider_models = Vec::new();
 121            for model in provider.provided_models(cx) {
 122                let model_info = Self::map_language_model_to_info(&model, &provider);
 123                let model_id = model_info.id.clone();
 124                provider_models.push(model_info);
 125                models.insert(model_id, model);
 126            }
 127            if !provider_models.is_empty() {
 128                language_model_list.insert(
 129                    acp_thread::AgentModelGroupName(provider.name().0.clone()),
 130                    provider_models,
 131                );
 132            }
 133        }
 134
 135        self.models = models;
 136        self.model_list = acp_thread::AgentModelList::Grouped(language_model_list);
 137        self.refresh_models_tx.send(()).ok();
 138    }
 139
 140    fn watch(&self) -> watch::Receiver<()> {
 141        self.refresh_models_rx.clone()
 142    }
 143
 144    pub fn model_from_id(&self, model_id: &acp::ModelId) -> Option<Arc<dyn LanguageModel>> {
 145        self.models.get(model_id).cloned()
 146    }
 147
 148    fn map_language_model_to_info(
 149        model: &Arc<dyn LanguageModel>,
 150        provider: &Arc<dyn LanguageModelProvider>,
 151    ) -> acp_thread::AgentModelInfo {
 152        acp_thread::AgentModelInfo {
 153            id: Self::model_id(model),
 154            name: model.name().0,
 155            description: None,
 156            icon: Some(match provider.icon() {
 157                IconOrSvg::Svg(path) => acp_thread::AgentModelIcon::Path(path),
 158                IconOrSvg::Icon(name) => acp_thread::AgentModelIcon::Named(name),
 159            }),
 160        }
 161    }
 162
 163    fn model_id(model: &Arc<dyn LanguageModel>) -> acp::ModelId {
 164        acp::ModelId::new(format!("{}/{}", model.provider_id().0, model.id().0))
 165    }
 166
 167    fn authenticate_all_language_model_providers(cx: &mut App) -> Task<()> {
 168        let authenticate_all_providers = LanguageModelRegistry::global(cx)
 169            .read(cx)
 170            .visible_providers()
 171            .iter()
 172            .map(|provider| (provider.id(), provider.name(), provider.authenticate(cx)))
 173            .collect::<Vec<_>>();
 174
 175        cx.background_spawn(async move {
 176            for (provider_id, provider_name, authenticate_task) in authenticate_all_providers {
 177                if let Err(err) = authenticate_task.await {
 178                    match err {
 179                        language_model::AuthenticateError::CredentialsNotFound => {
 180                            // Since we're authenticating these providers in the
 181                            // background for the purposes of populating the
 182                            // language selector, we don't care about providers
 183                            // where the credentials are not found.
 184                        }
 185                        language_model::AuthenticateError::ConnectionRefused => {
 186                            // Not logging connection refused errors as they are mostly from LM Studio's noisy auth failures.
 187                            // LM Studio only has one auth method (endpoint call) which fails for users who haven't enabled it.
 188                            // TODO: Better manage LM Studio auth logic to avoid these noisy failures.
 189                        }
 190                        _ => {
 191                            // Some providers have noisy failure states that we
 192                            // don't want to spam the logs with every time the
 193                            // language model selector is initialized.
 194                            //
 195                            // Ideally these should have more clear failure modes
 196                            // that we know are safe to ignore here, like what we do
 197                            // with `CredentialsNotFound` above.
 198                            match provider_id.0.as_ref() {
 199                                "lmstudio" | "ollama" => {
 200                                    // LM Studio and Ollama both make fetch requests to the local APIs to determine if they are "authenticated".
 201                                    //
 202                                    // These fail noisily, so we don't log them.
 203                                }
 204                                "copilot_chat" => {
 205                                    // Copilot Chat returns an error if Copilot is not enabled, so we don't log those errors.
 206                                }
 207                                _ => {
 208                                    log::error!(
 209                                        "Failed to authenticate provider: {}: {err:#}",
 210                                        provider_name.0
 211                                    );
 212                                }
 213                            }
 214                        }
 215                    }
 216                }
 217            }
 218        })
 219    }
 220}
 221
 222pub struct NativeAgent {
 223    /// Session ID -> Session mapping
 224    sessions: HashMap<acp::SessionId, Session>,
 225    history: Entity<HistoryStore>,
 226    /// Shared project context for all threads
 227    project_context: Entity<ProjectContext>,
 228    project_context_needs_refresh: watch::Sender<()>,
 229    _maintain_project_context: Task<Result<()>>,
 230    context_server_registry: Entity<ContextServerRegistry>,
 231    /// Shared templates for all threads
 232    templates: Arc<Templates>,
 233    /// Cached model information
 234    models: LanguageModels,
 235    project: Entity<Project>,
 236    prompt_store: Option<Entity<PromptStore>>,
 237    fs: Arc<dyn Fs>,
 238    _subscriptions: Vec<Subscription>,
 239}
 240
 241impl NativeAgent {
 242    pub async fn new(
 243        project: Entity<Project>,
 244        history: Entity<HistoryStore>,
 245        templates: Arc<Templates>,
 246        prompt_store: Option<Entity<PromptStore>>,
 247        fs: Arc<dyn Fs>,
 248        cx: &mut AsyncApp,
 249    ) -> Result<Entity<NativeAgent>> {
 250        log::debug!("Creating new NativeAgent");
 251
 252        let project_context = cx
 253            .update(|cx| Self::build_project_context(&project, prompt_store.as_ref(), cx))?
 254            .await;
 255
 256        cx.new(|cx| {
 257            let context_server_store = project.read(cx).context_server_store();
 258            let context_server_registry =
 259                cx.new(|cx| ContextServerRegistry::new(context_server_store.clone(), cx));
 260
 261            let mut subscriptions = vec![
 262                cx.subscribe(&project, Self::handle_project_event),
 263                cx.subscribe(
 264                    &LanguageModelRegistry::global(cx),
 265                    Self::handle_models_updated_event,
 266                ),
 267                cx.subscribe(
 268                    &context_server_store,
 269                    Self::handle_context_server_store_updated,
 270                ),
 271                cx.subscribe(
 272                    &context_server_registry,
 273                    Self::handle_context_server_registry_event,
 274                ),
 275            ];
 276            if let Some(prompt_store) = prompt_store.as_ref() {
 277                subscriptions.push(cx.subscribe(prompt_store, Self::handle_prompts_updated_event))
 278            }
 279
 280            let (project_context_needs_refresh_tx, project_context_needs_refresh_rx) =
 281                watch::channel(());
 282            Self {
 283                sessions: HashMap::default(),
 284                history,
 285                project_context: cx.new(|_| project_context),
 286                project_context_needs_refresh: project_context_needs_refresh_tx,
 287                _maintain_project_context: cx.spawn(async move |this, cx| {
 288                    Self::maintain_project_context(this, project_context_needs_refresh_rx, cx).await
 289                }),
 290                context_server_registry,
 291                templates,
 292                models: LanguageModels::new(cx),
 293                project,
 294                prompt_store,
 295                fs,
 296                _subscriptions: subscriptions,
 297            }
 298        })
 299    }
 300
 301    fn register_session(
 302        &mut self,
 303        thread_handle: Entity<Thread>,
 304        cx: &mut Context<Self>,
 305    ) -> Entity<AcpThread> {
 306        let connection = Rc::new(NativeAgentConnection(cx.entity()));
 307
 308        let thread = thread_handle.read(cx);
 309        let session_id = thread.id().clone();
 310        let title = thread.title();
 311        let project = thread.project.clone();
 312        let action_log = thread.action_log.clone();
 313        let prompt_capabilities_rx = thread.prompt_capabilities_rx.clone();
 314        let acp_thread = cx.new(|cx| {
 315            acp_thread::AcpThread::new(
 316                title,
 317                connection,
 318                project.clone(),
 319                action_log.clone(),
 320                session_id.clone(),
 321                prompt_capabilities_rx,
 322                cx,
 323            )
 324        });
 325
 326        let registry = LanguageModelRegistry::read_global(cx);
 327        let summarization_model = registry.thread_summary_model().map(|c| c.model);
 328
 329        thread_handle.update(cx, |thread, cx| {
 330            thread.set_summarization_model(summarization_model, cx);
 331            thread.add_default_tools(
 332                Rc::new(AcpThreadEnvironment {
 333                    acp_thread: acp_thread.downgrade(),
 334                }) as _,
 335                cx,
 336            )
 337        });
 338
 339        let subscriptions = vec![
 340            cx.observe_release(&acp_thread, |this, acp_thread, _cx| {
 341                this.sessions.remove(acp_thread.session_id());
 342            }),
 343            cx.subscribe(&thread_handle, Self::handle_thread_title_updated),
 344            cx.subscribe(&thread_handle, Self::handle_thread_token_usage_updated),
 345            cx.observe(&thread_handle, move |this, thread, cx| {
 346                this.save_thread(thread, cx)
 347            }),
 348        ];
 349
 350        self.sessions.insert(
 351            session_id,
 352            Session {
 353                thread: thread_handle,
 354                acp_thread: acp_thread.downgrade(),
 355                _subscriptions: subscriptions,
 356                pending_save: Task::ready(()),
 357            },
 358        );
 359
 360        self.update_available_commands(cx);
 361
 362        acp_thread
 363    }
 364
 365    pub fn models(&self) -> &LanguageModels {
 366        &self.models
 367    }
 368
 369    async fn maintain_project_context(
 370        this: WeakEntity<Self>,
 371        mut needs_refresh: watch::Receiver<()>,
 372        cx: &mut AsyncApp,
 373    ) -> Result<()> {
 374        while needs_refresh.changed().await.is_ok() {
 375            let project_context = this
 376                .update(cx, |this, cx| {
 377                    Self::build_project_context(&this.project, this.prompt_store.as_ref(), cx)
 378                })?
 379                .await;
 380            this.update(cx, |this, cx| {
 381                this.project_context = cx.new(|_| project_context);
 382            })?;
 383        }
 384
 385        Ok(())
 386    }
 387
 388    fn build_project_context(
 389        project: &Entity<Project>,
 390        prompt_store: Option<&Entity<PromptStore>>,
 391        cx: &mut App,
 392    ) -> Task<ProjectContext> {
 393        let worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
 394        let worktree_tasks = worktrees
 395            .into_iter()
 396            .map(|worktree| {
 397                Self::load_worktree_info_for_system_prompt(worktree, project.clone(), cx)
 398            })
 399            .collect::<Vec<_>>();
 400        let default_user_rules_task = if let Some(prompt_store) = prompt_store.as_ref() {
 401            prompt_store.read_with(cx, |prompt_store, cx| {
 402                let prompts = prompt_store.default_prompt_metadata();
 403                let load_tasks = prompts.into_iter().map(|prompt_metadata| {
 404                    let contents = prompt_store.load(prompt_metadata.id, cx);
 405                    async move { (contents.await, prompt_metadata) }
 406                });
 407                cx.background_spawn(future::join_all(load_tasks))
 408            })
 409        } else {
 410            Task::ready(vec![])
 411        };
 412
 413        cx.spawn(async move |_cx| {
 414            let (worktrees, default_user_rules) =
 415                future::join(future::join_all(worktree_tasks), default_user_rules_task).await;
 416
 417            let worktrees = worktrees
 418                .into_iter()
 419                .map(|(worktree, _rules_error)| {
 420                    // TODO: show error message
 421                    // if let Some(rules_error) = rules_error {
 422                    //     this.update(cx, |_, cx| cx.emit(rules_error)).ok();
 423                    // }
 424                    worktree
 425                })
 426                .collect::<Vec<_>>();
 427
 428            let default_user_rules = default_user_rules
 429                .into_iter()
 430                .flat_map(|(contents, prompt_metadata)| match contents {
 431                    Ok(contents) => Some(UserRulesContext {
 432                        uuid: prompt_metadata.id.as_user()?,
 433                        title: prompt_metadata.title.map(|title| title.to_string()),
 434                        contents,
 435                    }),
 436                    Err(_err) => {
 437                        // TODO: show error message
 438                        // this.update(cx, |_, cx| {
 439                        //     cx.emit(RulesLoadingError {
 440                        //         message: format!("{err:?}").into(),
 441                        //     });
 442                        // })
 443                        // .ok();
 444                        None
 445                    }
 446                })
 447                .collect::<Vec<_>>();
 448
 449            ProjectContext::new(worktrees, default_user_rules)
 450        })
 451    }
 452
 453    fn load_worktree_info_for_system_prompt(
 454        worktree: Entity<Worktree>,
 455        project: Entity<Project>,
 456        cx: &mut App,
 457    ) -> Task<(WorktreeContext, Option<RulesLoadingError>)> {
 458        let tree = worktree.read(cx);
 459        let root_name = tree.root_name_str().into();
 460        let abs_path = tree.abs_path();
 461
 462        let mut context = WorktreeContext {
 463            root_name,
 464            abs_path,
 465            rules_file: None,
 466        };
 467
 468        let rules_task = Self::load_worktree_rules_file(worktree, project, cx);
 469        let Some(rules_task) = rules_task else {
 470            return Task::ready((context, None));
 471        };
 472
 473        cx.spawn(async move |_| {
 474            let (rules_file, rules_file_error) = match rules_task.await {
 475                Ok(rules_file) => (Some(rules_file), None),
 476                Err(err) => (
 477                    None,
 478                    Some(RulesLoadingError {
 479                        message: format!("{err}").into(),
 480                    }),
 481                ),
 482            };
 483            context.rules_file = rules_file;
 484            (context, rules_file_error)
 485        })
 486    }
 487
 488    fn load_worktree_rules_file(
 489        worktree: Entity<Worktree>,
 490        project: Entity<Project>,
 491        cx: &mut App,
 492    ) -> Option<Task<Result<RulesFileContext>>> {
 493        let worktree = worktree.read(cx);
 494        let worktree_id = worktree.id();
 495        let selected_rules_file = RULES_FILE_NAMES
 496            .into_iter()
 497            .filter_map(|name| {
 498                worktree
 499                    .entry_for_path(RelPath::unix(name).unwrap())
 500                    .filter(|entry| entry.is_file())
 501                    .map(|entry| entry.path.clone())
 502            })
 503            .next();
 504
 505        // Note that Cline supports `.clinerules` being a directory, but that is not currently
 506        // supported. This doesn't seem to occur often in GitHub repositories.
 507        selected_rules_file.map(|path_in_worktree| {
 508            let project_path = ProjectPath {
 509                worktree_id,
 510                path: path_in_worktree.clone(),
 511            };
 512            let buffer_task =
 513                project.update(cx, |project, cx| project.open_buffer(project_path, cx));
 514            let rope_task = cx.spawn(async move |cx| {
 515                buffer_task.await?.read_with(cx, |buffer, cx| {
 516                    let project_entry_id = buffer.entry_id(cx).context("buffer has no file")?;
 517                    anyhow::Ok((project_entry_id, buffer.as_rope().clone()))
 518                })?
 519            });
 520            // Build a string from the rope on a background thread.
 521            cx.background_spawn(async move {
 522                let (project_entry_id, rope) = rope_task.await?;
 523                anyhow::Ok(RulesFileContext {
 524                    path_in_worktree,
 525                    text: rope.to_string().trim().to_string(),
 526                    project_entry_id: project_entry_id.to_usize(),
 527                })
 528            })
 529        })
 530    }
 531
 532    fn handle_thread_title_updated(
 533        &mut self,
 534        thread: Entity<Thread>,
 535        _: &TitleUpdated,
 536        cx: &mut Context<Self>,
 537    ) {
 538        let session_id = thread.read(cx).id();
 539        let Some(session) = self.sessions.get(session_id) else {
 540            return;
 541        };
 542        let thread = thread.downgrade();
 543        let acp_thread = session.acp_thread.clone();
 544        cx.spawn(async move |_, cx| {
 545            let title = thread.read_with(cx, |thread, _| thread.title())?;
 546            let task = acp_thread.update(cx, |acp_thread, cx| acp_thread.set_title(title, cx))?;
 547            task.await
 548        })
 549        .detach_and_log_err(cx);
 550    }
 551
 552    fn handle_thread_token_usage_updated(
 553        &mut self,
 554        thread: Entity<Thread>,
 555        usage: &TokenUsageUpdated,
 556        cx: &mut Context<Self>,
 557    ) {
 558        let Some(session) = self.sessions.get(thread.read(cx).id()) else {
 559            return;
 560        };
 561        session
 562            .acp_thread
 563            .update(cx, |acp_thread, cx| {
 564                acp_thread.update_token_usage(usage.0.clone(), cx);
 565            })
 566            .ok();
 567    }
 568
 569    fn handle_project_event(
 570        &mut self,
 571        _project: Entity<Project>,
 572        event: &project::Event,
 573        _cx: &mut Context<Self>,
 574    ) {
 575        match event {
 576            project::Event::WorktreeAdded(_) | project::Event::WorktreeRemoved(_) => {
 577                self.project_context_needs_refresh.send(()).ok();
 578            }
 579            project::Event::WorktreeUpdatedEntries(_, items) => {
 580                if items.iter().any(|(path, _, _)| {
 581                    RULES_FILE_NAMES
 582                        .iter()
 583                        .any(|name| path.as_ref() == RelPath::unix(name).unwrap())
 584                }) {
 585                    self.project_context_needs_refresh.send(()).ok();
 586                }
 587            }
 588            _ => {}
 589        }
 590    }
 591
 592    fn handle_prompts_updated_event(
 593        &mut self,
 594        _prompt_store: Entity<PromptStore>,
 595        _event: &prompt_store::PromptsUpdatedEvent,
 596        _cx: &mut Context<Self>,
 597    ) {
 598        self.project_context_needs_refresh.send(()).ok();
 599    }
 600
 601    fn handle_models_updated_event(
 602        &mut self,
 603        _registry: Entity<LanguageModelRegistry>,
 604        _event: &language_model::Event,
 605        cx: &mut Context<Self>,
 606    ) {
 607        self.models.refresh_list(cx);
 608
 609        let registry = LanguageModelRegistry::read_global(cx);
 610        let default_model = registry.default_model().map(|m| m.model);
 611        let summarization_model = registry.thread_summary_model().map(|m| m.model);
 612
 613        for session in self.sessions.values_mut() {
 614            session.thread.update(cx, |thread, cx| {
 615                if thread.model().is_none()
 616                    && let Some(model) = default_model.clone()
 617                {
 618                    thread.set_model(model, cx);
 619                    cx.notify();
 620                }
 621                thread.set_summarization_model(summarization_model.clone(), cx);
 622            });
 623        }
 624    }
 625
 626    fn handle_context_server_store_updated(
 627        &mut self,
 628        _store: Entity<project::context_server_store::ContextServerStore>,
 629        _event: &project::context_server_store::Event,
 630        cx: &mut Context<Self>,
 631    ) {
 632        self.update_available_commands(cx);
 633    }
 634
 635    fn handle_context_server_registry_event(
 636        &mut self,
 637        _registry: Entity<ContextServerRegistry>,
 638        event: &ContextServerRegistryEvent,
 639        cx: &mut Context<Self>,
 640    ) {
 641        match event {
 642            ContextServerRegistryEvent::ToolsChanged => {}
 643            ContextServerRegistryEvent::PromptsChanged => {
 644                self.update_available_commands(cx);
 645            }
 646        }
 647    }
 648
 649    fn update_available_commands(&self, cx: &mut Context<Self>) {
 650        let available_commands = self.build_available_commands(cx);
 651        for session in self.sessions.values() {
 652            if let Some(acp_thread) = session.acp_thread.upgrade() {
 653                acp_thread.update(cx, |thread, cx| {
 654                    thread
 655                        .handle_session_update(
 656                            acp::SessionUpdate::AvailableCommandsUpdate(
 657                                acp::AvailableCommandsUpdate::new(available_commands.clone()),
 658                            ),
 659                            cx,
 660                        )
 661                        .log_err();
 662                });
 663            }
 664        }
 665    }
 666
 667    fn build_available_commands(&self, cx: &App) -> Vec<acp::AvailableCommand> {
 668        let registry = self.context_server_registry.read(cx);
 669
 670        let mut prompt_name_counts: HashMap<&str, usize> = HashMap::default();
 671        for context_server_prompt in registry.prompts() {
 672            *prompt_name_counts
 673                .entry(context_server_prompt.prompt.name.as_str())
 674                .or_insert(0) += 1;
 675        }
 676
 677        registry
 678            .prompts()
 679            .flat_map(|context_server_prompt| {
 680                let prompt = &context_server_prompt.prompt;
 681
 682                let should_prefix = prompt_name_counts
 683                    .get(prompt.name.as_str())
 684                    .copied()
 685                    .unwrap_or(0)
 686                    > 1;
 687
 688                let name = if should_prefix {
 689                    format!("{}.{}", context_server_prompt.server_id, prompt.name)
 690                } else {
 691                    prompt.name.clone()
 692                };
 693
 694                let mut command = acp::AvailableCommand::new(
 695                    name,
 696                    prompt.description.clone().unwrap_or_default(),
 697                );
 698
 699                match prompt.arguments.as_deref() {
 700                    Some([arg]) => {
 701                        let hint = format!("<{}>", arg.name);
 702
 703                        command = command.input(acp::AvailableCommandInput::Unstructured(
 704                            acp::UnstructuredCommandInput::new(hint),
 705                        ));
 706                    }
 707                    Some([]) | None => {}
 708                    Some(_) => {
 709                        // skip >1 argument commands since we don't support them yet
 710                        return None;
 711                    }
 712                }
 713
 714                Some(command)
 715            })
 716            .collect()
 717    }
 718
 719    pub fn load_thread(
 720        &mut self,
 721        id: acp::SessionId,
 722        cx: &mut Context<Self>,
 723    ) -> Task<Result<Entity<Thread>>> {
 724        let database_future = ThreadsDatabase::connect(cx);
 725        cx.spawn(async move |this, cx| {
 726            let database = database_future.await.map_err(|err| anyhow!(err))?;
 727            let db_thread = database
 728                .load_thread(id.clone())
 729                .await?
 730                .with_context(|| format!("no thread found with ID: {id:?}"))?;
 731
 732            this.update(cx, |this, cx| {
 733                let summarization_model = LanguageModelRegistry::read_global(cx)
 734                    .thread_summary_model()
 735                    .map(|c| c.model);
 736
 737                cx.new(|cx| {
 738                    let mut thread = Thread::from_db(
 739                        id.clone(),
 740                        db_thread,
 741                        this.project.clone(),
 742                        this.project_context.clone(),
 743                        this.context_server_registry.clone(),
 744                        this.templates.clone(),
 745                        cx,
 746                    );
 747                    thread.set_summarization_model(summarization_model, cx);
 748                    thread
 749                })
 750            })
 751        })
 752    }
 753
 754    pub fn open_thread(
 755        &mut self,
 756        id: acp::SessionId,
 757        cx: &mut Context<Self>,
 758    ) -> Task<Result<Entity<AcpThread>>> {
 759        let task = self.load_thread(id, cx);
 760        cx.spawn(async move |this, cx| {
 761            let thread = task.await?;
 762            let acp_thread =
 763                this.update(cx, |this, cx| this.register_session(thread.clone(), cx))?;
 764            let events = thread.update(cx, |thread, cx| thread.replay(cx))?;
 765            cx.update(|cx| {
 766                NativeAgentConnection::handle_thread_events(events, acp_thread.downgrade(), cx)
 767            })?
 768            .await?;
 769            Ok(acp_thread)
 770        })
 771    }
 772
 773    pub fn thread_summary(
 774        &mut self,
 775        id: acp::SessionId,
 776        cx: &mut Context<Self>,
 777    ) -> Task<Result<SharedString>> {
 778        let thread = self.open_thread(id.clone(), cx);
 779        cx.spawn(async move |this, cx| {
 780            let acp_thread = thread.await?;
 781            let result = this
 782                .update(cx, |this, cx| {
 783                    this.sessions
 784                        .get(&id)
 785                        .unwrap()
 786                        .thread
 787                        .update(cx, |thread, cx| thread.summary(cx))
 788                })?
 789                .await
 790                .context("Failed to generate summary")?;
 791            drop(acp_thread);
 792            Ok(result)
 793        })
 794    }
 795
 796    fn save_thread(&mut self, thread: Entity<Thread>, cx: &mut Context<Self>) {
 797        if thread.read(cx).is_empty() {
 798            return;
 799        }
 800
 801        let database_future = ThreadsDatabase::connect(cx);
 802        let (id, db_thread) =
 803            thread.update(cx, |thread, cx| (thread.id().clone(), thread.to_db(cx)));
 804        let Some(session) = self.sessions.get_mut(&id) else {
 805            return;
 806        };
 807        let history = self.history.clone();
 808        session.pending_save = cx.spawn(async move |_, cx| {
 809            let Some(database) = database_future.await.map_err(|err| anyhow!(err)).log_err() else {
 810                return;
 811            };
 812            let db_thread = db_thread.await;
 813            database.save_thread(id, db_thread).await.log_err();
 814            history.update(cx, |history, cx| history.reload(cx)).ok();
 815        });
 816    }
 817
 818    fn send_mcp_prompt(
 819        &self,
 820        message_id: UserMessageId,
 821        session_id: agent_client_protocol::SessionId,
 822        prompt_name: String,
 823        server_id: ContextServerId,
 824        arguments: HashMap<String, String>,
 825        original_content: Vec<acp::ContentBlock>,
 826        cx: &mut Context<Self>,
 827    ) -> Task<Result<acp::PromptResponse>> {
 828        let server_store = self.context_server_registry.read(cx).server_store().clone();
 829        let path_style = self.project.read(cx).path_style(cx);
 830
 831        cx.spawn(async move |this, cx| {
 832            let prompt =
 833                crate::get_prompt(&server_store, &server_id, &prompt_name, arguments, cx).await?;
 834
 835            let (acp_thread, thread) = this.update(cx, |this, _cx| {
 836                let session = this
 837                    .sessions
 838                    .get(&session_id)
 839                    .context("Failed to get session")?;
 840                anyhow::Ok((session.acp_thread.clone(), session.thread.clone()))
 841            })??;
 842
 843            let mut last_is_user = true;
 844
 845            thread.update(cx, |thread, cx| {
 846                thread.push_acp_user_block(
 847                    message_id,
 848                    original_content.into_iter().skip(1),
 849                    path_style,
 850                    cx,
 851                );
 852            })?;
 853
 854            for message in prompt.messages {
 855                let context_server::types::PromptMessage { role, content } = message;
 856                let block = mcp_message_content_to_acp_content_block(content);
 857
 858                match role {
 859                    context_server::types::Role::User => {
 860                        let id = acp_thread::UserMessageId::new();
 861
 862                        acp_thread.update(cx, |acp_thread, cx| {
 863                            acp_thread.push_user_content_block_with_indent(
 864                                Some(id.clone()),
 865                                block.clone(),
 866                                true,
 867                                cx,
 868                            );
 869                            anyhow::Ok(())
 870                        })??;
 871
 872                        thread.update(cx, |thread, cx| {
 873                            thread.push_acp_user_block(id, [block], path_style, cx);
 874                            anyhow::Ok(())
 875                        })??;
 876                    }
 877                    context_server::types::Role::Assistant => {
 878                        acp_thread.update(cx, |acp_thread, cx| {
 879                            acp_thread.push_assistant_content_block_with_indent(
 880                                block.clone(),
 881                                false,
 882                                true,
 883                                cx,
 884                            );
 885                            anyhow::Ok(())
 886                        })??;
 887
 888                        thread.update(cx, |thread, cx| {
 889                            thread.push_acp_agent_block(block, cx);
 890                            anyhow::Ok(())
 891                        })??;
 892                    }
 893                }
 894
 895                last_is_user = role == context_server::types::Role::User;
 896            }
 897
 898            let response_stream = thread.update(cx, |thread, cx| {
 899                if last_is_user {
 900                    thread.send_existing(cx)
 901                } else {
 902                    // Resume if MCP prompt did not end with a user message
 903                    thread.resume(cx)
 904                }
 905            })??;
 906
 907            cx.update(|cx| {
 908                NativeAgentConnection::handle_thread_events(response_stream, acp_thread, cx)
 909            })?
 910            .await
 911        })
 912    }
 913}
 914
 915/// Wrapper struct that implements the AgentConnection trait
 916#[derive(Clone)]
 917pub struct NativeAgentConnection(pub Entity<NativeAgent>);
 918
 919impl NativeAgentConnection {
 920    pub fn thread(&self, session_id: &acp::SessionId, cx: &App) -> Option<Entity<Thread>> {
 921        self.0
 922            .read(cx)
 923            .sessions
 924            .get(session_id)
 925            .map(|session| session.thread.clone())
 926    }
 927
 928    pub fn load_thread(&self, id: acp::SessionId, cx: &mut App) -> Task<Result<Entity<Thread>>> {
 929        self.0.update(cx, |this, cx| this.load_thread(id, cx))
 930    }
 931
 932    fn run_turn(
 933        &self,
 934        session_id: acp::SessionId,
 935        cx: &mut App,
 936        f: impl 'static
 937        + FnOnce(Entity<Thread>, &mut App) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>,
 938    ) -> Task<Result<acp::PromptResponse>> {
 939        let Some((thread, acp_thread)) = self.0.update(cx, |agent, _cx| {
 940            agent
 941                .sessions
 942                .get_mut(&session_id)
 943                .map(|s| (s.thread.clone(), s.acp_thread.clone()))
 944        }) else {
 945            return Task::ready(Err(anyhow!("Session not found")));
 946        };
 947        log::debug!("Found session for: {}", session_id);
 948
 949        let response_stream = match f(thread, cx) {
 950            Ok(stream) => stream,
 951            Err(err) => return Task::ready(Err(err)),
 952        };
 953        Self::handle_thread_events(response_stream, acp_thread, cx)
 954    }
 955
 956    fn handle_thread_events(
 957        mut events: mpsc::UnboundedReceiver<Result<ThreadEvent>>,
 958        acp_thread: WeakEntity<AcpThread>,
 959        cx: &App,
 960    ) -> Task<Result<acp::PromptResponse>> {
 961        cx.spawn(async move |cx| {
 962            // Handle response stream and forward to session.acp_thread
 963            while let Some(result) = events.next().await {
 964                match result {
 965                    Ok(event) => {
 966                        log::trace!("Received completion event: {:?}", event);
 967
 968                        match event {
 969                            ThreadEvent::UserMessage(message) => {
 970                                acp_thread.update(cx, |thread, cx| {
 971                                    for content in message.content {
 972                                        thread.push_user_content_block(
 973                                            Some(message.id.clone()),
 974                                            content.into(),
 975                                            cx,
 976                                        );
 977                                    }
 978                                })?;
 979                            }
 980                            ThreadEvent::AgentText(text) => {
 981                                acp_thread.update(cx, |thread, cx| {
 982                                    thread.push_assistant_content_block(text.into(), false, cx)
 983                                })?;
 984                            }
 985                            ThreadEvent::AgentThinking(text) => {
 986                                acp_thread.update(cx, |thread, cx| {
 987                                    thread.push_assistant_content_block(text.into(), true, cx)
 988                                })?;
 989                            }
 990                            ThreadEvent::ToolCallAuthorization(ToolCallAuthorization {
 991                                tool_call,
 992                                options,
 993                                response,
 994                            }) => {
 995                                let outcome_task = acp_thread.update(cx, |thread, cx| {
 996                                    thread.request_tool_call_authorization(
 997                                        tool_call, options, true, cx,
 998                                    )
 999                                })??;
1000                                cx.background_spawn(async move {
1001                                    if let acp::RequestPermissionOutcome::Selected(
1002                                        acp::SelectedPermissionOutcome { option_id, .. },
1003                                    ) = outcome_task.await
1004                                    {
1005                                        response
1006                                            .send(option_id)
1007                                            .map(|_| anyhow!("authorization receiver was dropped"))
1008                                            .log_err();
1009                                    }
1010                                })
1011                                .detach();
1012                            }
1013                            ThreadEvent::ToolCall(tool_call) => {
1014                                acp_thread.update(cx, |thread, cx| {
1015                                    thread.upsert_tool_call(tool_call, cx)
1016                                })??;
1017                            }
1018                            ThreadEvent::ToolCallUpdate(update) => {
1019                                acp_thread.update(cx, |thread, cx| {
1020                                    thread.update_tool_call(update, cx)
1021                                })??;
1022                            }
1023                            ThreadEvent::Retry(status) => {
1024                                acp_thread.update(cx, |thread, cx| {
1025                                    thread.update_retry_status(status, cx)
1026                                })?;
1027                            }
1028                            ThreadEvent::Stop(stop_reason) => {
1029                                log::debug!("Assistant message complete: {:?}", stop_reason);
1030                                return Ok(acp::PromptResponse::new(stop_reason));
1031                            }
1032                        }
1033                    }
1034                    Err(e) => {
1035                        log::error!("Error in model response stream: {:?}", e);
1036                        return Err(e);
1037                    }
1038                }
1039            }
1040
1041            log::debug!("Response stream completed");
1042            anyhow::Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
1043        })
1044    }
1045}
1046
1047struct Command<'a> {
1048    prompt_name: &'a str,
1049    arg_value: &'a str,
1050    explicit_server_id: Option<&'a str>,
1051}
1052
1053impl<'a> Command<'a> {
1054    fn parse(prompt: &'a [acp::ContentBlock]) -> Option<Self> {
1055        let acp::ContentBlock::Text(text_content) = prompt.first()? else {
1056            return None;
1057        };
1058        let text = text_content.text.trim();
1059        let command = text.strip_prefix('/')?;
1060        let (command, arg_value) = command
1061            .split_once(char::is_whitespace)
1062            .unwrap_or((command, ""));
1063
1064        if let Some((server_id, prompt_name)) = command.split_once('.') {
1065            Some(Self {
1066                prompt_name,
1067                arg_value,
1068                explicit_server_id: Some(server_id),
1069            })
1070        } else {
1071            Some(Self {
1072                prompt_name: command,
1073                arg_value,
1074                explicit_server_id: None,
1075            })
1076        }
1077    }
1078}
1079
1080struct NativeAgentModelSelector {
1081    session_id: acp::SessionId,
1082    connection: NativeAgentConnection,
1083}
1084
1085impl acp_thread::AgentModelSelector for NativeAgentModelSelector {
1086    fn list_models(&self, cx: &mut App) -> Task<Result<acp_thread::AgentModelList>> {
1087        log::debug!("NativeAgentConnection::list_models called");
1088        let list = self.connection.0.read(cx).models.model_list.clone();
1089        Task::ready(if list.is_empty() {
1090            Err(anyhow::anyhow!("No models available"))
1091        } else {
1092            Ok(list)
1093        })
1094    }
1095
1096    fn select_model(&self, model_id: acp::ModelId, cx: &mut App) -> Task<Result<()>> {
1097        log::debug!(
1098            "Setting model for session {}: {}",
1099            self.session_id,
1100            model_id
1101        );
1102        let Some(thread) = self
1103            .connection
1104            .0
1105            .read(cx)
1106            .sessions
1107            .get(&self.session_id)
1108            .map(|session| session.thread.clone())
1109        else {
1110            return Task::ready(Err(anyhow!("Session not found")));
1111        };
1112
1113        let Some(model) = self.connection.0.read(cx).models.model_from_id(&model_id) else {
1114            return Task::ready(Err(anyhow!("Invalid model ID {}", model_id)));
1115        };
1116
1117        thread.update(cx, |thread, cx| {
1118            thread.set_model(model.clone(), cx);
1119        });
1120
1121        update_settings_file(
1122            self.connection.0.read(cx).fs.clone(),
1123            cx,
1124            move |settings, _cx| {
1125                let provider = model.provider_id().0.to_string();
1126                let model = model.id().0.to_string();
1127                settings
1128                    .agent
1129                    .get_or_insert_default()
1130                    .set_model(LanguageModelSelection {
1131                        provider: provider.into(),
1132                        model,
1133                    });
1134            },
1135        );
1136
1137        Task::ready(Ok(()))
1138    }
1139
1140    fn selected_model(&self, cx: &mut App) -> Task<Result<acp_thread::AgentModelInfo>> {
1141        let Some(thread) = self
1142            .connection
1143            .0
1144            .read(cx)
1145            .sessions
1146            .get(&self.session_id)
1147            .map(|session| session.thread.clone())
1148        else {
1149            return Task::ready(Err(anyhow!("Session not found")));
1150        };
1151        let Some(model) = thread.read(cx).model() else {
1152            return Task::ready(Err(anyhow!("Model not found")));
1153        };
1154        let Some(provider) = LanguageModelRegistry::read_global(cx).provider(&model.provider_id())
1155        else {
1156            return Task::ready(Err(anyhow!("Provider not found")));
1157        };
1158        Task::ready(Ok(LanguageModels::map_language_model_to_info(
1159            model, &provider,
1160        )))
1161    }
1162
1163    fn watch(&self, cx: &mut App) -> Option<watch::Receiver<()>> {
1164        Some(self.connection.0.read(cx).models.watch())
1165    }
1166
1167    fn should_render_footer(&self) -> bool {
1168        true
1169    }
1170}
1171
1172impl acp_thread::AgentConnection for NativeAgentConnection {
1173    fn telemetry_id(&self) -> SharedString {
1174        "zed".into()
1175    }
1176
1177    fn new_thread(
1178        self: Rc<Self>,
1179        project: Entity<Project>,
1180        cwd: &Path,
1181        cx: &mut App,
1182    ) -> Task<Result<Entity<acp_thread::AcpThread>>> {
1183        let agent = self.0.clone();
1184        log::debug!("Creating new thread for project at: {:?}", cwd);
1185
1186        cx.spawn(async move |cx| {
1187            log::debug!("Starting thread creation in async context");
1188
1189            // Create Thread
1190            let thread = agent.update(
1191                cx,
1192                |agent, cx: &mut gpui::Context<NativeAgent>| -> Result<_> {
1193                    // Fetch default model from registry settings
1194                    let registry = LanguageModelRegistry::read_global(cx);
1195                    // Log available models for debugging
1196                    let available_count = registry.available_models(cx).count();
1197                    log::debug!("Total available models: {}", available_count);
1198
1199                    let default_model = registry.default_model().and_then(|default_model| {
1200                        agent
1201                            .models
1202                            .model_from_id(&LanguageModels::model_id(&default_model.model))
1203                    });
1204                    Ok(cx.new(|cx| {
1205                        Thread::new(
1206                            project.clone(),
1207                            agent.project_context.clone(),
1208                            agent.context_server_registry.clone(),
1209                            agent.templates.clone(),
1210                            default_model,
1211                            cx,
1212                        )
1213                    }))
1214                },
1215            )??;
1216            agent.update(cx, |agent, cx| agent.register_session(thread, cx))
1217        })
1218    }
1219
1220    fn auth_methods(&self) -> &[acp::AuthMethod] {
1221        &[] // No auth for in-process
1222    }
1223
1224    fn authenticate(&self, _method: acp::AuthMethodId, _cx: &mut App) -> Task<Result<()>> {
1225        Task::ready(Ok(()))
1226    }
1227
1228    fn model_selector(&self, session_id: &acp::SessionId) -> Option<Rc<dyn AgentModelSelector>> {
1229        Some(Rc::new(NativeAgentModelSelector {
1230            session_id: session_id.clone(),
1231            connection: self.clone(),
1232        }) as Rc<dyn AgentModelSelector>)
1233    }
1234
1235    fn prompt(
1236        &self,
1237        id: Option<acp_thread::UserMessageId>,
1238        params: acp::PromptRequest,
1239        cx: &mut App,
1240    ) -> Task<Result<acp::PromptResponse>> {
1241        let id = id.expect("UserMessageId is required");
1242        let session_id = params.session_id.clone();
1243        log::info!("Received prompt request for session: {}", session_id);
1244        log::debug!("Prompt blocks count: {}", params.prompt.len());
1245
1246        if let Some(parsed_command) = Command::parse(&params.prompt) {
1247            let registry = self.0.read(cx).context_server_registry.read(cx);
1248
1249            let explicit_server_id = parsed_command
1250                .explicit_server_id
1251                .map(|server_id| ContextServerId(server_id.into()));
1252
1253            if let Some(prompt) =
1254                registry.find_prompt(explicit_server_id.as_ref(), parsed_command.prompt_name)
1255            {
1256                let arguments = if !parsed_command.arg_value.is_empty()
1257                    && let Some(arg_name) = prompt
1258                        .prompt
1259                        .arguments
1260                        .as_ref()
1261                        .and_then(|args| args.first())
1262                        .map(|arg| arg.name.clone())
1263                {
1264                    HashMap::from_iter([(arg_name, parsed_command.arg_value.to_string())])
1265                } else {
1266                    Default::default()
1267                };
1268
1269                let prompt_name = prompt.prompt.name.clone();
1270                let server_id = prompt.server_id.clone();
1271
1272                return self.0.update(cx, |agent, cx| {
1273                    agent.send_mcp_prompt(
1274                        id,
1275                        session_id.clone(),
1276                        prompt_name,
1277                        server_id,
1278                        arguments,
1279                        params.prompt,
1280                        cx,
1281                    )
1282                });
1283            };
1284        };
1285
1286        let path_style = self.0.read(cx).project.read(cx).path_style(cx);
1287
1288        self.run_turn(session_id, cx, move |thread, cx| {
1289            let content: Vec<UserMessageContent> = params
1290                .prompt
1291                .into_iter()
1292                .map(|block| UserMessageContent::from_content_block(block, path_style))
1293                .collect::<Vec<_>>();
1294            log::debug!("Converted prompt to message: {} chars", content.len());
1295            log::debug!("Message id: {:?}", id);
1296            log::debug!("Message content: {:?}", content);
1297
1298            thread.update(cx, |thread, cx| thread.send(id, content, cx))
1299        })
1300    }
1301
1302    fn resume(
1303        &self,
1304        session_id: &acp::SessionId,
1305        _cx: &App,
1306    ) -> Option<Rc<dyn acp_thread::AgentSessionResume>> {
1307        Some(Rc::new(NativeAgentSessionResume {
1308            connection: self.clone(),
1309            session_id: session_id.clone(),
1310        }) as _)
1311    }
1312
1313    fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
1314        log::info!("Cancelling on session: {}", session_id);
1315        self.0.update(cx, |agent, cx| {
1316            if let Some(agent) = agent.sessions.get(session_id) {
1317                agent.thread.update(cx, |thread, cx| thread.cancel(cx));
1318            }
1319        });
1320    }
1321
1322    fn truncate(
1323        &self,
1324        session_id: &agent_client_protocol::SessionId,
1325        cx: &App,
1326    ) -> Option<Rc<dyn acp_thread::AgentSessionTruncate>> {
1327        self.0.read_with(cx, |agent, _cx| {
1328            agent.sessions.get(session_id).map(|session| {
1329                Rc::new(NativeAgentSessionTruncate {
1330                    thread: session.thread.clone(),
1331                    acp_thread: session.acp_thread.clone(),
1332                }) as _
1333            })
1334        })
1335    }
1336
1337    fn set_title(
1338        &self,
1339        session_id: &acp::SessionId,
1340        _cx: &App,
1341    ) -> Option<Rc<dyn acp_thread::AgentSessionSetTitle>> {
1342        Some(Rc::new(NativeAgentSessionSetTitle {
1343            connection: self.clone(),
1344            session_id: session_id.clone(),
1345        }) as _)
1346    }
1347
1348    fn telemetry(&self) -> Option<Rc<dyn acp_thread::AgentTelemetry>> {
1349        Some(Rc::new(self.clone()) as Rc<dyn acp_thread::AgentTelemetry>)
1350    }
1351
1352    fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
1353        self
1354    }
1355}
1356
1357impl acp_thread::AgentTelemetry for NativeAgentConnection {
1358    fn thread_data(
1359        &self,
1360        session_id: &acp::SessionId,
1361        cx: &mut App,
1362    ) -> Task<Result<serde_json::Value>> {
1363        let Some(session) = self.0.read(cx).sessions.get(session_id) else {
1364            return Task::ready(Err(anyhow!("Session not found")));
1365        };
1366
1367        let task = session.thread.read(cx).to_db(cx);
1368        cx.background_spawn(async move {
1369            serde_json::to_value(task.await).context("Failed to serialize thread")
1370        })
1371    }
1372}
1373
1374struct NativeAgentSessionTruncate {
1375    thread: Entity<Thread>,
1376    acp_thread: WeakEntity<AcpThread>,
1377}
1378
1379impl acp_thread::AgentSessionTruncate for NativeAgentSessionTruncate {
1380    fn run(&self, message_id: acp_thread::UserMessageId, cx: &mut App) -> Task<Result<()>> {
1381        match self.thread.update(cx, |thread, cx| {
1382            thread.truncate(message_id.clone(), cx)?;
1383            Ok(thread.latest_token_usage())
1384        }) {
1385            Ok(usage) => {
1386                self.acp_thread
1387                    .update(cx, |thread, cx| {
1388                        thread.update_token_usage(usage, cx);
1389                    })
1390                    .ok();
1391                Task::ready(Ok(()))
1392            }
1393            Err(error) => Task::ready(Err(error)),
1394        }
1395    }
1396}
1397
1398struct NativeAgentSessionResume {
1399    connection: NativeAgentConnection,
1400    session_id: acp::SessionId,
1401}
1402
1403impl acp_thread::AgentSessionResume for NativeAgentSessionResume {
1404    fn run(&self, cx: &mut App) -> Task<Result<acp::PromptResponse>> {
1405        self.connection
1406            .run_turn(self.session_id.clone(), cx, |thread, cx| {
1407                thread.update(cx, |thread, cx| thread.resume(cx))
1408            })
1409    }
1410}
1411
1412struct NativeAgentSessionSetTitle {
1413    connection: NativeAgentConnection,
1414    session_id: acp::SessionId,
1415}
1416
1417impl acp_thread::AgentSessionSetTitle for NativeAgentSessionSetTitle {
1418    fn run(&self, title: SharedString, cx: &mut App) -> Task<Result<()>> {
1419        let Some(session) = self.connection.0.read(cx).sessions.get(&self.session_id) else {
1420            return Task::ready(Err(anyhow!("session not found")));
1421        };
1422        let thread = session.thread.clone();
1423        thread.update(cx, |thread, cx| thread.set_title(title, cx));
1424        Task::ready(Ok(()))
1425    }
1426}
1427
1428pub struct AcpThreadEnvironment {
1429    acp_thread: WeakEntity<AcpThread>,
1430}
1431
1432impl ThreadEnvironment for AcpThreadEnvironment {
1433    fn create_terminal(
1434        &self,
1435        command: String,
1436        cwd: Option<PathBuf>,
1437        output_byte_limit: Option<u64>,
1438        cx: &mut AsyncApp,
1439    ) -> Task<Result<Rc<dyn TerminalHandle>>> {
1440        let task = self.acp_thread.update(cx, |thread, cx| {
1441            thread.create_terminal(command, vec![], vec![], cwd, output_byte_limit, cx)
1442        });
1443
1444        let acp_thread = self.acp_thread.clone();
1445        cx.spawn(async move |cx| {
1446            let terminal = task?.await?;
1447
1448            let (drop_tx, drop_rx) = oneshot::channel();
1449            let terminal_id = terminal.read_with(cx, |terminal, _cx| terminal.id().clone())?;
1450
1451            cx.spawn(async move |cx| {
1452                drop_rx.await.ok();
1453                acp_thread.update(cx, |thread, cx| thread.release_terminal(terminal_id, cx))
1454            })
1455            .detach();
1456
1457            let handle = AcpTerminalHandle {
1458                terminal,
1459                _drop_tx: Some(drop_tx),
1460            };
1461
1462            Ok(Rc::new(handle) as _)
1463        })
1464    }
1465}
1466
1467pub struct AcpTerminalHandle {
1468    terminal: Entity<acp_thread::Terminal>,
1469    _drop_tx: Option<oneshot::Sender<()>>,
1470}
1471
1472impl TerminalHandle for AcpTerminalHandle {
1473    fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId> {
1474        self.terminal.read_with(cx, |term, _cx| term.id().clone())
1475    }
1476
1477    fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>> {
1478        self.terminal
1479            .read_with(cx, |term, _cx| term.wait_for_exit())
1480    }
1481
1482    fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse> {
1483        self.terminal
1484            .read_with(cx, |term, cx| term.current_output(cx))
1485    }
1486
1487    fn kill(&self, cx: &AsyncApp) -> Result<()> {
1488        cx.update(|cx| {
1489            self.terminal.update(cx, |terminal, cx| {
1490                terminal.kill(cx);
1491            });
1492        })?;
1493        Ok(())
1494    }
1495}
1496
1497#[cfg(test)]
1498mod internal_tests {
1499    use crate::HistoryEntryId;
1500
1501    use super::*;
1502    use acp_thread::{AgentConnection, AgentModelGroupName, AgentModelInfo, MentionUri};
1503    use fs::FakeFs;
1504    use gpui::TestAppContext;
1505    use indoc::formatdoc;
1506    use language_model::fake_provider::FakeLanguageModel;
1507    use serde_json::json;
1508    use settings::SettingsStore;
1509    use util::{path, rel_path::rel_path};
1510
1511    #[gpui::test]
1512    async fn test_maintaining_project_context(cx: &mut TestAppContext) {
1513        init_test(cx);
1514        let fs = FakeFs::new(cx.executor());
1515        fs.insert_tree(
1516            "/",
1517            json!({
1518                "a": {}
1519            }),
1520        )
1521        .await;
1522        let project = Project::test(fs.clone(), [], cx).await;
1523        let text_thread_store =
1524            cx.new(|cx| assistant_text_thread::TextThreadStore::fake(project.clone(), cx));
1525        let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx));
1526        let agent = NativeAgent::new(
1527            project.clone(),
1528            history_store,
1529            Templates::new(),
1530            None,
1531            fs.clone(),
1532            &mut cx.to_async(),
1533        )
1534        .await
1535        .unwrap();
1536        agent.read_with(cx, |agent, cx| {
1537            assert_eq!(agent.project_context.read(cx).worktrees, vec![])
1538        });
1539
1540        let worktree = project
1541            .update(cx, |project, cx| project.create_worktree("/a", true, cx))
1542            .await
1543            .unwrap();
1544        cx.run_until_parked();
1545        agent.read_with(cx, |agent, cx| {
1546            assert_eq!(
1547                agent.project_context.read(cx).worktrees,
1548                vec![WorktreeContext {
1549                    root_name: "a".into(),
1550                    abs_path: Path::new("/a").into(),
1551                    rules_file: None
1552                }]
1553            )
1554        });
1555
1556        // Creating `/a/.rules` updates the project context.
1557        fs.insert_file("/a/.rules", Vec::new()).await;
1558        cx.run_until_parked();
1559        agent.read_with(cx, |agent, cx| {
1560            let rules_entry = worktree
1561                .read(cx)
1562                .entry_for_path(rel_path(".rules"))
1563                .unwrap();
1564            assert_eq!(
1565                agent.project_context.read(cx).worktrees,
1566                vec![WorktreeContext {
1567                    root_name: "a".into(),
1568                    abs_path: Path::new("/a").into(),
1569                    rules_file: Some(RulesFileContext {
1570                        path_in_worktree: rel_path(".rules").into(),
1571                        text: "".into(),
1572                        project_entry_id: rules_entry.id.to_usize()
1573                    })
1574                }]
1575            )
1576        });
1577    }
1578
1579    #[gpui::test]
1580    async fn test_listing_models(cx: &mut TestAppContext) {
1581        init_test(cx);
1582        let fs = FakeFs::new(cx.executor());
1583        fs.insert_tree("/", json!({ "a": {}  })).await;
1584        let project = Project::test(fs.clone(), [], cx).await;
1585        let text_thread_store =
1586            cx.new(|cx| assistant_text_thread::TextThreadStore::fake(project.clone(), cx));
1587        let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx));
1588        let connection = NativeAgentConnection(
1589            NativeAgent::new(
1590                project.clone(),
1591                history_store,
1592                Templates::new(),
1593                None,
1594                fs.clone(),
1595                &mut cx.to_async(),
1596            )
1597            .await
1598            .unwrap(),
1599        );
1600
1601        // Create a thread/session
1602        let acp_thread = cx
1603            .update(|cx| {
1604                Rc::new(connection.clone()).new_thread(project.clone(), Path::new("/a"), cx)
1605            })
1606            .await
1607            .unwrap();
1608
1609        let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());
1610
1611        let models = cx
1612            .update(|cx| {
1613                connection
1614                    .model_selector(&session_id)
1615                    .unwrap()
1616                    .list_models(cx)
1617            })
1618            .await
1619            .unwrap();
1620
1621        let acp_thread::AgentModelList::Grouped(models) = models else {
1622            panic!("Unexpected model group");
1623        };
1624        assert_eq!(
1625            models,
1626            IndexMap::from_iter([(
1627                AgentModelGroupName("Fake".into()),
1628                vec![AgentModelInfo {
1629                    id: acp::ModelId::new("fake/fake"),
1630                    name: "Fake".into(),
1631                    description: None,
1632                    icon: Some(acp_thread::AgentModelIcon::Named(
1633                        ui::IconName::ZedAssistant
1634                    )),
1635                }]
1636            )])
1637        );
1638    }
1639
1640    #[gpui::test]
1641    async fn test_model_selection_persists_to_settings(cx: &mut TestAppContext) {
1642        init_test(cx);
1643        let fs = FakeFs::new(cx.executor());
1644        fs.create_dir(paths::settings_file().parent().unwrap())
1645            .await
1646            .unwrap();
1647        fs.insert_file(
1648            paths::settings_file(),
1649            json!({
1650                "agent": {
1651                    "default_model": {
1652                        "provider": "foo",
1653                        "model": "bar"
1654                    }
1655                }
1656            })
1657            .to_string()
1658            .into_bytes(),
1659        )
1660        .await;
1661        let project = Project::test(fs.clone(), [], cx).await;
1662
1663        let text_thread_store =
1664            cx.new(|cx| assistant_text_thread::TextThreadStore::fake(project.clone(), cx));
1665        let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx));
1666
1667        // Create the agent and connection
1668        let agent = NativeAgent::new(
1669            project.clone(),
1670            history_store,
1671            Templates::new(),
1672            None,
1673            fs.clone(),
1674            &mut cx.to_async(),
1675        )
1676        .await
1677        .unwrap();
1678        let connection = NativeAgentConnection(agent.clone());
1679
1680        // Create a thread/session
1681        let acp_thread = cx
1682            .update(|cx| {
1683                Rc::new(connection.clone()).new_thread(project.clone(), Path::new("/a"), cx)
1684            })
1685            .await
1686            .unwrap();
1687
1688        let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());
1689
1690        // Select a model
1691        let selector = connection.model_selector(&session_id).unwrap();
1692        let model_id = acp::ModelId::new("fake/fake");
1693        cx.update(|cx| selector.select_model(model_id.clone(), cx))
1694            .await
1695            .unwrap();
1696
1697        // Verify the thread has the selected model
1698        agent.read_with(cx, |agent, _| {
1699            let session = agent.sessions.get(&session_id).unwrap();
1700            session.thread.read_with(cx, |thread, _| {
1701                assert_eq!(thread.model().unwrap().id().0, "fake");
1702            });
1703        });
1704
1705        cx.run_until_parked();
1706
1707        // Verify settings file was updated
1708        let settings_content = fs.load(paths::settings_file()).await.unwrap();
1709        let settings_json: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1710
1711        // Check that the agent settings contain the selected model
1712        assert_eq!(
1713            settings_json["agent"]["default_model"]["model"],
1714            json!("fake")
1715        );
1716        assert_eq!(
1717            settings_json["agent"]["default_model"]["provider"],
1718            json!("fake")
1719        );
1720    }
1721
1722    #[gpui::test]
1723    async fn test_save_load_thread(cx: &mut TestAppContext) {
1724        init_test(cx);
1725        let fs = FakeFs::new(cx.executor());
1726        fs.insert_tree(
1727            "/",
1728            json!({
1729                "a": {
1730                    "b.md": "Lorem"
1731                }
1732            }),
1733        )
1734        .await;
1735        let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
1736        let text_thread_store =
1737            cx.new(|cx| assistant_text_thread::TextThreadStore::fake(project.clone(), cx));
1738        let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx));
1739        let agent = NativeAgent::new(
1740            project.clone(),
1741            history_store.clone(),
1742            Templates::new(),
1743            None,
1744            fs.clone(),
1745            &mut cx.to_async(),
1746        )
1747        .await
1748        .unwrap();
1749        let connection = Rc::new(NativeAgentConnection(agent.clone()));
1750
1751        let acp_thread = cx
1752            .update(|cx| {
1753                connection
1754                    .clone()
1755                    .new_thread(project.clone(), Path::new(""), cx)
1756            })
1757            .await
1758            .unwrap();
1759        let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
1760        let thread = agent.read_with(cx, |agent, _| {
1761            agent.sessions.get(&session_id).unwrap().thread.clone()
1762        });
1763
1764        // Ensure empty threads are not saved, even if they get mutated.
1765        let model = Arc::new(FakeLanguageModel::default());
1766        let summary_model = Arc::new(FakeLanguageModel::default());
1767        thread.update(cx, |thread, cx| {
1768            thread.set_model(model.clone(), cx);
1769            thread.set_summarization_model(Some(summary_model.clone()), cx);
1770        });
1771        cx.run_until_parked();
1772        assert_eq!(history_entries(&history_store, cx), vec![]);
1773
1774        let send = acp_thread.update(cx, |thread, cx| {
1775            thread.send(
1776                vec![
1777                    "What does ".into(),
1778                    acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
1779                        "b.md",
1780                        MentionUri::File {
1781                            abs_path: path!("/a/b.md").into(),
1782                        }
1783                        .to_uri()
1784                        .to_string(),
1785                    )),
1786                    " mean?".into(),
1787                ],
1788                cx,
1789            )
1790        });
1791        let send = cx.foreground_executor().spawn(send);
1792        cx.run_until_parked();
1793
1794        model.send_last_completion_stream_text_chunk("Lorem.");
1795        model.end_last_completion_stream();
1796        cx.run_until_parked();
1797        summary_model
1798            .send_last_completion_stream_text_chunk(&format!("Explaining {}", path!("/a/b.md")));
1799        summary_model.end_last_completion_stream();
1800
1801        send.await.unwrap();
1802        let uri = MentionUri::File {
1803            abs_path: path!("/a/b.md").into(),
1804        }
1805        .to_uri();
1806        acp_thread.read_with(cx, |thread, cx| {
1807            assert_eq!(
1808                thread.to_markdown(cx),
1809                formatdoc! {"
1810                    ## User
1811
1812                    What does [@b.md]({uri}) mean?
1813
1814                    ## Assistant
1815
1816                    Lorem.
1817
1818                "}
1819            )
1820        });
1821
1822        cx.run_until_parked();
1823
1824        // Drop the ACP thread, which should cause the session to be dropped as well.
1825        cx.update(|_| {
1826            drop(thread);
1827            drop(acp_thread);
1828        });
1829        agent.read_with(cx, |agent, _| {
1830            assert_eq!(agent.sessions.keys().cloned().collect::<Vec<_>>(), []);
1831        });
1832
1833        // Ensure the thread can be reloaded from disk.
1834        assert_eq!(
1835            history_entries(&history_store, cx),
1836            vec![(
1837                HistoryEntryId::AcpThread(session_id.clone()),
1838                format!("Explaining {}", path!("/a/b.md"))
1839            )]
1840        );
1841        let acp_thread = agent
1842            .update(cx, |agent, cx| agent.open_thread(session_id.clone(), cx))
1843            .await
1844            .unwrap();
1845        acp_thread.read_with(cx, |thread, cx| {
1846            assert_eq!(
1847                thread.to_markdown(cx),
1848                formatdoc! {"
1849                    ## User
1850
1851                    What does [@b.md]({uri}) mean?
1852
1853                    ## Assistant
1854
1855                    Lorem.
1856
1857                "}
1858            )
1859        });
1860    }
1861
1862    fn history_entries(
1863        history: &Entity<HistoryStore>,
1864        cx: &mut TestAppContext,
1865    ) -> Vec<(HistoryEntryId, String)> {
1866        history.read_with(cx, |history, _| {
1867            history
1868                .entries()
1869                .map(|e| (e.id(), e.title().to_string()))
1870                .collect::<Vec<_>>()
1871        })
1872    }
1873
1874    fn init_test(cx: &mut TestAppContext) {
1875        env_logger::try_init().ok();
1876        cx.update(|cx| {
1877            let settings_store = SettingsStore::test(cx);
1878            cx.set_global(settings_store);
1879
1880            LanguageModelRegistry::test(cx);
1881        });
1882    }
1883}
1884
1885fn mcp_message_content_to_acp_content_block(
1886    content: context_server::types::MessageContent,
1887) -> acp::ContentBlock {
1888    match content {
1889        context_server::types::MessageContent::Text {
1890            text,
1891            annotations: _,
1892        } => text.into(),
1893        context_server::types::MessageContent::Image {
1894            data,
1895            mime_type,
1896            annotations: _,
1897        } => acp::ContentBlock::Image(acp::ImageContent::new(data, mime_type)),
1898        context_server::types::MessageContent::Audio {
1899            data,
1900            mime_type,
1901            annotations: _,
1902        } => acp::ContentBlock::Audio(acp::AudioContent::new(data, mime_type)),
1903        context_server::types::MessageContent::Resource {
1904            resource,
1905            annotations: _,
1906        } => {
1907            let mut link =
1908                acp::ResourceLink::new(resource.uri.to_string(), resource.uri.to_string());
1909            if let Some(mime_type) = resource.mime_type {
1910                link = link.mime_type(mime_type);
1911            }
1912            acp::ContentBlock::ResourceLink(link)
1913        }
1914    }
1915}