agent.rs

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