agent.rs

   1mod db;
   2mod edit_agent;
   3mod legacy_thread;
   4mod native_agent_server;
   5pub mod outline;
   6mod pattern_extraction;
   7mod templates;
   8#[cfg(test)]
   9mod tests;
  10mod thread;
  11mod thread_store;
  12mod tool_permissions;
  13mod tools;
  14
  15use context_server::ContextServerId;
  16pub use db::*;
  17use itertools::Itertools;
  18pub use native_agent_server::NativeAgentServer;
  19pub use pattern_extraction::*;
  20pub use shell_command_parser::extract_commands;
  21pub use templates::*;
  22pub use thread::*;
  23pub use thread_store::*;
  24pub use tool_permissions::*;
  25pub use tools::*;
  26
  27use acp_thread::{
  28    AcpThread, AgentModelSelector, AgentSessionInfo, AgentSessionList, AgentSessionListRequest,
  29    AgentSessionListResponse, TokenUsageRatio, UserMessageId,
  30};
  31use agent_client_protocol as acp;
  32use anyhow::{Context as _, Result, anyhow};
  33use chrono::{DateTime, Utc};
  34use collections::{HashMap, HashSet, IndexMap};
  35use fs::Fs;
  36use futures::channel::{mpsc, oneshot};
  37use futures::future::Shared;
  38use futures::{FutureExt as _, StreamExt as _, future};
  39use gpui::{
  40    App, AppContext, AsyncApp, Context, Entity, EntityId, SharedString, Subscription, Task,
  41    WeakEntity,
  42};
  43use language_model::{IconOrSvg, LanguageModel, LanguageModelProvider, LanguageModelRegistry};
  44use project::{Project, ProjectItem, ProjectPath, Worktree};
  45use prompt_store::{
  46    ProjectContext, PromptStore, RULES_FILE_NAMES, RulesFileContext, UserRulesContext,
  47    WorktreeContext,
  48};
  49use serde::{Deserialize, Serialize};
  50use settings::{LanguageModelSelection, update_settings_file};
  51use std::any::Any;
  52use std::path::{Path, PathBuf};
  53use std::rc::Rc;
  54use std::sync::Arc;
  55use util::ResultExt;
  56use util::path_list::PathList;
  57use util::rel_path::RelPath;
  58
  59#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  60pub struct ProjectSnapshot {
  61    pub worktree_snapshots: Vec<project::telemetry_snapshot::TelemetryWorktreeSnapshot>,
  62    pub timestamp: DateTime<Utc>,
  63}
  64
  65pub struct RulesLoadingError {
  66    pub message: SharedString,
  67}
  68
  69struct ProjectState {
  70    project: Entity<Project>,
  71    project_context: Entity<ProjectContext>,
  72    project_context_needs_refresh: watch::Sender<()>,
  73    _maintain_project_context: Task<Result<()>>,
  74    context_server_registry: Entity<ContextServerRegistry>,
  75    _subscriptions: Vec<Subscription>,
  76}
  77
  78/// Holds both the internal Thread and the AcpThread for a session
  79struct Session {
  80    /// The internal thread that processes messages
  81    thread: Entity<Thread>,
  82    /// The ACP thread that handles protocol communication
  83    acp_thread: Entity<acp_thread::AcpThread>,
  84    project_id: EntityId,
  85    pending_save: Task<()>,
  86    _subscriptions: Vec<Subscription>,
  87}
  88
  89pub struct LanguageModels {
  90    /// Access language model by ID
  91    models: HashMap<acp::ModelId, Arc<dyn LanguageModel>>,
  92    /// Cached list for returning language model information
  93    model_list: acp_thread::AgentModelList,
  94    refresh_models_rx: watch::Receiver<()>,
  95    refresh_models_tx: watch::Sender<()>,
  96    _authenticate_all_providers_task: Task<()>,
  97}
  98
  99impl LanguageModels {
 100    fn new(cx: &mut App) -> Self {
 101        let (refresh_models_tx, refresh_models_rx) = watch::channel(());
 102
 103        let mut this = Self {
 104            models: HashMap::default(),
 105            model_list: acp_thread::AgentModelList::Grouped(IndexMap::default()),
 106            refresh_models_rx,
 107            refresh_models_tx,
 108            _authenticate_all_providers_task: Self::authenticate_all_language_model_providers(cx),
 109        };
 110        this.refresh_list(cx);
 111        this
 112    }
 113
 114    fn refresh_list(&mut self, cx: &App) {
 115        let providers = LanguageModelRegistry::global(cx)
 116            .read(cx)
 117            .visible_providers()
 118            .into_iter()
 119            .filter(|provider| provider.is_authenticated(cx))
 120            .collect::<Vec<_>>();
 121
 122        let mut language_model_list = IndexMap::default();
 123        let mut recommended_models = HashSet::default();
 124
 125        let mut recommended = Vec::new();
 126        for provider in &providers {
 127            for model in provider.recommended_models(cx) {
 128                recommended_models.insert((model.provider_id(), model.id()));
 129                recommended.push(Self::map_language_model_to_info(&model, provider));
 130            }
 131        }
 132        if !recommended.is_empty() {
 133            language_model_list.insert(
 134                acp_thread::AgentModelGroupName("Recommended".into()),
 135                recommended,
 136            );
 137        }
 138
 139        let mut models = HashMap::default();
 140        for provider in providers {
 141            let mut provider_models = Vec::new();
 142            for model in provider.provided_models(cx) {
 143                let model_info = Self::map_language_model_to_info(&model, &provider);
 144                let model_id = model_info.id.clone();
 145                provider_models.push(model_info);
 146                models.insert(model_id, model);
 147            }
 148            if !provider_models.is_empty() {
 149                language_model_list.insert(
 150                    acp_thread::AgentModelGroupName(provider.name().0.clone()),
 151                    provider_models,
 152                );
 153            }
 154        }
 155
 156        self.models = models;
 157        self.model_list = acp_thread::AgentModelList::Grouped(language_model_list);
 158        self.refresh_models_tx.send(()).ok();
 159    }
 160
 161    fn watch(&self) -> watch::Receiver<()> {
 162        self.refresh_models_rx.clone()
 163    }
 164
 165    pub fn model_from_id(&self, model_id: &acp::ModelId) -> Option<Arc<dyn LanguageModel>> {
 166        self.models.get(model_id).cloned()
 167    }
 168
 169    fn map_language_model_to_info(
 170        model: &Arc<dyn LanguageModel>,
 171        provider: &Arc<dyn LanguageModelProvider>,
 172    ) -> acp_thread::AgentModelInfo {
 173        acp_thread::AgentModelInfo {
 174            id: Self::model_id(model),
 175            name: model.name().0,
 176            description: None,
 177            icon: Some(match provider.icon() {
 178                IconOrSvg::Svg(path) => acp_thread::AgentModelIcon::Path(path),
 179                IconOrSvg::Icon(name) => acp_thread::AgentModelIcon::Named(name),
 180            }),
 181            is_latest: model.is_latest(),
 182            cost: model.model_cost_info().map(|cost| cost.to_shared_string()),
 183        }
 184    }
 185
 186    fn model_id(model: &Arc<dyn LanguageModel>) -> acp::ModelId {
 187        acp::ModelId::new(format!("{}/{}", model.provider_id().0, model.id().0))
 188    }
 189
 190    fn authenticate_all_language_model_providers(cx: &mut App) -> Task<()> {
 191        let authenticate_all_providers = LanguageModelRegistry::global(cx)
 192            .read(cx)
 193            .visible_providers()
 194            .iter()
 195            .map(|provider| (provider.id(), provider.name(), provider.authenticate(cx)))
 196            .collect::<Vec<_>>();
 197
 198        cx.background_spawn(async move {
 199            for (provider_id, provider_name, authenticate_task) in authenticate_all_providers {
 200                if let Err(err) = authenticate_task.await {
 201                    match err {
 202                        language_model::AuthenticateError::CredentialsNotFound => {
 203                            // Since we're authenticating these providers in the
 204                            // background for the purposes of populating the
 205                            // language selector, we don't care about providers
 206                            // where the credentials are not found.
 207                        }
 208                        language_model::AuthenticateError::ConnectionRefused => {
 209                            // Not logging connection refused errors as they are mostly from LM Studio's noisy auth failures.
 210                            // LM Studio only has one auth method (endpoint call) which fails for users who haven't enabled it.
 211                            // TODO: Better manage LM Studio auth logic to avoid these noisy failures.
 212                        }
 213                        _ => {
 214                            // Some providers have noisy failure states that we
 215                            // don't want to spam the logs with every time the
 216                            // language model selector is initialized.
 217                            //
 218                            // Ideally these should have more clear failure modes
 219                            // that we know are safe to ignore here, like what we do
 220                            // with `CredentialsNotFound` above.
 221                            match provider_id.0.as_ref() {
 222                                "lmstudio" | "ollama" => {
 223                                    // LM Studio and Ollama both make fetch requests to the local APIs to determine if they are "authenticated".
 224                                    //
 225                                    // These fail noisily, so we don't log them.
 226                                }
 227                                "copilot_chat" => {
 228                                    // Copilot Chat returns an error if Copilot is not enabled, so we don't log those errors.
 229                                }
 230                                _ => {
 231                                    log::error!(
 232                                        "Failed to authenticate provider: {}: {err:#}",
 233                                        provider_name.0
 234                                    );
 235                                }
 236                            }
 237                        }
 238                    }
 239                }
 240            }
 241        })
 242    }
 243}
 244
 245pub struct NativeAgent {
 246    /// Session ID -> Session mapping
 247    sessions: HashMap<acp::SessionId, Session>,
 248    thread_store: Entity<ThreadStore>,
 249    /// Project-specific state keyed by project EntityId
 250    projects: HashMap<EntityId, ProjectState>,
 251    /// Shared templates for all threads
 252    templates: Arc<Templates>,
 253    /// Cached model information
 254    models: LanguageModels,
 255    prompt_store: Option<Entity<PromptStore>>,
 256    fs: Arc<dyn Fs>,
 257    _subscriptions: Vec<Subscription>,
 258}
 259
 260impl NativeAgent {
 261    pub fn new(
 262        thread_store: Entity<ThreadStore>,
 263        templates: Arc<Templates>,
 264        prompt_store: Option<Entity<PromptStore>>,
 265        fs: Arc<dyn Fs>,
 266        cx: &mut App,
 267    ) -> Entity<NativeAgent> {
 268        log::debug!("Creating new NativeAgent");
 269
 270        cx.new(|cx| {
 271            let mut subscriptions = vec![cx.subscribe(
 272                &LanguageModelRegistry::global(cx),
 273                Self::handle_models_updated_event,
 274            )];
 275            if let Some(prompt_store) = prompt_store.as_ref() {
 276                subscriptions.push(cx.subscribe(prompt_store, Self::handle_prompts_updated_event))
 277            }
 278
 279            Self {
 280                sessions: HashMap::default(),
 281                thread_store,
 282                projects: HashMap::default(),
 283                templates,
 284                models: LanguageModels::new(cx),
 285                prompt_store,
 286                fs,
 287                _subscriptions: subscriptions,
 288            }
 289        })
 290    }
 291
 292    fn new_session(
 293        &mut self,
 294        project: Entity<Project>,
 295        cx: &mut Context<Self>,
 296    ) -> Entity<AcpThread> {
 297        let project_id = self.get_or_create_project_state(&project, cx);
 298        let project_state = &self.projects[&project_id];
 299
 300        let registry = LanguageModelRegistry::read_global(cx);
 301        let available_count = registry.available_models(cx).count();
 302        log::debug!("Total available models: {}", available_count);
 303
 304        let default_model = registry.default_model().and_then(|default_model| {
 305            self.models
 306                .model_from_id(&LanguageModels::model_id(&default_model.model))
 307        });
 308        let thread = cx.new(|cx| {
 309            Thread::new(
 310                project,
 311                project_state.project_context.clone(),
 312                project_state.context_server_registry.clone(),
 313                self.templates.clone(),
 314                default_model,
 315                cx,
 316            )
 317        });
 318
 319        self.register_session(thread, project_id, cx)
 320    }
 321
 322    fn register_session(
 323        &mut self,
 324        thread_handle: Entity<Thread>,
 325        project_id: EntityId,
 326        cx: &mut Context<Self>,
 327    ) -> Entity<AcpThread> {
 328        let connection = Rc::new(NativeAgentConnection(cx.entity()));
 329
 330        let thread = thread_handle.read(cx);
 331        let session_id = thread.id().clone();
 332        let parent_session_id = thread.parent_thread_id();
 333        let title = thread.title();
 334        let draft_prompt = thread.draft_prompt().map(Vec::from);
 335        let scroll_position = thread.ui_scroll_position();
 336        let token_usage = thread.latest_token_usage();
 337        let project = thread.project.clone();
 338        let action_log = thread.action_log.clone();
 339        let prompt_capabilities_rx = thread.prompt_capabilities_rx.clone();
 340        let acp_thread = cx.new(|cx| {
 341            let mut acp_thread = acp_thread::AcpThread::new(
 342                parent_session_id,
 343                title,
 344                None,
 345                connection,
 346                project.clone(),
 347                action_log.clone(),
 348                session_id.clone(),
 349                prompt_capabilities_rx,
 350                cx,
 351            );
 352            acp_thread.set_draft_prompt(draft_prompt);
 353            acp_thread.set_ui_scroll_position(scroll_position);
 354            acp_thread.update_token_usage(token_usage, cx);
 355            acp_thread
 356        });
 357
 358        let registry = LanguageModelRegistry::read_global(cx);
 359        let summarization_model = registry.thread_summary_model().map(|c| c.model);
 360
 361        let weak = cx.weak_entity();
 362        let weak_thread = thread_handle.downgrade();
 363        thread_handle.update(cx, |thread, cx| {
 364            thread.set_summarization_model(summarization_model, cx);
 365            thread.add_default_tools(
 366                Rc::new(NativeThreadEnvironment {
 367                    acp_thread: acp_thread.downgrade(),
 368                    thread: weak_thread,
 369                    agent: weak,
 370                }) as _,
 371                cx,
 372            )
 373        });
 374
 375        let subscriptions = vec![
 376            cx.subscribe(&thread_handle, Self::handle_thread_title_updated),
 377            cx.subscribe(&thread_handle, Self::handle_thread_token_usage_updated),
 378            cx.observe(&thread_handle, move |this, thread, cx| {
 379                this.save_thread(thread, cx)
 380            }),
 381        ];
 382
 383        self.sessions.insert(
 384            session_id,
 385            Session {
 386                thread: thread_handle,
 387                acp_thread: acp_thread.clone(),
 388                project_id,
 389                _subscriptions: subscriptions,
 390                pending_save: Task::ready(()),
 391            },
 392        );
 393
 394        self.update_available_commands_for_project(project_id, cx);
 395
 396        acp_thread
 397    }
 398
 399    pub fn models(&self) -> &LanguageModels {
 400        &self.models
 401    }
 402
 403    fn get_or_create_project_state(
 404        &mut self,
 405        project: &Entity<Project>,
 406        cx: &mut Context<Self>,
 407    ) -> EntityId {
 408        let project_id = project.entity_id();
 409        if self.projects.contains_key(&project_id) {
 410            return project_id;
 411        }
 412
 413        let project_context = cx.new(|_| ProjectContext::new(vec![], vec![]));
 414        self.register_project_with_initial_context(project.clone(), project_context, cx);
 415        if let Some(state) = self.projects.get_mut(&project_id) {
 416            state.project_context_needs_refresh.send(()).ok();
 417        }
 418        project_id
 419    }
 420
 421    fn register_project_with_initial_context(
 422        &mut self,
 423        project: Entity<Project>,
 424        project_context: Entity<ProjectContext>,
 425        cx: &mut Context<Self>,
 426    ) {
 427        let project_id = project.entity_id();
 428
 429        let context_server_store = project.read(cx).context_server_store();
 430        let context_server_registry =
 431            cx.new(|cx| ContextServerRegistry::new(context_server_store.clone(), cx));
 432
 433        let subscriptions = vec![
 434            cx.subscribe(&project, Self::handle_project_event),
 435            cx.subscribe(
 436                &context_server_store,
 437                Self::handle_context_server_store_updated,
 438            ),
 439            cx.subscribe(
 440                &context_server_registry,
 441                Self::handle_context_server_registry_event,
 442            ),
 443        ];
 444
 445        let (project_context_needs_refresh_tx, project_context_needs_refresh_rx) =
 446            watch::channel(());
 447
 448        self.projects.insert(
 449            project_id,
 450            ProjectState {
 451                project,
 452                project_context,
 453                project_context_needs_refresh: project_context_needs_refresh_tx,
 454                _maintain_project_context: cx.spawn(async move |this, cx| {
 455                    Self::maintain_project_context(
 456                        this,
 457                        project_id,
 458                        project_context_needs_refresh_rx,
 459                        cx,
 460                    )
 461                    .await
 462                }),
 463                context_server_registry,
 464                _subscriptions: subscriptions,
 465            },
 466        );
 467    }
 468
 469    fn session_project_state(&self, session_id: &acp::SessionId) -> Option<&ProjectState> {
 470        self.sessions
 471            .get(session_id)
 472            .and_then(|session| self.projects.get(&session.project_id))
 473    }
 474
 475    async fn maintain_project_context(
 476        this: WeakEntity<Self>,
 477        project_id: EntityId,
 478        mut needs_refresh: watch::Receiver<()>,
 479        cx: &mut AsyncApp,
 480    ) -> Result<()> {
 481        while needs_refresh.changed().await.is_ok() {
 482            let project_context = this
 483                .update(cx, |this, cx| {
 484                    let state = this
 485                        .projects
 486                        .get(&project_id)
 487                        .context("project state not found")?;
 488                    anyhow::Ok(Self::build_project_context(
 489                        &state.project,
 490                        this.prompt_store.as_ref(),
 491                        cx,
 492                    ))
 493                })??
 494                .await;
 495            this.update(cx, |this, cx| {
 496                if let Some(state) = this.projects.get_mut(&project_id) {
 497                    state.project_context = cx.new(|_| project_context);
 498                }
 499            })?;
 500        }
 501
 502        Ok(())
 503    }
 504
 505    fn build_project_context(
 506        project: &Entity<Project>,
 507        prompt_store: Option<&Entity<PromptStore>>,
 508        cx: &mut App,
 509    ) -> Task<ProjectContext> {
 510        let worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
 511        let worktree_tasks = worktrees
 512            .into_iter()
 513            .map(|worktree| {
 514                Self::load_worktree_info_for_system_prompt(worktree, project.clone(), cx)
 515            })
 516            .collect::<Vec<_>>();
 517        let default_user_rules_task = if let Some(prompt_store) = prompt_store.as_ref() {
 518            prompt_store.read_with(cx, |prompt_store, cx| {
 519                let prompts = prompt_store.default_prompt_metadata();
 520                let load_tasks = prompts.into_iter().map(|prompt_metadata| {
 521                    let contents = prompt_store.load(prompt_metadata.id, cx);
 522                    async move { (contents.await, prompt_metadata) }
 523                });
 524                cx.background_spawn(future::join_all(load_tasks))
 525            })
 526        } else {
 527            Task::ready(vec![])
 528        };
 529
 530        cx.spawn(async move |_cx| {
 531            let (worktrees, default_user_rules) =
 532                future::join(future::join_all(worktree_tasks), default_user_rules_task).await;
 533
 534            let worktrees = worktrees
 535                .into_iter()
 536                .map(|(worktree, _rules_error)| {
 537                    // TODO: show error message
 538                    // if let Some(rules_error) = rules_error {
 539                    //     this.update(cx, |_, cx| cx.emit(rules_error)).ok();
 540                    // }
 541                    worktree
 542                })
 543                .collect::<Vec<_>>();
 544
 545            let default_user_rules = default_user_rules
 546                .into_iter()
 547                .flat_map(|(contents, prompt_metadata)| match contents {
 548                    Ok(contents) => Some(UserRulesContext {
 549                        uuid: prompt_metadata.id.as_user()?,
 550                        title: prompt_metadata.title.map(|title| title.to_string()),
 551                        contents,
 552                    }),
 553                    Err(_err) => {
 554                        // TODO: show error message
 555                        // this.update(cx, |_, cx| {
 556                        //     cx.emit(RulesLoadingError {
 557                        //         message: format!("{err:?}").into(),
 558                        //     });
 559                        // })
 560                        // .ok();
 561                        None
 562                    }
 563                })
 564                .collect::<Vec<_>>();
 565
 566            ProjectContext::new(worktrees, default_user_rules)
 567        })
 568    }
 569
 570    fn load_worktree_info_for_system_prompt(
 571        worktree: Entity<Worktree>,
 572        project: Entity<Project>,
 573        cx: &mut App,
 574    ) -> Task<(WorktreeContext, Option<RulesLoadingError>)> {
 575        let tree = worktree.read(cx);
 576        let root_name = tree.root_name_str().into();
 577        let abs_path = tree.abs_path();
 578
 579        let mut context = WorktreeContext {
 580            root_name,
 581            abs_path,
 582            rules_file: None,
 583        };
 584
 585        let rules_task = Self::load_worktree_rules_file(worktree, project, cx);
 586        let Some(rules_task) = rules_task else {
 587            return Task::ready((context, None));
 588        };
 589
 590        cx.spawn(async move |_| {
 591            let (rules_file, rules_file_error) = match rules_task.await {
 592                Ok(rules_file) => (Some(rules_file), None),
 593                Err(err) => (
 594                    None,
 595                    Some(RulesLoadingError {
 596                        message: format!("{err}").into(),
 597                    }),
 598                ),
 599            };
 600            context.rules_file = rules_file;
 601            (context, rules_file_error)
 602        })
 603    }
 604
 605    fn load_worktree_rules_file(
 606        worktree: Entity<Worktree>,
 607        project: Entity<Project>,
 608        cx: &mut App,
 609    ) -> Option<Task<Result<RulesFileContext>>> {
 610        let worktree = worktree.read(cx);
 611        let worktree_id = worktree.id();
 612        let selected_rules_file = RULES_FILE_NAMES
 613            .into_iter()
 614            .filter_map(|name| {
 615                worktree
 616                    .entry_for_path(RelPath::unix(name).unwrap())
 617                    .filter(|entry| entry.is_file())
 618                    .map(|entry| entry.path.clone())
 619            })
 620            .next();
 621
 622        // Note that Cline supports `.clinerules` being a directory, but that is not currently
 623        // supported. This doesn't seem to occur often in GitHub repositories.
 624        selected_rules_file.map(|path_in_worktree| {
 625            let project_path = ProjectPath {
 626                worktree_id,
 627                path: path_in_worktree.clone(),
 628            };
 629            let buffer_task =
 630                project.update(cx, |project, cx| project.open_buffer(project_path, cx));
 631            let rope_task = cx.spawn(async move |cx| {
 632                let buffer = buffer_task.await?;
 633                let (project_entry_id, rope) = buffer.read_with(cx, |buffer, cx| {
 634                    let project_entry_id = buffer.entry_id(cx).context("buffer has no file")?;
 635                    anyhow::Ok((project_entry_id, buffer.as_rope().clone()))
 636                })?;
 637                anyhow::Ok((project_entry_id, rope))
 638            });
 639            // Build a string from the rope on a background thread.
 640            cx.background_spawn(async move {
 641                let (project_entry_id, rope) = rope_task.await?;
 642                anyhow::Ok(RulesFileContext {
 643                    path_in_worktree,
 644                    text: rope.to_string().trim().to_string(),
 645                    project_entry_id: project_entry_id.to_usize(),
 646                })
 647            })
 648        })
 649    }
 650
 651    fn handle_thread_title_updated(
 652        &mut self,
 653        thread: Entity<Thread>,
 654        _: &TitleUpdated,
 655        cx: &mut Context<Self>,
 656    ) {
 657        let session_id = thread.read(cx).id();
 658        let Some(session) = self.sessions.get(session_id) else {
 659            return;
 660        };
 661        let thread = thread.downgrade();
 662        let acp_thread = session.acp_thread.downgrade();
 663        cx.spawn(async move |_, cx| {
 664            let title = thread.read_with(cx, |thread, _| thread.title())?;
 665            let task = acp_thread.update(cx, |acp_thread, cx| acp_thread.set_title(title, cx))?;
 666            task.await
 667        })
 668        .detach_and_log_err(cx);
 669    }
 670
 671    fn handle_thread_token_usage_updated(
 672        &mut self,
 673        thread: Entity<Thread>,
 674        usage: &TokenUsageUpdated,
 675        cx: &mut Context<Self>,
 676    ) {
 677        let Some(session) = self.sessions.get(thread.read(cx).id()) else {
 678            return;
 679        };
 680        session.acp_thread.update(cx, |acp_thread, cx| {
 681            acp_thread.update_token_usage(usage.0.clone(), cx);
 682        });
 683    }
 684
 685    fn handle_project_event(
 686        &mut self,
 687        project: Entity<Project>,
 688        event: &project::Event,
 689        _cx: &mut Context<Self>,
 690    ) {
 691        let project_id = project.entity_id();
 692        let Some(state) = self.projects.get_mut(&project_id) else {
 693            return;
 694        };
 695        match event {
 696            project::Event::WorktreeAdded(_) | project::Event::WorktreeRemoved(_) => {
 697                state.project_context_needs_refresh.send(()).ok();
 698            }
 699            project::Event::WorktreeUpdatedEntries(_, items) => {
 700                if items.iter().any(|(path, _, _)| {
 701                    RULES_FILE_NAMES
 702                        .iter()
 703                        .any(|name| path.as_ref() == RelPath::unix(name).unwrap())
 704                }) {
 705                    state.project_context_needs_refresh.send(()).ok();
 706                }
 707            }
 708            _ => {}
 709        }
 710    }
 711
 712    fn handle_prompts_updated_event(
 713        &mut self,
 714        _prompt_store: Entity<PromptStore>,
 715        _event: &prompt_store::PromptsUpdatedEvent,
 716        _cx: &mut Context<Self>,
 717    ) {
 718        for state in self.projects.values_mut() {
 719            state.project_context_needs_refresh.send(()).ok();
 720        }
 721    }
 722
 723    fn handle_models_updated_event(
 724        &mut self,
 725        _registry: Entity<LanguageModelRegistry>,
 726        _event: &language_model::Event,
 727        cx: &mut Context<Self>,
 728    ) {
 729        self.models.refresh_list(cx);
 730
 731        let registry = LanguageModelRegistry::read_global(cx);
 732        let default_model = registry.default_model().map(|m| m.model);
 733        let summarization_model = registry.thread_summary_model().map(|m| m.model);
 734
 735        for session in self.sessions.values_mut() {
 736            session.thread.update(cx, |thread, cx| {
 737                if thread.model().is_none()
 738                    && let Some(model) = default_model.clone()
 739                {
 740                    thread.set_model(model, cx);
 741                    cx.notify();
 742                }
 743                thread.set_summarization_model(summarization_model.clone(), cx);
 744            });
 745        }
 746    }
 747
 748    fn handle_context_server_store_updated(
 749        &mut self,
 750        store: Entity<project::context_server_store::ContextServerStore>,
 751        _event: &project::context_server_store::ServerStatusChangedEvent,
 752        cx: &mut Context<Self>,
 753    ) {
 754        let project_id = self.projects.iter().find_map(|(id, state)| {
 755            if *state.context_server_registry.read(cx).server_store() == store {
 756                Some(*id)
 757            } else {
 758                None
 759            }
 760        });
 761        if let Some(project_id) = project_id {
 762            self.update_available_commands_for_project(project_id, cx);
 763        }
 764    }
 765
 766    fn handle_context_server_registry_event(
 767        &mut self,
 768        registry: Entity<ContextServerRegistry>,
 769        event: &ContextServerRegistryEvent,
 770        cx: &mut Context<Self>,
 771    ) {
 772        match event {
 773            ContextServerRegistryEvent::ToolsChanged => {}
 774            ContextServerRegistryEvent::PromptsChanged => {
 775                let project_id = self.projects.iter().find_map(|(id, state)| {
 776                    if state.context_server_registry == registry {
 777                        Some(*id)
 778                    } else {
 779                        None
 780                    }
 781                });
 782                if let Some(project_id) = project_id {
 783                    self.update_available_commands_for_project(project_id, cx);
 784                }
 785            }
 786        }
 787    }
 788
 789    fn update_available_commands_for_project(&self, project_id: EntityId, cx: &mut Context<Self>) {
 790        let available_commands =
 791            Self::build_available_commands_for_project(self.projects.get(&project_id), cx);
 792        for session in self.sessions.values() {
 793            if session.project_id != project_id {
 794                continue;
 795            }
 796            session.acp_thread.update(cx, |thread, cx| {
 797                thread
 798                    .handle_session_update(
 799                        acp::SessionUpdate::AvailableCommandsUpdate(
 800                            acp::AvailableCommandsUpdate::new(available_commands.clone()),
 801                        ),
 802                        cx,
 803                    )
 804                    .log_err();
 805            });
 806        }
 807    }
 808
 809    fn build_available_commands_for_project(
 810        project_state: Option<&ProjectState>,
 811        cx: &App,
 812    ) -> Vec<acp::AvailableCommand> {
 813        let Some(state) = project_state else {
 814            return vec![];
 815        };
 816        let registry = state.context_server_registry.read(cx);
 817
 818        let mut prompt_name_counts: HashMap<&str, usize> = HashMap::default();
 819        for context_server_prompt in registry.prompts() {
 820            *prompt_name_counts
 821                .entry(context_server_prompt.prompt.name.as_str())
 822                .or_insert(0) += 1;
 823        }
 824
 825        registry
 826            .prompts()
 827            .flat_map(|context_server_prompt| {
 828                let prompt = &context_server_prompt.prompt;
 829
 830                let should_prefix = prompt_name_counts
 831                    .get(prompt.name.as_str())
 832                    .copied()
 833                    .unwrap_or(0)
 834                    > 1;
 835
 836                let name = if should_prefix {
 837                    format!("{}.{}", context_server_prompt.server_id, prompt.name)
 838                } else {
 839                    prompt.name.clone()
 840                };
 841
 842                let mut command = acp::AvailableCommand::new(
 843                    name,
 844                    prompt.description.clone().unwrap_or_default(),
 845                );
 846
 847                match prompt.arguments.as_deref() {
 848                    Some([arg]) => {
 849                        let hint = format!("<{}>", arg.name);
 850
 851                        command = command.input(acp::AvailableCommandInput::Unstructured(
 852                            acp::UnstructuredCommandInput::new(hint),
 853                        ));
 854                    }
 855                    Some([]) | None => {}
 856                    Some(_) => {
 857                        // skip >1 argument commands since we don't support them yet
 858                        return None;
 859                    }
 860                }
 861
 862                Some(command)
 863            })
 864            .collect()
 865    }
 866
 867    pub fn load_thread(
 868        &mut self,
 869        id: acp::SessionId,
 870        project: Entity<Project>,
 871        cx: &mut Context<Self>,
 872    ) -> Task<Result<Entity<Thread>>> {
 873        let project_id = self.get_or_create_project_state(&project, cx);
 874        let database_future = ThreadsDatabase::connect(cx);
 875        cx.spawn(async move |this, cx| {
 876            let database = database_future.await.map_err(|err| anyhow!(err))?;
 877            let db_thread = database
 878                .load_thread(id.clone())
 879                .await?
 880                .with_context(|| format!("no thread found with ID: {id:?}"))?;
 881
 882            this.update(cx, |this, cx| {
 883                let project_state = this
 884                    .projects
 885                    .get(&project_id)
 886                    .context("project state not found")?;
 887                let summarization_model = LanguageModelRegistry::read_global(cx)
 888                    .thread_summary_model()
 889                    .map(|c| c.model);
 890
 891                Ok(cx.new(|cx| {
 892                    let mut thread = Thread::from_db(
 893                        id.clone(),
 894                        db_thread,
 895                        project_state.project.clone(),
 896                        project_state.project_context.clone(),
 897                        project_state.context_server_registry.clone(),
 898                        this.templates.clone(),
 899                        cx,
 900                    );
 901                    thread.set_summarization_model(summarization_model, cx);
 902                    thread
 903                }))
 904            })?
 905        })
 906    }
 907
 908    pub fn open_thread(
 909        &mut self,
 910        id: acp::SessionId,
 911        project: Entity<Project>,
 912        cx: &mut Context<Self>,
 913    ) -> Task<Result<Entity<AcpThread>>> {
 914        if let Some(session) = self.sessions.get(&id) {
 915            return Task::ready(Ok(session.acp_thread.clone()));
 916        }
 917
 918        let project_id = self.get_or_create_project_state(&project, cx);
 919        let task = self.load_thread(id, project, cx);
 920        cx.spawn(async move |this, cx| {
 921            let thread = task.await?;
 922            let acp_thread = this.update(cx, |this, cx| {
 923                this.register_session(thread.clone(), project_id, cx)
 924            })?;
 925            let events = thread.update(cx, |thread, cx| thread.replay(cx));
 926            cx.update(|cx| {
 927                NativeAgentConnection::handle_thread_events(events, acp_thread.downgrade(), cx)
 928            })
 929            .await?;
 930            Ok(acp_thread)
 931        })
 932    }
 933
 934    pub fn thread_summary(
 935        &mut self,
 936        id: acp::SessionId,
 937        project: Entity<Project>,
 938        cx: &mut Context<Self>,
 939    ) -> Task<Result<SharedString>> {
 940        let thread = self.open_thread(id.clone(), project, cx);
 941        cx.spawn(async move |this, cx| {
 942            let acp_thread = thread.await?;
 943            let result = this
 944                .update(cx, |this, cx| {
 945                    this.sessions
 946                        .get(&id)
 947                        .unwrap()
 948                        .thread
 949                        .update(cx, |thread, cx| thread.summary(cx))
 950                })?
 951                .await
 952                .context("Failed to generate summary")?;
 953            drop(acp_thread);
 954            Ok(result)
 955        })
 956    }
 957
 958    fn save_thread(&mut self, thread: Entity<Thread>, cx: &mut Context<Self>) {
 959        if thread.read(cx).is_empty() {
 960            return;
 961        }
 962
 963        let id = thread.read(cx).id().clone();
 964        let Some(session) = self.sessions.get_mut(&id) else {
 965            return;
 966        };
 967
 968        let project_id = session.project_id;
 969        let Some(state) = self.projects.get(&project_id) else {
 970            return;
 971        };
 972
 973        let folder_paths = PathList::new(
 974            &state
 975                .project
 976                .read(cx)
 977                .visible_worktrees(cx)
 978                .map(|worktree| worktree.read(cx).abs_path().to_path_buf())
 979                .collect::<Vec<_>>(),
 980        );
 981
 982        let draft_prompt = session.acp_thread.read(cx).draft_prompt().map(Vec::from);
 983        let database_future = ThreadsDatabase::connect(cx);
 984        let db_thread = thread.update(cx, |thread, cx| {
 985            thread.set_draft_prompt(draft_prompt);
 986            thread.to_db(cx)
 987        });
 988        let thread_store = self.thread_store.clone();
 989        session.pending_save = cx.spawn(async move |_, cx| {
 990            let Some(database) = database_future.await.map_err(|err| anyhow!(err)).log_err() else {
 991                return;
 992            };
 993            let db_thread = db_thread.await;
 994            database
 995                .save_thread(id, db_thread, folder_paths)
 996                .await
 997                .log_err();
 998            thread_store.update(cx, |store, cx| store.reload(cx));
 999        });
1000    }
1001
1002    fn send_mcp_prompt(
1003        &self,
1004        message_id: UserMessageId,
1005        session_id: acp::SessionId,
1006        prompt_name: String,
1007        server_id: ContextServerId,
1008        arguments: HashMap<String, String>,
1009        original_content: Vec<acp::ContentBlock>,
1010        cx: &mut Context<Self>,
1011    ) -> Task<Result<acp::PromptResponse>> {
1012        let Some(state) = self.session_project_state(&session_id) else {
1013            return Task::ready(Err(anyhow!("Project state not found for session")));
1014        };
1015        let server_store = state
1016            .context_server_registry
1017            .read(cx)
1018            .server_store()
1019            .clone();
1020        let path_style = state.project.read(cx).path_style(cx);
1021
1022        cx.spawn(async move |this, cx| {
1023            let prompt =
1024                crate::get_prompt(&server_store, &server_id, &prompt_name, arguments, cx).await?;
1025
1026            let (acp_thread, thread) = this.update(cx, |this, _cx| {
1027                let session = this
1028                    .sessions
1029                    .get(&session_id)
1030                    .context("Failed to get session")?;
1031                anyhow::Ok((session.acp_thread.clone(), session.thread.clone()))
1032            })??;
1033
1034            let mut last_is_user = true;
1035
1036            thread.update(cx, |thread, cx| {
1037                thread.push_acp_user_block(
1038                    message_id,
1039                    original_content.into_iter().skip(1),
1040                    path_style,
1041                    cx,
1042                );
1043            });
1044
1045            for message in prompt.messages {
1046                let context_server::types::PromptMessage { role, content } = message;
1047                let block = mcp_message_content_to_acp_content_block(content);
1048
1049                match role {
1050                    context_server::types::Role::User => {
1051                        let id = acp_thread::UserMessageId::new();
1052
1053                        acp_thread.update(cx, |acp_thread, cx| {
1054                            acp_thread.push_user_content_block_with_indent(
1055                                Some(id.clone()),
1056                                block.clone(),
1057                                true,
1058                                cx,
1059                            );
1060                        });
1061
1062                        thread.update(cx, |thread, cx| {
1063                            thread.push_acp_user_block(id, [block], path_style, cx);
1064                        });
1065                    }
1066                    context_server::types::Role::Assistant => {
1067                        acp_thread.update(cx, |acp_thread, cx| {
1068                            acp_thread.push_assistant_content_block_with_indent(
1069                                block.clone(),
1070                                false,
1071                                true,
1072                                cx,
1073                            );
1074                        });
1075
1076                        thread.update(cx, |thread, cx| {
1077                            thread.push_acp_agent_block(block, cx);
1078                        });
1079                    }
1080                }
1081
1082                last_is_user = role == context_server::types::Role::User;
1083            }
1084
1085            let response_stream = thread.update(cx, |thread, cx| {
1086                if last_is_user {
1087                    thread.send_existing(cx)
1088                } else {
1089                    // Resume if MCP prompt did not end with a user message
1090                    thread.resume(cx)
1091                }
1092            })?;
1093
1094            cx.update(|cx| {
1095                NativeAgentConnection::handle_thread_events(
1096                    response_stream,
1097                    acp_thread.downgrade(),
1098                    cx,
1099                )
1100            })
1101            .await
1102        })
1103    }
1104}
1105
1106/// Wrapper struct that implements the AgentConnection trait
1107#[derive(Clone)]
1108pub struct NativeAgentConnection(pub Entity<NativeAgent>);
1109
1110impl NativeAgentConnection {
1111    pub fn thread(&self, session_id: &acp::SessionId, cx: &App) -> Option<Entity<Thread>> {
1112        self.0
1113            .read(cx)
1114            .sessions
1115            .get(session_id)
1116            .map(|session| session.thread.clone())
1117    }
1118
1119    pub fn load_thread(
1120        &self,
1121        id: acp::SessionId,
1122        project: Entity<Project>,
1123        cx: &mut App,
1124    ) -> Task<Result<Entity<Thread>>> {
1125        self.0
1126            .update(cx, |this, cx| this.load_thread(id, project, cx))
1127    }
1128
1129    fn run_turn(
1130        &self,
1131        session_id: acp::SessionId,
1132        cx: &mut App,
1133        f: impl 'static
1134        + FnOnce(Entity<Thread>, &mut App) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>,
1135    ) -> Task<Result<acp::PromptResponse>> {
1136        let Some((thread, acp_thread)) = self.0.update(cx, |agent, _cx| {
1137            agent
1138                .sessions
1139                .get_mut(&session_id)
1140                .map(|s| (s.thread.clone(), s.acp_thread.clone()))
1141        }) else {
1142            return Task::ready(Err(anyhow!("Session not found")));
1143        };
1144        log::debug!("Found session for: {}", session_id);
1145
1146        let response_stream = match f(thread, cx) {
1147            Ok(stream) => stream,
1148            Err(err) => return Task::ready(Err(err)),
1149        };
1150        Self::handle_thread_events(response_stream, acp_thread.downgrade(), cx)
1151    }
1152
1153    fn handle_thread_events(
1154        mut events: mpsc::UnboundedReceiver<Result<ThreadEvent>>,
1155        acp_thread: WeakEntity<AcpThread>,
1156        cx: &App,
1157    ) -> Task<Result<acp::PromptResponse>> {
1158        cx.spawn(async move |cx| {
1159            // Handle response stream and forward to session.acp_thread
1160            while let Some(result) = events.next().await {
1161                match result {
1162                    Ok(event) => {
1163                        log::trace!("Received completion event: {:?}", event);
1164
1165                        match event {
1166                            ThreadEvent::UserMessage(message) => {
1167                                acp_thread.update(cx, |thread, cx| {
1168                                    for content in message.content {
1169                                        thread.push_user_content_block(
1170                                            Some(message.id.clone()),
1171                                            content.into(),
1172                                            cx,
1173                                        );
1174                                    }
1175                                })?;
1176                            }
1177                            ThreadEvent::AgentText(text) => {
1178                                acp_thread.update(cx, |thread, cx| {
1179                                    thread.push_assistant_content_block(text.into(), false, cx)
1180                                })?;
1181                            }
1182                            ThreadEvent::AgentThinking(text) => {
1183                                acp_thread.update(cx, |thread, cx| {
1184                                    thread.push_assistant_content_block(text.into(), true, cx)
1185                                })?;
1186                            }
1187                            ThreadEvent::ToolCallAuthorization(ToolCallAuthorization {
1188                                tool_call,
1189                                options,
1190                                response,
1191                                context: _,
1192                            }) => {
1193                                let outcome_task = acp_thread.update(cx, |thread, cx| {
1194                                    thread.request_tool_call_authorization(tool_call, options, cx)
1195                                })??;
1196                                cx.background_spawn(async move {
1197                                    if let acp::RequestPermissionOutcome::Selected(
1198                                        acp::SelectedPermissionOutcome { option_id, .. },
1199                                    ) = outcome_task.await
1200                                    {
1201                                        response
1202                                            .send(option_id)
1203                                            .map(|_| anyhow!("authorization receiver was dropped"))
1204                                            .log_err();
1205                                    }
1206                                })
1207                                .detach();
1208                            }
1209                            ThreadEvent::ToolCall(tool_call) => {
1210                                acp_thread.update(cx, |thread, cx| {
1211                                    thread.upsert_tool_call(tool_call, cx)
1212                                })??;
1213                            }
1214                            ThreadEvent::ToolCallUpdate(update) => {
1215                                acp_thread.update(cx, |thread, cx| {
1216                                    thread.update_tool_call(update, cx)
1217                                })??;
1218                            }
1219                            ThreadEvent::SubagentSpawned(session_id) => {
1220                                acp_thread.update(cx, |thread, cx| {
1221                                    thread.subagent_spawned(session_id, cx);
1222                                })?;
1223                            }
1224                            ThreadEvent::Retry(status) => {
1225                                acp_thread.update(cx, |thread, cx| {
1226                                    thread.update_retry_status(status, cx)
1227                                })?;
1228                            }
1229                            ThreadEvent::Stop(stop_reason) => {
1230                                log::debug!("Assistant message complete: {:?}", stop_reason);
1231                                return Ok(acp::PromptResponse::new(stop_reason));
1232                            }
1233                        }
1234                    }
1235                    Err(e) => {
1236                        log::error!("Error in model response stream: {:?}", e);
1237                        return Err(e);
1238                    }
1239                }
1240            }
1241
1242            log::debug!("Response stream completed");
1243            anyhow::Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
1244        })
1245    }
1246}
1247
1248struct Command<'a> {
1249    prompt_name: &'a str,
1250    arg_value: &'a str,
1251    explicit_server_id: Option<&'a str>,
1252}
1253
1254impl<'a> Command<'a> {
1255    fn parse(prompt: &'a [acp::ContentBlock]) -> Option<Self> {
1256        let acp::ContentBlock::Text(text_content) = prompt.first()? else {
1257            return None;
1258        };
1259        let text = text_content.text.trim();
1260        let command = text.strip_prefix('/')?;
1261        let (command, arg_value) = command
1262            .split_once(char::is_whitespace)
1263            .unwrap_or((command, ""));
1264
1265        if let Some((server_id, prompt_name)) = command.split_once('.') {
1266            Some(Self {
1267                prompt_name,
1268                arg_value,
1269                explicit_server_id: Some(server_id),
1270            })
1271        } else {
1272            Some(Self {
1273                prompt_name: command,
1274                arg_value,
1275                explicit_server_id: None,
1276            })
1277        }
1278    }
1279}
1280
1281struct NativeAgentModelSelector {
1282    session_id: acp::SessionId,
1283    connection: NativeAgentConnection,
1284}
1285
1286impl acp_thread::AgentModelSelector for NativeAgentModelSelector {
1287    fn list_models(&self, cx: &mut App) -> Task<Result<acp_thread::AgentModelList>> {
1288        log::debug!("NativeAgentConnection::list_models called");
1289        let list = self.connection.0.read(cx).models.model_list.clone();
1290        Task::ready(if list.is_empty() {
1291            Err(anyhow::anyhow!("No models available"))
1292        } else {
1293            Ok(list)
1294        })
1295    }
1296
1297    fn select_model(&self, model_id: acp::ModelId, cx: &mut App) -> Task<Result<()>> {
1298        log::debug!(
1299            "Setting model for session {}: {}",
1300            self.session_id,
1301            model_id
1302        );
1303        let Some(thread) = self
1304            .connection
1305            .0
1306            .read(cx)
1307            .sessions
1308            .get(&self.session_id)
1309            .map(|session| session.thread.clone())
1310        else {
1311            return Task::ready(Err(anyhow!("Session not found")));
1312        };
1313
1314        let Some(model) = self.connection.0.read(cx).models.model_from_id(&model_id) else {
1315            return Task::ready(Err(anyhow!("Invalid model ID {}", model_id)));
1316        };
1317
1318        // We want to reset the effort level when switching models, as the currently-selected effort level may
1319        // not be compatible.
1320        let effort = model
1321            .default_effort_level()
1322            .map(|effort_level| effort_level.value.to_string());
1323
1324        thread.update(cx, |thread, cx| {
1325            thread.set_model(model.clone(), cx);
1326            thread.set_thinking_effort(effort.clone(), cx);
1327            thread.set_thinking_enabled(model.supports_thinking(), cx);
1328        });
1329
1330        update_settings_file(
1331            self.connection.0.read(cx).fs.clone(),
1332            cx,
1333            move |settings, cx| {
1334                let provider = model.provider_id().0.to_string();
1335                let model = model.id().0.to_string();
1336                let enable_thinking = thread.read(cx).thinking_enabled();
1337                settings
1338                    .agent
1339                    .get_or_insert_default()
1340                    .set_model(LanguageModelSelection {
1341                        provider: provider.into(),
1342                        model,
1343                        enable_thinking,
1344                        effort,
1345                    });
1346            },
1347        );
1348
1349        Task::ready(Ok(()))
1350    }
1351
1352    fn selected_model(&self, cx: &mut App) -> Task<Result<acp_thread::AgentModelInfo>> {
1353        let Some(thread) = self
1354            .connection
1355            .0
1356            .read(cx)
1357            .sessions
1358            .get(&self.session_id)
1359            .map(|session| session.thread.clone())
1360        else {
1361            return Task::ready(Err(anyhow!("Session not found")));
1362        };
1363        let Some(model) = thread.read(cx).model() else {
1364            return Task::ready(Err(anyhow!("Model not found")));
1365        };
1366        let Some(provider) = LanguageModelRegistry::read_global(cx).provider(&model.provider_id())
1367        else {
1368            return Task::ready(Err(anyhow!("Provider not found")));
1369        };
1370        Task::ready(Ok(LanguageModels::map_language_model_to_info(
1371            model, &provider,
1372        )))
1373    }
1374
1375    fn watch(&self, cx: &mut App) -> Option<watch::Receiver<()>> {
1376        Some(self.connection.0.read(cx).models.watch())
1377    }
1378
1379    fn should_render_footer(&self) -> bool {
1380        true
1381    }
1382}
1383
1384impl acp_thread::AgentConnection for NativeAgentConnection {
1385    fn telemetry_id(&self) -> SharedString {
1386        "zed".into()
1387    }
1388
1389    fn new_session(
1390        self: Rc<Self>,
1391        project: Entity<Project>,
1392        cwd: &Path,
1393        cx: &mut App,
1394    ) -> Task<Result<Entity<acp_thread::AcpThread>>> {
1395        log::debug!("Creating new thread for project at: {cwd:?}");
1396        Task::ready(Ok(self
1397            .0
1398            .update(cx, |agent, cx| agent.new_session(project, cx))))
1399    }
1400
1401    fn supports_load_session(&self) -> bool {
1402        true
1403    }
1404
1405    fn load_session(
1406        self: Rc<Self>,
1407        session_id: acp::SessionId,
1408        project: Entity<Project>,
1409        _cwd: &Path,
1410        _title: Option<SharedString>,
1411        cx: &mut App,
1412    ) -> Task<Result<Entity<acp_thread::AcpThread>>> {
1413        self.0
1414            .update(cx, |agent, cx| agent.open_thread(session_id, project, cx))
1415    }
1416
1417    fn supports_close_session(&self) -> bool {
1418        true
1419    }
1420
1421    fn close_session(
1422        self: Rc<Self>,
1423        session_id: &acp::SessionId,
1424        cx: &mut App,
1425    ) -> Task<Result<()>> {
1426        self.0.update(cx, |agent, _cx| {
1427            let project_id = agent.sessions.get(session_id).map(|s| s.project_id);
1428            agent.sessions.remove(session_id);
1429
1430            if let Some(project_id) = project_id {
1431                let has_remaining = agent.sessions.values().any(|s| s.project_id == project_id);
1432                if !has_remaining {
1433                    agent.projects.remove(&project_id);
1434                }
1435            }
1436        });
1437        Task::ready(Ok(()))
1438    }
1439
1440    fn auth_methods(&self) -> &[acp::AuthMethod] {
1441        &[] // No auth for in-process
1442    }
1443
1444    fn authenticate(&self, _method: acp::AuthMethodId, _cx: &mut App) -> Task<Result<()>> {
1445        Task::ready(Ok(()))
1446    }
1447
1448    fn model_selector(&self, session_id: &acp::SessionId) -> Option<Rc<dyn AgentModelSelector>> {
1449        Some(Rc::new(NativeAgentModelSelector {
1450            session_id: session_id.clone(),
1451            connection: self.clone(),
1452        }) as Rc<dyn AgentModelSelector>)
1453    }
1454
1455    fn prompt(
1456        &self,
1457        id: Option<acp_thread::UserMessageId>,
1458        params: acp::PromptRequest,
1459        cx: &mut App,
1460    ) -> Task<Result<acp::PromptResponse>> {
1461        let id = id.expect("UserMessageId is required");
1462        let session_id = params.session_id.clone();
1463        log::info!("Received prompt request for session: {}", session_id);
1464        log::debug!("Prompt blocks count: {}", params.prompt.len());
1465
1466        let Some(project_state) = self.0.read(cx).session_project_state(&session_id) else {
1467            return Task::ready(Err(anyhow::anyhow!("Session not found")));
1468        };
1469
1470        if let Some(parsed_command) = Command::parse(&params.prompt) {
1471            let registry = project_state.context_server_registry.read(cx);
1472
1473            let explicit_server_id = parsed_command
1474                .explicit_server_id
1475                .map(|server_id| ContextServerId(server_id.into()));
1476
1477            if let Some(prompt) =
1478                registry.find_prompt(explicit_server_id.as_ref(), parsed_command.prompt_name)
1479            {
1480                let arguments = if !parsed_command.arg_value.is_empty()
1481                    && let Some(arg_name) = prompt
1482                        .prompt
1483                        .arguments
1484                        .as_ref()
1485                        .and_then(|args| args.first())
1486                        .map(|arg| arg.name.clone())
1487                {
1488                    HashMap::from_iter([(arg_name, parsed_command.arg_value.to_string())])
1489                } else {
1490                    Default::default()
1491                };
1492
1493                let prompt_name = prompt.prompt.name.clone();
1494                let server_id = prompt.server_id.clone();
1495
1496                return self.0.update(cx, |agent, cx| {
1497                    agent.send_mcp_prompt(
1498                        id,
1499                        session_id.clone(),
1500                        prompt_name,
1501                        server_id,
1502                        arguments,
1503                        params.prompt,
1504                        cx,
1505                    )
1506                });
1507            }
1508        };
1509
1510        let path_style = project_state.project.read(cx).path_style(cx);
1511
1512        self.run_turn(session_id, cx, move |thread, cx| {
1513            let content: Vec<UserMessageContent> = params
1514                .prompt
1515                .into_iter()
1516                .map(|block| UserMessageContent::from_content_block(block, path_style))
1517                .collect::<Vec<_>>();
1518            log::debug!("Converted prompt to message: {} chars", content.len());
1519            log::debug!("Message id: {:?}", id);
1520            log::debug!("Message content: {:?}", content);
1521
1522            thread.update(cx, |thread, cx| thread.send(id, content, cx))
1523        })
1524    }
1525
1526    fn retry(
1527        &self,
1528        session_id: &acp::SessionId,
1529        _cx: &App,
1530    ) -> Option<Rc<dyn acp_thread::AgentSessionRetry>> {
1531        Some(Rc::new(NativeAgentSessionRetry {
1532            connection: self.clone(),
1533            session_id: session_id.clone(),
1534        }) as _)
1535    }
1536
1537    fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
1538        log::info!("Cancelling on session: {}", session_id);
1539        self.0.update(cx, |agent, cx| {
1540            if let Some(session) = agent.sessions.get(session_id) {
1541                session
1542                    .thread
1543                    .update(cx, |thread, cx| thread.cancel(cx))
1544                    .detach();
1545            }
1546        });
1547    }
1548
1549    fn truncate(
1550        &self,
1551        session_id: &acp::SessionId,
1552        cx: &App,
1553    ) -> Option<Rc<dyn acp_thread::AgentSessionTruncate>> {
1554        self.0.read_with(cx, |agent, _cx| {
1555            agent.sessions.get(session_id).map(|session| {
1556                Rc::new(NativeAgentSessionTruncate {
1557                    thread: session.thread.clone(),
1558                    acp_thread: session.acp_thread.downgrade(),
1559                }) as _
1560            })
1561        })
1562    }
1563
1564    fn set_title(
1565        &self,
1566        session_id: &acp::SessionId,
1567        cx: &App,
1568    ) -> Option<Rc<dyn acp_thread::AgentSessionSetTitle>> {
1569        self.0.read_with(cx, |agent, _cx| {
1570            agent
1571                .sessions
1572                .get(session_id)
1573                .filter(|s| !s.thread.read(cx).is_subagent())
1574                .map(|session| {
1575                    Rc::new(NativeAgentSessionSetTitle {
1576                        thread: session.thread.clone(),
1577                    }) as _
1578                })
1579        })
1580    }
1581
1582    fn session_list(&self, cx: &mut App) -> Option<Rc<dyn AgentSessionList>> {
1583        let thread_store = self.0.read(cx).thread_store.clone();
1584        Some(Rc::new(NativeAgentSessionList::new(thread_store, cx)) as _)
1585    }
1586
1587    fn telemetry(&self) -> Option<Rc<dyn acp_thread::AgentTelemetry>> {
1588        Some(Rc::new(self.clone()) as Rc<dyn acp_thread::AgentTelemetry>)
1589    }
1590
1591    fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
1592        self
1593    }
1594}
1595
1596impl acp_thread::AgentTelemetry for NativeAgentConnection {
1597    fn thread_data(
1598        &self,
1599        session_id: &acp::SessionId,
1600        cx: &mut App,
1601    ) -> Task<Result<serde_json::Value>> {
1602        let Some(session) = self.0.read(cx).sessions.get(session_id) else {
1603            return Task::ready(Err(anyhow!("Session not found")));
1604        };
1605
1606        let task = session.thread.read(cx).to_db(cx);
1607        cx.background_spawn(async move {
1608            serde_json::to_value(task.await).context("Failed to serialize thread")
1609        })
1610    }
1611}
1612
1613pub struct NativeAgentSessionList {
1614    thread_store: Entity<ThreadStore>,
1615    updates_tx: smol::channel::Sender<acp_thread::SessionListUpdate>,
1616    updates_rx: smol::channel::Receiver<acp_thread::SessionListUpdate>,
1617    _subscription: Subscription,
1618}
1619
1620impl NativeAgentSessionList {
1621    fn new(thread_store: Entity<ThreadStore>, cx: &mut App) -> Self {
1622        let (tx, rx) = smol::channel::unbounded();
1623        let this_tx = tx.clone();
1624        let subscription = cx.observe(&thread_store, move |_, _| {
1625            this_tx
1626                .try_send(acp_thread::SessionListUpdate::Refresh)
1627                .ok();
1628        });
1629        Self {
1630            thread_store,
1631            updates_tx: tx,
1632            updates_rx: rx,
1633            _subscription: subscription,
1634        }
1635    }
1636
1637    pub fn thread_store(&self) -> &Entity<ThreadStore> {
1638        &self.thread_store
1639    }
1640}
1641
1642impl AgentSessionList for NativeAgentSessionList {
1643    fn list_sessions(
1644        &self,
1645        _request: AgentSessionListRequest,
1646        cx: &mut App,
1647    ) -> Task<Result<AgentSessionListResponse>> {
1648        let sessions = self
1649            .thread_store
1650            .read(cx)
1651            .entries()
1652            .map(|entry| AgentSessionInfo::from(&entry))
1653            .collect();
1654        Task::ready(Ok(AgentSessionListResponse::new(sessions)))
1655    }
1656
1657    fn supports_delete(&self) -> bool {
1658        true
1659    }
1660
1661    fn delete_session(&self, session_id: &acp::SessionId, cx: &mut App) -> Task<Result<()>> {
1662        self.thread_store
1663            .update(cx, |store, cx| store.delete_thread(session_id.clone(), cx))
1664    }
1665
1666    fn delete_sessions(&self, cx: &mut App) -> Task<Result<()>> {
1667        self.thread_store
1668            .update(cx, |store, cx| store.delete_threads(cx))
1669    }
1670
1671    fn watch(
1672        &self,
1673        _cx: &mut App,
1674    ) -> Option<smol::channel::Receiver<acp_thread::SessionListUpdate>> {
1675        Some(self.updates_rx.clone())
1676    }
1677
1678    fn notify_refresh(&self) {
1679        self.updates_tx
1680            .try_send(acp_thread::SessionListUpdate::Refresh)
1681            .ok();
1682    }
1683
1684    fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
1685        self
1686    }
1687}
1688
1689struct NativeAgentSessionTruncate {
1690    thread: Entity<Thread>,
1691    acp_thread: WeakEntity<AcpThread>,
1692}
1693
1694impl acp_thread::AgentSessionTruncate for NativeAgentSessionTruncate {
1695    fn run(&self, message_id: acp_thread::UserMessageId, cx: &mut App) -> Task<Result<()>> {
1696        match self.thread.update(cx, |thread, cx| {
1697            thread.truncate(message_id.clone(), cx)?;
1698            Ok(thread.latest_token_usage())
1699        }) {
1700            Ok(usage) => {
1701                self.acp_thread
1702                    .update(cx, |thread, cx| {
1703                        thread.update_token_usage(usage, cx);
1704                    })
1705                    .ok();
1706                Task::ready(Ok(()))
1707            }
1708            Err(error) => Task::ready(Err(error)),
1709        }
1710    }
1711}
1712
1713struct NativeAgentSessionRetry {
1714    connection: NativeAgentConnection,
1715    session_id: acp::SessionId,
1716}
1717
1718impl acp_thread::AgentSessionRetry for NativeAgentSessionRetry {
1719    fn run(&self, cx: &mut App) -> Task<Result<acp::PromptResponse>> {
1720        self.connection
1721            .run_turn(self.session_id.clone(), cx, |thread, cx| {
1722                thread.update(cx, |thread, cx| thread.resume(cx))
1723            })
1724    }
1725}
1726
1727struct NativeAgentSessionSetTitle {
1728    thread: Entity<Thread>,
1729}
1730
1731impl acp_thread::AgentSessionSetTitle for NativeAgentSessionSetTitle {
1732    fn run(&self, title: SharedString, cx: &mut App) -> Task<Result<()>> {
1733        self.thread
1734            .update(cx, |thread, cx| thread.set_title(title, cx));
1735        Task::ready(Ok(()))
1736    }
1737}
1738
1739pub struct NativeThreadEnvironment {
1740    agent: WeakEntity<NativeAgent>,
1741    thread: WeakEntity<Thread>,
1742    acp_thread: WeakEntity<AcpThread>,
1743}
1744
1745impl NativeThreadEnvironment {
1746    pub(crate) fn create_subagent_thread(
1747        &self,
1748        label: String,
1749        cx: &mut App,
1750    ) -> Result<Rc<dyn SubagentHandle>> {
1751        let Some(parent_thread_entity) = self.thread.upgrade() else {
1752            anyhow::bail!("Parent thread no longer exists".to_string());
1753        };
1754        let parent_thread = parent_thread_entity.read(cx);
1755        let current_depth = parent_thread.depth();
1756        let parent_session_id = parent_thread.id().clone();
1757
1758        if current_depth >= MAX_SUBAGENT_DEPTH {
1759            return Err(anyhow!(
1760                "Maximum subagent depth ({}) reached",
1761                MAX_SUBAGENT_DEPTH
1762            ));
1763        }
1764
1765        let subagent_thread: Entity<Thread> = cx.new(|cx| {
1766            let mut thread = Thread::new_subagent(&parent_thread_entity, cx);
1767            thread.set_title(label.into(), cx);
1768            thread
1769        });
1770
1771        let session_id = subagent_thread.read(cx).id().clone();
1772
1773        let acp_thread = self
1774            .agent
1775            .update(cx, |agent, cx| -> Result<Entity<AcpThread>> {
1776                let project_id = agent
1777                    .sessions
1778                    .get(&parent_session_id)
1779                    .map(|s| s.project_id)
1780                    .context("parent session not found")?;
1781                Ok(agent.register_session(subagent_thread.clone(), project_id, cx))
1782            })??;
1783
1784        let depth = current_depth + 1;
1785
1786        telemetry::event!(
1787            "Subagent Started",
1788            session = parent_thread_entity.read(cx).id().to_string(),
1789            subagent_session = session_id.to_string(),
1790            depth,
1791            is_resumed = false,
1792        );
1793
1794        self.prompt_subagent(session_id, subagent_thread, acp_thread)
1795    }
1796
1797    pub(crate) fn resume_subagent_thread(
1798        &self,
1799        session_id: acp::SessionId,
1800        cx: &mut App,
1801    ) -> Result<Rc<dyn SubagentHandle>> {
1802        let (subagent_thread, acp_thread) = self.agent.update(cx, |agent, _cx| {
1803            let session = agent
1804                .sessions
1805                .get(&session_id)
1806                .ok_or_else(|| anyhow!("No subagent session found with id {session_id}"))?;
1807            anyhow::Ok((session.thread.clone(), session.acp_thread.clone()))
1808        })??;
1809
1810        let depth = subagent_thread.read(cx).depth();
1811
1812        if let Some(parent_thread_entity) = self.thread.upgrade() {
1813            telemetry::event!(
1814                "Subagent Started",
1815                session = parent_thread_entity.read(cx).id().to_string(),
1816                subagent_session = session_id.to_string(),
1817                depth,
1818                is_resumed = true,
1819            );
1820        }
1821
1822        self.prompt_subagent(session_id, subagent_thread, acp_thread)
1823    }
1824
1825    fn prompt_subagent(
1826        &self,
1827        session_id: acp::SessionId,
1828        subagent_thread: Entity<Thread>,
1829        acp_thread: Entity<acp_thread::AcpThread>,
1830    ) -> Result<Rc<dyn SubagentHandle>> {
1831        let Some(parent_thread_entity) = self.thread.upgrade() else {
1832            anyhow::bail!("Parent thread no longer exists".to_string());
1833        };
1834        Ok(Rc::new(NativeSubagentHandle::new(
1835            session_id,
1836            subagent_thread,
1837            acp_thread,
1838            parent_thread_entity,
1839        )) as _)
1840    }
1841}
1842
1843impl ThreadEnvironment for NativeThreadEnvironment {
1844    fn create_terminal(
1845        &self,
1846        command: String,
1847        cwd: Option<PathBuf>,
1848        output_byte_limit: Option<u64>,
1849        cx: &mut AsyncApp,
1850    ) -> Task<Result<Rc<dyn TerminalHandle>>> {
1851        let task = self.acp_thread.update(cx, |thread, cx| {
1852            thread.create_terminal(command, vec![], vec![], cwd, output_byte_limit, cx)
1853        });
1854
1855        let acp_thread = self.acp_thread.clone();
1856        cx.spawn(async move |cx| {
1857            let terminal = task?.await?;
1858
1859            let (drop_tx, drop_rx) = oneshot::channel();
1860            let terminal_id = terminal.read_with(cx, |terminal, _cx| terminal.id().clone());
1861
1862            cx.spawn(async move |cx| {
1863                drop_rx.await.ok();
1864                acp_thread.update(cx, |thread, cx| thread.release_terminal(terminal_id, cx))
1865            })
1866            .detach();
1867
1868            let handle = AcpTerminalHandle {
1869                terminal,
1870                _drop_tx: Some(drop_tx),
1871            };
1872
1873            Ok(Rc::new(handle) as _)
1874        })
1875    }
1876
1877    fn create_subagent(&self, label: String, cx: &mut App) -> Result<Rc<dyn SubagentHandle>> {
1878        self.create_subagent_thread(label, cx)
1879    }
1880
1881    fn resume_subagent(
1882        &self,
1883        session_id: acp::SessionId,
1884        cx: &mut App,
1885    ) -> Result<Rc<dyn SubagentHandle>> {
1886        self.resume_subagent_thread(session_id, cx)
1887    }
1888}
1889
1890#[derive(Debug, Clone)]
1891enum SubagentPromptResult {
1892    Completed,
1893    Cancelled,
1894    ContextWindowWarning,
1895    Error(String),
1896}
1897
1898pub struct NativeSubagentHandle {
1899    session_id: acp::SessionId,
1900    parent_thread: WeakEntity<Thread>,
1901    subagent_thread: Entity<Thread>,
1902    acp_thread: Entity<acp_thread::AcpThread>,
1903}
1904
1905impl NativeSubagentHandle {
1906    fn new(
1907        session_id: acp::SessionId,
1908        subagent_thread: Entity<Thread>,
1909        acp_thread: Entity<acp_thread::AcpThread>,
1910        parent_thread_entity: Entity<Thread>,
1911    ) -> Self {
1912        NativeSubagentHandle {
1913            session_id,
1914            subagent_thread,
1915            parent_thread: parent_thread_entity.downgrade(),
1916            acp_thread,
1917        }
1918    }
1919}
1920
1921impl SubagentHandle for NativeSubagentHandle {
1922    fn id(&self) -> acp::SessionId {
1923        self.session_id.clone()
1924    }
1925
1926    fn num_entries(&self, cx: &App) -> usize {
1927        self.acp_thread.read(cx).entries().len()
1928    }
1929
1930    fn send(&self, message: String, cx: &AsyncApp) -> Task<Result<String>> {
1931        let thread = self.subagent_thread.clone();
1932        let acp_thread = self.acp_thread.clone();
1933        let subagent_session_id = self.session_id.clone();
1934        let parent_thread = self.parent_thread.clone();
1935
1936        cx.spawn(async move |cx| {
1937            let (task, _subscription) = cx.update(|cx| {
1938                let ratio_before_prompt = thread
1939                    .read(cx)
1940                    .latest_token_usage()
1941                    .map(|usage| usage.ratio());
1942
1943                parent_thread
1944                    .update(cx, |parent_thread, _cx| {
1945                        parent_thread.register_running_subagent(thread.downgrade())
1946                    })
1947                    .ok();
1948
1949                let task = acp_thread.update(cx, |acp_thread, cx| {
1950                    acp_thread.send(vec![message.into()], cx)
1951                });
1952
1953                let (token_limit_tx, token_limit_rx) = oneshot::channel::<()>();
1954                let mut token_limit_tx = Some(token_limit_tx);
1955
1956                let subscription = cx.subscribe(
1957                    &thread,
1958                    move |_thread, event: &TokenUsageUpdated, _cx| {
1959                        if let Some(usage) = &event.0 {
1960                            let old_ratio = ratio_before_prompt
1961                                .clone()
1962                                .unwrap_or(TokenUsageRatio::Normal);
1963                            let new_ratio = usage.ratio();
1964                            if old_ratio == TokenUsageRatio::Normal
1965                                && new_ratio == TokenUsageRatio::Warning
1966                            {
1967                                if let Some(tx) = token_limit_tx.take() {
1968                                    tx.send(()).ok();
1969                                }
1970                            }
1971                        }
1972                    },
1973                );
1974
1975                let wait_for_prompt = cx
1976                    .background_spawn(async move {
1977                        futures::select! {
1978                            response = task.fuse() => match response {
1979                                Ok(Some(response)) => {
1980                                    match response.stop_reason {
1981                                        acp::StopReason::Cancelled => SubagentPromptResult::Cancelled,
1982                                        acp::StopReason::MaxTokens => SubagentPromptResult::Error("The agent reached the maximum number of tokens.".into()),
1983                                        acp::StopReason::MaxTurnRequests => SubagentPromptResult::Error("The agent reached the maximum number of allowed requests between user turns. Try prompting again.".into()),
1984                                        acp::StopReason::Refusal => SubagentPromptResult::Error("The agent refused to process that prompt. Try again.".into()),
1985                                        acp::StopReason::EndTurn | _ => SubagentPromptResult::Completed,
1986                                    }
1987                                }
1988                                Ok(None) => SubagentPromptResult::Error("No response from the agent. You can try messaging again.".into()),
1989                                Err(error) => SubagentPromptResult::Error(error.to_string()),
1990                            },
1991                            _ = token_limit_rx.fuse() => SubagentPromptResult::ContextWindowWarning,
1992                        }
1993                    });
1994
1995                (wait_for_prompt, subscription)
1996            });
1997
1998            let result = match task.await {
1999                SubagentPromptResult::Completed => thread.read_with(cx, |thread, _cx| {
2000                    thread
2001                        .last_message()
2002                        .and_then(|message| {
2003                            let content = message.as_agent_message()?
2004                                .content
2005                                .iter()
2006                                .filter_map(|c| match c {
2007                                    AgentMessageContent::Text(text) => Some(text.as_str()),
2008                                    _ => None,
2009                                })
2010                                .join("\n\n");
2011                            if content.is_empty() {
2012                                None
2013                            } else {
2014                                Some( content)
2015                            }
2016                        })
2017                        .context("No response from subagent")
2018                }),
2019                SubagentPromptResult::Cancelled => Err(anyhow!("User canceled")),
2020                SubagentPromptResult::Error(message) => Err(anyhow!("{message}")),
2021                SubagentPromptResult::ContextWindowWarning => {
2022                    thread.update(cx, |thread, cx| thread.cancel(cx)).await;
2023                    Err(anyhow!(
2024                        "The agent is nearing the end of its context window and has been \
2025                         stopped. You can prompt the thread again to have the agent wrap up \
2026                         or hand off its work."
2027                    ))
2028                }
2029            };
2030
2031            parent_thread
2032                .update(cx, |parent_thread, cx| {
2033                    parent_thread.unregister_running_subagent(&subagent_session_id, cx)
2034                })
2035                .ok();
2036
2037            result
2038        })
2039    }
2040}
2041
2042pub struct AcpTerminalHandle {
2043    terminal: Entity<acp_thread::Terminal>,
2044    _drop_tx: Option<oneshot::Sender<()>>,
2045}
2046
2047impl TerminalHandle for AcpTerminalHandle {
2048    fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId> {
2049        Ok(self.terminal.read_with(cx, |term, _cx| term.id().clone()))
2050    }
2051
2052    fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>> {
2053        Ok(self
2054            .terminal
2055            .read_with(cx, |term, _cx| term.wait_for_exit()))
2056    }
2057
2058    fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse> {
2059        Ok(self
2060            .terminal
2061            .read_with(cx, |term, cx| term.current_output(cx)))
2062    }
2063
2064    fn kill(&self, cx: &AsyncApp) -> Result<()> {
2065        cx.update(|cx| {
2066            self.terminal.update(cx, |terminal, cx| {
2067                terminal.kill(cx);
2068            });
2069        });
2070        Ok(())
2071    }
2072
2073    fn was_stopped_by_user(&self, cx: &AsyncApp) -> Result<bool> {
2074        Ok(self
2075            .terminal
2076            .read_with(cx, |term, _cx| term.was_stopped_by_user()))
2077    }
2078}
2079
2080#[cfg(test)]
2081mod internal_tests {
2082    use super::*;
2083    use acp_thread::{AgentConnection, AgentModelGroupName, AgentModelInfo, MentionUri};
2084    use fs::FakeFs;
2085    use gpui::TestAppContext;
2086    use indoc::formatdoc;
2087    use language_model::fake_provider::{FakeLanguageModel, FakeLanguageModelProvider};
2088    use language_model::{
2089        LanguageModelCompletionEvent, LanguageModelProviderId, LanguageModelProviderName,
2090    };
2091    use serde_json::json;
2092    use settings::SettingsStore;
2093    use util::{path, rel_path::rel_path};
2094
2095    #[gpui::test]
2096    async fn test_maintaining_project_context(cx: &mut TestAppContext) {
2097        init_test(cx);
2098        let fs = FakeFs::new(cx.executor());
2099        fs.insert_tree(
2100            "/",
2101            json!({
2102                "a": {}
2103            }),
2104        )
2105        .await;
2106        let project = Project::test(fs.clone(), [], cx).await;
2107        let thread_store = cx.new(|cx| ThreadStore::new(cx));
2108        let agent =
2109            cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
2110
2111        // Creating a session registers the project and triggers context building.
2112        let connection = NativeAgentConnection(agent.clone());
2113        let _acp_thread = cx
2114            .update(|cx| Rc::new(connection).new_session(project.clone(), Path::new("/"), cx))
2115            .await
2116            .unwrap();
2117        cx.run_until_parked();
2118
2119        agent.read_with(cx, |agent, cx| {
2120            let project_id = project.entity_id();
2121            let state = agent.projects.get(&project_id).unwrap();
2122            assert_eq!(state.project_context.read(cx).worktrees, vec![])
2123        });
2124
2125        let worktree = project
2126            .update(cx, |project, cx| project.create_worktree("/a", true, cx))
2127            .await
2128            .unwrap();
2129        cx.run_until_parked();
2130        agent.read_with(cx, |agent, cx| {
2131            let project_id = project.entity_id();
2132            let state = agent.projects.get(&project_id).unwrap();
2133            assert_eq!(
2134                state.project_context.read(cx).worktrees,
2135                vec![WorktreeContext {
2136                    root_name: "a".into(),
2137                    abs_path: Path::new("/a").into(),
2138                    rules_file: None
2139                }]
2140            )
2141        });
2142
2143        // Creating `/a/.rules` updates the project context.
2144        fs.insert_file("/a/.rules", Vec::new()).await;
2145        cx.run_until_parked();
2146        agent.read_with(cx, |agent, cx| {
2147            let project_id = project.entity_id();
2148            let state = agent.projects.get(&project_id).unwrap();
2149            let rules_entry = worktree
2150                .read(cx)
2151                .entry_for_path(rel_path(".rules"))
2152                .unwrap();
2153            assert_eq!(
2154                state.project_context.read(cx).worktrees,
2155                vec![WorktreeContext {
2156                    root_name: "a".into(),
2157                    abs_path: Path::new("/a").into(),
2158                    rules_file: Some(RulesFileContext {
2159                        path_in_worktree: rel_path(".rules").into(),
2160                        text: "".into(),
2161                        project_entry_id: rules_entry.id.to_usize()
2162                    })
2163                }]
2164            )
2165        });
2166    }
2167
2168    #[gpui::test]
2169    async fn test_listing_models(cx: &mut TestAppContext) {
2170        init_test(cx);
2171        let fs = FakeFs::new(cx.executor());
2172        fs.insert_tree("/", json!({ "a": {}  })).await;
2173        let project = Project::test(fs.clone(), [], cx).await;
2174        let thread_store = cx.new(|cx| ThreadStore::new(cx));
2175        let connection =
2176            NativeAgentConnection(cx.update(|cx| {
2177                NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx)
2178            }));
2179
2180        // Create a thread/session
2181        let acp_thread = cx
2182            .update(|cx| {
2183                Rc::new(connection.clone()).new_session(project.clone(), Path::new("/a"), cx)
2184            })
2185            .await
2186            .unwrap();
2187
2188        let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());
2189
2190        let models = cx
2191            .update(|cx| {
2192                connection
2193                    .model_selector(&session_id)
2194                    .unwrap()
2195                    .list_models(cx)
2196            })
2197            .await
2198            .unwrap();
2199
2200        let acp_thread::AgentModelList::Grouped(models) = models else {
2201            panic!("Unexpected model group");
2202        };
2203        assert_eq!(
2204            models,
2205            IndexMap::from_iter([(
2206                AgentModelGroupName("Fake".into()),
2207                vec![AgentModelInfo {
2208                    id: acp::ModelId::new("fake/fake"),
2209                    name: "Fake".into(),
2210                    description: None,
2211                    icon: Some(acp_thread::AgentModelIcon::Named(
2212                        ui::IconName::ZedAssistant
2213                    )),
2214                    is_latest: false,
2215                    cost: None,
2216                }]
2217            )])
2218        );
2219    }
2220
2221    #[gpui::test]
2222    async fn test_model_selection_persists_to_settings(cx: &mut TestAppContext) {
2223        init_test(cx);
2224        let fs = FakeFs::new(cx.executor());
2225        fs.create_dir(paths::settings_file().parent().unwrap())
2226            .await
2227            .unwrap();
2228        fs.insert_file(
2229            paths::settings_file(),
2230            json!({
2231                "agent": {
2232                    "default_model": {
2233                        "provider": "foo",
2234                        "model": "bar"
2235                    }
2236                }
2237            })
2238            .to_string()
2239            .into_bytes(),
2240        )
2241        .await;
2242        let project = Project::test(fs.clone(), [], cx).await;
2243
2244        let thread_store = cx.new(|cx| ThreadStore::new(cx));
2245
2246        // Create the agent and connection
2247        let agent =
2248            cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
2249        let connection = NativeAgentConnection(agent.clone());
2250
2251        // Create a thread/session
2252        let acp_thread = cx
2253            .update(|cx| {
2254                Rc::new(connection.clone()).new_session(project.clone(), Path::new("/a"), cx)
2255            })
2256            .await
2257            .unwrap();
2258
2259        let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());
2260
2261        // Select a model
2262        let selector = connection.model_selector(&session_id).unwrap();
2263        let model_id = acp::ModelId::new("fake/fake");
2264        cx.update(|cx| selector.select_model(model_id.clone(), cx))
2265            .await
2266            .unwrap();
2267
2268        // Verify the thread has the selected model
2269        agent.read_with(cx, |agent, _| {
2270            let session = agent.sessions.get(&session_id).unwrap();
2271            session.thread.read_with(cx, |thread, _| {
2272                assert_eq!(thread.model().unwrap().id().0, "fake");
2273            });
2274        });
2275
2276        cx.run_until_parked();
2277
2278        // Verify settings file was updated
2279        let settings_content = fs.load(paths::settings_file()).await.unwrap();
2280        let settings_json: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
2281
2282        // Check that the agent settings contain the selected model
2283        assert_eq!(
2284            settings_json["agent"]["default_model"]["model"],
2285            json!("fake")
2286        );
2287        assert_eq!(
2288            settings_json["agent"]["default_model"]["provider"],
2289            json!("fake")
2290        );
2291
2292        // Register a thinking model and select it.
2293        cx.update(|cx| {
2294            let thinking_model = Arc::new(FakeLanguageModel::with_id_and_thinking(
2295                "fake-corp",
2296                "fake-thinking",
2297                "Fake Thinking",
2298                true,
2299            ));
2300            let thinking_provider = Arc::new(
2301                FakeLanguageModelProvider::new(
2302                    LanguageModelProviderId::from("fake-corp".to_string()),
2303                    LanguageModelProviderName::from("Fake Corp".to_string()),
2304                )
2305                .with_models(vec![thinking_model]),
2306            );
2307            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
2308                registry.register_provider(thinking_provider, cx);
2309            });
2310        });
2311        agent.update(cx, |agent, cx| agent.models.refresh_list(cx));
2312
2313        let selector = connection.model_selector(&session_id).unwrap();
2314        cx.update(|cx| selector.select_model(acp::ModelId::new("fake-corp/fake-thinking"), cx))
2315            .await
2316            .unwrap();
2317        cx.run_until_parked();
2318
2319        // Verify enable_thinking was written to settings as true.
2320        let settings_content = fs.load(paths::settings_file()).await.unwrap();
2321        let settings_json: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
2322        assert_eq!(
2323            settings_json["agent"]["default_model"]["enable_thinking"],
2324            json!(true),
2325            "selecting a thinking model should persist enable_thinking: true to settings"
2326        );
2327    }
2328
2329    #[gpui::test]
2330    async fn test_select_model_updates_thinking_enabled(cx: &mut TestAppContext) {
2331        init_test(cx);
2332        let fs = FakeFs::new(cx.executor());
2333        fs.create_dir(paths::settings_file().parent().unwrap())
2334            .await
2335            .unwrap();
2336        fs.insert_file(paths::settings_file(), b"{}".to_vec()).await;
2337        let project = Project::test(fs.clone(), [], cx).await;
2338
2339        let thread_store = cx.new(|cx| ThreadStore::new(cx));
2340        let agent =
2341            cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
2342        let connection = NativeAgentConnection(agent.clone());
2343
2344        let acp_thread = cx
2345            .update(|cx| {
2346                Rc::new(connection.clone()).new_session(project.clone(), Path::new("/a"), cx)
2347            })
2348            .await
2349            .unwrap();
2350        let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());
2351
2352        // Register a second provider with a thinking model.
2353        cx.update(|cx| {
2354            let thinking_model = Arc::new(FakeLanguageModel::with_id_and_thinking(
2355                "fake-corp",
2356                "fake-thinking",
2357                "Fake Thinking",
2358                true,
2359            ));
2360            let thinking_provider = Arc::new(
2361                FakeLanguageModelProvider::new(
2362                    LanguageModelProviderId::from("fake-corp".to_string()),
2363                    LanguageModelProviderName::from("Fake Corp".to_string()),
2364                )
2365                .with_models(vec![thinking_model]),
2366            );
2367            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
2368                registry.register_provider(thinking_provider, cx);
2369            });
2370        });
2371        // Refresh the agent's model list so it picks up the new provider.
2372        agent.update(cx, |agent, cx| agent.models.refresh_list(cx));
2373
2374        // Thread starts with thinking_enabled = false (the default).
2375        agent.read_with(cx, |agent, _| {
2376            let session = agent.sessions.get(&session_id).unwrap();
2377            session.thread.read_with(cx, |thread, _| {
2378                assert!(!thread.thinking_enabled(), "thinking defaults to false");
2379            });
2380        });
2381
2382        // Select the thinking model via select_model.
2383        let selector = connection.model_selector(&session_id).unwrap();
2384        cx.update(|cx| selector.select_model(acp::ModelId::new("fake-corp/fake-thinking"), cx))
2385            .await
2386            .unwrap();
2387
2388        // select_model should have enabled thinking based on the model's supports_thinking().
2389        agent.read_with(cx, |agent, _| {
2390            let session = agent.sessions.get(&session_id).unwrap();
2391            session.thread.read_with(cx, |thread, _| {
2392                assert!(
2393                    thread.thinking_enabled(),
2394                    "select_model should enable thinking when model supports it"
2395                );
2396            });
2397        });
2398
2399        // Switch back to the non-thinking model.
2400        let selector = connection.model_selector(&session_id).unwrap();
2401        cx.update(|cx| selector.select_model(acp::ModelId::new("fake/fake"), cx))
2402            .await
2403            .unwrap();
2404
2405        // select_model should have disabled thinking.
2406        agent.read_with(cx, |agent, _| {
2407            let session = agent.sessions.get(&session_id).unwrap();
2408            session.thread.read_with(cx, |thread, _| {
2409                assert!(
2410                    !thread.thinking_enabled(),
2411                    "select_model should disable thinking when model does not support it"
2412                );
2413            });
2414        });
2415    }
2416
2417    #[gpui::test]
2418    async fn test_loaded_thread_preserves_thinking_enabled(cx: &mut TestAppContext) {
2419        init_test(cx);
2420        let fs = FakeFs::new(cx.executor());
2421        fs.insert_tree("/", json!({ "a": {} })).await;
2422        let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
2423        let thread_store = cx.new(|cx| ThreadStore::new(cx));
2424        let agent = cx.update(|cx| {
2425            NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
2426        });
2427        let connection = Rc::new(NativeAgentConnection(agent.clone()));
2428
2429        // Register a thinking model.
2430        let thinking_model = Arc::new(FakeLanguageModel::with_id_and_thinking(
2431            "fake-corp",
2432            "fake-thinking",
2433            "Fake Thinking",
2434            true,
2435        ));
2436        let thinking_provider = Arc::new(
2437            FakeLanguageModelProvider::new(
2438                LanguageModelProviderId::from("fake-corp".to_string()),
2439                LanguageModelProviderName::from("Fake Corp".to_string()),
2440            )
2441            .with_models(vec![thinking_model.clone()]),
2442        );
2443        cx.update(|cx| {
2444            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
2445                registry.register_provider(thinking_provider, cx);
2446            });
2447        });
2448        agent.update(cx, |agent, cx| agent.models.refresh_list(cx));
2449
2450        // Create a thread and select the thinking model.
2451        let acp_thread = cx
2452            .update(|cx| {
2453                connection
2454                    .clone()
2455                    .new_session(project.clone(), Path::new("/a"), cx)
2456            })
2457            .await
2458            .unwrap();
2459        let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
2460
2461        let selector = connection.model_selector(&session_id).unwrap();
2462        cx.update(|cx| selector.select_model(acp::ModelId::new("fake-corp/fake-thinking"), cx))
2463            .await
2464            .unwrap();
2465
2466        // Verify thinking is enabled after selecting the thinking model.
2467        let thread = agent.read_with(cx, |agent, _| {
2468            agent.sessions.get(&session_id).unwrap().thread.clone()
2469        });
2470        thread.read_with(cx, |thread, _| {
2471            assert!(
2472                thread.thinking_enabled(),
2473                "thinking should be enabled after selecting thinking model"
2474            );
2475        });
2476
2477        // Send a message so the thread gets persisted.
2478        let send = acp_thread.update(cx, |thread, cx| thread.send(vec!["Hello".into()], cx));
2479        let send = cx.foreground_executor().spawn(send);
2480        cx.run_until_parked();
2481
2482        thinking_model.send_last_completion_stream_text_chunk("Response.");
2483        thinking_model.end_last_completion_stream();
2484
2485        send.await.unwrap();
2486        cx.run_until_parked();
2487
2488        // Close the session so it can be reloaded from disk.
2489        cx.update(|cx| connection.clone().close_session(&session_id, cx))
2490            .await
2491            .unwrap();
2492        drop(thread);
2493        drop(acp_thread);
2494        agent.read_with(cx, |agent, _| {
2495            assert!(agent.sessions.is_empty());
2496        });
2497
2498        // Reload the thread and verify thinking_enabled is still true.
2499        let reloaded_acp_thread = agent
2500            .update(cx, |agent, cx| {
2501                agent.open_thread(session_id.clone(), project.clone(), cx)
2502            })
2503            .await
2504            .unwrap();
2505        let reloaded_thread = agent.read_with(cx, |agent, _| {
2506            agent.sessions.get(&session_id).unwrap().thread.clone()
2507        });
2508        reloaded_thread.read_with(cx, |thread, _| {
2509            assert!(
2510                thread.thinking_enabled(),
2511                "thinking_enabled should be preserved when reloading a thread with a thinking model"
2512            );
2513        });
2514
2515        drop(reloaded_acp_thread);
2516    }
2517
2518    #[gpui::test]
2519    async fn test_loaded_thread_preserves_model(cx: &mut TestAppContext) {
2520        init_test(cx);
2521        let fs = FakeFs::new(cx.executor());
2522        fs.insert_tree("/", json!({ "a": {} })).await;
2523        let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
2524        let thread_store = cx.new(|cx| ThreadStore::new(cx));
2525        let agent = cx.update(|cx| {
2526            NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
2527        });
2528        let connection = Rc::new(NativeAgentConnection(agent.clone()));
2529
2530        // Register a model where id() != name(), like real Anthropic models
2531        // (e.g. id="claude-sonnet-4-5-thinking-latest", name="Claude Sonnet 4.5 Thinking").
2532        let model = Arc::new(FakeLanguageModel::with_id_and_thinking(
2533            "fake-corp",
2534            "custom-model-id",
2535            "Custom Model Display Name",
2536            false,
2537        ));
2538        let provider = Arc::new(
2539            FakeLanguageModelProvider::new(
2540                LanguageModelProviderId::from("fake-corp".to_string()),
2541                LanguageModelProviderName::from("Fake Corp".to_string()),
2542            )
2543            .with_models(vec![model.clone()]),
2544        );
2545        cx.update(|cx| {
2546            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
2547                registry.register_provider(provider, cx);
2548            });
2549        });
2550        agent.update(cx, |agent, cx| agent.models.refresh_list(cx));
2551
2552        // Create a thread and select the model.
2553        let acp_thread = cx
2554            .update(|cx| {
2555                connection
2556                    .clone()
2557                    .new_session(project.clone(), Path::new("/a"), cx)
2558            })
2559            .await
2560            .unwrap();
2561        let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
2562
2563        let selector = connection.model_selector(&session_id).unwrap();
2564        cx.update(|cx| selector.select_model(acp::ModelId::new("fake-corp/custom-model-id"), cx))
2565            .await
2566            .unwrap();
2567
2568        let thread = agent.read_with(cx, |agent, _| {
2569            agent.sessions.get(&session_id).unwrap().thread.clone()
2570        });
2571        thread.read_with(cx, |thread, _| {
2572            assert_eq!(
2573                thread.model().unwrap().id().0.as_ref(),
2574                "custom-model-id",
2575                "model should be set before persisting"
2576            );
2577        });
2578
2579        // Send a message so the thread gets persisted.
2580        let send = acp_thread.update(cx, |thread, cx| thread.send(vec!["Hello".into()], cx));
2581        let send = cx.foreground_executor().spawn(send);
2582        cx.run_until_parked();
2583
2584        model.send_last_completion_stream_text_chunk("Response.");
2585        model.end_last_completion_stream();
2586
2587        send.await.unwrap();
2588        cx.run_until_parked();
2589
2590        // Close the session so it can be reloaded from disk.
2591        cx.update(|cx| connection.clone().close_session(&session_id, cx))
2592            .await
2593            .unwrap();
2594        drop(thread);
2595        drop(acp_thread);
2596        agent.read_with(cx, |agent, _| {
2597            assert!(agent.sessions.is_empty());
2598        });
2599
2600        // Reload the thread and verify the model was preserved.
2601        let reloaded_acp_thread = agent
2602            .update(cx, |agent, cx| {
2603                agent.open_thread(session_id.clone(), project.clone(), cx)
2604            })
2605            .await
2606            .unwrap();
2607        let reloaded_thread = agent.read_with(cx, |agent, _| {
2608            agent.sessions.get(&session_id).unwrap().thread.clone()
2609        });
2610        reloaded_thread.read_with(cx, |thread, _| {
2611            let reloaded_model = thread
2612                .model()
2613                .expect("model should be present after reload");
2614            assert_eq!(
2615                reloaded_model.id().0.as_ref(),
2616                "custom-model-id",
2617                "reloaded thread should have the same model, not fall back to the default"
2618            );
2619        });
2620
2621        drop(reloaded_acp_thread);
2622    }
2623
2624    #[gpui::test]
2625    async fn test_save_load_thread(cx: &mut TestAppContext) {
2626        init_test(cx);
2627        let fs = FakeFs::new(cx.executor());
2628        fs.insert_tree(
2629            "/",
2630            json!({
2631                "a": {
2632                    "b.md": "Lorem"
2633                }
2634            }),
2635        )
2636        .await;
2637        let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
2638        let thread_store = cx.new(|cx| ThreadStore::new(cx));
2639        let agent = cx.update(|cx| {
2640            NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
2641        });
2642        let connection = Rc::new(NativeAgentConnection(agent.clone()));
2643
2644        let acp_thread = cx
2645            .update(|cx| {
2646                connection
2647                    .clone()
2648                    .new_session(project.clone(), Path::new(""), cx)
2649            })
2650            .await
2651            .unwrap();
2652        let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
2653        let thread = agent.read_with(cx, |agent, _| {
2654            agent.sessions.get(&session_id).unwrap().thread.clone()
2655        });
2656
2657        // Ensure empty threads are not saved, even if they get mutated.
2658        let model = Arc::new(FakeLanguageModel::default());
2659        let summary_model = Arc::new(FakeLanguageModel::default());
2660        thread.update(cx, |thread, cx| {
2661            thread.set_model(model.clone(), cx);
2662            thread.set_summarization_model(Some(summary_model.clone()), cx);
2663        });
2664        cx.run_until_parked();
2665        assert_eq!(thread_entries(&thread_store, cx), vec![]);
2666
2667        let send = acp_thread.update(cx, |thread, cx| {
2668            thread.send(
2669                vec![
2670                    "What does ".into(),
2671                    acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
2672                        "b.md",
2673                        MentionUri::File {
2674                            abs_path: path!("/a/b.md").into(),
2675                        }
2676                        .to_uri()
2677                        .to_string(),
2678                    )),
2679                    " mean?".into(),
2680                ],
2681                cx,
2682            )
2683        });
2684        let send = cx.foreground_executor().spawn(send);
2685        cx.run_until_parked();
2686
2687        model.send_last_completion_stream_text_chunk("Lorem.");
2688        model.send_last_completion_stream_event(LanguageModelCompletionEvent::UsageUpdate(
2689            language_model::TokenUsage {
2690                input_tokens: 150,
2691                output_tokens: 75,
2692                ..Default::default()
2693            },
2694        ));
2695        model.end_last_completion_stream();
2696        cx.run_until_parked();
2697        summary_model
2698            .send_last_completion_stream_text_chunk(&format!("Explaining {}", path!("/a/b.md")));
2699        summary_model.end_last_completion_stream();
2700
2701        send.await.unwrap();
2702        let uri = MentionUri::File {
2703            abs_path: path!("/a/b.md").into(),
2704        }
2705        .to_uri();
2706        acp_thread.read_with(cx, |thread, cx| {
2707            assert_eq!(
2708                thread.to_markdown(cx),
2709                formatdoc! {"
2710                    ## User
2711
2712                    What does [@b.md]({uri}) mean?
2713
2714                    ## Assistant
2715
2716                    Lorem.
2717
2718                "}
2719            )
2720        });
2721
2722        cx.run_until_parked();
2723
2724        // Set a draft prompt with rich content blocks before saving.
2725        let draft_blocks = vec![
2726            acp::ContentBlock::Text(acp::TextContent::new("Check out ")),
2727            acp::ContentBlock::ResourceLink(acp::ResourceLink::new("b.md", uri.to_string())),
2728            acp::ContentBlock::Text(acp::TextContent::new(" please")),
2729        ];
2730        acp_thread.update(cx, |thread, _cx| {
2731            thread.set_draft_prompt(Some(draft_blocks.clone()));
2732        });
2733        thread.update(cx, |thread, _cx| {
2734            thread.set_ui_scroll_position(Some(gpui::ListOffset {
2735                item_ix: 5,
2736                offset_in_item: gpui::px(12.5),
2737            }));
2738        });
2739        thread.update(cx, |_thread, cx| cx.notify());
2740        cx.run_until_parked();
2741
2742        // Close the session so it can be reloaded from disk.
2743        cx.update(|cx| connection.clone().close_session(&session_id, cx))
2744            .await
2745            .unwrap();
2746        drop(thread);
2747        drop(acp_thread);
2748        agent.read_with(cx, |agent, _| {
2749            assert_eq!(agent.sessions.keys().cloned().collect::<Vec<_>>(), []);
2750        });
2751
2752        // Ensure the thread can be reloaded from disk.
2753        assert_eq!(
2754            thread_entries(&thread_store, cx),
2755            vec![(
2756                session_id.clone(),
2757                format!("Explaining {}", path!("/a/b.md"))
2758            )]
2759        );
2760        let acp_thread = agent
2761            .update(cx, |agent, cx| {
2762                agent.open_thread(session_id.clone(), project.clone(), cx)
2763            })
2764            .await
2765            .unwrap();
2766        acp_thread.read_with(cx, |thread, cx| {
2767            assert_eq!(
2768                thread.to_markdown(cx),
2769                formatdoc! {"
2770                    ## User
2771
2772                    What does [@b.md]({uri}) mean?
2773
2774                    ## Assistant
2775
2776                    Lorem.
2777
2778                "}
2779            )
2780        });
2781
2782        // Ensure the draft prompt with rich content blocks survived the round-trip.
2783        acp_thread.read_with(cx, |thread, _| {
2784            assert_eq!(thread.draft_prompt(), Some(draft_blocks.as_slice()));
2785        });
2786
2787        // Ensure token usage survived the round-trip.
2788        acp_thread.read_with(cx, |thread, _| {
2789            let usage = thread
2790                .token_usage()
2791                .expect("token usage should be restored after reload");
2792            assert_eq!(usage.input_tokens, 150);
2793            assert_eq!(usage.output_tokens, 75);
2794        });
2795
2796        // Ensure scroll position survived the round-trip.
2797        acp_thread.read_with(cx, |thread, _| {
2798            let scroll = thread
2799                .ui_scroll_position()
2800                .expect("scroll position should be restored after reload");
2801            assert_eq!(scroll.item_ix, 5);
2802            assert_eq!(scroll.offset_in_item, gpui::px(12.5));
2803        });
2804    }
2805
2806    fn thread_entries(
2807        thread_store: &Entity<ThreadStore>,
2808        cx: &mut TestAppContext,
2809    ) -> Vec<(acp::SessionId, String)> {
2810        thread_store.read_with(cx, |store, _| {
2811            store
2812                .entries()
2813                .map(|entry| (entry.id.clone(), entry.title.to_string()))
2814                .collect::<Vec<_>>()
2815        })
2816    }
2817
2818    fn init_test(cx: &mut TestAppContext) {
2819        env_logger::try_init().ok();
2820        cx.update(|cx| {
2821            let settings_store = SettingsStore::test(cx);
2822            cx.set_global(settings_store);
2823
2824            LanguageModelRegistry::test(cx);
2825        });
2826    }
2827}
2828
2829fn mcp_message_content_to_acp_content_block(
2830    content: context_server::types::MessageContent,
2831) -> acp::ContentBlock {
2832    match content {
2833        context_server::types::MessageContent::Text {
2834            text,
2835            annotations: _,
2836        } => text.into(),
2837        context_server::types::MessageContent::Image {
2838            data,
2839            mime_type,
2840            annotations: _,
2841        } => acp::ContentBlock::Image(acp::ImageContent::new(data, mime_type)),
2842        context_server::types::MessageContent::Audio {
2843            data,
2844            mime_type,
2845            annotations: _,
2846        } => acp::ContentBlock::Audio(acp::AudioContent::new(data, mime_type)),
2847        context_server::types::MessageContent::Resource {
2848            resource,
2849            annotations: _,
2850        } => {
2851            let mut link =
2852                acp::ResourceLink::new(resource.uri.to_string(), resource.uri.to_string());
2853            if let Some(mime_type) = resource.mime_type {
2854                link = link.mime_type(mime_type);
2855            }
2856            acp::ContentBlock::ResourceLink(link)
2857        }
2858    }
2859}