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