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