1use crate::HistoryStore;
2use crate::{
3 ContextServerRegistry, Thread, ThreadEvent, ThreadsDatabase, ToolCallAuthorization,
4 UserMessageContent, templates::Templates,
5};
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: [&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::TokenUsageUpdate(usage) => {
677 acp_thread.update(cx, |thread, cx| {
678 thread.update_token_usage(Some(usage), cx)
679 })?;
680 }
681 ThreadEvent::TitleUpdate(title) => {
682 acp_thread
683 .update(cx, |thread, cx| thread.update_title(title, cx))??;
684 }
685 ThreadEvent::Retry(status) => {
686 acp_thread.update(cx, |thread, cx| {
687 thread.update_retry_status(status, cx)
688 })?;
689 }
690 ThreadEvent::Stop(stop_reason) => {
691 log::debug!("Assistant message complete: {:?}", stop_reason);
692 return Ok(acp::PromptResponse { stop_reason });
693 }
694 }
695 }
696 Err(e) => {
697 log::error!("Error in model response stream: {:?}", e);
698 return Err(e);
699 }
700 }
701 }
702
703 log::info!("Response stream completed");
704 anyhow::Ok(acp::PromptResponse {
705 stop_reason: acp::StopReason::EndTurn,
706 })
707 })
708 }
709}
710
711impl AgentModelSelector for NativeAgentConnection {
712 fn list_models(&self, cx: &mut App) -> Task<Result<acp_thread::AgentModelList>> {
713 log::debug!("NativeAgentConnection::list_models called");
714 let list = self.0.read(cx).models.model_list.clone();
715 Task::ready(if list.is_empty() {
716 Err(anyhow::anyhow!("No models available"))
717 } else {
718 Ok(list)
719 })
720 }
721
722 fn select_model(
723 &self,
724 session_id: acp::SessionId,
725 model_id: acp_thread::AgentModelId,
726 cx: &mut App,
727 ) -> Task<Result<()>> {
728 log::info!("Setting model for session {}: {}", session_id, model_id);
729 let Some(thread) = self
730 .0
731 .read(cx)
732 .sessions
733 .get(&session_id)
734 .map(|session| session.thread.clone())
735 else {
736 return Task::ready(Err(anyhow!("Session not found")));
737 };
738
739 let Some(model) = self.0.read(cx).models.model_from_id(&model_id) else {
740 return Task::ready(Err(anyhow!("Invalid model ID {}", model_id)));
741 };
742
743 thread.update(cx, |thread, cx| {
744 thread.set_model(model.clone(), cx);
745 });
746
747 update_settings_file::<AgentSettings>(
748 self.0.read(cx).fs.clone(),
749 cx,
750 move |settings, _cx| {
751 settings.set_model(model);
752 },
753 );
754
755 Task::ready(Ok(()))
756 }
757
758 fn selected_model(
759 &self,
760 session_id: &acp::SessionId,
761 cx: &mut App,
762 ) -> Task<Result<acp_thread::AgentModelInfo>> {
763 let session_id = session_id.clone();
764
765 let Some(thread) = self
766 .0
767 .read(cx)
768 .sessions
769 .get(&session_id)
770 .map(|session| session.thread.clone())
771 else {
772 return Task::ready(Err(anyhow!("Session not found")));
773 };
774 let Some(model) = thread.read(cx).model() else {
775 return Task::ready(Err(anyhow!("Model not found")));
776 };
777 let Some(provider) = LanguageModelRegistry::read_global(cx).provider(&model.provider_id())
778 else {
779 return Task::ready(Err(anyhow!("Provider not found")));
780 };
781 Task::ready(Ok(LanguageModels::map_language_model_to_info(
782 model, &provider,
783 )))
784 }
785
786 fn watch(&self, cx: &mut App) -> watch::Receiver<()> {
787 self.0.read(cx).models.watch()
788 }
789}
790
791impl acp_thread::AgentConnection for NativeAgentConnection {
792 fn new_thread(
793 self: Rc<Self>,
794 project: Entity<Project>,
795 cwd: &Path,
796 cx: &mut App,
797 ) -> Task<Result<Entity<acp_thread::AcpThread>>> {
798 let agent = self.0.clone();
799 log::info!("Creating new thread for project at: {:?}", cwd);
800
801 cx.spawn(async move |cx| {
802 log::debug!("Starting thread creation in async context");
803
804 let action_log = cx.new(|_cx| ActionLog::new(project.clone()))?;
805 // Create Thread
806 let thread = agent.update(
807 cx,
808 |agent, cx: &mut gpui::Context<NativeAgent>| -> Result<_> {
809 // Fetch default model from registry settings
810 let registry = LanguageModelRegistry::read_global(cx);
811 // Log available models for debugging
812 let available_count = registry.available_models(cx).count();
813 log::debug!("Total available models: {}", available_count);
814
815 let default_model = registry.default_model().and_then(|default_model| {
816 agent
817 .models
818 .model_from_id(&LanguageModels::model_id(&default_model.model))
819 });
820
821 let thread = cx.new(|cx| {
822 Thread::new(
823 project.clone(),
824 agent.project_context.clone(),
825 agent.context_server_registry.clone(),
826 action_log.clone(),
827 agent.templates.clone(),
828 default_model,
829 cx,
830 )
831 });
832
833 Ok(thread)
834 },
835 )??;
836 agent.update(cx, |agent, cx| agent.register_session(thread, cx))
837 })
838 }
839
840 fn auth_methods(&self) -> &[acp::AuthMethod] {
841 &[] // No auth for in-process
842 }
843
844 fn authenticate(&self, _method: acp::AuthMethodId, _cx: &mut App) -> Task<Result<()>> {
845 Task::ready(Ok(()))
846 }
847
848 fn model_selector(&self) -> Option<Rc<dyn AgentModelSelector>> {
849 Some(Rc::new(self.clone()) as Rc<dyn AgentModelSelector>)
850 }
851
852 fn prompt(
853 &self,
854 id: Option<acp_thread::UserMessageId>,
855 params: acp::PromptRequest,
856 cx: &mut App,
857 ) -> Task<Result<acp::PromptResponse>> {
858 let id = id.expect("UserMessageId is required");
859 let session_id = params.session_id.clone();
860 log::info!("Received prompt request for session: {}", session_id);
861 log::debug!("Prompt blocks count: {}", params.prompt.len());
862
863 self.run_turn(session_id, cx, |thread, cx| {
864 let content: Vec<UserMessageContent> = params
865 .prompt
866 .into_iter()
867 .map(Into::into)
868 .collect::<Vec<_>>();
869 log::info!("Converted prompt to message: {} chars", content.len());
870 log::debug!("Message id: {:?}", id);
871 log::debug!("Message content: {:?}", content);
872
873 thread.update(cx, |thread, cx| thread.send(id, content, cx))
874 })
875 }
876
877 fn resume(
878 &self,
879 session_id: &acp::SessionId,
880 _cx: &mut App,
881 ) -> Option<Rc<dyn acp_thread::AgentSessionResume>> {
882 Some(Rc::new(NativeAgentSessionResume {
883 connection: self.clone(),
884 session_id: session_id.clone(),
885 }) as _)
886 }
887
888 fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
889 log::info!("Cancelling on session: {}", session_id);
890 self.0.update(cx, |agent, cx| {
891 if let Some(agent) = agent.sessions.get(session_id) {
892 agent.thread.update(cx, |thread, cx| thread.cancel(cx));
893 }
894 });
895 }
896
897 fn session_editor(
898 &self,
899 session_id: &agent_client_protocol::SessionId,
900 cx: &mut App,
901 ) -> Option<Rc<dyn acp_thread::AgentSessionEditor>> {
902 self.0.update(cx, |agent, _cx| {
903 agent.sessions.get(session_id).map(|session| {
904 Rc::new(NativeAgentSessionEditor {
905 thread: session.thread.clone(),
906 acp_thread: session.acp_thread.clone(),
907 }) as _
908 })
909 })
910 }
911
912 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
913 self
914 }
915}
916
917struct NativeAgentSessionEditor {
918 thread: Entity<Thread>,
919 acp_thread: WeakEntity<AcpThread>,
920}
921
922impl acp_thread::AgentSessionEditor for NativeAgentSessionEditor {
923 fn truncate(&self, message_id: acp_thread::UserMessageId, cx: &mut App) -> Task<Result<()>> {
924 match self.thread.update(cx, |thread, cx| {
925 thread.truncate(message_id.clone(), cx)?;
926 Ok(thread.latest_token_usage())
927 }) {
928 Ok(usage) => {
929 self.acp_thread
930 .update(cx, |thread, cx| {
931 thread.update_token_usage(usage, cx);
932 })
933 .ok();
934 Task::ready(Ok(()))
935 }
936 Err(error) => Task::ready(Err(error)),
937 }
938 }
939}
940
941struct NativeAgentSessionResume {
942 connection: NativeAgentConnection,
943 session_id: acp::SessionId,
944}
945
946impl acp_thread::AgentSessionResume for NativeAgentSessionResume {
947 fn run(&self, cx: &mut App) -> Task<Result<acp::PromptResponse>> {
948 self.connection
949 .run_turn(self.session_id.clone(), cx, |thread, cx| {
950 thread.update(cx, |thread, cx| thread.resume(cx))
951 })
952 }
953}
954
955#[cfg(test)]
956mod tests {
957 use super::*;
958 use acp_thread::{AgentConnection, AgentModelGroupName, AgentModelId, AgentModelInfo};
959 use fs::FakeFs;
960 use gpui::TestAppContext;
961 use serde_json::json;
962 use settings::SettingsStore;
963
964 #[gpui::test]
965 async fn test_maintaining_project_context(cx: &mut TestAppContext) {
966 init_test(cx);
967 let fs = FakeFs::new(cx.executor());
968 fs.insert_tree(
969 "/",
970 json!({
971 "a": {}
972 }),
973 )
974 .await;
975 let project = Project::test(fs.clone(), [], cx).await;
976 let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
977 let history_store = cx.new(|cx| HistoryStore::new(context_store, [], cx));
978 let agent = NativeAgent::new(
979 project.clone(),
980 history_store,
981 Templates::new(),
982 None,
983 fs.clone(),
984 &mut cx.to_async(),
985 )
986 .await
987 .unwrap();
988 agent.read_with(cx, |agent, cx| {
989 assert_eq!(agent.project_context.read(cx).worktrees, vec![])
990 });
991
992 let worktree = project
993 .update(cx, |project, cx| project.create_worktree("/a", true, cx))
994 .await
995 .unwrap();
996 cx.run_until_parked();
997 agent.read_with(cx, |agent, cx| {
998 assert_eq!(
999 agent.project_context.read(cx).worktrees,
1000 vec![WorktreeContext {
1001 root_name: "a".into(),
1002 abs_path: Path::new("/a").into(),
1003 rules_file: None
1004 }]
1005 )
1006 });
1007
1008 // Creating `/a/.rules` updates the project context.
1009 fs.insert_file("/a/.rules", Vec::new()).await;
1010 cx.run_until_parked();
1011 agent.read_with(cx, |agent, cx| {
1012 let rules_entry = worktree.read(cx).entry_for_path(".rules").unwrap();
1013 assert_eq!(
1014 agent.project_context.read(cx).worktrees,
1015 vec![WorktreeContext {
1016 root_name: "a".into(),
1017 abs_path: Path::new("/a").into(),
1018 rules_file: Some(RulesFileContext {
1019 path_in_worktree: Path::new(".rules").into(),
1020 text: "".into(),
1021 project_entry_id: rules_entry.id.to_usize()
1022 })
1023 }]
1024 )
1025 });
1026 }
1027
1028 #[gpui::test]
1029 async fn test_listing_models(cx: &mut TestAppContext) {
1030 init_test(cx);
1031 let fs = FakeFs::new(cx.executor());
1032 fs.insert_tree("/", json!({ "a": {} })).await;
1033 let project = Project::test(fs.clone(), [], cx).await;
1034 let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1035 let history_store = cx.new(|cx| HistoryStore::new(context_store, [], cx));
1036 let connection = NativeAgentConnection(
1037 NativeAgent::new(
1038 project.clone(),
1039 history_store,
1040 Templates::new(),
1041 None,
1042 fs.clone(),
1043 &mut cx.to_async(),
1044 )
1045 .await
1046 .unwrap(),
1047 );
1048
1049 let models = cx.update(|cx| connection.list_models(cx)).await.unwrap();
1050
1051 let acp_thread::AgentModelList::Grouped(models) = models else {
1052 panic!("Unexpected model group");
1053 };
1054 assert_eq!(
1055 models,
1056 IndexMap::from_iter([(
1057 AgentModelGroupName("Fake".into()),
1058 vec![AgentModelInfo {
1059 id: AgentModelId("fake/fake".into()),
1060 name: "Fake".into(),
1061 icon: Some(ui::IconName::ZedAssistant),
1062 }]
1063 )])
1064 );
1065 }
1066
1067 #[gpui::test]
1068 async fn test_model_selection_persists_to_settings(cx: &mut TestAppContext) {
1069 init_test(cx);
1070 let fs = FakeFs::new(cx.executor());
1071 fs.create_dir(paths::settings_file().parent().unwrap())
1072 .await
1073 .unwrap();
1074 fs.insert_file(
1075 paths::settings_file(),
1076 json!({
1077 "agent": {
1078 "default_model": {
1079 "provider": "foo",
1080 "model": "bar"
1081 }
1082 }
1083 })
1084 .to_string()
1085 .into_bytes(),
1086 )
1087 .await;
1088 let project = Project::test(fs.clone(), [], cx).await;
1089
1090 let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1091 let history_store = cx.new(|cx| HistoryStore::new(context_store, [], cx));
1092
1093 // Create the agent and connection
1094 let agent = NativeAgent::new(
1095 project.clone(),
1096 history_store,
1097 Templates::new(),
1098 None,
1099 fs.clone(),
1100 &mut cx.to_async(),
1101 )
1102 .await
1103 .unwrap();
1104 let connection = NativeAgentConnection(agent.clone());
1105
1106 // Create a thread/session
1107 let acp_thread = cx
1108 .update(|cx| {
1109 Rc::new(connection.clone()).new_thread(project.clone(), Path::new("/a"), cx)
1110 })
1111 .await
1112 .unwrap();
1113
1114 let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());
1115
1116 // Select a model
1117 let model_id = AgentModelId("fake/fake".into());
1118 cx.update(|cx| connection.select_model(session_id.clone(), model_id.clone(), cx))
1119 .await
1120 .unwrap();
1121
1122 // Verify the thread has the selected model
1123 agent.read_with(cx, |agent, _| {
1124 let session = agent.sessions.get(&session_id).unwrap();
1125 session.thread.read_with(cx, |thread, _| {
1126 assert_eq!(thread.model().unwrap().id().0, "fake");
1127 });
1128 });
1129
1130 cx.run_until_parked();
1131
1132 // Verify settings file was updated
1133 let settings_content = fs.load(paths::settings_file()).await.unwrap();
1134 let settings_json: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1135
1136 // Check that the agent settings contain the selected model
1137 assert_eq!(
1138 settings_json["agent"]["default_model"]["model"],
1139 json!("fake")
1140 );
1141 assert_eq!(
1142 settings_json["agent"]["default_model"]["provider"],
1143 json!("fake")
1144 );
1145 }
1146
1147 fn init_test(cx: &mut TestAppContext) {
1148 env_logger::try_init().ok();
1149 cx.update(|cx| {
1150 let settings_store = SettingsStore::test(cx);
1151 cx.set_global(settings_store);
1152 Project::init_settings(cx);
1153 agent_settings::init(cx);
1154 language::init(cx);
1155 LanguageModelRegistry::test(cx);
1156 });
1157 }
1158}