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