agent.rs

   1use crate::{
   2    ContextServerRegistry, Thread, ThreadEvent, ThreadsDatabase, ToolCallAuthorization,
   3    UserMessageContent, templates::Templates,
   4};
   5use crate::{HistoryStore, TitleUpdated, TokenUsageUpdated};
   6use acp_thread::{AcpThread, AgentModelSelector};
   7use action_log::ActionLog;
   8use agent_client_protocol as acp;
   9use agent_settings::AgentSettings;
  10use anyhow::{Context as _, Result, anyhow};
  11use collections::{HashSet, IndexMap};
  12use fs::Fs;
  13use futures::channel::mpsc;
  14use futures::{StreamExt, future};
  15use gpui::{
  16    App, AppContext, AsyncApp, Context, Entity, SharedString, Subscription, Task, WeakEntity,
  17};
  18use language_model::{LanguageModel, LanguageModelProvider, LanguageModelRegistry};
  19use project::{Project, ProjectItem, ProjectPath, Worktree};
  20use prompt_store::{
  21    ProjectContext, PromptId, PromptStore, RulesFileContext, UserRulesContext, WorktreeContext,
  22};
  23use settings::update_settings_file;
  24use std::any::Any;
  25use std::collections::HashMap;
  26use std::path::Path;
  27use std::rc::Rc;
  28use std::sync::Arc;
  29use util::ResultExt;
  30
  31const RULES_FILE_NAMES: [&str; 9] = [
  32    ".rules",
  33    ".cursorrules",
  34    ".windsurfrules",
  35    ".clinerules",
  36    ".github/copilot-instructions.md",
  37    "CLAUDE.md",
  38    "AGENT.md",
  39    "AGENTS.md",
  40    "GEMINI.md",
  41];
  42
  43pub struct RulesLoadingError {
  44    pub message: SharedString,
  45}
  46
  47/// Holds both the internal Thread and the AcpThread for a session
  48struct Session {
  49    /// The internal thread that processes messages
  50    thread: Entity<Thread>,
  51    /// The ACP thread that handles protocol communication
  52    acp_thread: WeakEntity<acp_thread::AcpThread>,
  53    pending_save: Task<()>,
  54    _subscriptions: Vec<Subscription>,
  55}
  56
  57pub struct LanguageModels {
  58    /// Access language model by ID
  59    models: HashMap<acp_thread::AgentModelId, Arc<dyn LanguageModel>>,
  60    /// Cached list for returning language model information
  61    model_list: acp_thread::AgentModelList,
  62    refresh_models_rx: watch::Receiver<()>,
  63    refresh_models_tx: watch::Sender<()>,
  64    _authenticate_all_providers_task: Task<()>,
  65}
  66
  67impl LanguageModels {
  68    fn new(cx: &mut App) -> Self {
  69        let (refresh_models_tx, refresh_models_rx) = watch::channel(());
  70
  71        let mut this = Self {
  72            models: HashMap::default(),
  73            model_list: acp_thread::AgentModelList::Grouped(IndexMap::default()),
  74            refresh_models_rx,
  75            refresh_models_tx,
  76            _authenticate_all_providers_task: Self::authenticate_all_language_model_providers(cx),
  77        };
  78        this.refresh_list(cx);
  79        this
  80    }
  81
  82    fn refresh_list(&mut self, cx: &App) {
  83        let providers = LanguageModelRegistry::global(cx)
  84            .read(cx)
  85            .providers()
  86            .into_iter()
  87            .filter(|provider| provider.is_authenticated(cx))
  88            .collect::<Vec<_>>();
  89
  90        let mut language_model_list = IndexMap::default();
  91        let mut recommended_models = HashSet::default();
  92
  93        let mut recommended = Vec::new();
  94        for provider in &providers {
  95            for model in provider.recommended_models(cx) {
  96                recommended_models.insert((model.provider_id(), model.id()));
  97                recommended.push(Self::map_language_model_to_info(&model, provider));
  98            }
  99        }
 100        if !recommended.is_empty() {
 101            language_model_list.insert(
 102                acp_thread::AgentModelGroupName("Recommended".into()),
 103                recommended,
 104            );
 105        }
 106
 107        let mut models = HashMap::default();
 108        for provider in providers {
 109            let mut provider_models = Vec::new();
 110            for model in provider.provided_models(cx) {
 111                let model_info = Self::map_language_model_to_info(&model, &provider);
 112                let model_id = model_info.id.clone();
 113                if !recommended_models.contains(&(model.provider_id(), model.id())) {
 114                    provider_models.push(model_info);
 115                }
 116                models.insert(model_id, model);
 117            }
 118            if !provider_models.is_empty() {
 119                language_model_list.insert(
 120                    acp_thread::AgentModelGroupName(provider.name().0.clone()),
 121                    provider_models,
 122                );
 123            }
 124        }
 125
 126        self.models = models;
 127        self.model_list = acp_thread::AgentModelList::Grouped(language_model_list);
 128        self.refresh_models_tx.send(()).ok();
 129    }
 130
 131    fn watch(&self) -> watch::Receiver<()> {
 132        self.refresh_models_rx.clone()
 133    }
 134
 135    pub fn model_from_id(
 136        &self,
 137        model_id: &acp_thread::AgentModelId,
 138    ) -> Option<Arc<dyn LanguageModel>> {
 139        self.models.get(model_id).cloned()
 140    }
 141
 142    fn map_language_model_to_info(
 143        model: &Arc<dyn LanguageModel>,
 144        provider: &Arc<dyn LanguageModelProvider>,
 145    ) -> acp_thread::AgentModelInfo {
 146        acp_thread::AgentModelInfo {
 147            id: Self::model_id(model),
 148            name: model.name().0,
 149            icon: Some(provider.icon()),
 150        }
 151    }
 152
 153    fn model_id(model: &Arc<dyn LanguageModel>) -> acp_thread::AgentModelId {
 154        acp_thread::AgentModelId(format!("{}/{}", model.provider_id().0, model.id().0).into())
 155    }
 156
 157    fn authenticate_all_language_model_providers(cx: &mut App) -> Task<()> {
 158        let authenticate_all_providers = LanguageModelRegistry::global(cx)
 159            .read(cx)
 160            .providers()
 161            .iter()
 162            .map(|provider| (provider.id(), provider.name(), provider.authenticate(cx)))
 163            .collect::<Vec<_>>();
 164
 165        cx.background_spawn(async move {
 166            for (provider_id, provider_name, authenticate_task) in authenticate_all_providers {
 167                if let Err(err) = authenticate_task.await {
 168                    if matches!(err, language_model::AuthenticateError::CredentialsNotFound) {
 169                        // Since we're authenticating these providers in the
 170                        // background for the purposes of populating the
 171                        // language selector, we don't care about providers
 172                        // where the credentials are not found.
 173                    } else {
 174                        // Some providers have noisy failure states that we
 175                        // don't want to spam the logs with every time the
 176                        // language model selector is initialized.
 177                        //
 178                        // Ideally these should have more clear failure modes
 179                        // that we know are safe to ignore here, like what we do
 180                        // with `CredentialsNotFound` above.
 181                        match provider_id.0.as_ref() {
 182                            "lmstudio" | "ollama" => {
 183                                // LM Studio and Ollama both make fetch requests to the local APIs to determine if they are "authenticated".
 184                                //
 185                                // These fail noisily, so we don't log them.
 186                            }
 187                            "copilot_chat" => {
 188                                // Copilot Chat returns an error if Copilot is not enabled, so we don't log those errors.
 189                            }
 190                            _ => {
 191                                log::error!(
 192                                    "Failed to authenticate provider: {}: {err}",
 193                                    provider_name.0
 194                                );
 195                            }
 196                        }
 197                    }
 198                }
 199            }
 200        })
 201    }
 202}
 203
 204pub struct NativeAgent {
 205    /// Session ID -> Session mapping
 206    sessions: HashMap<acp::SessionId, Session>,
 207    history: Entity<HistoryStore>,
 208    /// Shared project context for all threads
 209    project_context: Entity<ProjectContext>,
 210    project_context_needs_refresh: watch::Sender<()>,
 211    _maintain_project_context: Task<Result<()>>,
 212    context_server_registry: Entity<ContextServerRegistry>,
 213    /// Shared templates for all threads
 214    templates: Arc<Templates>,
 215    /// Cached model information
 216    models: LanguageModels,
 217    project: Entity<Project>,
 218    prompt_store: Option<Entity<PromptStore>>,
 219    fs: Arc<dyn Fs>,
 220    _subscriptions: Vec<Subscription>,
 221}
 222
 223impl NativeAgent {
 224    pub async fn new(
 225        project: Entity<Project>,
 226        history: Entity<HistoryStore>,
 227        templates: Arc<Templates>,
 228        prompt_store: Option<Entity<PromptStore>>,
 229        fs: Arc<dyn Fs>,
 230        cx: &mut AsyncApp,
 231    ) -> Result<Entity<NativeAgent>> {
 232        log::debug!("Creating new NativeAgent");
 233
 234        let project_context = cx
 235            .update(|cx| Self::build_project_context(&project, prompt_store.as_ref(), cx))?
 236            .await;
 237
 238        cx.new(|cx| {
 239            let mut subscriptions = vec![
 240                cx.subscribe(&project, Self::handle_project_event),
 241                cx.subscribe(
 242                    &LanguageModelRegistry::global(cx),
 243                    Self::handle_models_updated_event,
 244                ),
 245            ];
 246            if let Some(prompt_store) = prompt_store.as_ref() {
 247                subscriptions.push(cx.subscribe(prompt_store, Self::handle_prompts_updated_event))
 248            }
 249
 250            let (project_context_needs_refresh_tx, project_context_needs_refresh_rx) =
 251                watch::channel(());
 252            Self {
 253                sessions: HashMap::new(),
 254                history,
 255                project_context: cx.new(|_| project_context),
 256                project_context_needs_refresh: project_context_needs_refresh_tx,
 257                _maintain_project_context: cx.spawn(async move |this, cx| {
 258                    Self::maintain_project_context(this, project_context_needs_refresh_rx, cx).await
 259                }),
 260                context_server_registry: cx.new(|cx| {
 261                    ContextServerRegistry::new(project.read(cx).context_server_store(), cx)
 262                }),
 263                templates,
 264                models: LanguageModels::new(cx),
 265                project,
 266                prompt_store,
 267                fs,
 268                _subscriptions: subscriptions,
 269            }
 270        })
 271    }
 272
 273    fn register_session(
 274        &mut self,
 275        thread_handle: Entity<Thread>,
 276        cx: &mut Context<Self>,
 277    ) -> Entity<AcpThread> {
 278        let connection = Rc::new(NativeAgentConnection(cx.entity()));
 279        let registry = LanguageModelRegistry::read_global(cx);
 280        let summarization_model = registry.thread_summary_model().map(|c| c.model);
 281
 282        thread_handle.update(cx, |thread, cx| {
 283            thread.set_summarization_model(summarization_model, cx);
 284            thread.add_default_tools(cx)
 285        });
 286
 287        let thread = thread_handle.read(cx);
 288        let session_id = thread.id().clone();
 289        let title = thread.title();
 290        let project = thread.project.clone();
 291        let action_log = thread.action_log.clone();
 292        let prompt_capabilities_rx = thread.prompt_capabilities_rx.clone();
 293        let acp_thread = cx.new(|cx| {
 294            acp_thread::AcpThread::new(
 295                title,
 296                connection,
 297                project.clone(),
 298                action_log.clone(),
 299                session_id.clone(),
 300                prompt_capabilities_rx,
 301                cx,
 302            )
 303        });
 304        let subscriptions = vec![
 305            cx.observe_release(&acp_thread, |this, acp_thread, _cx| {
 306                this.sessions.remove(acp_thread.session_id());
 307            }),
 308            cx.subscribe(&thread_handle, Self::handle_thread_title_updated),
 309            cx.subscribe(&thread_handle, Self::handle_thread_token_usage_updated),
 310            cx.observe(&thread_handle, move |this, thread, cx| {
 311                this.save_thread(thread, cx)
 312            }),
 313        ];
 314
 315        self.sessions.insert(
 316            session_id,
 317            Session {
 318                thread: thread_handle,
 319                acp_thread: acp_thread.downgrade(),
 320                _subscriptions: subscriptions,
 321                pending_save: Task::ready(()),
 322            },
 323        );
 324        acp_thread
 325    }
 326
 327    pub fn models(&self) -> &LanguageModels {
 328        &self.models
 329    }
 330
 331    async fn maintain_project_context(
 332        this: WeakEntity<Self>,
 333        mut needs_refresh: watch::Receiver<()>,
 334        cx: &mut AsyncApp,
 335    ) -> Result<()> {
 336        while needs_refresh.changed().await.is_ok() {
 337            let project_context = this
 338                .update(cx, |this, cx| {
 339                    Self::build_project_context(&this.project, this.prompt_store.as_ref(), cx)
 340                })?
 341                .await;
 342            this.update(cx, |this, cx| {
 343                this.project_context = cx.new(|_| project_context);
 344            })?;
 345        }
 346
 347        Ok(())
 348    }
 349
 350    fn build_project_context(
 351        project: &Entity<Project>,
 352        prompt_store: Option<&Entity<PromptStore>>,
 353        cx: &mut App,
 354    ) -> Task<ProjectContext> {
 355        let worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
 356        let worktree_tasks = worktrees
 357            .into_iter()
 358            .map(|worktree| {
 359                Self::load_worktree_info_for_system_prompt(worktree, project.clone(), cx)
 360            })
 361            .collect::<Vec<_>>();
 362        let default_user_rules_task = if let Some(prompt_store) = prompt_store.as_ref() {
 363            prompt_store.read_with(cx, |prompt_store, cx| {
 364                let prompts = prompt_store.default_prompt_metadata();
 365                let load_tasks = prompts.into_iter().map(|prompt_metadata| {
 366                    let contents = prompt_store.load(prompt_metadata.id, cx);
 367                    async move { (contents.await, prompt_metadata) }
 368                });
 369                cx.background_spawn(future::join_all(load_tasks))
 370            })
 371        } else {
 372            Task::ready(vec![])
 373        };
 374
 375        cx.spawn(async move |_cx| {
 376            let (worktrees, default_user_rules) =
 377                future::join(future::join_all(worktree_tasks), default_user_rules_task).await;
 378
 379            let worktrees = worktrees
 380                .into_iter()
 381                .map(|(worktree, _rules_error)| {
 382                    // TODO: show error message
 383                    // if let Some(rules_error) = rules_error {
 384                    //     this.update(cx, |_, cx| cx.emit(rules_error)).ok();
 385                    // }
 386                    worktree
 387                })
 388                .collect::<Vec<_>>();
 389
 390            let default_user_rules = default_user_rules
 391                .into_iter()
 392                .flat_map(|(contents, prompt_metadata)| match contents {
 393                    Ok(contents) => Some(UserRulesContext {
 394                        uuid: match prompt_metadata.id {
 395                            PromptId::User { uuid } => uuid,
 396                            PromptId::EditWorkflow => return None,
 397                        },
 398                        title: prompt_metadata.title.map(|title| title.to_string()),
 399                        contents,
 400                    }),
 401                    Err(_err) => {
 402                        // TODO: show error message
 403                        // this.update(cx, |_, cx| {
 404                        //     cx.emit(RulesLoadingError {
 405                        //         message: format!("{err:?}").into(),
 406                        //     });
 407                        // })
 408                        // .ok();
 409                        None
 410                    }
 411                })
 412                .collect::<Vec<_>>();
 413
 414            ProjectContext::new(worktrees, default_user_rules)
 415        })
 416    }
 417
 418    fn load_worktree_info_for_system_prompt(
 419        worktree: Entity<Worktree>,
 420        project: Entity<Project>,
 421        cx: &mut App,
 422    ) -> Task<(WorktreeContext, Option<RulesLoadingError>)> {
 423        let tree = worktree.read(cx);
 424        let root_name = tree.root_name().into();
 425        let abs_path = tree.abs_path();
 426
 427        let mut context = WorktreeContext {
 428            root_name,
 429            abs_path,
 430            rules_file: None,
 431        };
 432
 433        let rules_task = Self::load_worktree_rules_file(worktree, project, cx);
 434        let Some(rules_task) = rules_task else {
 435            return Task::ready((context, None));
 436        };
 437
 438        cx.spawn(async move |_| {
 439            let (rules_file, rules_file_error) = match rules_task.await {
 440                Ok(rules_file) => (Some(rules_file), None),
 441                Err(err) => (
 442                    None,
 443                    Some(RulesLoadingError {
 444                        message: format!("{err}").into(),
 445                    }),
 446                ),
 447            };
 448            context.rules_file = rules_file;
 449            (context, rules_file_error)
 450        })
 451    }
 452
 453    fn load_worktree_rules_file(
 454        worktree: Entity<Worktree>,
 455        project: Entity<Project>,
 456        cx: &mut App,
 457    ) -> Option<Task<Result<RulesFileContext>>> {
 458        let worktree = worktree.read(cx);
 459        let worktree_id = worktree.id();
 460        let selected_rules_file = RULES_FILE_NAMES
 461            .into_iter()
 462            .filter_map(|name| {
 463                worktree
 464                    .entry_for_path(name)
 465                    .filter(|entry| entry.is_file())
 466                    .map(|entry| entry.path.clone())
 467            })
 468            .next();
 469
 470        // Note that Cline supports `.clinerules` being a directory, but that is not currently
 471        // supported. This doesn't seem to occur often in GitHub repositories.
 472        selected_rules_file.map(|path_in_worktree| {
 473            let project_path = ProjectPath {
 474                worktree_id,
 475                path: path_in_worktree.clone(),
 476            };
 477            let buffer_task =
 478                project.update(cx, |project, cx| project.open_buffer(project_path, cx));
 479            let rope_task = cx.spawn(async move |cx| {
 480                buffer_task.await?.read_with(cx, |buffer, cx| {
 481                    let project_entry_id = buffer.entry_id(cx).context("buffer has no file")?;
 482                    anyhow::Ok((project_entry_id, buffer.as_rope().clone()))
 483                })?
 484            });
 485            // Build a string from the rope on a background thread.
 486            cx.background_spawn(async move {
 487                let (project_entry_id, rope) = rope_task.await?;
 488                anyhow::Ok(RulesFileContext {
 489                    path_in_worktree,
 490                    text: rope.to_string().trim().to_string(),
 491                    project_entry_id: project_entry_id.to_usize(),
 492                })
 493            })
 494        })
 495    }
 496
 497    fn handle_thread_title_updated(
 498        &mut self,
 499        thread: Entity<Thread>,
 500        _: &TitleUpdated,
 501        cx: &mut Context<Self>,
 502    ) {
 503        let session_id = thread.read(cx).id();
 504        let Some(session) = self.sessions.get(session_id) else {
 505            return;
 506        };
 507        let thread = thread.downgrade();
 508        let acp_thread = session.acp_thread.clone();
 509        cx.spawn(async move |_, cx| {
 510            let title = thread.read_with(cx, |thread, _| thread.title())?;
 511            let task = acp_thread.update(cx, |acp_thread, cx| acp_thread.set_title(title, cx))?;
 512            task.await
 513        })
 514        .detach_and_log_err(cx);
 515    }
 516
 517    fn handle_thread_token_usage_updated(
 518        &mut self,
 519        thread: Entity<Thread>,
 520        usage: &TokenUsageUpdated,
 521        cx: &mut Context<Self>,
 522    ) {
 523        let Some(session) = self.sessions.get(thread.read(cx).id()) else {
 524            return;
 525        };
 526        session
 527            .acp_thread
 528            .update(cx, |acp_thread, cx| {
 529                acp_thread.update_token_usage(usage.0.clone(), cx);
 530            })
 531            .ok();
 532    }
 533
 534    fn handle_project_event(
 535        &mut self,
 536        _project: Entity<Project>,
 537        event: &project::Event,
 538        _cx: &mut Context<Self>,
 539    ) {
 540        match event {
 541            project::Event::WorktreeAdded(_) | project::Event::WorktreeRemoved(_) => {
 542                self.project_context_needs_refresh.send(()).ok();
 543            }
 544            project::Event::WorktreeUpdatedEntries(_, items) => {
 545                if items.iter().any(|(path, _, _)| {
 546                    RULES_FILE_NAMES
 547                        .iter()
 548                        .any(|name| path.as_ref() == Path::new(name))
 549                }) {
 550                    self.project_context_needs_refresh.send(()).ok();
 551                }
 552            }
 553            _ => {}
 554        }
 555    }
 556
 557    fn handle_prompts_updated_event(
 558        &mut self,
 559        _prompt_store: Entity<PromptStore>,
 560        _event: &prompt_store::PromptsUpdatedEvent,
 561        _cx: &mut Context<Self>,
 562    ) {
 563        self.project_context_needs_refresh.send(()).ok();
 564    }
 565
 566    fn handle_models_updated_event(
 567        &mut self,
 568        _registry: Entity<LanguageModelRegistry>,
 569        _event: &language_model::Event,
 570        cx: &mut Context<Self>,
 571    ) {
 572        self.models.refresh_list(cx);
 573
 574        let registry = LanguageModelRegistry::read_global(cx);
 575        let default_model = registry.default_model().map(|m| m.model);
 576        let summarization_model = registry.thread_summary_model().map(|m| m.model);
 577
 578        for session in self.sessions.values_mut() {
 579            session.thread.update(cx, |thread, cx| {
 580                if thread.model().is_none()
 581                    && let Some(model) = default_model.clone()
 582                {
 583                    thread.set_model(model, cx);
 584                    cx.notify();
 585                }
 586                thread.set_summarization_model(summarization_model.clone(), cx);
 587            });
 588        }
 589    }
 590
 591    pub fn open_thread(
 592        &mut self,
 593        id: acp::SessionId,
 594        cx: &mut Context<Self>,
 595    ) -> Task<Result<Entity<AcpThread>>> {
 596        let database_future = ThreadsDatabase::connect(cx);
 597        cx.spawn(async move |this, cx| {
 598            let database = database_future.await.map_err(|err| anyhow!(err))?;
 599            let db_thread = database
 600                .load_thread(id.clone())
 601                .await?
 602                .with_context(|| format!("no thread found with ID: {id:?}"))?;
 603
 604            let thread = this.update(cx, |this, cx| {
 605                let action_log = cx.new(|_cx| ActionLog::new(this.project.clone()));
 606                cx.new(|cx| {
 607                    Thread::from_db(
 608                        id.clone(),
 609                        db_thread,
 610                        this.project.clone(),
 611                        this.project_context.clone(),
 612                        this.context_server_registry.clone(),
 613                        action_log.clone(),
 614                        this.templates.clone(),
 615                        cx,
 616                    )
 617                })
 618            })?;
 619            let acp_thread =
 620                this.update(cx, |this, cx| this.register_session(thread.clone(), cx))?;
 621            let events = thread.update(cx, |thread, cx| thread.replay(cx))?;
 622            cx.update(|cx| {
 623                NativeAgentConnection::handle_thread_events(events, acp_thread.downgrade(), cx)
 624            })?
 625            .await?;
 626            Ok(acp_thread)
 627        })
 628    }
 629
 630    pub fn thread_summary(
 631        &mut self,
 632        id: acp::SessionId,
 633        cx: &mut Context<Self>,
 634    ) -> Task<Result<SharedString>> {
 635        let thread = self.open_thread(id.clone(), cx);
 636        cx.spawn(async move |this, cx| {
 637            let acp_thread = thread.await?;
 638            let result = this
 639                .update(cx, |this, cx| {
 640                    this.sessions
 641                        .get(&id)
 642                        .unwrap()
 643                        .thread
 644                        .update(cx, |thread, cx| thread.summary(cx))
 645                })?
 646                .await?;
 647            drop(acp_thread);
 648            Ok(result)
 649        })
 650    }
 651
 652    fn save_thread(&mut self, thread: Entity<Thread>, cx: &mut Context<Self>) {
 653        if thread.read(cx).is_empty() {
 654            return;
 655        }
 656
 657        let database_future = ThreadsDatabase::connect(cx);
 658        let (id, db_thread) =
 659            thread.update(cx, |thread, cx| (thread.id().clone(), thread.to_db(cx)));
 660        let Some(session) = self.sessions.get_mut(&id) else {
 661            return;
 662        };
 663        let history = self.history.clone();
 664        session.pending_save = cx.spawn(async move |_, cx| {
 665            let Some(database) = database_future.await.map_err(|err| anyhow!(err)).log_err() else {
 666                return;
 667            };
 668            let db_thread = db_thread.await;
 669            database.save_thread(id, db_thread).await.log_err();
 670            history.update(cx, |history, cx| history.reload(cx)).ok();
 671        });
 672    }
 673}
 674
 675/// Wrapper struct that implements the AgentConnection trait
 676#[derive(Clone)]
 677pub struct NativeAgentConnection(pub Entity<NativeAgent>);
 678
 679impl NativeAgentConnection {
 680    pub fn thread(&self, session_id: &acp::SessionId, cx: &App) -> Option<Entity<Thread>> {
 681        self.0
 682            .read(cx)
 683            .sessions
 684            .get(session_id)
 685            .map(|session| session.thread.clone())
 686    }
 687
 688    fn run_turn(
 689        &self,
 690        session_id: acp::SessionId,
 691        cx: &mut App,
 692        f: impl 'static
 693        + FnOnce(Entity<Thread>, &mut App) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>,
 694    ) -> Task<Result<acp::PromptResponse>> {
 695        let Some((thread, acp_thread)) = self.0.update(cx, |agent, _cx| {
 696            agent
 697                .sessions
 698                .get_mut(&session_id)
 699                .map(|s| (s.thread.clone(), s.acp_thread.clone()))
 700        }) else {
 701            return Task::ready(Err(anyhow!("Session not found")));
 702        };
 703        log::debug!("Found session for: {}", session_id);
 704
 705        let response_stream = match f(thread, cx) {
 706            Ok(stream) => stream,
 707            Err(err) => return Task::ready(Err(err)),
 708        };
 709        Self::handle_thread_events(response_stream, acp_thread, cx)
 710    }
 711
 712    fn handle_thread_events(
 713        mut events: mpsc::UnboundedReceiver<Result<ThreadEvent>>,
 714        acp_thread: WeakEntity<AcpThread>,
 715        cx: &App,
 716    ) -> Task<Result<acp::PromptResponse>> {
 717        cx.spawn(async move |cx| {
 718            // Handle response stream and forward to session.acp_thread
 719            while let Some(result) = events.next().await {
 720                match result {
 721                    Ok(event) => {
 722                        log::trace!("Received completion event: {:?}", event);
 723
 724                        match event {
 725                            ThreadEvent::UserMessage(message) => {
 726                                acp_thread.update(cx, |thread, cx| {
 727                                    for content in message.content {
 728                                        thread.push_user_content_block(
 729                                            Some(message.id.clone()),
 730                                            content.into(),
 731                                            cx,
 732                                        );
 733                                    }
 734                                })?;
 735                            }
 736                            ThreadEvent::AgentText(text) => {
 737                                acp_thread.update(cx, |thread, cx| {
 738                                    thread.push_assistant_content_block(
 739                                        acp::ContentBlock::Text(acp::TextContent {
 740                                            text,
 741                                            annotations: None,
 742                                        }),
 743                                        false,
 744                                        cx,
 745                                    )
 746                                })?;
 747                            }
 748                            ThreadEvent::AgentThinking(text) => {
 749                                acp_thread.update(cx, |thread, cx| {
 750                                    thread.push_assistant_content_block(
 751                                        acp::ContentBlock::Text(acp::TextContent {
 752                                            text,
 753                                            annotations: None,
 754                                        }),
 755                                        true,
 756                                        cx,
 757                                    )
 758                                })?;
 759                            }
 760                            ThreadEvent::ToolCallAuthorization(ToolCallAuthorization {
 761                                tool_call,
 762                                options,
 763                                response,
 764                            }) => {
 765                                let recv = acp_thread.update(cx, |thread, cx| {
 766                                    thread.request_tool_call_authorization(tool_call, options, cx)
 767                                })?;
 768                                cx.background_spawn(async move {
 769                                    if let Some(recv) = recv.log_err()
 770                                        && let Some(option) = recv
 771                                            .await
 772                                            .context("authorization sender was dropped")
 773                                            .log_err()
 774                                    {
 775                                        response
 776                                            .send(option)
 777                                            .map(|_| anyhow!("authorization receiver was dropped"))
 778                                            .log_err();
 779                                    }
 780                                })
 781                                .detach();
 782                            }
 783                            ThreadEvent::ToolCall(tool_call) => {
 784                                acp_thread.update(cx, |thread, cx| {
 785                                    thread.upsert_tool_call(tool_call, cx)
 786                                })??;
 787                            }
 788                            ThreadEvent::ToolCallUpdate(update) => {
 789                                acp_thread.update(cx, |thread, cx| {
 790                                    thread.update_tool_call(update, cx)
 791                                })??;
 792                            }
 793                            ThreadEvent::Retry(status) => {
 794                                acp_thread.update(cx, |thread, cx| {
 795                                    thread.update_retry_status(status, cx)
 796                                })?;
 797                            }
 798                            ThreadEvent::Stop(stop_reason) => {
 799                                log::debug!("Assistant message complete: {:?}", stop_reason);
 800                                return Ok(acp::PromptResponse { stop_reason });
 801                            }
 802                        }
 803                    }
 804                    Err(e) => {
 805                        log::error!("Error in model response stream: {:?}", e);
 806                        return Err(e);
 807                    }
 808                }
 809            }
 810
 811            log::debug!("Response stream completed");
 812            anyhow::Ok(acp::PromptResponse {
 813                stop_reason: acp::StopReason::EndTurn,
 814            })
 815        })
 816    }
 817}
 818
 819impl AgentModelSelector for NativeAgentConnection {
 820    fn list_models(&self, cx: &mut App) -> Task<Result<acp_thread::AgentModelList>> {
 821        log::debug!("NativeAgentConnection::list_models called");
 822        let list = self.0.read(cx).models.model_list.clone();
 823        Task::ready(if list.is_empty() {
 824            Err(anyhow::anyhow!("No models available"))
 825        } else {
 826            Ok(list)
 827        })
 828    }
 829
 830    fn select_model(
 831        &self,
 832        session_id: acp::SessionId,
 833        model_id: acp_thread::AgentModelId,
 834        cx: &mut App,
 835    ) -> Task<Result<()>> {
 836        log::debug!("Setting model for session {}: {}", session_id, model_id);
 837        let Some(thread) = self
 838            .0
 839            .read(cx)
 840            .sessions
 841            .get(&session_id)
 842            .map(|session| session.thread.clone())
 843        else {
 844            return Task::ready(Err(anyhow!("Session not found")));
 845        };
 846
 847        let Some(model) = self.0.read(cx).models.model_from_id(&model_id) else {
 848            return Task::ready(Err(anyhow!("Invalid model ID {}", model_id)));
 849        };
 850
 851        thread.update(cx, |thread, cx| {
 852            thread.set_model(model.clone(), cx);
 853        });
 854
 855        update_settings_file::<AgentSettings>(
 856            self.0.read(cx).fs.clone(),
 857            cx,
 858            move |settings, _cx| {
 859                settings.set_model(model);
 860            },
 861        );
 862
 863        Task::ready(Ok(()))
 864    }
 865
 866    fn selected_model(
 867        &self,
 868        session_id: &acp::SessionId,
 869        cx: &mut App,
 870    ) -> Task<Result<acp_thread::AgentModelInfo>> {
 871        let session_id = session_id.clone();
 872
 873        let Some(thread) = self
 874            .0
 875            .read(cx)
 876            .sessions
 877            .get(&session_id)
 878            .map(|session| session.thread.clone())
 879        else {
 880            return Task::ready(Err(anyhow!("Session not found")));
 881        };
 882        let Some(model) = thread.read(cx).model() else {
 883            return Task::ready(Err(anyhow!("Model not found")));
 884        };
 885        let Some(provider) = LanguageModelRegistry::read_global(cx).provider(&model.provider_id())
 886        else {
 887            return Task::ready(Err(anyhow!("Provider not found")));
 888        };
 889        Task::ready(Ok(LanguageModels::map_language_model_to_info(
 890            model, &provider,
 891        )))
 892    }
 893
 894    fn watch(&self, cx: &mut App) -> watch::Receiver<()> {
 895        self.0.read(cx).models.watch()
 896    }
 897}
 898
 899impl acp_thread::AgentConnection for NativeAgentConnection {
 900    fn new_thread(
 901        self: Rc<Self>,
 902        project: Entity<Project>,
 903        cwd: &Path,
 904        cx: &mut App,
 905    ) -> Task<Result<Entity<acp_thread::AcpThread>>> {
 906        let agent = self.0.clone();
 907        log::debug!("Creating new thread for project at: {:?}", cwd);
 908
 909        cx.spawn(async move |cx| {
 910            log::debug!("Starting thread creation in async context");
 911
 912            // Create Thread
 913            let thread = agent.update(
 914                cx,
 915                |agent, cx: &mut gpui::Context<NativeAgent>| -> Result<_> {
 916                    // Fetch default model from registry settings
 917                    let registry = LanguageModelRegistry::read_global(cx);
 918                    // Log available models for debugging
 919                    let available_count = registry.available_models(cx).count();
 920                    log::debug!("Total available models: {}", available_count);
 921
 922                    let default_model = registry.default_model().and_then(|default_model| {
 923                        agent
 924                            .models
 925                            .model_from_id(&LanguageModels::model_id(&default_model.model))
 926                    });
 927                    Ok(cx.new(|cx| {
 928                        Thread::new(
 929                            project.clone(),
 930                            agent.project_context.clone(),
 931                            agent.context_server_registry.clone(),
 932                            agent.templates.clone(),
 933                            default_model,
 934                            cx,
 935                        )
 936                    }))
 937                },
 938            )??;
 939            agent.update(cx, |agent, cx| agent.register_session(thread, cx))
 940        })
 941    }
 942
 943    fn auth_methods(&self) -> &[acp::AuthMethod] {
 944        &[] // No auth for in-process
 945    }
 946
 947    fn authenticate(&self, _method: acp::AuthMethodId, _cx: &mut App) -> Task<Result<()>> {
 948        Task::ready(Ok(()))
 949    }
 950
 951    fn model_selector(&self) -> Option<Rc<dyn AgentModelSelector>> {
 952        Some(Rc::new(self.clone()) as Rc<dyn AgentModelSelector>)
 953    }
 954
 955    fn prompt(
 956        &self,
 957        id: Option<acp_thread::UserMessageId>,
 958        params: acp::PromptRequest,
 959        cx: &mut App,
 960    ) -> Task<Result<acp::PromptResponse>> {
 961        let id = id.expect("UserMessageId is required");
 962        let session_id = params.session_id.clone();
 963        log::info!("Received prompt request for session: {}", session_id);
 964        log::debug!("Prompt blocks count: {}", params.prompt.len());
 965
 966        self.run_turn(session_id, cx, |thread, cx| {
 967            let content: Vec<UserMessageContent> = params
 968                .prompt
 969                .into_iter()
 970                .map(Into::into)
 971                .collect::<Vec<_>>();
 972            log::debug!("Converted prompt to message: {} chars", content.len());
 973            log::debug!("Message id: {:?}", id);
 974            log::debug!("Message content: {:?}", content);
 975
 976            thread.update(cx, |thread, cx| thread.send(id, content, cx))
 977        })
 978    }
 979
 980    fn resume(
 981        &self,
 982        session_id: &acp::SessionId,
 983        _cx: &App,
 984    ) -> Option<Rc<dyn acp_thread::AgentSessionResume>> {
 985        Some(Rc::new(NativeAgentSessionResume {
 986            connection: self.clone(),
 987            session_id: session_id.clone(),
 988        }) as _)
 989    }
 990
 991    fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
 992        log::info!("Cancelling on session: {}", session_id);
 993        self.0.update(cx, |agent, cx| {
 994            if let Some(agent) = agent.sessions.get(session_id) {
 995                agent.thread.update(cx, |thread, cx| thread.cancel(cx));
 996            }
 997        });
 998    }
 999
