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