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