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