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(tool_call, options, cx)
 775                                })??;
 776                                cx.background_spawn(async move {
 777                                    if let acp::RequestPermissionOutcome::Selected { option_id } =
 778                                        outcome_task.await
 779                                    {
 780                                        response
 781                                            .send(option_id)
 782                                            .map(|_| anyhow!("authorization receiver was dropped"))
 783                                            .log_err();
 784                                    }
 785                                })
 786                                .detach();
 787                            }
 788                            ThreadEvent::ToolCall(tool_call) => {
 789                                acp_thread.update(cx, |thread, cx| {
 790                                    thread.upsert_tool_call(tool_call, cx)
 791                                })??;
 792                            }
 793                            ThreadEvent::ToolCallUpdate(update) => {
 794                                acp_thread.update(cx, |thread, cx| {
 795                                    thread.update_tool_call(update, cx)
 796                                })??;
 797                            }
 798                            ThreadEvent::Retry(status) => {
 799                                acp_thread.update(cx, |thread, cx| {
 800                                    thread.update_retry_status(status, cx)
 801                                })?;
 802                            }
 803                            ThreadEvent::Stop(stop_reason) => {
 804                                log::debug!("Assistant message complete: {:?}", stop_reason);
 805                                return Ok(acp::PromptResponse { stop_reason });
 806                            }
 807                        }
 808                    }
 809                    Err(e) => {
 810                        log::error!("Error in model response stream: {:?}", e);
 811                        return Err(e);
 812                    }
 813                }
 814            }
 815
 816            log::debug!("Response stream completed");
 817            anyhow::Ok(acp::PromptResponse {
 818                stop_reason: acp::StopReason::EndTurn,
 819            })
 820        })
 821    }
 822}
 823
 824impl AgentModelSelector for NativeAgentConnection {
 825    fn list_models(&self, cx: &mut App) -> Task<Result<acp_thread::AgentModelList>> {
 826        log::debug!("NativeAgentConnection::list_models called");
 827        let list = self.0.read(cx).models.model_list.clone();
 828        Task::ready(if list.is_empty() {
 829            Err(anyhow::anyhow!("No models available"))
 830        } else {
 831            Ok(list)
 832        })
 833    }
 834
 835    fn select_model(
 836        &self,
 837        session_id: acp::SessionId,
 838        model_id: acp_thread::AgentModelId,
 839        cx: &mut App,
 840    ) -> Task<Result<()>> {
 841        log::debug!("Setting model for session {}: {}", session_id, model_id);
 842        let Some(thread) = self
 843            .0
 844            .read(cx)
 845            .sessions
 846            .get(&session_id)
 847            .map(|session| session.thread.clone())
 848        else {
 849            return Task::ready(Err(anyhow!("Session not found")));
 850        };
 851
 852        let Some(model) = self.0.read(cx).models.model_from_id(&model_id) else {
 853            return Task::ready(Err(anyhow!("Invalid model ID {}", model_id)));
 854        };
 855
 856        thread.update(cx, |thread, cx| {
 857            thread.set_model(model.clone(), cx);
 858        });
 859
 860        update_settings_file::<AgentSettings>(
 861            self.0.read(cx).fs.clone(),
 862            cx,
 863            move |settings, _cx| {
 864                settings.set_model(model);
 865            },
 866        );
 867
 868        Task::ready(Ok(()))
 869    }
 870
 871    fn selected_model(
 872        &self,
 873        session_id: &acp::SessionId,
 874        cx: &mut App,
 875    ) -> Task<Result<acp_thread::AgentModelInfo>> {
 876        let session_id = session_id.clone();
 877
 878        let Some(thread) = self
 879            .0
 880            .read(cx)
 881            .sessions
 882            .get(&session_id)
 883            .map(|session| session.thread.clone())
 884        else {
 885            return Task::ready(Err(anyhow!("Session not found")));
 886        };
 887        let Some(model) = thread.read(cx).model() else {
 888            return Task::ready(Err(anyhow!("Model not found")));
 889        };
 890        let Some(provider) = LanguageModelRegistry::read_global(cx).provider(&model.provider_id())
 891        else {
 892            return Task::ready(Err(anyhow!("Provider not found")));
 893        };
 894        Task::ready(Ok(LanguageModels::map_language_model_to_info(
 895            model, &provider,
 896        )))
 897    }
 898
 899    fn watch(&self, cx: &mut App) -> watch::Receiver<()> {
 900        self.0.read(cx).models.watch()
 901    }
 902}
 903
 904impl acp_thread::AgentConnection for NativeAgentConnection {
 905    fn new_thread(
 906        self: Rc<Self>,
 907        project: Entity<Project>,
 908        cwd: &Path,
 909        cx: &mut App,
 910    ) -> Task<Result<Entity<acp_thread::AcpThread>>> {
 911        let agent = self.0.clone();
 912        log::debug!("Creating new thread for project at: {:?}", cwd);
 913
 914        cx.spawn(async move |cx| {
 915            log::debug!("Starting thread creation in async context");
 916
 917            // Create Thread
 918            let thread = agent.update(
 919                cx,
 920                |agent, cx: &mut gpui::Context<NativeAgent>| -> Result<_> {
 921                    // Fetch default model from registry settings
 922                    let registry = LanguageModelRegistry::read_global(cx);
 923                    // Log available models for debugging
 924                    let available_count = registry.available_models(cx).count();
 925                    log::debug!("Total available models: {}", available_count);
 926
 927                    let default_model = registry.default_model().and_then(|default_model| {
 928                        agent
 929                            .models
 930                            .model_from_id(&LanguageModels::model_id(&default_model.model))
 931                    });
 932                    Ok(cx.new(|cx| {
 933                        Thread::new(
 934                            project.clone(),
 935                            agent.project_context.clone(),
 936                            agent.context_server_registry.clone(),
 937                            agent.templates.clone(),
 938                            default_model,
 939                            cx,
 940                        )
 941                    }))
 942                },
 943            )??;
 944            agent.update(cx, |agent, cx| agent.register_session(thread, cx))
 945        })
 946    }
 947
 948    fn auth_methods(&self) -> &[acp::AuthMethod] {
 949        &[] // No auth for in-process
 950    }
 951
 952    fn authenticate(&self, _method: acp::AuthMethodId, _cx: &mut App) -> Task<Result<()>> {
 953        Task::ready(Ok(()))
 954    }
 955
 956    fn model_selector(&self) -> Option<Rc<dyn AgentModelSelector>> {
 957        Some(Rc::new(self.clone()) as Rc<dyn AgentModelSelector>)
 958    }
 959
 960    fn prompt(
 961        &self,
 962        id: Option<acp_thread::UserMessageId>,
 963        params: acp::PromptRequest,
 964        cx: &mut App,
 965    ) -> Task<Result<acp::PromptResponse>> {
 966        let id = id.expect("UserMessageId is required");
 967        let session_id = params.session_id.clone();
 968        log::info!("Received prompt request for session: {}", session_id);
 969        log::debug!("Prompt blocks count: {}", params.prompt.len());
 970
 971        self.run_turn(session_id, cx, |thread, cx| {
 972            let content: Vec<UserMessageContent> = params
 973                .prompt
 974                .into_iter()
 975                .map(Into::into)
 976                .collect::<Vec<_>>();
 977            log::debug!("Converted prompt to message: {} chars", content.len());
 978            log::debug!("Message id: {:?}", id);
 979            log::debug!("Message content: {:?}", content);
 980
 981            thread.update(cx, |thread, cx| thread.send(id, content, cx))
 982        })
 983    }
 984
 985    fn resume(
 986        &self,
 987        session_id: &acp::SessionId,
 988        _cx: &App,
 989    ) -> Option<Rc<dyn acp_thread::AgentSessionResume>> {
 990        Some(Rc::new(NativeAgentSessionResume {
 991            connection: self.clone(),
 992            session_id: session_id.clone(),
 993        }) as _)
 994    }
 995
 996    fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
 997        log::info!("Cancelling on session: {}", session_id);
 998        self.0.update(cx, |agent, cx| {
 999            if let Some(agent) = agent.sessions.get(session_id) {
1000                agent.thread.update(cx, |thread, cx| thread.cancel(cx));
1001            }
1002        });
1003    }
1004
1005    fn truncate(
1006        &self,
1007        session_id: &agent_client_protocol::SessionId,
1008        cx: &App,
1009    ) -> Option<Rc<dyn acp_thread::AgentSessionTruncate>> {
1010        self.0.read_with(cx, |agent, _cx| {
1011            agent.sessions.get(session_id).map(|session| {
1012                Rc::new(NativeAgentSessionTruncate {
1013                    thread: session.thread.clone(),
1014                    acp_thread: session.acp_thread.clone(),
1015                }) as _
1016            })
1017        })
1018    }
1019
1020    fn set_title(
1021        &self,
1022        session_id: &acp::SessionId,
1023        _cx: &App,
1024    ) -> Option<Rc<dyn acp_thread::AgentSessionSetTitle>> {
1025        Some(Rc::new(NativeAgentSessionSetTitle {
1026            connection: self.clone(),
1027            session_id: session_id.clone(),
1028        }) as _)
1029    }
1030
1031    fn telemetry(&self) -> Option<Rc<dyn acp_thread::AgentTelemetry>> {
1032        Some(Rc::new(self.clone()) as Rc<dyn acp_thread::AgentTelemetry>)
1033    }
1034
1035    fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
1036        self
1037    }
1038}
1039
1040impl acp_thread::AgentTelemetry for NativeAgentConnection {
1041    fn agent_name(&self) -> String {
1042        "Zed".into()
1043    }
1044
1045    fn thread_data(
1046        &self,
1047        session_id: &acp::SessionId,
1048        cx: &mut App,
1049    ) -> Task<Result<serde_json::Value>> {
1050        let Some(session) = self.0.read(cx).sessions.get(session_id) else {
1051            return Task::ready(Err(anyhow!("Session not found")));
1052        };
1053
1054        let task = session.thread.read(cx).to_db(cx);
1055        cx.background_spawn(async move {
1056            serde_json::to_value(task.await).context("Failed to serialize thread")
1057        })
1058    }
1059}
1060
1061struct NativeAgentSessionTruncate {
1062    thread: Entity<Thread>,
1063    acp_thread: WeakEntity<AcpThread>,
1064}
1065
1066impl acp_thread::AgentSessionTruncate for NativeAgentSessionTruncate {
1067    fn run(&self, message_id: acp_thread::UserMessageId, cx: &mut App) -> Task<Result<()>> {
1068        match self.thread.update(cx, |thread, cx| {
1069            thread.truncate(message_id.clone(), cx)?;
1070            Ok(thread.latest_token_usage())
1071        }) {
1072            Ok(usage) => {
1073                self.acp_thread
1074                    .update(cx, |thread, cx| {
1075                        thread.update_token_usage(usage, cx);
1076                    })
1077                    .ok();
1078                Task::ready(Ok(()))
1079            }
1080            Err(error) => Task::ready(Err(error)),
1081        }
1082    }
1083}
1084
1085struct NativeAgentSessionResume {
1086    connection: NativeAgentConnection,
1087    session_id: acp::SessionId,
1088}
1089
1090impl acp_thread::AgentSessionResume for NativeAgentSessionResume {
1091    fn run(&self, cx: &mut App) -> Task<Result<acp::PromptResponse>> {
1092        self.connection
1093            .run_turn(self.session_id.clone(), cx, |thread, cx| {
1094                thread.update(cx, |thread, cx| thread.resume(cx))
1095            })
1096    }
1097}
1098
1099struct NativeAgentSessionSetTitle {
1100    connection: NativeAgentConnection,
1101    session_id: acp::SessionId,
1102}
1103
1104impl acp_thread::AgentSessionSetTitle for NativeAgentSessionSetTitle {
1105    fn run(&self, title: SharedString, cx: &mut App) -> Task<Result<()>> {
1106        let Some(session) = self.connection.0.read(cx).sessions.get(&self.session_id) else {
1107            return Task::ready(Err(anyhow!("session not found")));
1108        };
1109        let thread = session.thread.clone();
1110        thread.update(cx, |thread, cx| thread.set_title(title, cx));
1111        Task::ready(Ok(()))
1112    }
1113}
1114
1115pub struct AcpThreadEnvironment {
1116    acp_thread: WeakEntity<AcpThread>,
1117}
1118
1119impl ThreadEnvironment for AcpThreadEnvironment {
1120    fn create_terminal(
1121        &self,
1122        command: String,
1123        cwd: Option<PathBuf>,
1124        output_byte_limit: Option<u64>,
1125        cx: &mut AsyncApp,
1126    ) -> Task<Result<Rc<dyn TerminalHandle>>> {
1127        let task = self.acp_thread.update(cx, |thread, cx| {
1128            thread.create_terminal(command, vec![], vec![], cwd, output_byte_limit, cx)
1129        });
1130
1131        let acp_thread = self.acp_thread.clone();
1132        cx.spawn(async move |cx| {
1133            let terminal = task?.await?;
1134
1135            let (drop_tx, drop_rx) = oneshot::channel();
1136            let terminal_id = terminal.read_with(cx, |terminal, _cx| terminal.id().clone())?;
1137
1138            cx.spawn(async move |cx| {
1139                drop_rx.await.ok();
1140                acp_thread.update(cx, |thread, cx| thread.release_terminal(terminal_id, cx))
1141            })
1142            .detach();
1143
1144            let handle = AcpTerminalHandle {
1145                terminal,
1146                _drop_tx: Some(drop_tx),
1147            };
1148
1149            Ok(Rc::new(handle) as _)
1150        })
1151    }
1152}
1153
1154pub struct AcpTerminalHandle {
1155    terminal: Entity<acp_thread::Terminal>,
1156    _drop_tx: Option<oneshot::Sender<()>>,
1157}
1158
1159impl TerminalHandle for AcpTerminalHandle {
1160    fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId> {
1161        self.terminal.read_with(cx, |term, _cx| term.id().clone())
1162    }
1163
1164    fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>> {
1165        self.terminal
1166            .read_with(cx, |term, _cx| term.wait_for_exit())
1167    }
1168
1169    fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse> {
1170        self.terminal
1171            .read_with(cx, |term, cx| term.current_output(cx))
1172    }
1173}
1174
1175#[cfg(test)]
1176mod tests {
1177    use crate::HistoryEntryId;
1178
1179    use super::*;
1180    use acp_thread::{
1181        AgentConnection, AgentModelGroupName, AgentModelId, AgentModelInfo, MentionUri,
1182    };
1183    use fs::FakeFs;
1184    use gpui::TestAppContext;
1185    use indoc::indoc;
1186    use language_model::fake_provider::FakeLanguageModel;
1187    use serde_json::json;
1188    use settings::SettingsStore;
1189    use util::path;
1190
1191    #[gpui::test]
1192    async fn test_maintaining_project_context(cx: &mut TestAppContext) {
1193        init_test(cx);
1194        let fs = FakeFs::new(cx.executor());
1195        fs.insert_tree(
1196            "/",
1197            json!({
1198                "a": {}
1199            }),
1200        )
1201        .await;
1202        let project = Project::test(fs.clone(), [], cx).await;
1203        let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1204        let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1205        let agent = NativeAgent::new(
1206            project.clone(),
1207            history_store,
1208            Templates::new(),
1209            None,
1210            fs.clone(),
1211            &mut cx.to_async(),
1212        )
1213        .await
1214        .unwrap();
1215        agent.read_with(cx, |agent, cx| {
1216            assert_eq!(agent.project_context.read(cx).worktrees, vec![])
1217        });
1218
1219        let worktree = project
1220            .update(cx, |project, cx| project.create_worktree("/a", true, cx))
1221            .await
1222            .unwrap();
1223        cx.run_until_parked();
1224        agent.read_with(cx, |agent, cx| {
1225            assert_eq!(
1226                agent.project_context.read(cx).worktrees,
1227                vec![WorktreeContext {
1228                    root_name: "a".into(),
1229                    abs_path: Path::new("/a").into(),
1230                    rules_file: None
1231                }]
1232            )
1233        });
1234
1235        // Creating `/a/.rules` updates the project context.
1236        fs.insert_file("/a/.rules", Vec::new()).await;
1237        cx.run_until_parked();
1238        agent.read_with(cx, |agent, cx| {
1239            let rules_entry = worktree.read(cx).entry_for_path(".rules").unwrap();
1240            assert_eq!(
1241                agent.project_context.read(cx).worktrees,
1242                vec![WorktreeContext {
1243                    root_name: "a".into(),
1244                    abs_path: Path::new("/a").into(),
1245                    rules_file: Some(RulesFileContext {
1246                        path_in_worktree: Path::new(".rules").into(),
1247                        text: "".into(),
1248                        project_entry_id: rules_entry.id.to_usize()
1249                    })
1250                }]
1251            )
1252        });
1253    }
1254
1255    #[gpui::test]
1256    async fn test_listing_models(cx: &mut TestAppContext) {
1257        init_test(cx);
1258        let fs = FakeFs::new(cx.executor());
1259        fs.insert_tree("/", json!({ "a": {}  })).await;
1260        let project = Project::test(fs.clone(), [], cx).await;
1261        let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1262        let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1263        let connection = NativeAgentConnection(
1264            NativeAgent::new(
1265                project.clone(),
1266                history_store,
1267                Templates::new(),
1268                None,
1269                fs.clone(),
1270                &mut cx.to_async(),
1271            )
1272            .await
1273            .unwrap(),
1274        );
1275
1276        let models = cx.update(|cx| connection.list_models(cx)).await.unwrap();
1277
1278        let acp_thread::AgentModelList::Grouped(models) = models else {
1279            panic!("Unexpected model group");
1280        };
1281        assert_eq!(
1282            models,
1283            IndexMap::from_iter([(
1284                AgentModelGroupName("Fake".into()),
1285                vec![AgentModelInfo {
1286                    id: AgentModelId("fake/fake".into()),
1287                    name: "Fake".into(),
1288                    icon: Some(ui::IconName::ZedAssistant),
1289                }]
1290            )])
1291        );
1292    }
1293
1294    #[gpui::test]
1295    async fn test_model_selection_persists_to_settings(cx: &mut TestAppContext) {
1296        init_test(cx);
1297        let fs = FakeFs::new(cx.executor());
1298        fs.create_dir(paths::settings_file().parent().unwrap())
1299            .await
1300            .unwrap();
1301        fs.insert_file(
1302            paths::settings_file(),
1303            json!({
1304                "agent": {
1305                    "default_model": {
1306                        "provider": "foo",
1307                        "model": "bar"
1308                    }
1309                }
1310            })
1311            .to_string()
1312            .into_bytes(),
1313        )
1314        .await;
1315        let project = Project::test(fs.clone(), [], cx).await;
1316
1317        let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1318        let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1319
1320        // Create the agent and connection
1321        let agent = NativeAgent::new(
1322            project.clone(),
1323            history_store,
1324            Templates::new(),
1325            None,
1326            fs.clone(),
1327            &mut cx.to_async(),
1328        )
1329        .await
1330        .unwrap();
1331        let connection = NativeAgentConnection(agent.clone());
1332
1333        // Create a thread/session
1334        let acp_thread = cx
1335            .update(|cx| {
1336                Rc::new(connection.clone()).new_thread(project.clone(), Path::new("/a"), cx)
1337            })
1338            .await
1339            .unwrap();
1340
1341        let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());
1342
1343        // Select a model
1344        let model_id = AgentModelId("fake/fake".into());
1345        cx.update(|cx| connection.select_model(session_id.clone(), model_id.clone(), cx))
1346            .await
1347            .unwrap();
1348
1349        // Verify the thread has the selected model
1350        agent.read_with(cx, |agent, _| {
1351            let session = agent.sessions.get(&session_id).unwrap();
1352            session.thread.read_with(cx, |thread, _| {
1353                assert_eq!(thread.model().unwrap().id().0, "fake");
1354            });
1355        });
1356
1357        cx.run_until_parked();
1358
1359        // Verify settings file was updated
1360        let settings_content = fs.load(paths::settings_file()).await.unwrap();
1361        let settings_json: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1362
1363        // Check that the agent settings contain the selected model
1364        assert_eq!(
1365            settings_json["agent"]["default_model"]["model"],
1366            json!("fake")
1367        );
1368        assert_eq!(
1369            settings_json["agent"]["default_model"]["provider"],
1370            json!("fake")
1371        );
1372    }
1373
1374    #[gpui::test]
1375    #[cfg_attr(target_os = "windows", ignore)] // TODO: Fix this test on Windows
1376    async fn test_save_load_thread(cx: &mut TestAppContext) {
1377        init_test(cx);
1378        let fs = FakeFs::new(cx.executor());
1379        fs.insert_tree(
1380            "/",
1381            json!({
1382                "a": {
1383                    "b.md": "Lorem"
1384                }
1385            }),
1386        )
1387        .await;
1388        let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
1389        let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1390        let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1391        let agent = NativeAgent::new(
1392            project.clone(),
1393            history_store.clone(),
1394            Templates::new(),
1395            None,
1396            fs.clone(),
1397            &mut cx.to_async(),
1398        )
1399        .await
1400        .unwrap();
1401        let connection = Rc::new(NativeAgentConnection(agent.clone()));
1402
1403        let acp_thread = cx
1404            .update(|cx| {
1405                connection
1406                    .clone()
1407                    .new_thread(project.clone(), Path::new(""), cx)
1408            })
1409            .await
1410            .unwrap();
1411        let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
1412        let thread = agent.read_with(cx, |agent, _| {
1413            agent.sessions.get(&session_id).unwrap().thread.clone()
1414        });
1415
1416        // Ensure empty threads are not saved, even if they get mutated.
1417        let model = Arc::new(FakeLanguageModel::default());
1418        let summary_model = Arc::new(FakeLanguageModel::default());
1419        thread.update(cx, |thread, cx| {
1420            thread.set_model(model.clone(), cx);
1421            thread.set_summarization_model(Some(summary_model.clone()), cx);
1422        });
1423        cx.run_until_parked();
1424        assert_eq!(history_entries(&history_store, cx), vec![]);
1425
1426        let send = acp_thread.update(cx, |thread, cx| {
1427            thread.send(
1428                vec![
1429                    "What does ".into(),
1430                    acp::ContentBlock::ResourceLink(acp::ResourceLink {
1431                        name: "b.md".into(),
1432                        uri: MentionUri::File {
1433                            abs_path: path!("/a/b.md").into(),
1434                        }
1435                        .to_uri()
1436                        .to_string(),
1437                        annotations: None,
1438                        description: None,
1439                        mime_type: None,
1440                        size: None,
1441                        title: None,
1442                    }),
1443                    " mean?".into(),
1444                ],
1445                cx,
1446            )
1447        });
1448        let send = cx.foreground_executor().spawn(send);
1449        cx.run_until_parked();
1450
1451        model.send_last_completion_stream_text_chunk("Lorem.");
1452        model.end_last_completion_stream();
1453        cx.run_until_parked();
1454        summary_model.send_last_completion_stream_text_chunk("Explaining /a/b.md");
1455        summary_model.end_last_completion_stream();
1456
1457        send.await.unwrap();
1458        acp_thread.read_with(cx, |thread, cx| {
1459            assert_eq!(
1460                thread.to_markdown(cx),
1461                indoc! {"
1462                    ## User
1463
1464                    What does [@b.md](file:///a/b.md) mean?
1465
1466                    ## Assistant
1467
1468                    Lorem.
1469
1470                "}
1471            )
1472        });
1473
1474        cx.run_until_parked();
1475
1476        // Drop the ACP thread, which should cause the session to be dropped as well.
1477        cx.update(|_| {
1478            drop(thread);
1479            drop(acp_thread);
1480        });
1481        agent.read_with(cx, |agent, _| {
1482            assert_eq!(agent.sessions.keys().cloned().collect::<Vec<_>>(), []);
1483        });
1484
1485        // Ensure the thread can be reloaded from disk.
1486        assert_eq!(
1487            history_entries(&history_store, cx),
1488            vec![(
1489                HistoryEntryId::AcpThread(session_id.clone()),
1490                "Explaining /a/b.md".into()
1491            )]
1492        );
1493        let acp_thread = agent
1494            .update(cx, |agent, cx| agent.open_thread(session_id.clone(), cx))
1495            .await
1496            .unwrap();
1497        acp_thread.read_with(cx, |thread, cx| {
1498            assert_eq!(
1499                thread.to_markdown(cx),
1500                indoc! {"
1501                    ## User
1502
1503                    What does [@b.md](file:///a/b.md) mean?
1504
1505                    ## Assistant
1506
1507                    Lorem.
1508
1509                "}
1510            )
1511        });
1512    }
1513
1514    fn history_entries(
1515        history: &Entity<HistoryStore>,
1516        cx: &mut TestAppContext,
1517    ) -> Vec<(HistoryEntryId, String)> {
1518        history.read_with(cx, |history, _| {
1519            history
1520                .entries()
1521                .map(|e| (e.id(), e.title().to_string()))
1522                .collect::<Vec<_>>()
1523        })
1524    }
1525
1526    fn init_test(cx: &mut TestAppContext) {
1527        env_logger::try_init().ok();
1528        cx.update(|cx| {
1529            let settings_store = SettingsStore::test(cx);
1530            cx.set_global(settings_store);
1531            Project::init_settings(cx);
1532            agent_settings::init(cx);
1533            language::init(cx);
1534            LanguageModelRegistry::test(cx);
1535        });
1536    }
1537}