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