agent.rs

   1use crate::{
   2    ContextServerRegistry, Thread, ThreadEvent, ThreadsDatabase, ToolCallAuthorization,
   3    UserMessageContent, templates::Templates,
   4};
   5use crate::{HistoryStore, TerminalHandle, ThreadEnvironment, TitleUpdated, TokenUsageUpdated};
   6use acp_thread::{AcpThread, AgentModelSelector};
   7use action_log::ActionLog;
   8use agent_client_protocol as acp;
   9use anyhow::{Context as _, Result, anyhow};
  10use collections::{HashSet, IndexMap};
  11use fs::Fs;
  12use futures::channel::{mpsc, oneshot};
  13use futures::future::Shared;
  14use futures::{StreamExt, future};
  15use gpui::{
  16    App, AppContext, AsyncApp, Context, Entity, SharedString, Subscription, Task, WeakEntity,
  17};
  18use language_model::{LanguageModel, LanguageModelProvider, LanguageModelRegistry};
  19use project::{Project, ProjectItem, ProjectPath, Worktree};
  20use prompt_store::{
  21    ProjectContext, PromptId, PromptStore, RulesFileContext, UserRulesContext, WorktreeContext,
  22};
  23use settings::update_settings_file;
  24use std::any::Any;
  25use std::collections::HashMap;
  26use std::path::{Path, PathBuf};
  27use std::rc::Rc;
  28use std::sync::Arc;
  29use util::ResultExt;
  30
  31const RULES_FILE_NAMES: [&str; 9] = [
  32    ".rules",
  33    ".cursorrules",
  34    ".windsurfrules",
  35    ".clinerules",
  36    ".github/copilot-instructions.md",
  37    "CLAUDE.md",
  38    "AGENT.md",
  39    "AGENTS.md",
  40    "GEMINI.md",
  41];
  42
  43pub struct RulesLoadingError {
  44    pub message: SharedString,
  45}
  46
  47/// Holds both the internal Thread and the AcpThread for a session
  48struct Session {
  49    /// The internal thread that processes messages
  50    thread: Entity<Thread>,
  51    /// The ACP thread that handles protocol communication
  52    acp_thread: WeakEntity<acp_thread::AcpThread>,
  53    pending_save: Task<()>,
  54    _subscriptions: Vec<Subscription>,
  55}
  56
  57pub struct LanguageModels {
  58    /// Access language model by ID
  59    models: HashMap<acp_thread::AgentModelId, Arc<dyn LanguageModel>>,
  60    /// Cached list for returning language model information
  61    model_list: acp_thread::AgentModelList,
  62    refresh_models_rx: watch::Receiver<()>,
  63    refresh_models_tx: watch::Sender<()>,
  64    _authenticate_all_providers_task: Task<()>,
  65}
  66
  67impl LanguageModels {
  68    fn new(cx: &mut App) -> Self {
  69        let (refresh_models_tx, refresh_models_rx) = watch::channel(());
  70
  71        let mut this = Self {
  72            models: HashMap::default(),
  73            model_list: acp_thread::AgentModelList::Grouped(IndexMap::default()),
  74            refresh_models_rx,
  75            refresh_models_tx,
  76            _authenticate_all_providers_task: Self::authenticate_all_language_model_providers(cx),
  77        };
  78        this.refresh_list(cx);
  79        this
  80    }
  81
  82    fn refresh_list(&mut self, cx: &App) {
  83        let providers = LanguageModelRegistry::global(cx)
  84            .read(cx)
  85            .providers()
  86            .into_iter()
  87            .filter(|provider| provider.is_authenticated(cx))
  88            .collect::<Vec<_>>();
  89
  90        let mut language_model_list = IndexMap::default();
  91        let mut recommended_models = HashSet::default();
  92
  93        let mut recommended = Vec::new();
  94        for provider in &providers {
  95            for model in provider.recommended_models(cx) {
  96                recommended_models.insert((model.provider_id(), model.id()));
  97                recommended.push(Self::map_language_model_to_info(&model, provider));
  98            }
  99        }
 100        if !recommended.is_empty() {
 101            language_model_list.insert(
 102                acp_thread::AgentModelGroupName("Recommended".into()),
 103                recommended,
 104            );
 105        }
 106
 107        let mut models = HashMap::default();
 108        for provider in providers {
 109            let mut provider_models = Vec::new();
 110            for model in provider.provided_models(cx) {
 111                let model_info = Self::map_language_model_to_info(&model, &provider);
 112                let model_id = model_info.id.clone();
 113                if !recommended_models.contains(&(model.provider_id(), model.id())) {
 114                    provider_models.push(model_info);
 115                }
 116                models.insert(model_id, model);
 117            }
 118            if !provider_models.is_empty() {
 119                language_model_list.insert(
 120                    acp_thread::AgentModelGroupName(provider.name().0.clone()),
 121                    provider_models,
 122                );
 123            }
 124        }
 125
 126        self.models = models;
 127        self.model_list = acp_thread::AgentModelList::Grouped(language_model_list);
 128        self.refresh_models_tx.send(()).ok();
 129    }
 130
 131    fn watch(&self) -> watch::Receiver<()> {
 132        self.refresh_models_rx.clone()
 133    }
 134
 135    pub fn model_from_id(
 136        &self,
 137        model_id: &acp_thread::AgentModelId,
 138    ) -> Option<Arc<dyn LanguageModel>> {
 139        self.models.get(model_id).cloned()
 140    }
 141
 142    fn map_language_model_to_info(
 143        model: &Arc<dyn LanguageModel>,
 144        provider: &Arc<dyn LanguageModelProvider>,
 145    ) -> acp_thread::AgentModelInfo {
 146        acp_thread::AgentModelInfo {
 147            id: Self::model_id(model),
 148            name: model.name().0,
 149            icon: Some(provider.icon()),
 150        }
 151    }
 152
 153    fn model_id(model: &Arc<dyn LanguageModel>) -> acp_thread::AgentModelId {
 154        acp_thread::AgentModelId(format!("{}/{}", model.provider_id().0, model.id().0).into())
 155    }
 156
 157    fn authenticate_all_language_model_providers(cx: &mut App) -> Task<()> {
 158        let authenticate_all_providers = LanguageModelRegistry::global(cx)
 159            .read(cx)
 160            .providers()
 161            .iter()
 162            .map(|provider| (provider.id(), provider.name(), provider.authenticate(cx)))
 163            .collect::<Vec<_>>();
 164
 165        cx.background_spawn(async move {
 166            for (provider_id, provider_name, authenticate_task) in authenticate_all_providers {
 167                if let Err(err) = authenticate_task.await {
 168                    match err {
 169                        language_model::AuthenticateError::CredentialsNotFound => {
 170                            // Since we're authenticating these providers in the
 171                            // background for the purposes of populating the
 172                            // language selector, we don't care about providers
 173                            // where the credentials are not found.
 174                        }
 175                        language_model::AuthenticateError::ConnectionRefused => {
 176                            // Not logging connection refused errors as they are mostly from LM Studio's noisy auth failures.
 177                            // LM Studio only has one auth method (endpoint call) which fails for users who haven't enabled it.
 178                            // TODO: Better manage LM Studio auth logic to avoid these noisy failures.
 179                        }
 180                        _ => {
 181                            // Some providers have noisy failure states that we
 182                            // don't want to spam the logs with every time the
 183                            // language model selector is initialized.
 184                            //
 185                            // Ideally these should have more clear failure modes
 186                            // that we know are safe to ignore here, like what we do
 187                            // with `CredentialsNotFound` above.
 188                            match provider_id.0.as_ref() {
 189                                "lmstudio" | "ollama" => {
 190                                    // LM Studio and Ollama both make fetch requests to the local APIs to determine if they are "authenticated".
 191                                    //
 192                                    // These fail noisily, so we don't log them.
 193                                }
 194                                "copilot_chat" => {
 195                                    // Copilot Chat returns an error if Copilot is not enabled, so we don't log those errors.
 196                                }
 197                                _ => {
 198                                    log::error!(
 199                                        "Failed to authenticate provider: {}: {err}",
 200                                        provider_name.0
 201                                    );
 202                                }
 203                            }
 204                        }
 205                    }
 206                }
 207            }
 208        })
 209    }
 210}
 211
 212pub struct NativeAgent {
 213    /// Session ID -> Session mapping
 214    sessions: HashMap<acp::SessionId, Session>,
 215    history: Entity<HistoryStore>,
 216    /// Shared project context for all threads
 217    project_context: Entity<ProjectContext>,
 218    project_context_needs_refresh: watch::Sender<()>,
 219    _maintain_project_context: Task<Result<()>>,
 220    context_server_registry: Entity<ContextServerRegistry>,
 221    /// Shared templates for all threads
 222    templates: Arc<Templates>,
 223    /// Cached model information
 224    models: LanguageModels,
 225    project: Entity<Project>,
 226    prompt_store: Option<Entity<PromptStore>>,
 227    fs: Arc<dyn Fs>,
 228    _subscriptions: Vec<Subscription>,
 229}
 230
 231impl NativeAgent {
 232    pub async fn new(
 233        project: Entity<Project>,
 234        history: Entity<HistoryStore>,
 235        templates: Arc<Templates>,
 236        prompt_store: Option<Entity<PromptStore>>,
 237        fs: Arc<dyn Fs>,
 238        cx: &mut AsyncApp,
 239    ) -> Result<Entity<NativeAgent>> {
 240        log::debug!("Creating new NativeAgent");
 241
 242        let project_context = cx
 243            .update(|cx| Self::build_project_context(&project, prompt_store.as_ref(), cx))?
 244            .await;
 245
 246        cx.new(|cx| {
 247            let mut subscriptions = vec![
 248                cx.subscribe(&project, Self::handle_project_event),
 249                cx.subscribe(
 250                    &LanguageModelRegistry::global(cx),
 251                    Self::handle_models_updated_event,
 252                ),
 253            ];
 254            if let Some(prompt_store) = prompt_store.as_ref() {
 255                subscriptions.push(cx.subscribe(prompt_store, Self::handle_prompts_updated_event))
 256            }
 257
 258            let (project_context_needs_refresh_tx, project_context_needs_refresh_rx) =
 259                watch::channel(());
 260            Self {
 261                sessions: HashMap::new(),
 262                history,
 263                project_context: cx.new(|_| project_context),
 264                project_context_needs_refresh: project_context_needs_refresh_tx,
 265                _maintain_project_context: cx.spawn(async move |this, cx| {
 266                    Self::maintain_project_context(this, project_context_needs_refresh_rx, cx).await
 267                }),
 268                context_server_registry: cx.new(|cx| {
 269                    ContextServerRegistry::new(project.read(cx).context_server_store(), cx)
 270                }),
 271                templates,
 272                models: LanguageModels::new(cx),
 273                project,
 274                prompt_store,
 275                fs,
 276                _subscriptions: subscriptions,
 277            }
 278        })
 279    }
 280
 281    fn register_session(
 282        &mut self,
 283        thread_handle: Entity<Thread>,
 284        cx: &mut Context<Self>,
 285    ) -> Entity<AcpThread> {
 286        let connection = Rc::new(NativeAgentConnection(cx.entity()));
 287
 288        let thread = thread_handle.read(cx);
 289        let session_id = thread.id().clone();
 290        let title = thread.title();
 291        let project = thread.project.clone();
 292        let action_log = thread.action_log.clone();
 293        let prompt_capabilities_rx = thread.prompt_capabilities_rx.clone();
 294        let acp_thread = cx.new(|cx| {
 295            acp_thread::AcpThread::new(
 296                title,
 297                connection,
 298                project.clone(),
 299                action_log.clone(),
 300                session_id.clone(),
 301                prompt_capabilities_rx,
 302                cx,
 303            )
 304        });
 305
 306        let registry = LanguageModelRegistry::read_global(cx);
 307        let summarization_model = registry.thread_summary_model().map(|c| c.model);
 308
 309        thread_handle.update(cx, |thread, cx| {
 310            thread.set_summarization_model(summarization_model, cx);
 311            thread.add_default_tools(
 312                Rc::new(AcpThreadEnvironment {
 313                    acp_thread: acp_thread.downgrade(),
 314                }) as _,
 315                cx,
 316            )
 317        });
 318
 319        let subscriptions = vec![
 320            cx.observe_release(&acp_thread, |this, acp_thread, _cx| {
 321                this.sessions.remove(acp_thread.session_id());
 322            }),
 323            cx.subscribe(&thread_handle, Self::handle_thread_title_updated),
 324            cx.subscribe(&thread_handle, Self::handle_thread_token_usage_updated),
 325            cx.observe(&thread_handle, move |this, thread, cx| {
 326                this.save_thread(thread, cx)
 327            }),
 328        ];
 329
 330        self.sessions.insert(
 331            session_id,
 332            Session {
 333                thread: thread_handle,
 334                acp_thread: acp_thread.downgrade(),
 335                _subscriptions: subscriptions,
 336                pending_save: Task::ready(()),
 337            },
 338        );
 339        acp_thread
 340    }
 341
 342    pub fn models(&self) -> &LanguageModels {
 343        &self.models
 344    }
 345
 346    async fn maintain_project_context(
 347        this: WeakEntity<Self>,
 348        mut needs_refresh: watch::Receiver<()>,
 349        cx: &mut AsyncApp,
 350    ) -> Result<()> {
 351        while needs_refresh.changed().await.is_ok() {
 352            let project_context = this
 353                .update(cx, |this, cx| {
 354                    Self::build_project_context(&this.project, this.prompt_store.as_ref(), cx)
 355                })?
 356                .await;
 357            this.update(cx, |this, cx| {
 358                this.project_context = cx.new(|_| project_context);
 359            })?;
 360        }
 361
 362        Ok(())
 363    }
 364
 365    fn build_project_context(
 366        project: &Entity<Project>,
 367        prompt_store: Option<&Entity<PromptStore>>,
 368        cx: &mut App,
 369    ) -> Task<ProjectContext> {
 370        let worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
 371        let worktree_tasks = worktrees
 372            .into_iter()
 373            .map(|worktree| {
 374                Self::load_worktree_info_for_system_prompt(worktree, project.clone(), cx)
 375            })
 376            .collect::<Vec<_>>();
 377        let default_user_rules_task = if let Some(prompt_store) = prompt_store.as_ref() {
 378            prompt_store.read_with(cx, |prompt_store, cx| {
 379                let prompts = prompt_store.default_prompt_metadata();
 380                let load_tasks = prompts.into_iter().map(|prompt_metadata| {
 381                    let contents = prompt_store.load(prompt_metadata.id, cx);
 382                    async move { (contents.await, prompt_metadata) }
 383                });
 384                cx.background_spawn(future::join_all(load_tasks))
 385            })
 386        } else {
 387            Task::ready(vec![])
 388        };
 389
 390        cx.spawn(async move |_cx| {
 391            let (worktrees, default_user_rules) =
 392                future::join(future::join_all(worktree_tasks), default_user_rules_task).await;
 393
 394            let worktrees = worktrees
 395                .into_iter()
 396                .map(|(worktree, _rules_error)| {
 397                    // TODO: show error message
 398                    // if let Some(rules_error) = rules_error {
 399                    //     this.update(cx, |_, cx| cx.emit(rules_error)).ok();
 400                    // }
 401                    worktree
 402                })
 403                .collect::<Vec<_>>();
 404
 405            let default_user_rules = default_user_rules
 406                .into_iter()
 407                .flat_map(|(contents, prompt_metadata)| match contents {
 408                    Ok(contents) => Some(UserRulesContext {
 409                        uuid: match prompt_metadata.id {
 410                            PromptId::User { uuid } => uuid,
 411                            PromptId::EditWorkflow => return None,
 412                        },
 413                        title: prompt_metadata.title.map(|title| title.to_string()),
 414                        contents,
 415                    }),
 416                    Err(_err) => {
 417                        // TODO: show error message
 418                        // this.update(cx, |_, cx| {
 419                        //     cx.emit(RulesLoadingError {
 420                        //         message: format!("{err:?}").into(),
 421                        //     });
 422                        // })
 423                        // .ok();
 424                        None
 425                    }
 426                })
 427                .collect::<Vec<_>>();
 428
 429            ProjectContext::new(worktrees, default_user_rules)
 430        })
 431    }
 432
 433    fn load_worktree_info_for_system_prompt(
 434        worktree: Entity<Worktree>,
 435        project: Entity<Project>,
 436        cx: &mut App,
 437    ) -> Task<(WorktreeContext, Option<RulesLoadingError>)> {
 438        let tree = worktree.read(cx);
 439        let root_name = tree.root_name().into();
 440        let abs_path = tree.abs_path();
 441
 442        let mut context = WorktreeContext {
 443            root_name,
 444            abs_path,
 445            rules_file: None,
 446        };
 447
 448        let rules_task = Self::load_worktree_rules_file(worktree, project, cx);
 449        let Some(rules_task) = rules_task else {
 450            return Task::ready((context, None));
 451        };
 452
 453        cx.spawn(async move |_| {
 454            let (rules_file, rules_file_error) = match rules_task.await {
 455                Ok(rules_file) => (Some(rules_file), None),
 456                Err(err) => (
 457                    None,
 458                    Some(RulesLoadingError {
 459                        message: format!("{err}").into(),
 460                    }),
 461                ),
 462            };
 463            context.rules_file = rules_file;
 464            (context, rules_file_error)
 465        })
 466    }
 467
 468    fn load_worktree_rules_file(
 469        worktree: Entity<Worktree>,
 470        project: Entity<Project>,
 471        cx: &mut App,
 472    ) -> Option<Task<Result<RulesFileContext>>> {
 473        let worktree = worktree.read(cx);
 474        let worktree_id = worktree.id();
 475        let selected_rules_file = RULES_FILE_NAMES
 476            .into_iter()
 477            .filter_map(|name| {
 478                worktree
 479                    .entry_for_path(name)
 480                    .filter(|entry| entry.is_file())
 481                    .map(|entry| entry.path.clone())
 482            })
 483            .next();
 484
 485        // Note that Cline supports `.clinerules` being a directory, but that is not currently
 486        // supported. This doesn't seem to occur often in GitHub repositories.
 487        selected_rules_file.map(|path_in_worktree| {
 488            let project_path = ProjectPath {
 489                worktree_id,
 490                path: path_in_worktree.clone(),
 491            };
 492            let buffer_task =
 493                project.update(cx, |project, cx| project.open_buffer(project_path, cx));
 494            let rope_task = cx.spawn(async move |cx| {
 495                buffer_task.await?.read_with(cx, |buffer, cx| {
 496                    let project_entry_id = buffer.entry_id(cx).context("buffer has no file")?;
 497                    anyhow::Ok((project_entry_id, buffer.as_rope().clone()))
 498                })?
 499            });
 500            // Build a string from the rope on a background thread.
 501            cx.background_spawn(async move {
 502                let (project_entry_id, rope) = rope_task.await?;
 503                anyhow::Ok(RulesFileContext {
 504                    path_in_worktree,
 505                    text: rope.to_string().trim().to_string(),
 506                    project_entry_id: project_entry_id.to_usize(),
 507                })
 508            })
 509        })
 510    }
 511
 512    fn handle_thread_title_updated(
 513        &mut self,
 514        thread: Entity<Thread>,
 515        _: &TitleUpdated,
 516        cx: &mut Context<Self>,
 517    ) {
 518        let session_id = thread.read(cx).id();
 519        let Some(session) = self.sessions.get(session_id) else {
 520            return;
 521        };
 522        let thread = thread.downgrade();
 523        let acp_thread = session.acp_thread.clone();
 524        cx.spawn(async move |_, cx| {
 525            let title = thread.read_with(cx, |thread, _| thread.title())?;
 526            let task = acp_thread.update(cx, |acp_thread, cx| acp_thread.set_title(title, cx))?;
 527            task.await
 528        })
 529        .detach_and_log_err(cx);
 530    }
 531
 532    fn handle_thread_token_usage_updated(
 533        &mut self,
 534        thread: Entity<Thread>,
 535        usage: &TokenUsageUpdated,
 536        cx: &mut Context<Self>,
 537    ) {
 538        let Some(session) = self.sessions.get(thread.read(cx).id()) else {
 539            return;
 540        };
 541        session
 542            .acp_thread
 543            .update(cx, |acp_thread, cx| {
 544                acp_thread.update_token_usage(usage.0.clone(), cx);
 545            })
 546            .ok();
 547    }
 548
 549    fn handle_project_event(
 550        &mut self,
 551        _project: Entity<Project>,
 552        event: &project::Event,
 553        _cx: &mut Context<Self>,
 554    ) {
 555        match event {
 556            project::Event::WorktreeAdded(_) | project::Event::WorktreeRemoved(_) => {
 557                self.project_context_needs_refresh.send(()).ok();
 558            }
 559            project::Event::WorktreeUpdatedEntries(_, items) => {
 560                if items.iter().any(|(path, _, _)| {
 561                    RULES_FILE_NAMES
 562                        .iter()
 563                        .any(|name| path.as_ref() == Path::new(name))
 564                }) {
 565                    self.project_context_needs_refresh.send(()).ok();
 566                }
 567            }
 568            _ => {}
 569        }
 570    }
 571
 572    fn handle_prompts_updated_event(
 573        &mut self,
 574        _prompt_store: Entity<PromptStore>,
 575        _event: &prompt_store::PromptsUpdatedEvent,
 576        _cx: &mut Context<Self>,
 577    ) {
 578        self.project_context_needs_refresh.send(()).ok();
 579    }
 580
 581    fn handle_models_updated_event(
 582        &mut self,
 583        _registry: Entity<LanguageModelRegistry>,
 584        _event: &language_model::Event,
 585        cx: &mut Context<Self>,
 586    ) {
 587        self.models.refresh_list(cx);
 588
 589        let registry = LanguageModelRegistry::read_global(cx);
 590        let default_model = registry.default_model().map(|m| m.model);
 591        let summarization_model = registry.thread_summary_model().map(|m| m.model);
 592
 593        for session in self.sessions.values_mut() {
 594            session.thread.update(cx, |thread, cx| {
 595                if thread.model().is_none()
 596                    && let Some(model) = default_model.clone()
 597                {
 598                    thread.set_model(model, cx);
 599                    cx.notify();
 600                }
 601                thread.set_summarization_model(summarization_model.clone(), cx);
 602            });
 603        }
 604    }
 605
 606    pub fn open_thread(
 607        &mut self,
 608        id: acp::SessionId,
 609        cx: &mut Context<Self>,
 610    ) -> Task<Result<Entity<AcpThread>>> {
 611        let database_future = ThreadsDatabase::connect(cx);
 612        cx.spawn(async move |this, cx| {
 613            let database = database_future.await.map_err(|err| anyhow!(err))?;
 614            let db_thread = database
 615                .load_thread(id.clone())
 616                .await?
 617                .with_context(|| format!("no thread found with ID: {id:?}"))?;
 618
 619            let thread = this.update(cx, |this, cx| {
 620                let action_log = cx.new(|_cx| ActionLog::new(this.project.clone()));
 621                cx.new(|cx| {
 622                    Thread::from_db(
 623                        id.clone(),
 624                        db_thread,
 625                        this.project.clone(),
 626                        this.project_context.clone(),
 627                        this.context_server_registry.clone(),
 628                        action_log.clone(),
 629                        this.templates.clone(),
 630                        cx,
 631                    )
 632                })
 633            })?;
 634            let acp_thread =
 635                this.update(cx, |this, cx| this.register_session(thread.clone(), cx))?;
 636            let events = thread.update(cx, |thread, cx| thread.replay(cx))?;
 637            cx.update(|cx| {
 638                NativeAgentConnection::handle_thread_events(events, acp_thread.downgrade(), cx)
 639            })?
 640            .await?;
 641            Ok(acp_thread)
 642        })
 643    }
 644
 645    pub fn thread_summary(
 646        &mut self,
 647        id: acp::SessionId,
 648        cx: &mut Context<Self>,
 649    ) -> Task<Result<SharedString>> {
 650        let thread = self.open_thread(id.clone(), cx);
 651        cx.spawn(async move |this, cx| {
 652            let acp_thread = thread.await?;
 653            let result = this
 654                .update(cx, |this, cx| {
 655                    this.sessions
 656                        .get(&id)
 657                        .unwrap()
 658                        .thread
 659                        .update(cx, |thread, cx| thread.summary(cx))
 660                })?
 661                .await?;
 662            drop(acp_thread);
 663            Ok(result)
 664        })
 665    }
 666
 667    fn save_thread(&mut self, thread: Entity<Thread>, cx: &mut Context<Self>) {
 668        if thread.read(cx).is_empty() {
 669            return;
 670        }
 671
 672        let database_future = ThreadsDatabase::connect(cx);
 673        let (id, db_thread) =
 674            thread.update(cx, |thread, cx| (thread.id().clone(), thread.to_db(cx)));
 675        let Some(session) = self.sessions.get_mut(&id) else {
 676            return;
 677        };
 678        let history = self.history.clone();
 679        session.pending_save = cx.spawn(async move |_, cx| {
 680            let Some(database) = database_future.await.map_err(|err| anyhow!(err)).log_err() else {
 681                return;
 682            };
 683            let db_thread = db_thread.await;
 684            database.save_thread(id, db_thread).await.log_err();
 685            history.update(cx, |history, cx| history.reload(cx)).ok();
 686        });
 687    }
 688}
 689
 690/// Wrapper struct that implements the AgentConnection trait
 691#[derive(Clone)]
 692pub struct NativeAgentConnection(pub Entity<NativeAgent>);
 693
 694impl NativeAgentConnection {
 695    pub fn thread(&self, session_id: &acp::SessionId, cx: &App) -> Option<Entity<Thread>> {
 696        self.0
 697            .read(cx)
 698            .sessions
 699            .get(session_id)
 700            .map(|session| session.thread.clone())
 701    }
 702
 703    fn run_turn(
 704        &self,
 705        session_id: acp::SessionId,
 706        cx: &mut App,
 707        f: impl 'static
 708        + FnOnce(Entity<Thread>, &mut App) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>,
 709    ) -> Task<Result<acp::PromptResponse>> {
 710        let Some((thread, acp_thread)) = self.0.update(cx, |agent, _cx| {
 711            agent
 712                .sessions
 713                .get_mut(&session_id)
 714                .map(|s| (s.thread.clone(), s.acp_thread.clone()))
 715        }) else {
 716            return Task::ready(Err(anyhow!("Session not found")));
 717        };
 718        log::debug!("Found session for: {}", session_id);
 719
 720        let response_stream = match f(thread, cx) {
 721            Ok(stream) => stream,
 722            Err(err) => return Task::ready(Err(err)),
 723        };
 724        Self::handle_thread_events(response_stream, acp_thread, cx)
 725    }
 726
 727    fn handle_thread_events(
 728        mut events: mpsc::UnboundedReceiver<Result<ThreadEvent>>,
 729        acp_thread: WeakEntity<AcpThread>,
 730        cx: &App,
 731    ) -> Task<Result<acp::PromptResponse>> {
 732        cx.spawn(async move |cx| {
 733            // Handle response stream and forward to session.acp_thread
 734            while let Some(result) = events.next().await {
 735                match result {
 736                    Ok(event) => {
 737                        log::trace!("Received completion event: {:?}", event);
 738
 739                        match event {
 740                            ThreadEvent::UserMessage(message) => {
 741                                acp_thread.update(cx, |thread, cx| {
 742                                    for content in message.content {
 743                                        thread.push_user_content_block(
 744                                            Some(message.id.clone()),
 745                                            content.into(),
 746                                            cx,
 747                                        );
 748                                    }
 749                                })?;
 750                            }
 751                            ThreadEvent::AgentText(text) => {
 752                                acp_thread.update(cx, |thread, cx| {
 753                                    thread.push_assistant_content_block(
 754                                        acp::ContentBlock::Text(acp::TextContent {
 755                                            text,
 756                                            annotations: None,
 757                                            meta: None,
 758                                        }),
 759                                        false,
 760                                        cx,
 761                                    )
 762                                })?;
 763                            }
 764                            ThreadEvent::AgentThinking(text) => {
 765                                acp_thread.update(cx, |thread, cx| {
 766                                    thread.push_assistant_content_block(
 767                                        acp::ContentBlock::Text(acp::TextContent {
 768                                            text,
 769                                            annotations: None,
 770                                            meta: None,
 771                                        }),
 772                                        true,
 773                                        cx,
 774                                    )
 775                                })?;
 776                            }
 777                            ThreadEvent::ToolCallAuthorization(ToolCallAuthorization {
 778                                tool_call,
 779                                options,
 780                                response,
 781                            }) => {
 782                                let outcome_task = acp_thread.update(cx, |thread, cx| {
 783                                    thread.request_tool_call_authorization(
 784                                        tool_call, options, true, cx,
 785                                    )
 786                                })??;
 787                                cx.background_spawn(async move {
 788                                    if let acp::RequestPermissionOutcome::Selected { option_id } =
 789                                        outcome_task.await
 790                                    {
 791                                        response
 792                                            .send(option_id)
 793                                            .map(|_| anyhow!("authorization receiver was dropped"))
 794                                            .log_err();
 795                                    }
 796                                })
 797                                .detach();
 798                            }
 799                            ThreadEvent::ToolCall(tool_call) => {
 800                                acp_thread.update(cx, |thread, cx| {
 801                                    thread.upsert_tool_call(tool_call, cx)
 802                                })??;
 803                            }
 804                            ThreadEvent::ToolCallUpdate(update) => {
 805                                acp_thread.update(cx, |thread, cx| {
 806                                    thread.update_tool_call(update, cx)
 807                                })??;
 808                            }
 809                            ThreadEvent::Retry(status) => {
 810                                acp_thread.update(cx, |thread, cx| {
 811                                    thread.update_retry_status(status, cx)
 812                                })?;
 813                            }
 814                            ThreadEvent::Stop(stop_reason) => {
 815                                log::debug!("Assistant message complete: {:?}", stop_reason);
 816                                return Ok(acp::PromptResponse {
 817                                    stop_reason,
 818                                    meta: None,
 819                                });
 820                            }
 821                        }
 822                    }
 823                    Err(e) => {
 824                        log::error!("Error in model response stream: {:?}", e);
 825                        return Err(e);
 826                    }
 827                }
 828            }
 829
 830            log::debug!("Response stream completed");
 831            anyhow::Ok(acp::PromptResponse {
 832                stop_reason: acp::StopReason::EndTurn,
 833                meta: None,
 834            })
 835        })
 836    }
 837}
 838
 839impl AgentModelSelector for NativeAgentConnection {
 840    fn list_models(&self, cx: &mut App) -> Task<Result<acp_thread::AgentModelList>> {
 841        log::debug!("NativeAgentConnection::list_models called");
 842        let list = self.0.read(cx).models.model_list.clone();
 843        Task::ready(if list.is_empty() {
 844            Err(anyhow::anyhow!("No models available"))
 845        } else {
 846            Ok(list)
 847        })
 848    }
 849
 850    fn select_model(
 851        &self,
 852        session_id: acp::SessionId,
 853        model_id: acp_thread::AgentModelId,
 854        cx: &mut App,
 855    ) -> Task<Result<()>> {
 856        log::debug!("Setting model for session {}: {}", session_id, model_id);
 857        let Some(thread) = self
 858            .0
 859            .read(cx)
 860            .sessions
 861            .get(&session_id)
 862            .map(|session| session.thread.clone())
 863        else {
 864            return Task::ready(Err(anyhow!("Session not found")));
 865        };
 866
 867        let Some(model) = self.0.read(cx).models.model_from_id(&model_id) else {
 868            return Task::ready(Err(anyhow!("Invalid model ID {}", model_id)));
 869        };
 870
 871        thread.update(cx, |thread, cx| {
 872            thread.set_model(model.clone(), cx);
 873        });
 874
 875        update_settings_file(self.0.read(cx).fs.clone(), cx, move |settings, _cx| {
 876            settings.agent.get_or_insert_default().set_model(model);
 877        });
 878
 879        Task::ready(Ok(()))
 880    }
 881
 882    fn selected_model(
 883        &self,
 884        session_id: &acp::SessionId,
 885        cx: &mut App,
 886    ) -> Task<Result<acp_thread::AgentModelInfo>> {
 887        let session_id = session_id.clone();
 888
 889        let Some(thread) = self
 890            .0
 891            .read(cx)
 892            .sessions
 893            .get(&session_id)
 894            .map(|session| session.thread.clone())
 895        else {
 896            return Task::ready(Err(anyhow!("Session not found")));
 897        };
 898        let Some(model) = thread.read(cx).model() else {
 899            return Task::ready(Err(anyhow!("Model not found")));
 900        };
 901        let Some(provider) = LanguageModelRegistry::read_global(cx).provider(&model.provider_id())
 902        else {
 903            return Task::ready(Err(anyhow!("Provider not found")));
 904        };
 905        Task::ready(Ok(LanguageModels::map_language_model_to_info(
 906            model, &provider,
 907        )))
 908    }
 909
 910    fn watch(&self, cx: &mut App) -> watch::Receiver<()> {
 911        self.0.read(cx).models.watch()
 912    }
 913}
 914
 915impl acp_thread::AgentConnection for NativeAgentConnection {
 916    fn new_thread(
 917        self: Rc<Self>,
 918        project: Entity<Project>,
 919        cwd: &Path,
 920        cx: &mut App,
 921    ) -> Task<Result<Entity<acp_thread::AcpThread>>> {
 922        let agent = self.0.clone();
 923        log::debug!("Creating new thread for project at: {:?}", cwd);
 924
 925        cx.spawn(async move |cx| {
 926            log::debug!("Starting thread creation in async context");
 927
 928            // Create Thread
 929            let thread = agent.update(
 930                cx,
 931                |agent, cx: &mut gpui::Context<NativeAgent>| -> Result<_> {
 932                    // Fetch default model from registry settings
 933                    let registry = LanguageModelRegistry::read_global(cx);
 934                    // Log available models for debugging
 935                    let available_count = registry.available_models(cx).count();
 936                    log::debug!("Total available models: {}", available_count);
 937
 938                    let default_model = registry.default_model().and_then(|default_model| {
 939                        agent
 940                            .models
 941                            .model_from_id(&LanguageModels::model_id(&default_model.model))
 942                    });
 943                    Ok(cx.new(|cx| {
 944                        Thread::new(
 945                            project.clone(),
 946                            agent.project_context.clone(),
 947                            agent.context_server_registry.clone(),
 948                            agent.templates.clone(),
 949                            default_model,
 950                            cx,
 951                        )
 952                    }))
 953                },
 954            )??;
 955            agent.update(cx, |agent, cx| agent.register_session(thread, cx))
 956        })
 957    }
 958
 959    fn auth_methods(&self) -> &[acp::AuthMethod] {
 960        &[] // No auth for in-process
 961    }
 962
 963    fn authenticate(&self, _method: acp::AuthMethodId, _cx: &mut App) -> Task<Result<()>> {
 964        Task::ready(Ok(()))
 965    }
 966
 967    fn model_selector(&self) -> Option<Rc<dyn AgentModelSelector>> {
 968        Some(Rc::new(self.clone()) as Rc<dyn AgentModelSelector>)
 969    }
 970
 971    fn prompt(
 972        &self,
 973        id: Option<acp_thread::UserMessageId>,
 974        params: acp::PromptRequest,
 975        cx: &mut App,
 976    ) -> Task<Result<acp::PromptResponse>> {
 977        let id = id.expect("UserMessageId is required");
 978        let session_id = params.session_id.clone();
 979        log::info!("Received prompt request for session: {}", session_id);
 980        log::debug!("Prompt blocks count: {}", params.prompt.len());
 981
 982        self.run_turn(session_id, cx, |thread, cx| {
 983            let content: Vec<UserMessageContent> = params
 984                .prompt
 985                .into_iter()
 986                .map(Into::into)
 987                .collect::<Vec<_>>();
 988            log::debug!("Converted prompt to message: {} chars", content.len());
 989            log::debug!("Message id: {:?}", id);
 990            log::debug!("Message content: {:?}", content);
 991
 992            thread.update(cx, |thread, cx| thread.send(id, content, cx))
 993        })
 994    }
 995
 996    fn resume(
 997        &self,
 998        session_id: &acp::SessionId,
 999        _cx: &App,
1000    ) -> Option<Rc<dyn acp_thread::AgentSessionResume>> {
1001        Some(Rc::new(NativeAgentSessionResume {
1002            connection: self.clone(),
1003            session_id: session_id.clone(),
1004        }) as _)
1005    }
1006
1007    fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
1008        log::info!("Cancelling on session: {}", session_id);
1009        self.0.update(cx, |agent, cx| {
1010            if let Some(agent) = agent.sessions.get(session_id) {
1011                agent.thread.update(cx, |thread, cx| thread.cancel(cx));
1012            }
1013        });
1014    }
1015
1016    fn truncate(
1017        &self,
1018        session_id: &agent_client_protocol::SessionId,
1019        cx: &App,
1020    ) -> Option<Rc<dyn acp_thread::AgentSessionTruncate>> {
1021        self.0.read_with(cx, |agent, _cx| {
1022            agent.sessions.get(session_id).map(|session| {
1023                Rc::new(NativeAgentSessionTruncate {
1024                    thread: session.thread.clone(),
1025                    acp_thread: session.acp_thread.clone(),
1026                }) as _
1027            })
1028        })
1029    }
1030
1031    fn set_title(
1032        &self,
1033        session_id: &acp::SessionId,
1034        _cx: &App,
1035    ) -> Option<Rc<dyn acp_thread::AgentSessionSetTitle>> {
1036        Some(Rc::new(NativeAgentSessionSetTitle {
1037            connection: self.clone(),
1038            session_id: session_id.clone(),
1039        }) as _)
1040    }
1041
1042    fn telemetry(&self) -> Option<Rc<dyn acp_thread::AgentTelemetry>> {
1043        Some(Rc::new(self.clone()) as Rc<dyn acp_thread::AgentTelemetry>)
1044    }
1045
1046    fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
1047        self
1048    }
1049}
1050
1051impl acp_thread::AgentTelemetry for NativeAgentConnection {
1052    fn agent_name(&self) -> String {
1053        "Zed".into()
1054    }
1055
1056    fn thread_data(
1057        &self,
1058        session_id: &acp::SessionId,
1059        cx: &mut App,
1060    ) -> Task<Result<serde_json::Value>> {
1061        let Some(session) = self.0.read(cx).sessions.get(session_id) else {
1062            return Task::ready(Err(anyhow!("Session not found")));
1063        };
1064
1065        let task = session.thread.read(cx).to_db(cx);
1066        cx.background_spawn(async move {
1067            serde_json::to_value(task.await).context("Failed to serialize thread")
1068        })
1069    }
1070}
1071
1072struct NativeAgentSessionTruncate {
1073    thread: Entity<Thread>,
1074    acp_thread: WeakEntity<AcpThread>,
1075}
1076
1077impl acp_thread::AgentSessionTruncate for NativeAgentSessionTruncate {
1078    fn run(&self, message_id: acp_thread::UserMessageId, cx: &mut App) -> Task<Result<()>> {
1079        match self.thread.update(cx, |thread, cx| {
1080            thread.truncate(message_id.clone(), cx)?;
1081            Ok(thread.latest_token_usage())
1082        }) {
1083            Ok(usage) => {
1084                self.acp_thread
1085                    .update(cx, |thread, cx| {
1086                        thread.update_token_usage(usage, cx);
1087                    })
1088                    .ok();
1089                Task::ready(Ok(()))
1090            }
1091            Err(error) => Task::ready(Err(error)),
1092        }
1093    }
1094}
1095
1096struct NativeAgentSessionResume {
1097    connection: NativeAgentConnection,
1098    session_id: acp::SessionId,
1099}
1100
1101impl acp_thread::AgentSessionResume for NativeAgentSessionResume {
1102    fn run(&self, cx: &mut App) -> Task<Result<acp::PromptResponse>> {
1103        self.connection
1104            .run_turn(self.session_id.clone(), cx, |thread, cx| {
1105                thread.update(cx, |thread, cx| thread.resume(cx))
1106            })
1107    }
1108}
1109
1110struct NativeAgentSessionSetTitle {
1111    connection: NativeAgentConnection,
1112    session_id: acp::SessionId,
1113}
1114
1115impl acp_thread::AgentSessionSetTitle for NativeAgentSessionSetTitle {
1116    fn run(&self, title: SharedString, cx: &mut App) -> Task<Result<()>> {
1117        let Some(session) = self.connection.0.read(cx).sessions.get(&self.session_id) else {
1118            return Task::ready(Err(anyhow!("session not found")));
1119        };
1120        let thread = session.thread.clone();
1121        thread.update(cx, |thread, cx| thread.set_title(title, cx));
1122        Task::ready(Ok(()))
1123    }
1124}
1125
1126pub struct AcpThreadEnvironment {
1127    acp_thread: WeakEntity<AcpThread>,
1128}
1129
1130impl ThreadEnvironment for AcpThreadEnvironment {
1131    fn create_terminal(
1132        &self,
1133        command: String,
1134        cwd: Option<PathBuf>,
1135        output_byte_limit: Option<u64>,
1136        cx: &mut AsyncApp,
1137    ) -> Task<Result<Rc<dyn TerminalHandle>>> {
1138        let task = self.acp_thread.update(cx, |thread, cx| {
1139            thread.create_terminal(command, vec![], vec![], cwd, output_byte_limit, cx)
1140        });
1141
1142        let acp_thread = self.acp_thread.clone();
1143        cx.spawn(async move |cx| {
1144            let terminal = task?.await?;
1145
1146            let (drop_tx, drop_rx) = oneshot::channel();
1147            let terminal_id = terminal.read_with(cx, |terminal, _cx| terminal.id().clone())?;
1148
1149            cx.spawn(async move |cx| {
1150                drop_rx.await.ok();
1151                acp_thread.update(cx, |thread, cx| thread.release_terminal(terminal_id, cx))
1152            })
1153            .detach();
1154
1155            let handle = AcpTerminalHandle {
1156                terminal,
1157                _drop_tx: Some(drop_tx),
1158            };
1159
1160            Ok(Rc::new(handle) as _)
1161        })
1162    }
1163}
1164
1165pub struct AcpTerminalHandle {
1166    terminal: Entity<acp_thread::Terminal>,
1167    _drop_tx: Option<oneshot::Sender<()>>,
1168}
1169
1170impl TerminalHandle for AcpTerminalHandle {
1171    fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId> {
1172        self.terminal.read_with(cx, |term, _cx| term.id().clone())
1173    }
1174
1175    fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>> {
1176        self.terminal
1177            .read_with(cx, |term, _cx| term.wait_for_exit())
1178    }
1179
1180    fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse> {
1181        self.terminal
1182            .read_with(cx, |term, cx| term.current_output(cx))
1183    }
1184}
1185
1186#[cfg(test)]
1187mod tests {
1188    use crate::HistoryEntryId;
1189
1190    use super::*;
1191    use acp_thread::{
1192        AgentConnection, AgentModelGroupName, AgentModelId, AgentModelInfo, MentionUri,
1193    };
1194    use fs::FakeFs;
1195    use gpui::TestAppContext;
1196    use indoc::indoc;
1197    use language_model::fake_provider::FakeLanguageModel;
1198    use serde_json::json;
1199    use settings::SettingsStore;
1200    use util::path;
1201
1202    #[gpui::test]
1203    async fn test_maintaining_project_context(cx: &mut TestAppContext) {
1204        init_test(cx);
1205        let fs = FakeFs::new(cx.executor());
1206        fs.insert_tree(
1207            "/",
1208            json!({
1209                "a": {}
1210            }),
1211        )
1212        .await;
1213        let project = Project::test(fs.clone(), [], cx).await;
1214        let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1215        let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1216        let agent = NativeAgent::new(
1217            project.clone(),
1218            history_store,
1219            Templates::new(),
1220            None,
1221            fs.clone(),
1222            &mut cx.to_async(),
1223        )
1224        .await
1225        .unwrap();
1226        agent.read_with(cx, |agent, cx| {
1227            assert_eq!(agent.project_context.read(cx).worktrees, vec![])
1228        });
1229
1230        let worktree = project
1231            .update(cx, |project, cx| project.create_worktree("/a", true, cx))
1232            .await
1233            .unwrap();
1234        cx.run_until_parked();
1235        agent.read_with(cx, |agent, cx| {
1236            assert_eq!(
1237                agent.project_context.read(cx).worktrees,
1238                vec![WorktreeContext {
1239                    root_name: "a".into(),
1240                    abs_path: Path::new("/a").into(),
1241                    rules_file: None
1242                }]
1243            )
1244        });
1245
1246        // Creating `/a/.rules` updates the project context.
1247        fs.insert_file("/a/.rules", Vec::new()).await;
1248        cx.run_until_parked();
1249        agent.read_with(cx, |agent, cx| {
1250            let rules_entry = worktree.read(cx).entry_for_path(".rules").unwrap();
1251            assert_eq!(
1252                agent.project_context.read(cx).worktrees,
1253                vec![WorktreeContext {
1254                    root_name: "a".into(),
1255                    abs_path: Path::new("/a").into(),
1256                    rules_file: Some(RulesFileContext {
1257                        path_in_worktree: Path::new(".rules").into(),
1258                        text: "".into(),
1259                        project_entry_id: rules_entry.id.to_usize()
1260                    })
1261                }]
1262            )
1263        });
1264    }
1265
1266    #[gpui::test]
1267    async fn test_listing_models(cx: &mut TestAppContext) {
1268        init_test(cx);
1269        let fs = FakeFs::new(cx.executor());
1270        fs.insert_tree("/", json!({ "a": {}  })).await;
1271        let project = Project::test(fs.clone(), [], cx).await;
1272        let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1273        let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1274        let connection = NativeAgentConnection(
1275            NativeAgent::new(
1276                project.clone(),
1277                history_store,
1278                Templates::new(),
1279                None,
1280                fs.clone(),
1281                &mut cx.to_async(),
1282            )
1283            .await
1284            .unwrap(),
1285        );
1286
1287        let models = cx.update(|cx| connection.list_models(cx)).await.unwrap();
1288
1289        let acp_thread::AgentModelList::Grouped(models) = models else {
1290            panic!("Unexpected model group");
1291        };
1292        assert_eq!(
1293            models,
1294            IndexMap::from_iter([(
1295                AgentModelGroupName("Fake".into()),
1296                vec![AgentModelInfo {
1297                    id: AgentModelId("fake/fake".into()),
1298                    name: "Fake".into(),
1299                    icon: Some(ui::IconName::ZedAssistant),
1300                }]
1301            )])
1302        );
1303    }
1304
1305    #[gpui::test]
1306    async fn test_model_selection_persists_to_settings(cx: &mut TestAppContext) {
1307        init_test(cx);
1308        let fs = FakeFs::new(cx.executor());
1309        fs.create_dir(paths::settings_file().parent().unwrap())
1310            .await
1311            .unwrap();
1312        fs.insert_file(
1313            paths::settings_file(),
1314            json!({
1315                "agent": {
1316                    "default_model": {
1317                        "provider": "foo",
1318                        "model": "bar"
1319                    }
1320                }
1321            })
1322            .to_string()
1323            .into_bytes(),
1324        )
1325        .await;
1326        let project = Project::test(fs.clone(), [], cx).await;
1327
1328        let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1329        let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1330
1331        // Create the agent and connection
1332        let agent = NativeAgent::new(
1333            project.clone(),
1334            history_store,
1335            Templates::new(),
1336            None,
1337            fs.clone(),
1338            &mut cx.to_async(),
1339        )
1340        .await
1341        .unwrap();
1342        let connection = NativeAgentConnection(agent.clone());
1343
1344        // Create a thread/session
1345        let acp_thread = cx
1346            .update(|cx| {
1347                Rc::new(connection.clone()).new_thread(project.clone(), Path::new("/a"), cx)
1348            })
1349            .await
1350            .unwrap();
1351
1352        let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());
1353
1354        // Select a model
1355        let model_id = AgentModelId("fake/fake".into());
1356        cx.update(|cx| connection.select_model(session_id.clone(), model_id.clone(), cx))
1357            .await
1358            .unwrap();
1359
1360        // Verify the thread has the selected model
1361        agent.read_with(cx, |agent, _| {
1362            let session = agent.sessions.get(&session_id).unwrap();
1363            session.thread.read_with(cx, |thread, _| {
1364                assert_eq!(thread.model().unwrap().id().0, "fake");
1365            });
1366        });
1367
1368        cx.run_until_parked();
1369
1370        // Verify settings file was updated
1371        let settings_content = fs.load(paths::settings_file()).await.unwrap();
1372        let settings_json: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1373
1374        // Check that the agent settings contain the selected model
1375        assert_eq!(
1376            settings_json["agent"]["default_model"]["model"],
1377            json!("fake")
1378        );
1379        assert_eq!(
1380            settings_json["agent"]["default_model"]["provider"],
1381            json!("fake")
1382        );
1383    }
1384
1385    #[gpui::test]
1386    #[cfg_attr(target_os = "windows", ignore)] // TODO: Fix this test on Windows
1387    async fn test_save_load_thread(cx: &mut TestAppContext) {
1388        init_test(cx);
1389        let fs = FakeFs::new(cx.executor());
1390        fs.insert_tree(
1391            "/",
1392            json!({
1393                "a": {
1394                    "b.md": "Lorem"
1395                }
1396            }),
1397        )
1398        .await;
1399        let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
1400        let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1401        let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1402        let agent = NativeAgent::new(
1403            project.clone(),
1404            history_store.clone(),
1405            Templates::new(),
1406            None,
1407            fs.clone(),
1408            &mut cx.to_async(),
1409        )
1410        .await
1411        .unwrap();
1412        let connection = Rc::new(NativeAgentConnection(agent.clone()));
1413
1414        let acp_thread = cx
1415            .update(|cx| {
1416                connection
1417                    .clone()
1418                    .new_thread(project.clone(), Path::new(""), cx)
1419            })
1420            .await
1421            .unwrap();
1422        let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
1423        let thread = agent.read_with(cx, |agent, _| {
1424            agent.sessions.get(&session_id).unwrap().thread.clone()
1425        });
1426
1427        // Ensure empty threads are not saved, even if they get mutated.
1428        let model = Arc::new(FakeLanguageModel::default());
1429        let summary_model = Arc::new(FakeLanguageModel::default());
1430        thread.update(cx, |thread, cx| {
1431            thread.set_model(model.clone(), cx);
1432            thread.set_summarization_model(Some(summary_model.clone()), cx);
1433        });
1434        cx.run_until_parked();
1435        assert_eq!(history_entries(&history_store, cx), vec![]);
1436
1437        let send = acp_thread.update(cx, |thread, cx| {
1438            thread.send(
1439                vec![
1440                    "What does ".into(),
1441                    acp::ContentBlock::ResourceLink(acp::ResourceLink {
1442                        name: "b.md".into(),
1443                        uri: MentionUri::File {
1444                            abs_path: path!("/a/b.md").into(),
1445                        }
1446                        .to_uri()
1447                        .to_string(),
1448                        annotations: None,
1449                        description: None,
1450                        mime_type: None,
1451                        size: None,
1452                        title: None,
1453                        meta: None,
1454                    }),
1455                    " mean?".into(),
1456                ],
1457                cx,
1458            )
1459        });
1460        let send = cx.foreground_executor().spawn(send);
1461        cx.run_until_parked();
1462
1463        model.send_last_completion_stream_text_chunk("Lorem.");
1464        model.end_last_completion_stream();
1465        cx.run_until_parked();
1466        summary_model.send_last_completion_stream_text_chunk("Explaining /a/b.md");
1467        summary_model.end_last_completion_stream();
1468
1469        send.await.unwrap();
1470        acp_thread.read_with(cx, |thread, cx| {
1471            assert_eq!(
1472                thread.to_markdown(cx),
1473                indoc! {"
1474                    ## User
1475
1476                    What does [@b.md](file:///a/b.md) mean?
1477
1478                    ## Assistant
1479
1480                    Lorem.
1481
1482                "}
1483            )
1484        });
1485
1486        cx.run_until_parked();
1487
1488        // Drop the ACP thread, which should cause the session to be dropped as well.
1489        cx.update(|_| {
1490            drop(thread);
1491            drop(acp_thread);
1492        });
1493        agent.read_with(cx, |agent, _| {
1494            assert_eq!(agent.sessions.keys().cloned().collect::<Vec<_>>(), []);
1495        });
1496
1497        // Ensure the thread can be reloaded from disk.
1498        assert_eq!(
1499            history_entries(&history_store, cx),
1500            vec![(
1501                HistoryEntryId::AcpThread(session_id.clone()),
1502                "Explaining /a/b.md".into()
1503            )]
1504        );
1505        let acp_thread = agent
1506            .update(cx, |agent, cx| agent.open_thread(session_id.clone(), cx))
1507            .await
1508            .unwrap();
1509        acp_thread.read_with(cx, |thread, cx| {
1510            assert_eq!(
1511                thread.to_markdown(cx),
1512                indoc! {"
1513                    ## User
1514
1515                    What does [@b.md](file:///a/b.md) mean?
1516
1517                    ## Assistant
1518
1519                    Lorem.
1520
1521                "}
1522            )
1523        });
1524    }
1525
1526    fn history_entries(
1527        history: &Entity<HistoryStore>,
1528        cx: &mut TestAppContext,
1529    ) -> Vec<(HistoryEntryId, String)> {
1530        history.read_with(cx, |history, _| {
1531            history
1532                .entries()
1533                .map(|e| (e.id(), e.title().to_string()))
1534                .collect::<Vec<_>>()
1535        })
1536    }
1537
1538    fn init_test(cx: &mut TestAppContext) {
1539        env_logger::try_init().ok();
1540        cx.update(|cx| {
1541            let settings_store = SettingsStore::test(cx);
1542            cx.set_global(settings_store);
1543            Project::init_settings(cx);
1544            agent_settings::init(cx);
1545            language::init(cx);
1546            LanguageModelRegistry::test(cx);
1547        });
1548    }
1549}