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