1000    fn truncate(
1001        &self,
1002        session_id: &agent_client_protocol::SessionId,
1003        cx: &App,
1004    ) -> Option<Rc<dyn acp_thread::AgentSessionTruncate>> {
1005        self.0.read_with(cx, |agent, _cx| {
1006            agent.sessions.get(session_id).map(|session| {
1007                Rc::new(NativeAgentSessionEditor {
1008                    thread: session.thread.clone(),
1009                    acp_thread: session.acp_thread.clone(),
1010                }) as _
1011            })
1012        })
1013    }
1014
1015    fn set_title(
1016        &self,
1017        session_id: &acp::SessionId,
1018        _cx: &App,
1019    ) -> Option<Rc<dyn acp_thread::AgentSessionSetTitle>> {
1020        Some(Rc::new(NativeAgentSessionSetTitle {
1021            connection: self.clone(),
1022            session_id: session_id.clone(),
1023        }) as _)
1024    }
1025
1026    fn telemetry(&self) -> Option<Rc<dyn acp_thread::AgentTelemetry>> {
1027        Some(Rc::new(self.clone()) as Rc<dyn acp_thread::AgentTelemetry>)
1028    }
1029
1030    fn list_commands(&self, session_id: &acp::SessionId, _cx: &mut App) -> Task<Result<acp::ListCommandsResponse>> {
1031        // Native agent doesn't support custom commands yet
1032        let _session_id = session_id.clone();
1033        Task::ready(Ok(acp::ListCommandsResponse {
1034            commands: vec![],
1035        }))
1036    }
1037
1038    fn run_command(&self, _request: acp::RunCommandRequest, _cx: &mut App) -> Task<Result<()>> {
1039        // Native agent doesn't support custom commands yet
1040        Task::ready(Err(anyhow!("Custom commands not supported")))
1041    }
1042
1043    fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
1044        self
1045    }
1046}
1047
1048impl acp_thread::AgentTelemetry for NativeAgentConnection {
1049    fn agent_name(&self) -> String {
1050        "Zed".into()
1051    }
1052
1053    fn thread_data(
1054        &self,
1055        session_id: &acp::SessionId,
1056        cx: &mut App,
1057    ) -> Task<Result<serde_json::Value>> {
1058        let Some(session) = self.0.read(cx).sessions.get(session_id) else {
1059            return Task::ready(Err(anyhow!("Session not found")));
1060        };
1061
1062        let task = session.thread.read(cx).to_db(cx);
1063        cx.background_spawn(async move {
1064            serde_json::to_value(task.await).context("Failed to serialize thread")
1065        })
1066    }
1067}
1068
1069struct NativeAgentSessionEditor {
1070    thread: Entity<Thread>,
1071    acp_thread: WeakEntity<AcpThread>,
1072}
1073
1074impl acp_thread::AgentSessionTruncate for NativeAgentSessionEditor {
1075    fn run(&self, message_id: acp_thread::UserMessageId, cx: &mut App) -> Task<Result<()>> {
1076        match self.thread.update(cx, |thread, cx| {
1077            thread.truncate(message_id.clone(), cx)?;
1078            Ok(thread.latest_token_usage())
1079        }) {
1080            Ok(usage) => {
1081                self.acp_thread
1082                    .update(cx, |thread, cx| {
1083                        thread.update_token_usage(usage, cx);
1084                    })
1085                    .ok();
1086                Task::ready(Ok(()))
1087            }
1088            Err(error) => Task::ready(Err(error)),
1089        }
1090    }
1091}
1092
1093struct NativeAgentSessionResume {
1094    connection: NativeAgentConnection,
1095    session_id: acp::SessionId,
1096}
1097
1098impl acp_thread::AgentSessionResume for NativeAgentSessionResume {
1099    fn run(&self, cx: &mut App) -> Task<Result<acp::PromptResponse>> {
1100        self.connection
1101            .run_turn(self.session_id.clone(), cx, |thread, cx| {
1102                thread.update(cx, |thread, cx| thread.resume(cx))
1103            })
1104    }
1105}
1106
1107struct NativeAgentSessionSetTitle {
1108    connection: NativeAgentConnection,
1109    session_id: acp::SessionId,
1110}
1111
1112impl acp_thread::AgentSessionSetTitle for NativeAgentSessionSetTitle {
1113    fn run(&self, title: SharedString, cx: &mut App) -> Task<Result<()>> {
1114        let Some(session) = self.connection.0.read(cx).sessions.get(&self.session_id) else {
1115            return Task::ready(Err(anyhow!("session not found")));
1116        };
1117        let thread = session.thread.clone();
1118        thread.update(cx, |thread, cx| thread.set_title(title, cx));
1119        Task::ready(Ok(()))
1120    }
1121}
1122
1123#[cfg(test)]
1124mod tests {
1125    use crate::HistoryEntryId;
1126
1127    use super::*;
1128    use acp_thread::{
1129        AgentConnection, AgentModelGroupName, AgentModelId, AgentModelInfo, MentionUri,
1130    };
1131    use fs::FakeFs;
1132    use gpui::TestAppContext;
1133    use indoc::indoc;
1134    use language_model::fake_provider::FakeLanguageModel;
1135    use serde_json::json;
1136    use settings::SettingsStore;
1137    use util::path;
1138
1139    #[gpui::test]
1140    async fn test_maintaining_project_context(cx: &mut TestAppContext) {
1141        init_test(cx);
1142        let fs = FakeFs::new(cx.executor());
1143        fs.insert_tree(
1144            "/",
1145            json!({
1146                "a": {}
1147            }),
1148        )
1149        .await;
1150        let project = Project::test(fs.clone(), [], cx).await;
1151        let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1152        let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1153        let agent = NativeAgent::new(
1154            project.clone(),
1155            history_store,
1156            Templates::new(),
1157            None,
1158            fs.clone(),
1159            &mut cx.to_async(),
1160        )
1161        .await
1162        .unwrap();
1163        agent.read_with(cx, |agent, cx| {
1164            assert_eq!(agent.project_context.read(cx).worktrees, vec![])
1165        });
1166
1167        let worktree = project
1168            .update(cx, |project, cx| project.create_worktree("/a", true, cx))
1169            .await
1170            .unwrap();
1171        cx.run_until_parked();
1172        agent.read_with(cx, |agent, cx| {
1173            assert_eq!(
1174                agent.project_context.read(cx).worktrees,
1175                vec![WorktreeContext {
1176                    root_name: "a".into(),
1177                    abs_path: Path::new("/a").into(),
1178                    rules_file: None
1179                }]
1180            )
1181        });
1182
1183        // Creating `/a/.rules` updates the project context.
1184        fs.insert_file("/a/.rules", Vec::new()).await;
1185        cx.run_until_parked();
1186        agent.read_with(cx, |agent, cx| {
1187            let rules_entry = worktree.read(cx).entry_for_path(".rules").unwrap();
1188            assert_eq!(
1189                agent.project_context.read(cx).worktrees,
1190                vec![WorktreeContext {
1191                    root_name: "a".into(),
1192                    abs_path: Path::new("/a").into(),
1193                    rules_file: Some(RulesFileContext {
1194                        path_in_worktree: Path::new(".rules").into(),
1195                        text: "".into(),
1196                        project_entry_id: rules_entry.id.to_usize()
1197                    })
1198                }]
1199            )
1200        });
1201    }
1202
1203    #[gpui::test]
1204    async fn test_listing_models(cx: &mut TestAppContext) {
1205        init_test(cx);
1206        let fs = FakeFs::new(cx.executor());
1207        fs.insert_tree("/", json!({ "a": {}  })).await;
1208        let project = Project::test(fs.clone(), [], cx).await;
1209        let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1210        let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1211        let connection = NativeAgentConnection(
1212            NativeAgent::new(
1213                project.clone(),
1214                history_store,
1215                Templates::new(),
1216                None,
1217                fs.clone(),
1218                &mut cx.to_async(),
1219            )
1220            .await
1221            .unwrap(),
1222        );
1223
1224        let models = cx.update(|cx| connection.list_models(cx)).await.unwrap();
1225
1226        let acp_thread::AgentModelList::Grouped(models) = models else {
1227            panic!("Unexpected model group");
1228        };
1229        assert_eq!(
1230            models,
1231            IndexMap::from_iter([(
1232                AgentModelGroupName("Fake".into()),
1233                vec![AgentModelInfo {
1234                    id: AgentModelId("fake/fake".into()),
1235                    name: "Fake".into(),
1236                    icon: Some(ui::IconName::ZedAssistant),
1237                }]
1238            )])
1239        );
1240    }
1241
1242    #[gpui::test]
1243    async fn test_model_selection_persists_to_settings(cx: &mut TestAppContext) {
1244        init_test(cx);
1245        let fs = FakeFs::new(cx.executor());
1246        fs.create_dir(paths::settings_file().parent().unwrap())
1247            .await
1248            .unwrap();
1249        fs.insert_file(
1250            paths::settings_file(),
1251            json!({
1252                "agent": {
1253                    "default_model": {
1254                        "provider": "foo",
1255                        "model": "bar"
1256                    }
1257                }
1258            })
1259            .to_string()
1260            .into_bytes(),
1261        )
1262        .await;
1263        let project = Project::test(fs.clone(), [], cx).await;
1264
1265        let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1266        let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1267
1268        // Create the agent and connection
1269        let agent = NativeAgent::new(
1270            project.clone(),
1271            history_store,
1272            Templates::new(),
1273            None,
1274            fs.clone(),
1275            &mut cx.to_async(),
1276        )
1277        .await
1278        .unwrap();
1279        let connection = NativeAgentConnection(agent.clone());
1280
1281        // Create a thread/session
1282        let acp_thread = cx
1283            .update(|cx| {
1284                Rc::new(connection.clone()).new_thread(project.clone(), Path::new("/a"), cx)
1285            })
1286            .await
1287            .unwrap();
1288
1289        let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());
1290
1291        // Select a model
1292        let model_id = AgentModelId("fake/fake".into());
1293        cx.update(|cx| connection.select_model(session_id.clone(), model_id.clone(), cx))
1294            .await
1295            .unwrap();
1296
1297        // Verify the thread has the selected model
1298        agent.read_with(cx, |agent, _| {
1299            let session = agent.sessions.get(&session_id).unwrap();
1300            session.thread.read_with(cx, |thread, _| {
1301                assert_eq!(thread.model().unwrap().id().0, "fake");
1302            });
1303        });
1304
1305        cx.run_until_parked();
1306
1307        // Verify settings file was updated
1308        let settings_content = fs.load(paths::settings_file()).await.unwrap();
1309        let settings_json: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1310
1311        // Check that the agent settings contain the selected model
1312        assert_eq!(
1313            settings_json["agent"]["default_model"]["model"],
1314            json!("fake")
1315        );
1316        assert_eq!(
1317            settings_json["agent"]["default_model"]["provider"],
1318            json!("fake")
1319        );
1320    }
1321
1322    #[gpui::test]
1323    #[cfg_attr(target_os = "windows", ignore)] // TODO: Fix this test on Windows
1324    async fn test_save_load_thread(cx: &mut TestAppContext) {
1325        init_test(cx);
1326        let fs = FakeFs::new(cx.executor());
1327        fs.insert_tree(
1328            "/",
1329            json!({
1330                "a": {
1331                    "b.md": "Lorem"
1332                }
1333            }),
1334        )
1335        .await;
1336        let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
1337        let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1338        let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1339        let agent = NativeAgent::new(
1340            project.clone(),
1341            history_store.clone(),
1342            Templates::new(),
1343            None,
1344            fs.clone(),
1345            &mut cx.to_async(),
1346        )
1347        .await
1348        .unwrap();
1349        let connection = Rc::new(NativeAgentConnection(agent.clone()));
1350
1351        let acp_thread = cx
1352            .update(|cx| {
1353                connection
1354                    .clone()
1355                    .new_thread(project.clone(), Path::new(""), cx)
1356            })
1357            .await
1358            .unwrap();
1359        let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
1360        let thread = agent.read_with(cx, |agent, _| {
1361            agent.sessions.get(&session_id).unwrap().thread.clone()
1362        });
1363
1364        // Ensure empty threads are not saved, even if they get mutated.
1365        let model = Arc::new(FakeLanguageModel::default());
1366        let summary_model = Arc::new(FakeLanguageModel::default());
1367        thread.update(cx, |thread, cx| {
1368            thread.set_model(model.clone(), cx);
1369            thread.set_summarization_model(Some(summary_model.clone()), cx);
1370        });
1371        cx.run_until_parked();
1372        assert_eq!(history_entries(&history_store, cx), vec![]);
1373
1374        let send = acp_thread.update(cx, |thread, cx| {
1375            thread.send(
1376                vec![
1377                    "What does ".into(),
1378                    acp::ContentBlock::ResourceLink(acp::ResourceLink {
1379                        name: "b.md".into(),
1380                        uri: MentionUri::File {
1381                            abs_path: path!("/a/b.md").into(),
1382                        }
1383                        .to_uri()
1384                        .to_string(),
1385                        annotations: None,
1386                        description: None,
1387                        mime_type: None,
1388                        size: None,
1389                        title: None,
1390                    }),
1391                    " mean?".into(),
1392                ],
1393                cx,
1394            )
1395        });
1396        let send = cx.foreground_executor().spawn(send);
1397        cx.run_until_parked();
1398
1399        model.send_last_completion_stream_text_chunk("Lorem.");
1400        model.end_last_completion_stream();
1401        cx.run_until_parked();
1402        summary_model.send_last_completion_stream_text_chunk("Explaining /a/b.md");
1403        summary_model.end_last_completion_stream();
1404
1405        send.await.unwrap();
1406        acp_thread.read_with(cx, |thread, cx| {
1407            assert_eq!(
1408                thread.to_markdown(cx),
1409                indoc! {"
1410                    ## User
1411
1412                    What does [@b.md](file:///a/b.md) mean?
1413
1414                    ## Assistant
1415
1416                    Lorem.
1417
1418                "}
1419            )
1420        });
1421
1422        cx.run_until_parked();
1423
1424        // Drop the ACP thread, which should cause the session to be dropped as well.
1425        cx.update(|_| {
1426            drop(thread);
1427            drop(acp_thread);
1428        });
1429        agent.read_with(cx, |agent, _| {
1430            assert_eq!(agent.sessions.keys().cloned().collect::<Vec<_>>(), []);
1431        });
1432
1433        // Ensure the thread can be reloaded from disk.
1434        assert_eq!(
1435            history_entries(&history_store, cx),
1436            vec![(
1437                HistoryEntryId::AcpThread(session_id.clone()),
1438                "Explaining /a/b.md".into()
1439            )]
1440        );
1441        let acp_thread = agent
1442            .update(cx, |agent, cx| agent.open_thread(session_id.clone(), cx))
1443            .await
1444            .unwrap();
1445        acp_thread.read_with(cx, |thread, cx| {
1446            assert_eq!(
1447                thread.to_markdown(cx),
1448                indoc! {"
1449                    ## User
1450
1451                    What does [@b.md](file:///a/b.md) mean?
1452
1453                    ## Assistant
1454
1455                    Lorem.
1456
1457                "}
1458            )
1459        });
1460    }
1461
1462    fn history_entries(
1463        history: &Entity<HistoryStore>,
1464        cx: &mut TestAppContext,
1465    ) -> Vec<(HistoryEntryId, String)> {
1466        history.read_with(cx, |history, _| {
1467            history
1468                .entries()
1469                .map(|e| (e.id(), e.title().to_string()))
1470                .collect::<Vec<_>>()
1471        })
1472    }
1473
1474    fn init_test(cx: &mut TestAppContext) {
1475        env_logger::try_init().ok();
1476        cx.update(|cx| {
1477            let settings_store = SettingsStore::test(cx);
1478            cx.set_global(settings_store);
1479            Project::init_settings(cx);
1480            agent_settings::init(cx);
1481            language::init(cx);
1482            LanguageModelRegistry::test(cx);
1483        });
1484    }
1485}