1use crate::{
2 ContextServerRegistry, Thread, ThreadEvent, ToolCallAuthorization, UserMessageContent,
3 templates::Templates,
4};
5use crate::{HistoryStore, ThreadsDatabase};
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;
14use futures::{StreamExt, future};
15use gpui::{
16 App, AppContext, AsyncApp, Context, Entity, SharedString, Subscription, Task, WeakEntity,
17};
18use language_model::{LanguageModel, LanguageModelProvider, LanguageModelRegistry};
19use project::{Project, ProjectItem, ProjectPath, Worktree};
20use prompt_store::{
21 ProjectContext, PromptId, PromptStore, RulesFileContext, UserRulesContext, WorktreeContext,
22};
23use settings::update_settings_file;
24use std::any::Any;
25use std::collections::HashMap;
26use std::path::Path;
27use std::rc::Rc;
28use std::sync::Arc;
29use util::ResultExt;
30
31const RULES_FILE_NAMES: [&'static str; 9] = [
32 ".rules",
33 ".cursorrules",
34 ".windsurfrules",
35 ".clinerules",
36 ".github/copilot-instructions.md",
37 "CLAUDE.md",
38 "AGENT.md",
39 "AGENTS.md",
40 "GEMINI.md",
41];
42
43pub struct RulesLoadingError {
44 pub message: SharedString,
45}
46
47/// Holds both the internal Thread and the AcpThread for a session
48struct Session {
49 /// The internal thread that processes messages
50 thread: Entity<Thread>,
51 /// The ACP thread that handles protocol communication
52 acp_thread: WeakEntity<acp_thread::AcpThread>,
53 pending_save: Task<()>,
54 _subscriptions: Vec<Subscription>,
55}
56
57pub struct LanguageModels {
58 /// Access language model by ID
59 models: HashMap<acp_thread::AgentModelId, Arc<dyn LanguageModel>>,
60 /// Cached list for returning language model information
61 model_list: acp_thread::AgentModelList,
62 refresh_models_rx: watch::Receiver<()>,
63 refresh_models_tx: watch::Sender<()>,
64}
65
66impl LanguageModels {
67 fn new(cx: &App) -> Self {
68 let (refresh_models_tx, refresh_models_rx) = watch::channel(());
69 let mut this = Self {
70 models: HashMap::default(),
71 model_list: acp_thread::AgentModelList::Grouped(IndexMap::default()),
72 refresh_models_rx,
73 refresh_models_tx,
74 };
75 this.refresh_list(cx);
76 this
77 }
78
79 fn refresh_list(&mut self, cx: &App) {
80 let providers = LanguageModelRegistry::global(cx)
81 .read(cx)
82 .providers()
83 .into_iter()
84 .filter(|provider| provider.is_authenticated(cx))
85 .collect::<Vec<_>>();
86
87 let mut language_model_list = IndexMap::default();
88 let mut recommended_models = HashSet::default();
89
90 let mut recommended = Vec::new();
91 for provider in &providers {
92 for model in provider.recommended_models(cx) {
93 recommended_models.insert(model.id());
94 recommended.push(Self::map_language_model_to_info(&model, provider));
95 }
96 }
97 if !recommended.is_empty() {
98 language_model_list.insert(
99 acp_thread::AgentModelGroupName("Recommended".into()),
100 recommended,
101 );
102 }
103
104 let mut models = HashMap::default();
105 for provider in providers {
106 let mut provider_models = Vec::new();
107 for model in provider.provided_models(cx) {
108 let model_info = Self::map_language_model_to_info(&model, &provider);
109 let model_id = model_info.id.clone();
110 if !recommended_models.contains(&model.id()) {
111 provider_models.push(model_info);
112 }
113 models.insert(model_id, model);
114 }
115 if !provider_models.is_empty() {
116 language_model_list.insert(
117 acp_thread::AgentModelGroupName(provider.name().0.clone()),
118 provider_models,
119 );
120 }
121 }
122
123 self.models = models;
124 self.model_list = acp_thread::AgentModelList::Grouped(language_model_list);
125 self.refresh_models_tx.send(()).ok();
126 }
127
128 fn watch(&self) -> watch::Receiver<()> {
129 self.refresh_models_rx.clone()
130 }
131
132 pub fn model_from_id(
133 &self,
134 model_id: &acp_thread::AgentModelId,
135 ) -> Option<Arc<dyn LanguageModel>> {
136 self.models.get(model_id).cloned()
137 }
138
139 fn map_language_model_to_info(
140 model: &Arc<dyn LanguageModel>,
141 provider: &Arc<dyn LanguageModelProvider>,
142 ) -> acp_thread::AgentModelInfo {
143 acp_thread::AgentModelInfo {
144 id: Self::model_id(model),
145 name: model.name().0,
146 icon: Some(provider.icon()),
147 }
148 }
149
150 fn model_id(model: &Arc<dyn LanguageModel>) -> acp_thread::AgentModelId {
151 acp_thread::AgentModelId(format!("{}/{}", model.provider_id().0, model.id().0).into())
152 }
153}
154
155pub struct NativeAgent {
156 /// Session ID -> Session mapping
157 sessions: HashMap<acp::SessionId, Session>,
158 history: Entity<HistoryStore>,
159 /// Shared project context for all threads
160 project_context: Entity<ProjectContext>,
161 project_context_needs_refresh: watch::Sender<()>,
162 _maintain_project_context: Task<Result<()>>,
163 context_server_registry: Entity<ContextServerRegistry>,
164 /// Shared templates for all threads
165 templates: Arc<Templates>,
166 /// Cached model information
167 models: LanguageModels,
168 project: Entity<Project>,
169 prompt_store: Option<Entity<PromptStore>>,
170 fs: Arc<dyn Fs>,
171 _subscriptions: Vec<Subscription>,
172}
173
174impl NativeAgent {
175 pub async fn new(
176 project: Entity<Project>,
177 history: Entity<HistoryStore>,
178 templates: Arc<Templates>,
179 prompt_store: Option<Entity<PromptStore>>,
180 fs: Arc<dyn Fs>,
181 cx: &mut AsyncApp,
182 ) -> Result<Entity<NativeAgent>> {
183 log::info!("Creating new NativeAgent");
184
185 let project_context = cx
186 .update(|cx| Self::build_project_context(&project, prompt_store.as_ref(), cx))?
187 .await;
188
189 cx.new(|cx| {
190 let mut subscriptions = vec![
191 cx.subscribe(&project, Self::handle_project_event),
192 cx.subscribe(
193 &LanguageModelRegistry::global(cx),
194 Self::handle_models_updated_event,
195 ),
196 ];
197 if let Some(prompt_store) = prompt_store.as_ref() {
198 subscriptions.push(cx.subscribe(prompt_store, Self::handle_prompts_updated_event))
199 }
200
201 let (project_context_needs_refresh_tx, project_context_needs_refresh_rx) =
202 watch::channel(());
203 Self {
204 sessions: HashMap::new(),
205 history,
206 project_context: cx.new(|_| project_context),
207 project_context_needs_refresh: project_context_needs_refresh_tx,
208 _maintain_project_context: cx.spawn(async move |this, cx| {
209 Self::maintain_project_context(this, project_context_needs_refresh_rx, cx).await
210 }),
211 context_server_registry: cx.new(|cx| {
212 ContextServerRegistry::new(project.read(cx).context_server_store(), cx)
213 }),
214 templates,
215 models: LanguageModels::new(cx),
216 project,
217 prompt_store,
218 fs,
219 _subscriptions: subscriptions,
220 }
221 })
222 }
223
224 fn register_session(
225 &mut self,
226 thread_handle: Entity<Thread>,
227 cx: &mut Context<Self>,
228 ) -> Entity<AcpThread> {
229 let connection = Rc::new(NativeAgentConnection(cx.entity()));
230 let registry = LanguageModelRegistry::read_global(cx);
231 let summarization_model = registry.thread_summary_model().map(|c| c.model);
232
233 thread_handle.update(cx, |thread, cx| {
234 thread.set_summarization_model(summarization_model, cx);
235 thread.add_default_tools(cx)
236 });
237
238 let thread = thread_handle.read(cx);
239 let session_id = thread.id().clone();
240 let title = thread.title();
241 let project = thread.project.clone();
242 let action_log = thread.action_log.clone();
243 let acp_thread = cx.new(|_cx| {
244 acp_thread::AcpThread::new(
245 title,
246 connection,
247 project.clone(),
248 action_log.clone(),
249 session_id.clone(),
250 )
251 });
252 let subscriptions = vec![
253 cx.observe_release(&acp_thread, |this, acp_thread, _cx| {
254 this.sessions.remove(acp_thread.session_id());
255 }),
256 cx.observe(&thread_handle, move |this, thread, cx| {
257 this.save_thread(thread.clone(), cx)
258 }),
259 ];
260
261 self.sessions.insert(
262 session_id,
263 Session {
264 thread: thread_handle,
265 acp_thread: acp_thread.downgrade(),
266 _subscriptions: subscriptions,
267 pending_save: Task::ready(()),
268 },
269 );
270 acp_thread
271 }
272
273 pub fn models(&self) -> &LanguageModels {
274 &self.models
275 }
276
277 async fn maintain_project_context(
278 this: WeakEntity<Self>,
279 mut needs_refresh: watch::Receiver<()>,
280 cx: &mut AsyncApp,
281 ) -> Result<()> {
282 while needs_refresh.changed().await.is_ok() {
283 let project_context = this
284 .update(cx, |this, cx| {
285 Self::build_project_context(&this.project, this.prompt_store.as_ref(), cx)
286 })?
287 .await;
288 this.update(cx, |this, cx| {
289 this.project_context = cx.new(|_| project_context);
290 })?;
291 }
292
293 Ok(())
294 }
295
296 fn build_project_context(
297 project: &Entity<Project>,
298 prompt_store: Option<&Entity<PromptStore>>,
299 cx: &mut App,
300 ) -> Task<ProjectContext> {
301 let worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
302 let worktree_tasks = worktrees
303 .into_iter()
304 .map(|worktree| {
305 Self::load_worktree_info_for_system_prompt(worktree, project.clone(), cx)
306 })
307 .collect::<Vec<_>>();
308 let default_user_rules_task = if let Some(prompt_store) = prompt_store.as_ref() {
309 prompt_store.read_with(cx, |prompt_store, cx| {
310 let prompts = prompt_store.default_prompt_metadata();
311 let load_tasks = prompts.into_iter().map(|prompt_metadata| {
312 let contents = prompt_store.load(prompt_metadata.id, cx);
313 async move { (contents.await, prompt_metadata) }
314 });
315 cx.background_spawn(future::join_all(load_tasks))
316 })
317 } else {
318 Task::ready(vec![])
319 };
320
321 cx.spawn(async move |_cx| {
322 let (worktrees, default_user_rules) =
323 future::join(future::join_all(worktree_tasks), default_user_rules_task).await;
324
325 let worktrees = worktrees
326 .into_iter()
327 .map(|(worktree, _rules_error)| {
328 // TODO: show error message
329 // if let Some(rules_error) = rules_error {
330 // this.update(cx, |_, cx| cx.emit(rules_error)).ok();
331 // }
332 worktree
333 })
334 .collect::<Vec<_>>();
335
336 let default_user_rules = default_user_rules
337 .into_iter()
338 .flat_map(|(contents, prompt_metadata)| match contents {
339 Ok(contents) => Some(UserRulesContext {
340 uuid: match prompt_metadata.id {
341 PromptId::User { uuid } => uuid,
342 PromptId::EditWorkflow => return None,
343 },
344 title: prompt_metadata.title.map(|title| title.to_string()),
345 contents,
346 }),
347 Err(_err) => {
348 // TODO: show error message
349 // this.update(cx, |_, cx| {
350 // cx.emit(RulesLoadingError {
351 // message: format!("{err:?}").into(),
352 // });
353 // })
354 // .ok();
355 None
356 }
357 })
358 .collect::<Vec<_>>();
359
360 ProjectContext::new(worktrees, default_user_rules)
361 })
362 }
363
364 fn load_worktree_info_for_system_prompt(
365 worktree: Entity<Worktree>,
366 project: Entity<Project>,
367 cx: &mut App,
368 ) -> Task<(WorktreeContext, Option<RulesLoadingError>)> {
369 let tree = worktree.read(cx);
370 let root_name = tree.root_name().into();
371 let abs_path = tree.abs_path();
372
373 let mut context = WorktreeContext {
374 root_name,
375 abs_path,
376 rules_file: None,
377 };
378
379 let rules_task = Self::load_worktree_rules_file(worktree, project, cx);
380 let Some(rules_task) = rules_task else {
381 return Task::ready((context, None));
382 };
383
384 cx.spawn(async move |_| {
385 let (rules_file, rules_file_error) = match rules_task.await {
386 Ok(rules_file) => (Some(rules_file), None),
387 Err(err) => (
388 None,
389 Some(RulesLoadingError {
390 message: format!("{err}").into(),
391 }),
392 ),
393 };
394 context.rules_file = rules_file;
395 (context, rules_file_error)
396 })
397 }
398
399 fn load_worktree_rules_file(
400 worktree: Entity<Worktree>,
401 project: Entity<Project>,
402 cx: &mut App,
403 ) -> Option<Task<Result<RulesFileContext>>> {
404 let worktree = worktree.read(cx);
405 let worktree_id = worktree.id();
406 let selected_rules_file = RULES_FILE_NAMES
407 .into_iter()
408 .filter_map(|name| {
409 worktree
410 .entry_for_path(name)
411 .filter(|entry| entry.is_file())
412 .map(|entry| entry.path.clone())
413 })
414 .next();
415
416 // Note that Cline supports `.clinerules` being a directory, but that is not currently
417 // supported. This doesn't seem to occur often in GitHub repositories.
418 selected_rules_file.map(|path_in_worktree| {
419 let project_path = ProjectPath {
420 worktree_id,
421 path: path_in_worktree.clone(),
422 };
423 let buffer_task =
424 project.update(cx, |project, cx| project.open_buffer(project_path, cx));
425 let rope_task = cx.spawn(async move |cx| {
426 buffer_task.await?.read_with(cx, |buffer, cx| {
427 let project_entry_id = buffer.entry_id(cx).context("buffer has no file")?;
428 anyhow::Ok((project_entry_id, buffer.as_rope().clone()))
429 })?
430 });
431 // Build a string from the rope on a background thread.
432 cx.background_spawn(async move {
433 let (project_entry_id, rope) = rope_task.await?;
434 anyhow::Ok(RulesFileContext {
435 path_in_worktree,
436 text: rope.to_string().trim().to_string(),
437 project_entry_id: project_entry_id.to_usize(),
438 })
439 })
440 })
441 }
442
443 fn handle_project_event(
444 &mut self,
445 _project: Entity<Project>,
446 event: &project::Event,
447 _cx: &mut Context<Self>,
448 ) {
449 match event {
450 project::Event::WorktreeAdded(_) | project::Event::WorktreeRemoved(_) => {
451 self.project_context_needs_refresh.send(()).ok();
452 }
453 project::Event::WorktreeUpdatedEntries(_, items) => {
454 if items.iter().any(|(path, _, _)| {
455 RULES_FILE_NAMES
456 .iter()
457 .any(|name| path.as_ref() == Path::new(name))
458 }) {
459 self.project_context_needs_refresh.send(()).ok();
460 }
461 }
462 _ => {}
463 }
464 }
465
466 fn handle_prompts_updated_event(
467 &mut self,
468 _prompt_store: Entity<PromptStore>,
469 _event: &prompt_store::PromptsUpdatedEvent,
470 _cx: &mut Context<Self>,
471 ) {
472 self.project_context_needs_refresh.send(()).ok();
473 }
474
475 fn handle_models_updated_event(
476 &mut self,
477 _registry: Entity<LanguageModelRegistry>,
478 _event: &language_model::Event,
479 cx: &mut Context<Self>,
480 ) {
481 self.models.refresh_list(cx);
482
483 let registry = LanguageModelRegistry::read_global(cx);
484 let default_model = registry.default_model().map(|m| m.model.clone());
485 let summarization_model = registry.thread_summary_model().map(|m| m.model.clone());
486
487 for session in self.sessions.values_mut() {
488 session.thread.update(cx, |thread, cx| {
489 if thread.model().is_none()
490 && let Some(model) = default_model.clone()
491 {
492 thread.set_model(model, cx);
493 cx.notify();
494 }
495 thread.set_summarization_model(summarization_model.clone(), cx);
496 });
497 }
498 }
499
500 pub fn open_thread(
501 &mut self,
502 id: acp::SessionId,
503 cx: &mut Context<Self>,
504 ) -> Task<Result<Entity<AcpThread>>> {
505 let database_future = ThreadsDatabase::connect(cx);
506 cx.spawn(async move |this, cx| {
507 let database = database_future.await.map_err(|err| anyhow!(err))?;
508 let db_thread = database
509 .load_thread(id.clone())
510 .await?
511 .with_context(|| format!("no thread found with ID: {id:?}"))?;
512
513 let thread = this.update(cx, |this, cx| {
514 let action_log = cx.new(|_cx| ActionLog::new(this.project.clone()));
515 cx.new(|cx| {
516 Thread::from_db(
517 id.clone(),
518 db_thread,
519 this.project.clone(),
520 this.project_context.clone(),
521 this.context_server_registry.clone(),
522 action_log.clone(),
523 this.templates.clone(),
524 cx,
525 )
526 })
527 })?;
528 let acp_thread =
529 this.update(cx, |this, cx| this.register_session(thread.clone(), cx))?;
530 let events = thread.update(cx, |thread, cx| thread.replay(cx))?;
531 cx.update(|cx| {
532 NativeAgentConnection::handle_thread_events(events, acp_thread.downgrade(), cx)
533 })?
534 .await?;
535 Ok(acp_thread)
536 })
537 }
538
539 fn save_thread(&mut self, thread: Entity<Thread>, cx: &mut Context<Self>) {
540 let database_future = ThreadsDatabase::connect(cx);
541 let (id, db_thread) =
542 thread.update(cx, |thread, cx| (thread.id().clone(), thread.to_db(cx)));
543 let Some(session) = self.sessions.get_mut(&id) else {
544 return;
545 };
546 let history = self.history.clone();
547 session.pending_save = cx.spawn(async move |_, cx| {
548 let Some(database) = database_future.await.map_err(|err| anyhow!(err)).log_err() else {
549 return;
550 };
551 let db_thread = db_thread.await;
552 database.save_thread(id, db_thread).await.log_err();
553 history.update(cx, |history, cx| history.reload(cx)).ok();
554 });
555 }
556}
557
558/// Wrapper struct that implements the AgentConnection trait
559#[derive(Clone)]
560pub struct NativeAgentConnection(pub Entity<NativeAgent>);
561
562impl NativeAgentConnection {
563 pub fn thread(&self, session_id: &acp::SessionId, cx: &App) -> Option<Entity<Thread>> {
564 self.0
565 .read(cx)
566 .sessions
567 .get(session_id)
568 .map(|session| session.thread.clone())
569 }
570
571 fn run_turn(
572 &self,
573 session_id: acp::SessionId,
574 cx: &mut App,
575 f: impl 'static
576 + FnOnce(Entity<Thread>, &mut App) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>,
577 ) -> Task<Result<acp::PromptResponse>> {
578 let Some((thread, acp_thread)) = self.0.update(cx, |agent, _cx| {
579 agent
580 .sessions
581 .get_mut(&session_id)
582 .map(|s| (s.thread.clone(), s.acp_thread.clone()))
583 }) else {
584 return Task::ready(Err(anyhow!("Session not found")));
585 };
586 log::debug!("Found session for: {}", session_id);
587
588 let response_stream = match f(thread, cx) {
589 Ok(stream) => stream,
590 Err(err) => return Task::ready(Err(err)),
591 };
592 Self::handle_thread_events(response_stream, acp_thread, cx)
593 }
594
595 fn handle_thread_events(
596 mut events: mpsc::UnboundedReceiver<Result<ThreadEvent>>,
597 acp_thread: WeakEntity<AcpThread>,
598 cx: &App,
599 ) -> Task<Result<acp::PromptResponse>> {
600 cx.spawn(async move |cx| {
601 // Handle response stream and forward to session.acp_thread
602 while let Some(result) = events.next().await {
603 match result {
604 Ok(event) => {
605 log::trace!("Received completion event: {:?}", event);
606
607 match event {
608 ThreadEvent::UserMessage(message) => {
609 acp_thread.update(cx, |thread, cx| {
610 for content in message.content {
611 thread.push_user_content_block(
612 Some(message.id.clone()),
613 content.into(),
614 cx,
615 );
616 }
617 })?;
618 }
619 ThreadEvent::AgentText(text) => {
620 acp_thread.update(cx, |thread, cx| {
621 thread.push_assistant_content_block(
622 acp::ContentBlock::Text(acp::TextContent {
623 text,
624 annotations: None,
625 }),
626 false,
627 cx,
628 )
629 })?;
630 }
631 ThreadEvent::AgentThinking(text) => {
632 acp_thread.update(cx, |thread, cx| {
633 thread.push_assistant_content_block(
634 acp::ContentBlock::Text(acp::TextContent {
635 text,
636 annotations: None,
637 }),
638 true,
639 cx,
640 )
641 })?;
642 }
643 ThreadEvent::ToolCallAuthorization(ToolCallAuthorization {
644 tool_call,
645 options,
646 response,
647 }) => {
648 let recv = acp_thread.update(cx, |thread, cx| {
649 thread.request_tool_call_authorization(tool_call, options, cx)
650 })?;
651 cx.background_spawn(async move {
652 if let Some(recv) = recv.log_err()
653 && let Some(option) = recv
654 .await
655 .context("authorization sender was dropped")
656 .log_err()
657 {
658 response
659 .send(option)
660 .map(|_| anyhow!("authorization receiver was dropped"))
661 .log_err();
662 }
663 })
664 .detach();
665 }
666 ThreadEvent::ToolCall(tool_call) => {
667 acp_thread.update(cx, |thread, cx| {
668 thread.upsert_tool_call(tool_call, cx)
669 })??;
670 }
671 ThreadEvent::ToolCallUpdate(update) => {
672 acp_thread.update(cx, |thread, cx| {
673 thread.update_tool_call(update, cx)
674 })??;
675 }
676 ThreadEvent::TitleUpdate(title) => {
677 acp_thread
678 .update(cx, |thread, cx| thread.update_title(title, cx))??;
679 }
680 ThreadEvent::Retry(status) => {
681 acp_thread.update(cx, |thread, cx| {
682 thread.update_retry_status(status, cx)
683 })?;
684 }
685 ThreadEvent::Stop(stop_reason) => {
686 log::debug!("Assistant message complete: {:?}", stop_reason);
687 return Ok(acp::PromptResponse { stop_reason });
688 }
689 }
690 }
691 Err(e) => {
692 log::error!("Error in model response stream: {:?}", e);
693 return Err(e);
694 }
695 }
696 }
697
698 log::info!("Response stream completed");
699 anyhow::Ok(acp::PromptResponse {
700 stop_reason: acp::StopReason::EndTurn,
701 })
702 })
703 }
704}
705
706impl AgentModelSelector for NativeAgentConnection {
707 fn list_models(&self, cx: &mut App) -> Task<Result<acp_thread::AgentModelList>> {
708 log::debug!("NativeAgentConnection::list_models called");
709 let list = self.0.read(cx).models.model_list.clone();
710 Task::ready(if list.is_empty() {
711 Err(anyhow::anyhow!("No models available"))
712 } else {
713 Ok(list)
714 })
715 }
716
717 fn select_model(
718 &self,
719 session_id: acp::SessionId,
720 model_id: acp_thread::AgentModelId,
721 cx: &mut App,
722 ) -> Task<Result<()>> {
723 log::info!("Setting model for session {}: {}", session_id, model_id);
724 let Some(thread) = self
725 .0
726 .read(cx)
727 .sessions
728 .get(&session_id)
729 .map(|session| session.thread.clone())
730 else {
731 return Task::ready(Err(anyhow!("Session not found")));
732 };
733
734 let Some(model) = self.0.read(cx).models.model_from_id(&model_id) else {
735 return Task::ready(Err(anyhow!("Invalid model ID {}", model_id)));
736 };
737
738 thread.update(cx, |thread, cx| {
739 thread.set_model(model.clone(), cx);
740 });
741
742 update_settings_file::<AgentSettings>(
743 self.0.read(cx).fs.clone(),
744 cx,
745 move |settings, _cx| {
746 settings.set_model(model);
747 },
748 );
749
750 Task::ready(Ok(()))
751 }
752
753 fn selected_model(
754 &self,
755 session_id: &acp::SessionId,
756 cx: &mut App,
757 ) -> Task<Result<acp_thread::AgentModelInfo>> {
758 let session_id = session_id.clone();
759
760 let Some(thread) = self
761 .0
762 .read(cx)
763 .sessions
764 .get(&session_id)
765 .map(|session| session.thread.clone())
766 else {
767 return Task::ready(Err(anyhow!("Session not found")));
768 };
769 let Some(model) = thread.read(cx).model() else {
770 return Task::ready(Err(anyhow!("Model not found")));
771 };
772 let Some(provider) = LanguageModelRegistry::read_global(cx).provider(&model.provider_id())
773 else {
774 return Task::ready(Err(anyhow!("Provider not found")));
775 };
776 Task::ready(Ok(LanguageModels::map_language_model_to_info(
777 model, &provider,
778 )))
779 }
780
781 fn watch(&self, cx: &mut App) -> watch::Receiver<()> {
782 self.0.read(cx).models.watch()
783 }
784}
785
786impl acp_thread::AgentConnection for NativeAgentConnection {
787 fn new_thread(
788 self: Rc<Self>,
789 project: Entity<Project>,
790 cwd: &Path,
791 cx: &mut App,
792 ) -> Task<Result<Entity<acp_thread::AcpThread>>> {
793 let agent = self.0.clone();
794 log::info!("Creating new thread for project at: {:?}", cwd);
795
796 cx.spawn(async move |cx| {
797 log::debug!("Starting thread creation in async context");
798
799 let action_log = cx.new(|_cx| ActionLog::new(project.clone()))?;
800 // Create Thread
801 let thread = agent.update(
802 cx,
803 |agent, cx: &mut gpui::Context<NativeAgent>| -> Result<_> {
804 // Fetch default model from registry settings
805 let registry = LanguageModelRegistry::read_global(cx);
806 // Log available models for debugging
807 let available_count = registry.available_models(cx).count();
808 log::debug!("Total available models: {}", available_count);
809
810 let default_model = registry.default_model().and_then(|default_model| {
811 agent
812 .models
813 .model_from_id(&LanguageModels::model_id(&default_model.model))
814 });
815
816 let thread = cx.new(|cx| {
817 Thread::new(
818 project.clone(),
819 agent.project_context.clone(),
820 agent.context_server_registry.clone(),
821 action_log.clone(),
822 agent.templates.clone(),
823 default_model,
824 cx,
825 )
826 });
827
828 Ok(thread)
829 },
830 )??;
831 agent.update(cx, |agent, cx| agent.register_session(thread, cx))
832 })
833 }
834
835 fn auth_methods(&self) -> &[acp::AuthMethod] {
836 &[] // No auth for in-process
837 }
838
839 fn authenticate(&self, _method: acp::AuthMethodId, _cx: &mut App) -> Task<Result<()>> {
840 Task::ready(Ok(()))
841 }
842
843 fn model_selector(&self) -> Option<Rc<dyn AgentModelSelector>> {
844 Some(Rc::new(self.clone()) as Rc<dyn AgentModelSelector>)
845 }
846
847 fn prompt(
848 &self,
849 id: Option<acp_thread::UserMessageId>,
850 params: acp::PromptRequest,
851 cx: &mut App,
852 ) -> Task<Result<acp::PromptResponse>> {
853 let id = id.expect("UserMessageId is required");
854 let session_id = params.session_id.clone();
855 log::info!("Received prompt request for session: {}", session_id);
856 log::debug!("Prompt blocks count: {}", params.prompt.len());
857
858 self.run_turn(session_id, cx, |thread, cx| {
859 let content: Vec<UserMessageContent> = params
860 .prompt
861 .into_iter()
862 .map(Into::into)
863 .collect::<Vec<_>>();
864 log::info!("Converted prompt to message: {} chars", content.len());
865 log::debug!("Message id: {:?}", id);
866 log::debug!("Message content: {:?}", content);
867
868 thread.update(cx, |thread, cx| thread.send(id, content, cx))
869 })
870 }
871
872 fn resume(
873 &self,
874 session_id: &acp::SessionId,
875 _cx: &mut App,
876 ) -> Option<Rc<dyn acp_thread::AgentSessionResume>> {
877 Some(Rc::new(NativeAgentSessionResume {
878 connection: self.clone(),
879 session_id: session_id.clone(),
880 }) as _)
881 }
882
883 fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
884 log::info!("Cancelling on session: {}", session_id);
885 self.0.update(cx, |agent, cx| {
886 if let Some(agent) = agent.sessions.get(session_id) {
887 agent.thread.update(cx, |thread, cx| thread.cancel(cx));
888 }
889 });
890 }
891
892 fn session_editor(
893 &self,
894 session_id: &agent_client_protocol::SessionId,
895 cx: &mut App,
896 ) -> Option<Rc<dyn acp_thread::AgentSessionEditor>> {
897 self.0.update(cx, |agent, _cx| {
898 agent
899 .sessions
900 .get(session_id)
901 .map(|session| Rc::new(NativeAgentSessionEditor(session.thread.clone())) as _)
902 })
903 }
904
905 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
906 self
907 }
908}
909
910struct NativeAgentSessionEditor(Entity<Thread>);
911
912impl acp_thread::AgentSessionEditor for NativeAgentSessionEditor {
913 fn truncate(&self, message_id: acp_thread::UserMessageId, cx: &mut App) -> Task<Result<()>> {
914 Task::ready(
915 self.0
916 .update(cx, |thread, cx| thread.truncate(message_id, cx)),
917 )
918 }
919}
920
921struct NativeAgentSessionResume {
922 connection: NativeAgentConnection,
923 session_id: acp::SessionId,
924}
925
926impl acp_thread::AgentSessionResume for NativeAgentSessionResume {
927 fn run(&self, cx: &mut App) -> Task<Result<acp::PromptResponse>> {
928 self.connection
929 .run_turn(self.session_id.clone(), cx, |thread, cx| {
930 thread.update(cx, |thread, cx| thread.resume(cx))
931 })
932 }
933}
934
935#[cfg(test)]
936mod tests {
937 use super::*;
938 use acp_thread::{AgentConnection, AgentModelGroupName, AgentModelId, AgentModelInfo};
939 use fs::FakeFs;
940 use gpui::TestAppContext;
941 use serde_json::json;
942 use settings::SettingsStore;
943
944 #[gpui::test]
945 async fn test_maintaining_project_context(cx: &mut TestAppContext) {
946 init_test(cx);
947 let fs = FakeFs::new(cx.executor());
948 fs.insert_tree(
949 "/",
950 json!({
951 "a": {}
952 }),
953 )
954 .await;
955 let project = Project::test(fs.clone(), [], cx).await;
956 let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
957 let history_store = cx.new(|cx| HistoryStore::new(context_store, [], cx));
958 let agent = NativeAgent::new(
959 project.clone(),
960 history_store,
961 Templates::new(),
962 None,
963 fs.clone(),
964 &mut cx.to_async(),
965 )
966 .await
967 .unwrap();
968 agent.read_with(cx, |agent, cx| {
969 assert_eq!(agent.project_context.read(cx).worktrees, vec![])
970 });
971
972 let worktree = project
973 .update(cx, |project, cx| project.create_worktree("/a", true, cx))
974 .await
975 .unwrap();
976 cx.run_until_parked();
977 agent.read_with(cx, |agent, cx| {
978 assert_eq!(
979 agent.project_context.read(cx).worktrees,
980 vec![WorktreeContext {
981 root_name: "a".into(),
982 abs_path: Path::new("/a").into(),
983 rules_file: None
984 }]
985 )
986 });
987
988 // Creating `/a/.rules` updates the project context.
989 fs.insert_file("/a/.rules", Vec::new()).await;
990 cx.run_until_parked();
991 agent.read_with(cx, |agent, cx| {
992 let rules_entry = worktree.read(cx).entry_for_path(".rules").unwrap();
993 assert_eq!(
994 agent.project_context.read(cx).worktrees,
995 vec![WorktreeContext {
996 root_name: "a".into(),
997 abs_path: Path::new("/a").into(),
998 rules_file: Some(RulesFileContext {
999 path_in_worktree: Path::new(".rules").into(),
1000 text: "".into(),
1001 project_entry_id: rules_entry.id.to_usize()
1002 })
1003 }]
1004 )
1005 });
1006 }
1007
1008 #[gpui::test]
1009 async fn test_listing_models(cx: &mut TestAppContext) {
1010 init_test(cx);
1011 let fs = FakeFs::new(cx.executor());
1012 fs.insert_tree("/", json!({ "a": {} })).await;
1013 let project = Project::test(fs.clone(), [], cx).await;
1014 let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1015 let history_store = cx.new(|cx| HistoryStore::new(context_store, [], cx));
1016 let connection = NativeAgentConnection(
1017 NativeAgent::new(
1018 project.clone(),
1019 history_store,
1020 Templates::new(),
1021 None,
1022 fs.clone(),
1023 &mut cx.to_async(),
1024 )
1025 .await
1026 .unwrap(),
1027 );
1028
1029 let models = cx.update(|cx| connection.list_models(cx)).await.unwrap();
1030
1031 let acp_thread::AgentModelList::Grouped(models) = models else {
1032 panic!("Unexpected model group");
1033 };
1034 assert_eq!(
1035 models,
1036 IndexMap::from_iter([(
1037 AgentModelGroupName("Fake".into()),
1038 vec![AgentModelInfo {
1039 id: AgentModelId("fake/fake".into()),
1040 name: "Fake".into(),
1041 icon: Some(ui::IconName::ZedAssistant),
1042 }]
1043 )])
1044 );
1045 }
1046
1047 #[gpui::test]
1048 async fn test_model_selection_persists_to_settings(cx: &mut TestAppContext) {
1049 init_test(cx);
1050 let fs = FakeFs::new(cx.executor());
1051 fs.create_dir(paths::settings_file().parent().unwrap())
1052 .await
1053 .unwrap();
1054 fs.insert_file(
1055 paths::settings_file(),
1056 json!({
1057 "agent": {
1058 "default_model": {
1059 "provider": "foo",
1060 "model": "bar"
1061 }
1062 }
1063 })
1064 .to_string()
1065 .into_bytes(),
1066 )
1067 .await;
1068 let project = Project::test(fs.clone(), [], cx).await;
1069
1070 let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1071 let history_store = cx.new(|cx| HistoryStore::new(context_store, [], cx));
1072
1073 // Create the agent and connection
1074 let agent = NativeAgent::new(
1075 project.clone(),
1076 history_store,
1077 Templates::new(),
1078 None,
1079 fs.clone(),
1080 &mut cx.to_async(),
1081 )
1082 .await
1083 .unwrap();
1084 let connection = NativeAgentConnection(agent.clone());
1085
1086 // Create a thread/session
1087 let acp_thread = cx
1088 .update(|cx| {
1089 Rc::new(connection.clone()).new_thread(project.clone(), Path::new("/a"), cx)
1090 })
1091 .await
1092 .unwrap();
1093
1094 let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());
1095
1096 // Select a model
1097 let model_id = AgentModelId("fake/fake".into());
1098 cx.update(|cx| connection.select_model(session_id.clone(), model_id.clone(), cx))
1099 .await
1100 .unwrap();
1101
1102 // Verify the thread has the selected model
1103 agent.read_with(cx, |agent, _| {
1104 let session = agent.sessions.get(&session_id).unwrap();
1105 session.thread.read_with(cx, |thread, _| {
1106 assert_eq!(thread.model().unwrap().id().0, "fake");
1107 });
1108 });
1109
1110 cx.run_until_parked();
1111
1112 // Verify settings file was updated
1113 let settings_content = fs.load(paths::settings_file()).await.unwrap();
1114 let settings_json: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1115
1116 // Check that the agent settings contain the selected model
1117 assert_eq!(
1118 settings_json["agent"]["default_model"]["model"],
1119 json!("fake")
1120 );
1121 assert_eq!(
1122 settings_json["agent"]["default_model"]["provider"],
1123 json!("fake")
1124 );
1125 }
1126
1127 fn init_test(cx: &mut TestAppContext) {
1128 env_logger::try_init().ok();
1129 cx.update(|cx| {
1130 let settings_store = SettingsStore::test(cx);
1131 cx.set_global(settings_store);
1132 Project::init_settings(cx);
1133 agent_settings::init(cx);
1134 language::init(cx);
1135 LanguageModelRegistry::test(cx);
1136 });
1137 }
1138}