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(&self, session_id: &acp::SessionId, cx: &mut App) -> Task<Result<()>> {
1422        self.0.update(cx, |agent, _cx| {
1423            let project_id = agent.sessions.get(session_id).map(|s| s.project_id);
1424            agent.sessions.remove(session_id);
1425
1426            if let Some(project_id) = project_id {
1427                let has_remaining = agent.sessions.values().any(|s| s.project_id == project_id);
1428                if !has_remaining {
1429                    agent.projects.remove(&project_id);
1430                }
1431            }
1432        });
1433        Task::ready(Ok(()))
1434    }
1435
1436    fn auth_methods(&self) -> &[acp::AuthMethod] {
1437        &[] // No auth for in-process
1438    }
1439
1440    fn authenticate(&self, _method: acp::AuthMethodId, _cx: &mut App) -> Task<Result<()>> {
1441        Task::ready(Ok(()))
1442    }
1443
1444    fn model_selector(&self, session_id: &acp::SessionId) -> Option<Rc<dyn AgentModelSelector>> {
1445        Some(Rc::new(NativeAgentModelSelector {
1446            session_id: session_id.clone(),
1447            connection: self.clone(),
1448        }) as Rc<dyn AgentModelSelector>)
1449    }
1450
1451    fn prompt(
1452        &self,
1453        id: Option<acp_thread::UserMessageId>,
1454        params: acp::PromptRequest,
1455        cx: &mut App,
1456    ) -> Task<Result<acp::PromptResponse>> {
1457        let id = id.expect("UserMessageId is required");
1458        let session_id = params.session_id.clone();
1459        log::info!("Received prompt request for session: {}", session_id);
1460        log::debug!("Prompt blocks count: {}", params.prompt.len());
1461
1462        let Some(project_state) = self.0.read(cx).session_project_state(&session_id) else {
1463            return Task::ready(Err(anyhow::anyhow!("Session not found")));
1464        };
1465
1466        if let Some(parsed_command) = Command::parse(&params.prompt) {
1467            let registry = project_state.context_server_registry.read(cx);
1468
1469            let explicit_server_id = parsed_command
1470                .explicit_server_id
1471                .map(|server_id| ContextServerId(server_id.into()));
1472
1473            if let Some(prompt) =
1474                registry.find_prompt(explicit_server_id.as_ref(), parsed_command.prompt_name)
1475            {
1476                let arguments = if !parsed_command.arg_value.is_empty()
1477                    && let Some(arg_name) = prompt
1478                        .prompt
1479                        .arguments
1480                        .as_ref()
1481                        .and_then(|args| args.first())
1482                        .map(|arg| arg.name.clone())
1483                {
1484                    HashMap::from_iter([(arg_name, parsed_command.arg_value.to_string())])
1485                } else {
1486                    Default::default()
1487                };
1488
1489                let prompt_name = prompt.prompt.name.clone();
1490                let server_id = prompt.server_id.clone();
1491
1492                return self.0.update(cx, |agent, cx| {
1493                    agent.send_mcp_prompt(
1494                        id,
1495                        session_id.clone(),
1496                        prompt_name,
1497                        server_id,
1498                        arguments,
1499                        params.prompt,
1500                        cx,
1501                    )
1502                });
1503            }
1504        };
1505
1506        let path_style = project_state.project.read(cx).path_style(cx);
1507
1508        self.run_turn(session_id, cx, move |thread, cx| {
1509            let content: Vec<UserMessageContent> = params
1510                .prompt
1511                .into_iter()
1512                .map(|block| UserMessageContent::from_content_block(block, path_style))
1513                .collect::<Vec<_>>();
1514            log::debug!("Converted prompt to message: {} chars", content.len());
1515            log::debug!("Message id: {:?}", id);
1516            log::debug!("Message content: {:?}", content);
1517
1518            thread.update(cx, |thread, cx| thread.send(id, content, cx))
1519        })
1520    }
1521
1522    fn retry(
1523        &self,
1524        session_id: &acp::SessionId,
1525        _cx: &App,
1526    ) -> Option<Rc<dyn acp_thread::AgentSessionRetry>> {
1527        Some(Rc::new(NativeAgentSessionRetry {
1528            connection: self.clone(),
1529            session_id: session_id.clone(),
1530        }) as _)
1531    }
1532
1533    fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
1534        log::info!("Cancelling on session: {}", session_id);
1535        self.0.update(cx, |agent, cx| {
1536            if let Some(session) = agent.sessions.get(session_id) {
1537                session
1538                    .thread
1539                    .update(cx, |thread, cx| thread.cancel(cx))
1540                    .detach();
1541            }
1542        });
1543    }
1544
1545    fn truncate(
1546        &self,
1547        session_id: &acp::SessionId,
1548        cx: &App,
1549    ) -> Option<Rc<dyn acp_thread::AgentSessionTruncate>> {
1550        self.0.read_with(cx, |agent, _cx| {
1551            agent.sessions.get(session_id).map(|session| {
1552                Rc::new(NativeAgentSessionTruncate {
1553                    thread: session.thread.clone(),
1554                    acp_thread: session.acp_thread.downgrade(),
1555                }) as _
1556            })
1557        })
1558    }
1559
1560    fn set_title(
1561        &self,
1562        session_id: &acp::SessionId,
1563        cx: &App,
1564    ) -> Option<Rc<dyn acp_thread::AgentSessionSetTitle>> {
1565        self.0.read_with(cx, |agent, _cx| {
1566            agent
1567                .sessions
1568                .get(session_id)
1569                .filter(|s| !s.thread.read(cx).is_subagent())
1570                .map(|session| {
1571                    Rc::new(NativeAgentSessionSetTitle {
1572                        thread: session.thread.clone(),
1573                    }) as _
1574                })
1575        })
1576    }
1577
1578    fn session_list(&self, cx: &mut App) -> Option<Rc<dyn AgentSessionList>> {
1579        let thread_store = self.0.read(cx).thread_store.clone();
1580        Some(Rc::new(NativeAgentSessionList::new(thread_store, cx)) as _)
1581    }
1582
1583    fn telemetry(&self) -> Option<Rc<dyn acp_thread::AgentTelemetry>> {
1584        Some(Rc::new(self.clone()) as Rc<dyn acp_thread::AgentTelemetry>)
1585    }
1586
1587    fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
1588        self
1589    }
1590}
1591
1592impl acp_thread::AgentTelemetry for NativeAgentConnection {
1593    fn thread_data(
1594        &self,
1595        session_id: &acp::SessionId,
1596        cx: &mut App,
1597    ) -> Task<Result<serde_json::Value>> {
1598        let Some(session) = self.0.read(cx).sessions.get(session_id) else {
1599            return Task::ready(Err(anyhow!("Session not found")));
1600        };
1601
1602        let task = session.thread.read(cx).to_db(cx);
1603        cx.background_spawn(async move {
1604            serde_json::to_value(task.await).context("Failed to serialize thread")
1605        })
1606    }
1607}
1608
1609pub struct NativeAgentSessionList {
1610    thread_store: Entity<ThreadStore>,
1611    updates_tx: smol::channel::Sender<acp_thread::SessionListUpdate>,
1612    updates_rx: smol::channel::Receiver<acp_thread::SessionListUpdate>,
1613    _subscription: Subscription,
1614}
1615
1616impl NativeAgentSessionList {
1617    fn new(thread_store: Entity<ThreadStore>, cx: &mut App) -> Self {
1618        let (tx, rx) = smol::channel::unbounded();
1619        let this_tx = tx.clone();
1620        let subscription = cx.observe(&thread_store, move |_, _| {
1621            this_tx
1622                .try_send(acp_thread::SessionListUpdate::Refresh)
1623                .ok();
1624        });
1625        Self {
1626            thread_store,
1627            updates_tx: tx,
1628            updates_rx: rx,
1629            _subscription: subscription,
1630        }
1631    }
1632
1633    pub fn thread_store(&self) -> &Entity<ThreadStore> {
1634        &self.thread_store
1635    }
1636}
1637
1638impl AgentSessionList for NativeAgentSessionList {
1639    fn list_sessions(
1640        &self,
1641        _request: AgentSessionListRequest,
1642        cx: &mut App,
1643    ) -> Task<Result<AgentSessionListResponse>> {
1644        let sessions = self
1645            .thread_store
1646            .read(cx)
1647            .entries()
1648            .map(|entry| AgentSessionInfo::from(&entry))
1649            .collect();
1650        Task::ready(Ok(AgentSessionListResponse::new(sessions)))
1651    }
1652
1653    fn supports_delete(&self) -> bool {
1654        true
1655    }
1656
1657    fn delete_session(&self, session_id: &acp::SessionId, cx: &mut App) -> Task<Result<()>> {
1658        self.thread_store
1659            .update(cx, |store, cx| store.delete_thread(session_id.clone(), cx))
1660    }
1661
1662    fn delete_sessions(&self, cx: &mut App) -> Task<Result<()>> {
1663        self.thread_store
1664            .update(cx, |store, cx| store.delete_threads(cx))
1665    }
1666
1667    fn watch(
1668        &self,
1669        _cx: &mut App,
1670    ) -> Option<smol::channel::Receiver<acp_thread::SessionListUpdate>> {
1671        Some(self.updates_rx.clone())
1672    }
1673
1674    fn notify_refresh(&self) {
1675        self.updates_tx
1676            .try_send(acp_thread::SessionListUpdate::Refresh)
1677            .ok();
1678    }
1679
1680    fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
1681        self
1682    }
1683}
1684
1685struct NativeAgentSessionTruncate {
1686    thread: Entity<Thread>,
1687    acp_thread: WeakEntity<AcpThread>,
1688}
1689
1690impl acp_thread::AgentSessionTruncate for NativeAgentSessionTruncate {
1691    fn run(&self, message_id: acp_thread::UserMessageId, cx: &mut App) -> Task<Result<()>> {
1692        match self.thread.update(cx, |thread, cx| {
1693            thread.truncate(message_id.clone(), cx)?;
1694            Ok(thread.latest_token_usage())
1695        }) {
1696            Ok(usage) => {
1697                self.acp_thread
1698                    .update(cx, |thread, cx| {
1699                        thread.update_token_usage(usage, cx);
1700                    })
1701                    .ok();
1702                Task::ready(Ok(()))
1703            }
1704            Err(error) => Task::ready(Err(error)),
1705        }
1706    }
1707}
1708
1709struct NativeAgentSessionRetry {
1710    connection: NativeAgentConnection,
1711    session_id: acp::SessionId,
1712}
1713
1714impl acp_thread::AgentSessionRetry for NativeAgentSessionRetry {
1715    fn run(&self, cx: &mut App) -> Task<Result<acp::PromptResponse>> {
1716        self.connection
1717            .run_turn(self.session_id.clone(), cx, |thread, cx| {
1718                thread.update(cx, |thread, cx| thread.resume(cx))
1719            })
1720    }
1721}
1722
1723struct NativeAgentSessionSetTitle {
1724    thread: Entity<Thread>,
1725}
1726
1727impl acp_thread::AgentSessionSetTitle for NativeAgentSessionSetTitle {
1728    fn run(&self, title: SharedString, cx: &mut App) -> Task<Result<()>> {
1729        self.thread
1730            .update(cx, |thread, cx| thread.set_title(title, cx));
1731        Task::ready(Ok(()))
1732    }
1733}
1734
1735pub struct NativeThreadEnvironment {
1736    agent: WeakEntity<NativeAgent>,
1737    thread: WeakEntity<Thread>,
1738    acp_thread: WeakEntity<AcpThread>,
1739}
1740
1741impl NativeThreadEnvironment {
1742    pub(crate) fn create_subagent_thread(
1743        &self,
1744        label: String,
1745        cx: &mut App,
1746    ) -> Result<Rc<dyn SubagentHandle>> {
1747        let Some(parent_thread_entity) = self.thread.upgrade() else {
1748            anyhow::bail!("Parent thread no longer exists".to_string());
1749        };
1750        let parent_thread = parent_thread_entity.read(cx);
1751        let current_depth = parent_thread.depth();
1752        let parent_session_id = parent_thread.id().clone();
1753
1754        if current_depth >= MAX_SUBAGENT_DEPTH {
1755            return Err(anyhow!(
1756                "Maximum subagent depth ({}) reached",
1757                MAX_SUBAGENT_DEPTH
1758            ));
1759        }
1760
1761        let subagent_thread: Entity<Thread> = cx.new(|cx| {
1762            let mut thread = Thread::new_subagent(&parent_thread_entity, cx);
1763            thread.set_title(label.into(), cx);
1764            thread
1765        });
1766
1767        let session_id = subagent_thread.read(cx).id().clone();
1768
1769        let acp_thread = self
1770            .agent
1771            .update(cx, |agent, cx| -> Result<Entity<AcpThread>> {
1772                let project_id = agent
1773                    .sessions
1774                    .get(&parent_session_id)
1775                    .map(|s| s.project_id)
1776                    .context("parent session not found")?;
1777                Ok(agent.register_session(subagent_thread.clone(), project_id, cx))
1778            })??;
1779
1780        let depth = current_depth + 1;
1781
1782        telemetry::event!(
1783            "Subagent Started",
1784            session = parent_thread_entity.read(cx).id().to_string(),
1785            subagent_session = session_id.to_string(),
1786            depth,
1787            is_resumed = false,
1788        );
1789
1790        self.prompt_subagent(session_id, subagent_thread, acp_thread)
1791    }
1792
1793    pub(crate) fn resume_subagent_thread(
1794        &self,
1795        session_id: acp::SessionId,
1796        cx: &mut App,
1797    ) -> Result<Rc<dyn SubagentHandle>> {
1798        let (subagent_thread, acp_thread) = self.agent.update(cx, |agent, _cx| {
1799            let session = agent
1800                .sessions
1801                .get(&session_id)
1802                .ok_or_else(|| anyhow!("No subagent session found with id {session_id}"))?;
1803            anyhow::Ok((session.thread.clone(), session.acp_thread.clone()))
1804        })??;
1805
1806        let depth = subagent_thread.read(cx).depth();
1807
1808        if let Some(parent_thread_entity) = self.thread.upgrade() {
1809            telemetry::event!(
1810                "Subagent Started",
1811                session = parent_thread_entity.read(cx).id().to_string(),
1812                subagent_session = session_id.to_string(),
1813                depth,
1814                is_resumed = true,
1815            );
1816        }
1817
1818        self.prompt_subagent(session_id, subagent_thread, acp_thread)
1819    }
1820
1821    fn prompt_subagent(
1822        &self,
1823        session_id: acp::SessionId,
1824        subagent_thread: Entity<Thread>,
1825        acp_thread: Entity<acp_thread::AcpThread>,
1826    ) -> Result<Rc<dyn SubagentHandle>> {
1827        let Some(parent_thread_entity) = self.thread.upgrade() else {
1828            anyhow::bail!("Parent thread no longer exists".to_string());
1829        };
1830        Ok(Rc::new(NativeSubagentHandle::new(
1831            session_id,
1832            subagent_thread,
1833            acp_thread,
1834            parent_thread_entity,
1835        )) as _)
1836    }
1837}
1838
1839impl ThreadEnvironment for NativeThreadEnvironment {
1840    fn create_terminal(
1841        &self,
1842        command: String,
1843        cwd: Option<PathBuf>,
1844        output_byte_limit: Option<u64>,
1845        cx: &mut AsyncApp,
1846    ) -> Task<Result<Rc<dyn TerminalHandle>>> {
1847        let task = self.acp_thread.update(cx, |thread, cx| {
1848            thread.create_terminal(command, vec![], vec![], cwd, output_byte_limit, cx)
1849        });
1850
1851        let acp_thread = self.acp_thread.clone();
1852        cx.spawn(async move |cx| {
1853            let terminal = task?.await?;
1854
1855            let (drop_tx, drop_rx) = oneshot::channel();
1856            let terminal_id = terminal.read_with(cx, |terminal, _cx| terminal.id().clone());
1857
1858            cx.spawn(async move |cx| {
1859                drop_rx.await.ok();
1860                acp_thread.update(cx, |thread, cx| thread.release_terminal(terminal_id, cx))
1861            })
1862            .detach();
1863
1864            let handle = AcpTerminalHandle {
1865                terminal,
1866                _drop_tx: Some(drop_tx),
1867            };
1868
1869            Ok(Rc::new(handle) as _)
1870        })
1871    }
1872
1873    fn create_subagent(&self, label: String, cx: &mut App) -> Result<Rc<dyn SubagentHandle>> {
1874        self.create_subagent_thread(label, cx)
1875    }
1876
1877    fn resume_subagent(
1878        &self,
1879        session_id: acp::SessionId,
1880        cx: &mut App,
1881    ) -> Result<Rc<dyn SubagentHandle>> {
1882        self.resume_subagent_thread(session_id, cx)
1883    }
1884}
1885
1886#[derive(Debug, Clone)]
1887enum SubagentPromptResult {
1888    Completed,
1889    Cancelled,
1890    ContextWindowWarning,
1891    Error(String),
1892}
1893
1894pub struct NativeSubagentHandle {
1895    session_id: acp::SessionId,
1896    parent_thread: WeakEntity<Thread>,
1897    subagent_thread: Entity<Thread>,
1898    acp_thread: Entity<acp_thread::AcpThread>,
1899}
1900
1901impl NativeSubagentHandle {
1902    fn new(
1903        session_id: acp::SessionId,
1904        subagent_thread: Entity<Thread>,
1905        acp_thread: Entity<acp_thread::AcpThread>,
1906        parent_thread_entity: Entity<Thread>,
1907    ) -> Self {
1908        NativeSubagentHandle {
1909            session_id,
1910            subagent_thread,
1911            parent_thread: parent_thread_entity.downgrade(),
1912            acp_thread,
1913        }
1914    }
1915}
1916
1917impl SubagentHandle for NativeSubagentHandle {
1918    fn id(&self) -> acp::SessionId {
1919        self.session_id.clone()
1920    }
1921
1922    fn num_entries(&self, cx: &App) -> usize {
1923        self.acp_thread.read(cx).entries().len()
1924    }
1925
1926    fn send(&self, message: String, cx: &AsyncApp) -> Task<Result<String>> {
1927        let thread = self.subagent_thread.clone();
1928        let acp_thread = self.acp_thread.clone();
1929        let subagent_session_id = self.session_id.clone();
1930        let parent_thread = self.parent_thread.clone();
1931
1932        cx.spawn(async move |cx| {
1933            let (task, _subscription) = cx.update(|cx| {
1934                let ratio_before_prompt = thread
1935                    .read(cx)
1936                    .latest_token_usage()
1937                    .map(|usage| usage.ratio());
1938
1939                parent_thread
1940                    .update(cx, |parent_thread, _cx| {
1941                        parent_thread.register_running_subagent(thread.downgrade())
1942                    })
1943                    .ok();
1944
1945                let task = acp_thread.update(cx, |acp_thread, cx| {
1946                    acp_thread.send(vec![message.into()], cx)
1947                });
1948
1949                let (token_limit_tx, token_limit_rx) = oneshot::channel::<()>();
1950                let mut token_limit_tx = Some(token_limit_tx);
1951
1952                let subscription = cx.subscribe(
1953                    &thread,
1954                    move |_thread, event: &TokenUsageUpdated, _cx| {
1955                        if let Some(usage) = &event.0 {
1956                            let old_ratio = ratio_before_prompt
1957                                .clone()
1958                                .unwrap_or(TokenUsageRatio::Normal);
1959                            let new_ratio = usage.ratio();
1960                            if old_ratio == TokenUsageRatio::Normal
1961                                && new_ratio == TokenUsageRatio::Warning
1962                            {
1963                                if let Some(tx) = token_limit_tx.take() {
1964                                    tx.send(()).ok();
1965                                }
1966                            }
1967                        }
1968                    },
1969                );
1970
1971                let wait_for_prompt = cx
1972                    .background_spawn(async move {
1973                        futures::select! {
1974                            response = task.fuse() => match response {
1975                                Ok(Some(response)) => {
1976                                    match response.stop_reason {
1977                                        acp::StopReason::Cancelled => SubagentPromptResult::Cancelled,
1978                                        acp::StopReason::MaxTokens => SubagentPromptResult::Error("The agent reached the maximum number of tokens.".into()),
1979                                        acp::StopReason::MaxTurnRequests => SubagentPromptResult::Error("The agent reached the maximum number of allowed requests between user turns. Try prompting again.".into()),
1980                                        acp::StopReason::Refusal => SubagentPromptResult::Error("The agent refused to process that prompt. Try again.".into()),
1981                                        acp::StopReason::EndTurn | _ => SubagentPromptResult::Completed,
1982                                    }
1983                                }
1984                                Ok(None) => SubagentPromptResult::Error("No response from the agent. You can try messaging again.".into()),
1985                                Err(error) => SubagentPromptResult::Error(error.to_string()),
1986                            },
1987                            _ = token_limit_rx.fuse() => SubagentPromptResult::ContextWindowWarning,
1988                        }
1989                    });
1990
1991                (wait_for_prompt, subscription)
1992            });
1993
1994            let result = match task.await {
1995                SubagentPromptResult::Completed => thread.read_with(cx, |thread, _cx| {
1996                    thread
1997                        .last_message()
1998                        .and_then(|message| {
1999                            let content = message.as_agent_message()?
2000                                .content
2001                                .iter()
2002                                .filter_map(|c| match c {
2003                                    AgentMessageContent::Text(text) => Some(text.as_str()),
2004                                    _ => None,
2005                                })
2006                                .join("\n\n");
2007                            if content.is_empty() {
2008                                None
2009                            } else {
2010                                Some( content)
2011                            }
2012                        })
2013                        .context("No response from subagent")
2014                }),
2015                SubagentPromptResult::Cancelled => Err(anyhow!("User canceled")),
2016                SubagentPromptResult::Error(message) => Err(anyhow!("{message}")),
2017                SubagentPromptResult::ContextWindowWarning => {
2018                    thread.update(cx, |thread, cx| thread.cancel(cx)).await;
2019                    Err(anyhow!(
2020                        "The agent is nearing the end of its context window and has been \
2021                         stopped. You can prompt the thread again to have the agent wrap up \
2022                         or hand off its work."
2023                    ))
2024                }
2025            };
2026
2027            parent_thread
2028                .update(cx, |parent_thread, cx| {
2029                    parent_thread.unregister_running_subagent(&subagent_session_id, cx)
2030                })
2031                .ok();
2032
2033            result
2034        })
2035    }
2036}
2037
2038pub struct AcpTerminalHandle {
2039    terminal: Entity<acp_thread::Terminal>,
2040    _drop_tx: Option<oneshot::Sender<()>>,
2041}
2042
2043impl TerminalHandle for AcpTerminalHandle {
2044    fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId> {
2045        Ok(self.terminal.read_with(cx, |term, _cx| term.id().clone()))
2046    }
2047
2048    fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>> {
2049        Ok(self
2050            .terminal
2051            .read_with(cx, |term, _cx| term.wait_for_exit()))
2052    }
2053
2054    fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse> {
2055        Ok(self
2056            .terminal
2057            .read_with(cx, |term, cx| term.current_output(cx)))
2058    }
2059
2060    fn kill(&self, cx: &AsyncApp) -> Result<()> {
2061        cx.update(|cx| {
2062            self.terminal.update(cx, |terminal, cx| {
2063                terminal.kill(cx);
2064            });
2065        });
2066        Ok(())
2067    }
2068
2069    fn was_stopped_by_user(&self, cx: &AsyncApp) -> Result<bool> {
2070        Ok(self
2071            .terminal
2072            .read_with(cx, |term, _cx| term.was_stopped_by_user()))
2073    }
2074}
2075
2076#[cfg(test)]
2077mod internal_tests {
2078    use super::*;
2079    use acp_thread::{AgentConnection, AgentModelGroupName, AgentModelInfo, MentionUri};
2080    use fs::FakeFs;
2081    use gpui::TestAppContext;
2082    use indoc::formatdoc;
2083    use language_model::fake_provider::{FakeLanguageModel, FakeLanguageModelProvider};
2084    use language_model::{
2085        LanguageModelCompletionEvent, LanguageModelProviderId, LanguageModelProviderName,
2086    };
2087    use serde_json::json;
2088    use settings::SettingsStore;
2089    use util::{path, rel_path::rel_path};
2090
2091    #[gpui::test]
2092    async fn test_maintaining_project_context(cx: &mut TestAppContext) {
2093        init_test(cx);
2094        let fs = FakeFs::new(cx.executor());
2095        fs.insert_tree(
2096            "/",
2097            json!({
2098                "a": {}
2099            }),
2100        )
2101        .await;
2102        let project = Project::test(fs.clone(), [], cx).await;
2103        let thread_store = cx.new(|cx| ThreadStore::new(cx));
2104        let agent =
2105            cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
2106
2107        // Creating a session registers the project and triggers context building.
2108        let connection = NativeAgentConnection(agent.clone());
2109        let _acp_thread = cx
2110            .update(|cx| Rc::new(connection).new_session(project.clone(), Path::new("/"), cx))
2111            .await
2112            .unwrap();
2113        cx.run_until_parked();
2114
2115        agent.read_with(cx, |agent, cx| {
2116            let project_id = project.entity_id();
2117            let state = agent.projects.get(&project_id).unwrap();
2118            assert_eq!(state.project_context.read(cx).worktrees, vec![])
2119        });
2120
2121        let worktree = project
2122            .update(cx, |project, cx| project.create_worktree("/a", true, cx))
2123            .await
2124            .unwrap();
2125        cx.run_until_parked();
2126        agent.read_with(cx, |agent, cx| {
2127            let project_id = project.entity_id();
2128            let state = agent.projects.get(&project_id).unwrap();
2129            assert_eq!(
2130                state.project_context.read(cx).worktrees,
2131                vec![WorktreeContext {
2132                    root_name: "a".into(),
2133                    abs_path: Path::new("/a").into(),
2134                    rules_file: None
2135                }]
2136            )
2137        });
2138
2139        // Creating `/a/.rules` updates the project context.
2140        fs.insert_file("/a/.rules", Vec::new()).await;
2141        cx.run_until_parked();
2142        agent.read_with(cx, |agent, cx| {
2143            let project_id = project.entity_id();
2144            let state = agent.projects.get(&project_id).unwrap();
2145            let rules_entry = worktree
2146                .read(cx)
2147                .entry_for_path(rel_path(".rules"))
2148                .unwrap();
2149            assert_eq!(
2150                state.project_context.read(cx).worktrees,
2151                vec![WorktreeContext {
2152                    root_name: "a".into(),
2153                    abs_path: Path::new("/a").into(),
2154                    rules_file: Some(RulesFileContext {
2155                        path_in_worktree: rel_path(".rules").into(),
2156                        text: "".into(),
2157                        project_entry_id: rules_entry.id.to_usize()
2158                    })
2159                }]
2160            )
2161        });
2162    }
2163
2164    #[gpui::test]
2165    async fn test_listing_models(cx: &mut TestAppContext) {
2166        init_test(cx);
2167        let fs = FakeFs::new(cx.executor());
2168        fs.insert_tree("/", json!({ "a": {}  })).await;
2169        let project = Project::test(fs.clone(), [], cx).await;
2170        let thread_store = cx.new(|cx| ThreadStore::new(cx));
2171        let connection =
2172            NativeAgentConnection(cx.update(|cx| {
2173                NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx)
2174            }));
2175
2176        // Create a thread/session
2177        let acp_thread = cx
2178            .update(|cx| {
2179                Rc::new(connection.clone()).new_session(project.clone(), Path::new("/a"), cx)
2180            })
2181            .await
2182            .unwrap();
2183
2184        let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());
2185
2186        let models = cx
2187            .update(|cx| {
2188                connection
2189                    .model_selector(&session_id)
2190                    .unwrap()
2191                    .list_models(cx)
2192            })
2193            .await
2194            .unwrap();
2195
2196        let acp_thread::AgentModelList::Grouped(models) = models else {
2197            panic!("Unexpected model group");
2198        };
2199        assert_eq!(
2200            models,
2201            IndexMap::from_iter([(
2202                AgentModelGroupName("Fake".into()),
2203                vec![AgentModelInfo {
2204                    id: acp::ModelId::new("fake/fake"),
2205                    name: "Fake".into(),
2206                    description: None,
2207                    icon: Some(acp_thread::AgentModelIcon::Named(
2208                        ui::IconName::ZedAssistant
2209                    )),
2210                    is_latest: false,
2211                    cost: None,
2212                }]
2213            )])
2214        );
2215    }
2216
2217    #[gpui::test]
2218    async fn test_model_selection_persists_to_settings(cx: &mut TestAppContext) {
2219        init_test(cx);
2220        let fs = FakeFs::new(cx.executor());
2221        fs.create_dir(paths::settings_file().parent().unwrap())
2222            .await
2223            .unwrap();
2224        fs.insert_file(
2225            paths::settings_file(),
2226            json!({
2227                "agent": {
2228                    "default_model": {
2229                        "provider": "foo",
2230                        "model": "bar"
2231                    }
2232                }
2233            })
2234            .to_string()
2235            .into_bytes(),
2236        )
2237        .await;
2238        let project = Project::test(fs.clone(), [], cx).await;
2239
2240        let thread_store = cx.new(|cx| ThreadStore::new(cx));
2241
2242        // Create the agent and connection
2243        let agent =
2244            cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
2245        let connection = NativeAgentConnection(agent.clone());
2246
2247        // Create a thread/session
2248        let acp_thread = cx
2249            .update(|cx| {
2250                Rc::new(connection.clone()).new_session(project.clone(), Path::new("/a"), cx)
2251            })
2252            .await
2253            .unwrap();
2254
2255        let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());
2256
2257        // Select a model
2258        let selector = connection.model_selector(&session_id).unwrap();
2259        let model_id = acp::ModelId::new("fake/fake");
2260        cx.update(|cx| selector.select_model(model_id.clone(), cx))
2261            .await
2262            .unwrap();
2263
2264        // Verify the thread has the selected model
2265        agent.read_with(cx, |agent, _| {
2266            let session = agent.sessions.get(&session_id).unwrap();
2267            session.thread.read_with(cx, |thread, _| {
2268                assert_eq!(thread.model().unwrap().id().0, "fake");
2269            });
2270        });
2271
2272        cx.run_until_parked();
2273
2274        // Verify settings file was updated
2275        let settings_content = fs.load(paths::settings_file()).await.unwrap();
2276        let settings_json: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
2277
2278        // Check that the agent settings contain the selected model
2279        assert_eq!(
2280            settings_json["agent"]["default_model"]["model"],
2281            json!("fake")
2282        );
2283        assert_eq!(
2284            settings_json["agent"]["default_model"]["provider"],
2285            json!("fake")
2286        );
2287
2288        // Register a thinking model and select it.
2289        cx.update(|cx| {
2290            let thinking_model = Arc::new(FakeLanguageModel::with_id_and_thinking(
2291                "fake-corp",
2292                "fake-thinking",
2293                "Fake Thinking",
2294                true,
2295            ));
2296            let thinking_provider = Arc::new(
2297                FakeLanguageModelProvider::new(
2298                    LanguageModelProviderId::from("fake-corp".to_string()),
2299                    LanguageModelProviderName::from("Fake Corp".to_string()),
2300                )
2301                .with_models(vec![thinking_model]),
2302            );
2303            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
2304                registry.register_provider(thinking_provider, cx);
2305            });
2306        });
2307        agent.update(cx, |agent, cx| agent.models.refresh_list(cx));
2308
2309        let selector = connection.model_selector(&session_id).unwrap();
2310        cx.update(|cx| selector.select_model(acp::ModelId::new("fake-corp/fake-thinking"), cx))
2311            .await
2312            .unwrap();
2313        cx.run_until_parked();
2314
2315        // Verify enable_thinking was written to settings as true.
2316        let settings_content = fs.load(paths::settings_file()).await.unwrap();
2317        let settings_json: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
2318        assert_eq!(
2319            settings_json["agent"]["default_model"]["enable_thinking"],
2320            json!(true),
2321            "selecting a thinking model should persist enable_thinking: true to settings"
2322        );
2323    }
2324
2325    #[gpui::test]
2326    async fn test_select_model_updates_thinking_enabled(cx: &mut TestAppContext) {
2327        init_test(cx);
2328        let fs = FakeFs::new(cx.executor());
2329        fs.create_dir(paths::settings_file().parent().unwrap())
2330            .await
2331            .unwrap();
2332        fs.insert_file(paths::settings_file(), b"{}".to_vec()).await;
2333        let project = Project::test(fs.clone(), [], cx).await;
2334
2335        let thread_store = cx.new(|cx| ThreadStore::new(cx));
2336        let agent =
2337            cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
2338        let connection = NativeAgentConnection(agent.clone());
2339
2340        let acp_thread = cx
2341            .update(|cx| {
2342                Rc::new(connection.clone()).new_session(project.clone(), Path::new("/a"), cx)
2343            })
2344            .await
2345            .unwrap();
2346        let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());
2347
2348        // Register a second provider with a thinking model.
2349        cx.update(|cx| {
2350            let thinking_model = Arc::new(FakeLanguageModel::with_id_and_thinking(
2351                "fake-corp",
2352                "fake-thinking",
2353                "Fake Thinking",
2354                true,
2355            ));
2356            let thinking_provider = Arc::new(
2357                FakeLanguageModelProvider::new(
2358                    LanguageModelProviderId::from("fake-corp".to_string()),
2359                    LanguageModelProviderName::from("Fake Corp".to_string()),
2360                )
2361                .with_models(vec![thinking_model]),
2362            );
2363            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
2364                registry.register_provider(thinking_provider, cx);
2365            });
2366        });
2367        // Refresh the agent's model list so it picks up the new provider.
2368        agent.update(cx, |agent, cx| agent.models.refresh_list(cx));
2369
2370        // Thread starts with thinking_enabled = false (the default).
2371        agent.read_with(cx, |agent, _| {
2372            let session = agent.sessions.get(&session_id).unwrap();
2373            session.thread.read_with(cx, |thread, _| {
2374                assert!(!thread.thinking_enabled(), "thinking defaults to false");
2375            });
2376        });
2377
2378        // Select the thinking model via select_model.
2379        let selector = connection.model_selector(&session_id).unwrap();
2380        cx.update(|cx| selector.select_model(acp::ModelId::new("fake-corp/fake-thinking"), cx))
2381            .await
2382            .unwrap();
2383
2384        // select_model should have enabled thinking based on the model's supports_thinking().
2385        agent.read_with(cx, |agent, _| {
2386            let session = agent.sessions.get(&session_id).unwrap();
2387            session.thread.read_with(cx, |thread, _| {
2388                assert!(
2389                    thread.thinking_enabled(),
2390                    "select_model should enable thinking when model supports it"
2391                );
2392            });
2393        });
2394
2395        // Switch back to the non-thinking model.
2396        let selector = connection.model_selector(&session_id).unwrap();
2397        cx.update(|cx| selector.select_model(acp::ModelId::new("fake/fake"), cx))
2398            .await
2399            .unwrap();
2400
2401        // select_model should have disabled thinking.
2402        agent.read_with(cx, |agent, _| {
2403            let session = agent.sessions.get(&session_id).unwrap();
2404            session.thread.read_with(cx, |thread, _| {
2405                assert!(
2406                    !thread.thinking_enabled(),
2407                    "select_model should disable thinking when model does not support it"
2408                );
2409            });
2410        });
2411    }
2412
2413    #[gpui::test]
2414    async fn test_loaded_thread_preserves_thinking_enabled(cx: &mut TestAppContext) {
2415        init_test(cx);
2416        let fs = FakeFs::new(cx.executor());
2417        fs.insert_tree("/", json!({ "a": {} })).await;
2418        let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
2419        let thread_store = cx.new(|cx| ThreadStore::new(cx));
2420        let agent = cx.update(|cx| {
2421            NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
2422        });
2423        let connection = Rc::new(NativeAgentConnection(agent.clone()));
2424
2425        // Register a thinking model.
2426        let thinking_model = Arc::new(FakeLanguageModel::with_id_and_thinking(
2427            "fake-corp",
2428            "fake-thinking",
2429            "Fake Thinking",
2430            true,
2431        ));
2432        let thinking_provider = Arc::new(
2433            FakeLanguageModelProvider::new(
2434                LanguageModelProviderId::from("fake-corp".to_string()),
2435                LanguageModelProviderName::from("Fake Corp".to_string()),
2436            )
2437            .with_models(vec![thinking_model.clone()]),
2438        );
2439        cx.update(|cx| {
2440            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
2441                registry.register_provider(thinking_provider, cx);
2442            });
2443        });
2444        agent.update(cx, |agent, cx| agent.models.refresh_list(cx));
2445
2446        // Create a thread and select the thinking model.
2447        let acp_thread = cx
2448            .update(|cx| {
2449                connection
2450                    .clone()
2451                    .new_session(project.clone(), Path::new("/a"), cx)
2452            })
2453            .await
2454            .unwrap();
2455        let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
2456
2457        let selector = connection.model_selector(&session_id).unwrap();
2458        cx.update(|cx| selector.select_model(acp::ModelId::new("fake-corp/fake-thinking"), cx))
2459            .await
2460            .unwrap();
2461
2462        // Verify thinking is enabled after selecting the thinking model.
2463        let thread = agent.read_with(cx, |agent, _| {
2464            agent.sessions.get(&session_id).unwrap().thread.clone()
2465        });
2466        thread.read_with(cx, |thread, _| {
2467            assert!(
2468                thread.thinking_enabled(),
2469                "thinking should be enabled after selecting thinking model"
2470            );
2471        });
2472
2473        // Send a message so the thread gets persisted.
2474        let send = acp_thread.update(cx, |thread, cx| thread.send(vec!["Hello".into()], cx));
2475        let send = cx.foreground_executor().spawn(send);
2476        cx.run_until_parked();
2477
2478        thinking_model.send_last_completion_stream_text_chunk("Response.");
2479        thinking_model.end_last_completion_stream();
2480
2481        send.await.unwrap();
2482        cx.run_until_parked();
2483
2484        // Close the session so it can be reloaded from disk.
2485        cx.update(|cx| connection.clone().close_session(&session_id, cx))
2486            .await
2487            .unwrap();
2488        drop(thread);
2489        drop(acp_thread);
2490        agent.read_with(cx, |agent, _| {
2491            assert!(agent.sessions.is_empty());
2492        });
2493
2494        // Reload the thread and verify thinking_enabled is still true.
2495        let reloaded_acp_thread = agent
2496            .update(cx, |agent, cx| {
2497                agent.open_thread(session_id.clone(), project.clone(), cx)
2498            })
2499            .await
2500            .unwrap();
2501        let reloaded_thread = agent.read_with(cx, |agent, _| {
2502            agent.sessions.get(&session_id).unwrap().thread.clone()
2503        });
2504        reloaded_thread.read_with(cx, |thread, _| {
2505            assert!(
2506                thread.thinking_enabled(),
2507                "thinking_enabled should be preserved when reloading a thread with a thinking model"
2508            );
2509        });
2510
2511        drop(reloaded_acp_thread);
2512    }
2513
2514    #[gpui::test]
2515    async fn test_loaded_thread_preserves_model(cx: &mut TestAppContext) {
2516        init_test(cx);
2517        let fs = FakeFs::new(cx.executor());
2518        fs.insert_tree("/", json!({ "a": {} })).await;
2519        let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
2520        let thread_store = cx.new(|cx| ThreadStore::new(cx));
2521        let agent = cx.update(|cx| {
2522            NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
2523        });
2524        let connection = Rc::new(NativeAgentConnection(agent.clone()));
2525
2526        // Register a model where id() != name(), like real Anthropic models
2527        // (e.g. id="claude-sonnet-4-5-thinking-latest", name="Claude Sonnet 4.5 Thinking").
2528        let model = Arc::new(FakeLanguageModel::with_id_and_thinking(
2529            "fake-corp",
2530            "custom-model-id",
2531            "Custom Model Display Name",
2532            false,
2533        ));
2534        let provider = Arc::new(
2535            FakeLanguageModelProvider::new(
2536                LanguageModelProviderId::from("fake-corp".to_string()),
2537                LanguageModelProviderName::from("Fake Corp".to_string()),
2538            )
2539            .with_models(vec![model.clone()]),
2540        );
2541        cx.update(|cx| {
2542            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
2543                registry.register_provider(provider, cx);
2544            });
2545        });
2546        agent.update(cx, |agent, cx| agent.models.refresh_list(cx));
2547
2548        // Create a thread and select the model.
2549        let acp_thread = cx
2550            .update(|cx| {
2551                connection
2552                    .clone()
2553                    .new_session(project.clone(), Path::new("/a"), cx)
2554            })
2555            .await
2556            .unwrap();
2557        let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
2558
2559        let selector = connection.model_selector(&session_id).unwrap();
2560        cx.update(|cx| selector.select_model(acp::ModelId::new("fake-corp/custom-model-id"), cx))
2561            .await
2562            .unwrap();
2563
2564        let thread = agent.read_with(cx, |agent, _| {
2565            agent.sessions.get(&session_id).unwrap().thread.clone()
2566        });
2567        thread.read_with(cx, |thread, _| {
2568            assert_eq!(
2569                thread.model().unwrap().id().0.as_ref(),
2570                "custom-model-id",
2571                "model should be set before persisting"
2572            );
2573        });
2574
2575        // Send a message so the thread gets persisted.
2576        let send = acp_thread.update(cx, |thread, cx| thread.send(vec!["Hello".into()], cx));
2577        let send = cx.foreground_executor().spawn(send);
2578        cx.run_until_parked();
2579
2580        model.send_last_completion_stream_text_chunk("Response.");
2581        model.end_last_completion_stream();
2582
2583        send.await.unwrap();
2584        cx.run_until_parked();
2585
2586        // Close the session so it can be reloaded from disk.
2587        cx.update(|cx| connection.clone().close_session(&session_id, cx))
2588            .await
2589            .unwrap();
2590        drop(thread);
2591        drop(acp_thread);
2592        agent.read_with(cx, |agent, _| {
2593            assert!(agent.sessions.is_empty());
2594        });
2595
2596        // Reload the thread and verify the model was preserved.
2597        let reloaded_acp_thread = agent
2598            .update(cx, |agent, cx| {
2599                agent.open_thread(session_id.clone(), project.clone(), cx)
2600            })
2601            .await
2602            .unwrap();
2603        let reloaded_thread = agent.read_with(cx, |agent, _| {
2604            agent.sessions.get(&session_id).unwrap().thread.clone()
2605        });
2606        reloaded_thread.read_with(cx, |thread, _| {
2607            let reloaded_model = thread
2608                .model()
2609                .expect("model should be present after reload");
2610            assert_eq!(
2611                reloaded_model.id().0.as_ref(),
2612                "custom-model-id",
2613                "reloaded thread should have the same model, not fall back to the default"
2614            );
2615        });
2616
2617        drop(reloaded_acp_thread);
2618    }
2619
2620    #[gpui::test]
2621    async fn test_save_load_thread(cx: &mut TestAppContext) {
2622        init_test(cx);
2623        let fs = FakeFs::new(cx.executor());
2624        fs.insert_tree(
2625            "/",
2626            json!({
2627                "a": {
2628                    "b.md": "Lorem"
2629                }
2630            }),
2631        )
2632        .await;
2633        let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
2634        let thread_store = cx.new(|cx| ThreadStore::new(cx));
2635        let agent = cx.update(|cx| {
2636            NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
2637        });
2638        let connection = Rc::new(NativeAgentConnection(agent.clone()));
2639
2640        let acp_thread = cx
2641            .update(|cx| {
2642                connection
2643                    .clone()
2644                    .new_session(project.clone(), Path::new(""), cx)
2645            })
2646            .await
2647            .unwrap();
2648        let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
2649        let thread = agent.read_with(cx, |agent, _| {
2650            agent.sessions.get(&session_id).unwrap().thread.clone()
2651        });
2652
2653        // Ensure empty threads are not saved, even if they get mutated.
2654        let model = Arc::new(FakeLanguageModel::default());
2655        let summary_model = Arc::new(FakeLanguageModel::default());
2656        thread.update(cx, |thread, cx| {
2657            thread.set_model(model.clone(), cx);
2658            thread.set_summarization_model(Some(summary_model.clone()), cx);
2659        });
2660        cx.run_until_parked();
2661        assert_eq!(thread_entries(&thread_store, cx), vec![]);
2662
2663        let send = acp_thread.update(cx, |thread, cx| {
2664            thread.send(
2665                vec![
2666                    "What does ".into(),
2667                    acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
2668                        "b.md",
2669                        MentionUri::File {
2670                            abs_path: path!("/a/b.md").into(),
2671                        }
2672                        .to_uri()
2673                        .to_string(),
2674                    )),
2675                    " mean?".into(),
2676                ],
2677                cx,
2678            )
2679        });
2680        let send = cx.foreground_executor().spawn(send);
2681        cx.run_until_parked();
2682
2683        model.send_last_completion_stream_text_chunk("Lorem.");
2684        model.send_last_completion_stream_event(LanguageModelCompletionEvent::UsageUpdate(
2685            language_model::TokenUsage {
2686                input_tokens: 150,
2687                output_tokens: 75,
2688                ..Default::default()
2689            },
2690        ));
2691        model.end_last_completion_stream();
2692        cx.run_until_parked();
2693        summary_model
2694            .send_last_completion_stream_text_chunk(&format!("Explaining {}", path!("/a/b.md")));
2695        summary_model.end_last_completion_stream();
2696
2697        send.await.unwrap();
2698        let uri = MentionUri::File {
2699            abs_path: path!("/a/b.md").into(),
2700        }
2701        .to_uri();
2702        acp_thread.read_with(cx, |thread, cx| {
2703            assert_eq!(
2704                thread.to_markdown(cx),
2705                formatdoc! {"
2706                    ## User
2707
2708                    What does [@b.md]({uri}) mean?
2709
2710                    ## Assistant
2711
2712                    Lorem.
2713
2714                "}
2715            )
2716        });
2717
2718        cx.run_until_parked();
2719
2720        // Set a draft prompt with rich content blocks before saving.
2721        let draft_blocks = vec![
2722            acp::ContentBlock::Text(acp::TextContent::new("Check out ")),
2723            acp::ContentBlock::ResourceLink(acp::ResourceLink::new("b.md", uri.to_string())),
2724            acp::ContentBlock::Text(acp::TextContent::new(" please")),
2725        ];
2726        acp_thread.update(cx, |thread, _cx| {
2727            thread.set_draft_prompt(Some(draft_blocks.clone()));
2728        });
2729        thread.update(cx, |thread, _cx| {
2730            thread.set_ui_scroll_position(Some(gpui::ListOffset {
2731                item_ix: 5,
2732                offset_in_item: gpui::px(12.5),
2733            }));
2734        });
2735        thread.update(cx, |_thread, cx| cx.notify());
2736        cx.run_until_parked();
2737
2738        // Close the session so it can be reloaded from disk.
2739        cx.update(|cx| connection.clone().close_session(&session_id, cx))
2740            .await
2741            .unwrap();
2742        drop(thread);
2743        drop(acp_thread);
2744        agent.read_with(cx, |agent, _| {
2745            assert_eq!(agent.sessions.keys().cloned().collect::<Vec<_>>(), []);
2746        });
2747
2748        // Ensure the thread can be reloaded from disk.
2749        assert_eq!(
2750            thread_entries(&thread_store, cx),
2751            vec![(
2752                session_id.clone(),
2753                format!("Explaining {}", path!("/a/b.md"))
2754            )]
2755        );
2756        let acp_thread = agent
2757            .update(cx, |agent, cx| {
2758                agent.open_thread(session_id.clone(), project.clone(), cx)
2759            })
2760            .await
2761            .unwrap();
2762        acp_thread.read_with(cx, |thread, cx| {
2763            assert_eq!(
2764                thread.to_markdown(cx),
2765                formatdoc! {"
2766                    ## User
2767
2768                    What does [@b.md]({uri}) mean?
2769
2770                    ## Assistant
2771
2772                    Lorem.
2773
2774                "}
2775            )
2776        });
2777
2778        // Ensure the draft prompt with rich content blocks survived the round-trip.
2779        acp_thread.read_with(cx, |thread, _| {
2780            assert_eq!(thread.draft_prompt(), Some(draft_blocks.as_slice()));
2781        });
2782
2783        // Ensure token usage survived the round-trip.
2784        acp_thread.read_with(cx, |thread, _| {
2785            let usage = thread
2786                .token_usage()
2787                .expect("token usage should be restored after reload");
2788            assert_eq!(usage.input_tokens, 150);
2789            assert_eq!(usage.output_tokens, 75);
2790        });
2791
2792        // Ensure scroll position survived the round-trip.
2793        acp_thread.read_with(cx, |thread, _| {
2794            let scroll = thread
2795                .ui_scroll_position()
2796                .expect("scroll position should be restored after reload");
2797            assert_eq!(scroll.item_ix, 5);
2798            assert_eq!(scroll.offset_in_item, gpui::px(12.5));
2799        });
2800    }
2801
2802    fn thread_entries(
2803        thread_store: &Entity<ThreadStore>,
2804        cx: &mut TestAppContext,
2805    ) -> Vec<(acp::SessionId, String)> {
2806        thread_store.read_with(cx, |store, _| {
2807            store
2808                .entries()
2809                .map(|entry| (entry.id.clone(), entry.title.to_string()))
2810                .collect::<Vec<_>>()
2811        })
2812    }
2813
2814    fn init_test(cx: &mut TestAppContext) {
2815        env_logger::try_init().ok();
2816        cx.update(|cx| {
2817            let settings_store = SettingsStore::test(cx);
2818            cx.set_global(settings_store);
2819
2820            LanguageModelRegistry::test(cx);
2821        });
2822    }
2823}
2824
2825fn mcp_message_content_to_acp_content_block(
2826    content: context_server::types::MessageContent,
2827) -> acp::ContentBlock {
2828    match content {
2829        context_server::types::MessageContent::Text {
2830            text,
2831            annotations: _,
2832        } => text.into(),
2833        context_server::types::MessageContent::Image {
2834            data,
2835            mime_type,
2836            annotations: _,
2837        } => acp::ContentBlock::Image(acp::ImageContent::new(data, mime_type)),
2838        context_server::types::MessageContent::Audio {
2839            data,
2840            mime_type,
2841            annotations: _,
2842        } => acp::ContentBlock::Audio(acp::AudioContent::new(data, mime_type)),
2843        context_server::types::MessageContent::Resource {
2844            resource,
2845            annotations: _,
2846        } => {
2847            let mut link =
2848                acp::ResourceLink::new(resource.uri.to_string(), resource.uri.to_string());
2849            if let Some(mime_type) = resource.mime_type {
2850                link = link.mime_type(mime_type);
2851            }
2852            acp::ContentBlock::ResourceLink(link)
2853        }
2854    }
2855}