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