agent.rs

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