1mod connection;
2pub use connection::*;
3
4use agent_client_protocol as acp;
5use agentic_coding_protocol as acp_old;
6use anyhow::{Context as _, Result};
7use assistant_tool::ActionLog;
8use buffer_diff::BufferDiff;
9use editor::{Bias, MultiBuffer, PathKey};
10use futures::{FutureExt, channel::oneshot, future::BoxFuture};
11use gpui::{AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task, WeakEntity};
12use itertools::{Itertools, PeekingNext};
13use language::{
14 Anchor, Buffer, BufferSnapshot, Capability, LanguageRegistry, OffsetRangeExt as _, Point,
15 text_diff,
16};
17use markdown::Markdown;
18use project::{AgentLocation, Project};
19use std::cell::RefCell;
20use std::collections::HashMap;
21use std::error::Error;
22use std::fmt::Formatter;
23use std::rc::Rc;
24use std::{
25 fmt::Display,
26 mem,
27 path::{Path, PathBuf},
28 sync::Arc,
29};
30use ui::App;
31use util::ResultExt;
32
33#[derive(Debug)]
34pub struct UserMessage {
35 pub content: ContentBlock,
36}
37
38impl UserMessage {
39 pub fn from_acp(
40 message: impl IntoIterator<Item = acp::ContentBlock>,
41 language_registry: Arc<LanguageRegistry>,
42 cx: &mut App,
43 ) -> Self {
44 let mut content = ContentBlock::Empty;
45 for chunk in message {
46 content.append(chunk, &language_registry, cx)
47 }
48 Self { content: content }
49 }
50
51 fn to_markdown(&self, cx: &App) -> String {
52 format!("## User\n{}\n", self.content.to_markdown(cx))
53 }
54}
55
56#[derive(Debug)]
57pub struct MentionPath<'a>(&'a Path);
58
59impl<'a> MentionPath<'a> {
60 const PREFIX: &'static str = "@file:";
61
62 pub fn new(path: &'a Path) -> Self {
63 MentionPath(path)
64 }
65
66 pub fn try_parse(url: &'a str) -> Option<Self> {
67 let path = url.strip_prefix(Self::PREFIX)?;
68 Some(MentionPath(Path::new(path)))
69 }
70
71 pub fn path(&self) -> &Path {
72 self.0
73 }
74}
75
76impl Display for MentionPath<'_> {
77 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78 write!(
79 f,
80 "[@{}]({}{})",
81 self.0.file_name().unwrap_or_default().display(),
82 Self::PREFIX,
83 self.0.display()
84 )
85 }
86}
87
88#[derive(Debug, PartialEq)]
89pub struct AssistantMessage {
90 pub chunks: Vec<AssistantMessageChunk>,
91}
92
93impl AssistantMessage {
94 pub fn to_markdown(&self, cx: &App) -> String {
95 format!(
96 "## Assistant\n\n{}\n\n",
97 self.chunks
98 .iter()
99 .map(|chunk| chunk.to_markdown(cx))
100 .join("\n\n")
101 )
102 }
103}
104
105#[derive(Debug, PartialEq)]
106pub enum AssistantMessageChunk {
107 Message { block: ContentBlock },
108 Thought { block: ContentBlock },
109}
110
111impl AssistantMessageChunk {
112 pub fn from_str(chunk: &str, language_registry: &Arc<LanguageRegistry>, cx: &mut App) -> Self {
113 Self::Message {
114 block: ContentBlock::new(
115 acp::ContentBlock::Text(acp::TextContent {
116 text: chunk.to_owned().into(),
117 annotations: None,
118 }),
119 language_registry,
120 cx,
121 ),
122 }
123 }
124
125 fn to_markdown(&self, cx: &App) -> String {
126 match self {
127 Self::Message { block } => block.to_markdown(cx).to_string(),
128 Self::Thought { block } => {
129 format!("<thinking>\n{}\n</thinking>", block.to_markdown(cx))
130 }
131 }
132 }
133}
134
135#[derive(Debug)]
136pub enum AgentThreadEntry {
137 UserMessage(UserMessage),
138 AssistantMessage(AssistantMessage),
139 ToolCall(ToolCall),
140}
141
142impl AgentThreadEntry {
143 fn to_markdown(&self, cx: &App) -> String {
144 match self {
145 Self::UserMessage(message) => message.to_markdown(cx),
146 Self::AssistantMessage(message) => message.to_markdown(cx),
147 Self::ToolCall(too_call) => too_call.to_markdown(cx),
148 }
149 }
150
151 // todo! return all diffs?
152 pub fn first_diff(&self) -> Option<&Diff> {
153 if let AgentThreadEntry::ToolCall(call) = self {
154 call.first_diff()
155 } else {
156 None
157 }
158 }
159
160 pub fn locations(&self) -> Option<&[acp::ToolCallLocation]> {
161 if let AgentThreadEntry::ToolCall(ToolCall { locations, .. }) = self {
162 Some(locations)
163 } else {
164 None
165 }
166 }
167}
168
169#[derive(Debug)]
170pub struct ToolCall {
171 pub id: acp::ToolCallId,
172 pub label: Entity<Markdown>,
173 pub kind: acp::ToolKind,
174 pub content: Vec<ToolCallContent>,
175 pub status: ToolCallStatus,
176 pub locations: Vec<acp::ToolCallLocation>,
177}
178
179impl ToolCall {
180 fn from_acp(
181 tool_call: acp::ToolCall,
182 status: ToolCallStatus,
183 language_registry: Arc<LanguageRegistry>,
184 cx: &mut App,
185 ) -> Self {
186 Self {
187 id: tool_call.id,
188 label: cx.new(|cx| {
189 Markdown::new(
190 tool_call.label.into(),
191 Some(language_registry.clone()),
192 None,
193 cx,
194 )
195 }),
196 kind: tool_call.kind,
197 content: tool_call
198 .content
199 .into_iter()
200 .map(|content| ToolCallContent::from_acp(content, language_registry.clone(), cx))
201 .collect(),
202 locations: tool_call.locations,
203 status,
204 }
205 }
206
207 pub fn first_diff(&self) -> Option<&Diff> {
208 self.content.iter().find_map(|content| match content {
209 ToolCallContent::ContentBlock { .. } => None,
210 ToolCallContent::Diff { diff } => Some(diff),
211 })
212 }
213
214 fn to_markdown(&self, cx: &App) -> String {
215 let mut markdown = format!(
216 "**Tool Call: {}**\nStatus: {}\n\n",
217 self.label.read(cx).source(),
218 self.status
219 );
220 for content in &self.content {
221 markdown.push_str(content.to_markdown(cx).as_str());
222 markdown.push_str("\n\n");
223 }
224 markdown
225 }
226}
227
228#[derive(Debug)]
229pub enum ToolCallStatus {
230 WaitingForConfirmation {
231 options: Vec<acp::PermissionOption>,
232 respond_tx: oneshot::Sender<acp::PermissionOptionId>,
233 },
234 Allowed {
235 status: acp::ToolCallStatus,
236 },
237 Rejected,
238 Canceled,
239}
240
241impl Display for ToolCallStatus {
242 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
243 write!(
244 f,
245 "{}",
246 match self {
247 ToolCallStatus::WaitingForConfirmation { .. } => "Waiting for confirmation",
248 ToolCallStatus::Allowed { status } => match status {
249 acp::ToolCallStatus::InProgress => "In Progress",
250 acp::ToolCallStatus::Completed => "Completed",
251 acp::ToolCallStatus::Failed => "Failed",
252 },
253 ToolCallStatus::Rejected => "Rejected",
254 ToolCallStatus::Canceled => "Canceled",
255 }
256 )
257 }
258}
259
260#[derive(Debug, PartialEq, Clone)]
261enum ContentBlock {
262 Empty,
263 Markdown { markdown: Entity<Markdown> },
264}
265
266impl ContentBlock {
267 pub fn new(
268 block: acp::ContentBlock,
269 language_registry: &Arc<LanguageRegistry>,
270 cx: &mut App,
271 ) -> Self {
272 let mut this = Self::Empty;
273 this.append(block, language_registry, cx);
274 this
275 }
276
277 pub fn new_combined(
278 blocks: impl IntoIterator<Item = acp::ContentBlock>,
279 language_registry: Arc<LanguageRegistry>,
280 cx: &mut App,
281 ) -> Self {
282 let mut this = Self::Empty;
283 for block in blocks {
284 this.append(block, &language_registry, cx);
285 }
286 this
287 }
288
289 pub fn append(
290 &mut self,
291 block: acp::ContentBlock,
292 language_registry: &Arc<LanguageRegistry>,
293 cx: &mut App,
294 ) {
295 let new_content = match block {
296 acp::ContentBlock::Text(text_content) => text_content.text.clone(),
297 acp::ContentBlock::ResourceLink(resource_link) => {
298 if let Some(path) = resource_link.uri.strip_prefix("file://") {
299 format!("{}", MentionPath(path.as_ref()))
300 } else {
301 resource_link.uri.clone()
302 }
303 }
304 acp::ContentBlock::Image(_)
305 | acp::ContentBlock::Audio(_)
306 | acp::ContentBlock::Resource(_) => String::new(),
307 };
308
309 match self {
310 ContentBlock::Empty => {
311 *self = ContentBlock::Markdown {
312 markdown: cx.new(|cx| {
313 Markdown::new(
314 new_content.into(),
315 Some(language_registry.clone()),
316 None,
317 cx,
318 )
319 }),
320 };
321 }
322 ContentBlock::Markdown { markdown } => {
323 markdown.update(cx, |markdown, cx| markdown.append(&new_content, cx));
324 }
325 }
326 }
327
328 fn to_markdown<'a>(&'a self, cx: &'a App) -> &'a str {
329 match self {
330 ContentBlock::Empty => "",
331 ContentBlock::Markdown { markdown } => markdown.read(cx).source(),
332 }
333 }
334}
335
336#[derive(Debug)]
337pub enum ToolCallContent {
338 ContentBlock { content: ContentBlock },
339 Diff { diff: Diff },
340}
341
342impl ToolCallContent {
343 pub fn from_acp(
344 content: acp::ToolCallContent,
345 language_registry: Arc<LanguageRegistry>,
346 cx: &mut App,
347 ) -> Self {
348 match content {
349 acp::ToolCallContent::ContentBlock { content } => Self::ContentBlock {
350 content: ContentBlock::new(content, &language_registry, cx),
351 },
352 acp::ToolCallContent::Diff { diff } => Self::Diff {
353 diff: Diff::from_acp(diff, language_registry, cx),
354 },
355 }
356 }
357
358 pub fn from_acp_contents(
359 content: Vec<acp::ToolCallContent>,
360 language_registry: Arc<LanguageRegistry>,
361 cx: &mut App,
362 ) -> Vec<Self> {
363 content
364 .into_iter()
365 .peekable()
366 .batching(|it| match it.next()? {
367 acp::ToolCallContent::ContentBlock { content } => {
368 let mut block = ContentBlock::new(content, &language_registry, cx);
369 while let Some(acp::ToolCallContent::ContentBlock { content }) =
370 it.peeking_next(|c| matches!(c, acp::ToolCallContent::ContentBlock { .. }))
371 {
372 block.append(content, &language_registry, cx);
373 }
374 Some(ToolCallContent::ContentBlock { content: block })
375 }
376 content @ acp::ToolCallContent::Diff { .. } => Some(ToolCallContent::from_acp(
377 content,
378 language_registry.clone(),
379 cx,
380 )),
381 })
382 .collect()
383 }
384
385 pub fn to_markdown(&self, cx: &App) -> String {
386 match self {
387 Self::ContentBlock { content } => content.to_markdown(cx).to_string(),
388 Self::Diff { diff } => diff.to_markdown(cx),
389 }
390 }
391}
392
393#[derive(Debug)]
394pub struct Diff {
395 pub multibuffer: Entity<MultiBuffer>,
396 pub path: PathBuf,
397 pub new_buffer: Entity<Buffer>,
398 pub old_buffer: Entity<Buffer>,
399 _task: Task<Result<()>>,
400}
401
402impl Diff {
403 pub fn from_acp(
404 diff: acp::Diff,
405 language_registry: Arc<LanguageRegistry>,
406 cx: &mut App,
407 ) -> Self {
408 let acp::Diff {
409 path,
410 old_text,
411 new_text,
412 } = diff;
413
414 let multibuffer = cx.new(|_cx| MultiBuffer::without_headers(Capability::ReadOnly));
415
416 let new_buffer = cx.new(|cx| Buffer::local(new_text, cx));
417 let old_buffer = cx.new(|cx| Buffer::local(old_text.unwrap_or("".into()), cx));
418 let new_buffer_snapshot = new_buffer.read(cx).text_snapshot();
419 let old_buffer_snapshot = old_buffer.read(cx).snapshot();
420 let buffer_diff = cx.new(|cx| BufferDiff::new(&new_buffer_snapshot, cx));
421 let diff_task = buffer_diff.update(cx, |diff, cx| {
422 diff.set_base_text(
423 old_buffer_snapshot,
424 Some(language_registry.clone()),
425 new_buffer_snapshot,
426 cx,
427 )
428 });
429
430 let task = cx.spawn({
431 let multibuffer = multibuffer.clone();
432 let path = path.clone();
433 let new_buffer = new_buffer.clone();
434 async move |cx| {
435 diff_task.await?;
436
437 multibuffer
438 .update(cx, |multibuffer, cx| {
439 let hunk_ranges = {
440 let buffer = new_buffer.read(cx);
441 let diff = buffer_diff.read(cx);
442 diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, cx)
443 .map(|diff_hunk| diff_hunk.buffer_range.to_point(&buffer))
444 .collect::<Vec<_>>()
445 };
446
447 multibuffer.set_excerpts_for_path(
448 PathKey::for_buffer(&new_buffer, cx),
449 new_buffer.clone(),
450 hunk_ranges,
451 editor::DEFAULT_MULTIBUFFER_CONTEXT,
452 cx,
453 );
454 multibuffer.add_diff(buffer_diff.clone(), cx);
455 })
456 .log_err();
457
458 if let Some(language) = language_registry
459 .language_for_file_path(&path)
460 .await
461 .log_err()
462 {
463 new_buffer.update(cx, |buffer, cx| buffer.set_language(Some(language), cx))?;
464 }
465
466 anyhow::Ok(())
467 }
468 });
469
470 Self {
471 multibuffer,
472 path,
473 new_buffer,
474 old_buffer,
475 _task: task,
476 }
477 }
478
479 fn to_markdown(&self, cx: &App) -> String {
480 let buffer_text = self
481 .multibuffer
482 .read(cx)
483 .all_buffers()
484 .iter()
485 .map(|buffer| buffer.read(cx).text())
486 .join("\n");
487 format!("Diff: {}\n```\n{}\n```\n", self.path.display(), buffer_text)
488 }
489}
490
491#[derive(Debug, Default)]
492pub struct Plan {
493 pub entries: Vec<PlanEntry>,
494}
495
496#[derive(Debug)]
497pub struct PlanStats<'a> {
498 pub in_progress_entry: Option<&'a PlanEntry>,
499 pub pending: u32,
500 pub completed: u32,
501}
502
503impl Plan {
504 pub fn is_empty(&self) -> bool {
505 self.entries.is_empty()
506 }
507
508 pub fn stats(&self) -> PlanStats<'_> {
509 let mut stats = PlanStats {
510 in_progress_entry: None,
511 pending: 0,
512 completed: 0,
513 };
514
515 for entry in &self.entries {
516 match &entry.status {
517 acp::PlanEntryStatus::Pending => {
518 stats.pending += 1;
519 }
520 acp::PlanEntryStatus::InProgress => {
521 stats.in_progress_entry = stats.in_progress_entry.or(Some(entry));
522 }
523 acp::PlanEntryStatus::Completed => {
524 stats.completed += 1;
525 }
526 }
527 }
528
529 stats
530 }
531}
532
533#[derive(Debug)]
534pub struct PlanEntry {
535 pub content: Entity<Markdown>,
536 pub priority: acp::PlanEntryPriority,
537 pub status: acp::PlanEntryStatus,
538}
539
540impl PlanEntry {
541 pub fn from_acp(entry: acp::PlanEntry, cx: &mut App) -> Self {
542 Self {
543 content: cx.new(|cx| Markdown::new_text(entry.content.into(), cx)),
544 priority: entry.priority,
545 status: entry.status,
546 }
547 }
548}
549
550pub struct AcpThread {
551 title: SharedString,
552 entries: Vec<AgentThreadEntry>,
553 plan: Plan,
554 project: Entity<Project>,
555 action_log: Entity<ActionLog>,
556 shared_buffers: HashMap<Entity<Buffer>, BufferSnapshot>,
557 send_task: Option<Task<()>>,
558 connection: Arc<dyn AgentConnection>,
559 child_status: Option<Task<Result<()>>>,
560 session_id: acp::SessionId,
561}
562
563pub enum AcpThreadEvent {
564 NewEntry,
565 EntryUpdated(usize),
566}
567
568impl EventEmitter<AcpThreadEvent> for AcpThread {}
569
570#[derive(PartialEq, Eq)]
571pub enum ThreadStatus {
572 Idle,
573 WaitingForToolConfirmation,
574 Generating,
575}
576
577#[derive(Debug, Clone)]
578pub enum LoadError {
579 Unsupported {
580 error_message: SharedString,
581 upgrade_message: SharedString,
582 upgrade_command: String,
583 },
584 Exited(i32),
585 Other(SharedString),
586}
587
588impl Display for LoadError {
589 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
590 match self {
591 LoadError::Unsupported { error_message, .. } => write!(f, "{}", error_message),
592 LoadError::Exited(status) => write!(f, "Server exited with status {}", status),
593 LoadError::Other(msg) => write!(f, "{}", msg),
594 }
595 }
596}
597
598impl Error for LoadError {}
599
600impl AcpThread {
601 pub fn new(
602 connection: impl AgentConnection + 'static,
603 title: SharedString,
604 child_status: Option<Task<Result<()>>>,
605 project: Entity<Project>,
606 session_id: acp::SessionId,
607 cx: &mut Context<Self>,
608 ) -> Self {
609 let action_log = cx.new(|_| ActionLog::new(project.clone()));
610
611 Self {
612 action_log,
613 shared_buffers: Default::default(),
614 entries: Default::default(),
615 plan: Default::default(),
616 title,
617 project,
618 send_task: None,
619 connection: Arc::new(connection),
620 child_status,
621 session_id,
622 }
623 }
624
625 pub fn action_log(&self) -> &Entity<ActionLog> {
626 &self.action_log
627 }
628
629 pub fn project(&self) -> &Entity<Project> {
630 &self.project
631 }
632
633 pub fn title(&self) -> SharedString {
634 self.title.clone()
635 }
636
637 pub fn entries(&self) -> &[AgentThreadEntry] {
638 &self.entries
639 }
640
641 pub fn status(&self) -> ThreadStatus {
642 if self.send_task.is_some() {
643 if self.waiting_for_tool_confirmation() {
644 ThreadStatus::WaitingForToolConfirmation
645 } else {
646 ThreadStatus::Generating
647 }
648 } else {
649 ThreadStatus::Idle
650 }
651 }
652
653 pub fn has_pending_edit_tool_calls(&self) -> bool {
654 for entry in self.entries.iter().rev() {
655 match entry {
656 AgentThreadEntry::UserMessage(_) => return false,
657 AgentThreadEntry::ToolCall(call) if call.first_diff().is_some() => return true,
658 AgentThreadEntry::ToolCall(_) | AgentThreadEntry::AssistantMessage(_) => {}
659 }
660 }
661
662 false
663 }
664
665 pub fn push_entry(&mut self, entry: AgentThreadEntry, cx: &mut Context<Self>) {
666 self.entries.push(entry);
667 cx.emit(AcpThreadEvent::NewEntry);
668 }
669
670 pub fn push_assistant_chunk(
671 &mut self,
672 chunk: acp::ContentBlock,
673 is_thought: bool,
674 cx: &mut Context<Self>,
675 ) {
676 let language_registry = self.project.read(cx).languages().clone();
677 let entries_len = self.entries.len();
678 if let Some(last_entry) = self.entries.last_mut()
679 && let AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) = last_entry
680 {
681 cx.emit(AcpThreadEvent::EntryUpdated(entries_len - 1));
682 match (chunks.last_mut(), is_thought) {
683 (Some(AssistantMessageChunk::Message { block }), false)
684 | (Some(AssistantMessageChunk::Thought { block }), true) => {
685 block.append(chunk, &language_registry, cx)
686 }
687 _ => {
688 let block = ContentBlock::new(chunk, &language_registry, cx);
689 if is_thought {
690 chunks.push(AssistantMessageChunk::Thought { block })
691 } else {
692 chunks.push(AssistantMessageChunk::Message { block })
693 }
694 }
695 }
696 } else {
697 let block = ContentBlock::new(chunk, &language_registry, cx);
698 let chunk = if is_thought {
699 AssistantMessageChunk::Thought { block }
700 } else {
701 AssistantMessageChunk::Message { block }
702 };
703
704 self.push_entry(
705 AgentThreadEntry::AssistantMessage(AssistantMessage {
706 chunks: vec![chunk],
707 }),
708 cx,
709 );
710 }
711 }
712
713 pub fn update_tool_call(
714 &mut self,
715 tool_call: acp::ToolCall,
716 cx: &mut Context<Self>,
717 ) -> Result<()> {
718 let status = ToolCallStatus::Allowed {
719 status: tool_call.status,
720 };
721 self.update_tool_call_inner(tool_call, status, cx)
722 }
723
724 pub fn update_tool_call_inner(
725 &mut self,
726 tool_call: acp::ToolCall,
727 status: ToolCallStatus,
728 cx: &mut Context<Self>,
729 ) -> Result<()> {
730 let language_registry = self.project.read(cx).languages().clone();
731 let call = ToolCall::from_acp(tool_call, status, language_registry, cx);
732
733 let location = call.locations.last().cloned();
734
735 if let Some((ix, current_call)) = self.tool_call_mut(&call.id) {
736 match ¤t_call.status {
737 ToolCallStatus::WaitingForConfirmation { .. } => {
738 anyhow::bail!("Tool call hasn't been authorized yet")
739 }
740 ToolCallStatus::Rejected => {
741 anyhow::bail!("Tool call was rejected and therefore can't be updated")
742 }
743 ToolCallStatus::Allowed { .. } | ToolCallStatus::Canceled => {}
744 }
745
746 *current_call = call;
747
748 cx.emit(AcpThreadEvent::EntryUpdated(ix));
749 } else {
750 self.push_entry(AgentThreadEntry::ToolCall(call), cx);
751 }
752
753 if let Some(location) = location {
754 self.set_project_location(location, cx)
755 }
756
757 Ok(())
758 }
759
760 fn tool_call(&mut self, id: &acp::ToolCallId) -> Option<(usize, &ToolCall)> {
761 // todo! use map
762 self.entries
763 .iter()
764 .enumerate()
765 .rev()
766 .find_map(|(index, tool_call)| {
767 if let AgentThreadEntry::ToolCall(tool_call) = tool_call
768 && &tool_call.id == id
769 {
770 Some((index, tool_call))
771 } else {
772 None
773 }
774 })
775 }
776
777 fn tool_call_mut(&mut self, id: &acp::ToolCallId) -> Option<(usize, &mut ToolCall)> {
778 // todo! use map
779 self.entries
780 .iter_mut()
781 .enumerate()
782 .rev()
783 .find_map(|(index, tool_call)| {
784 if let AgentThreadEntry::ToolCall(tool_call) = tool_call
785 && &tool_call.id == id
786 {
787 Some((index, tool_call))
788 } else {
789 None
790 }
791 })
792 }
793
794 pub fn request_tool_call_permission(
795 &mut self,
796 tool_call: acp::ToolCall,
797 options: Vec<acp::PermissionOption>,
798 cx: &mut Context<Self>,
799 ) -> oneshot::Receiver<acp::PermissionOptionId> {
800 let (tx, rx) = oneshot::channel();
801
802 let status = ToolCallStatus::WaitingForConfirmation {
803 options,
804 respond_tx: tx,
805 };
806
807 self.update_tool_call_inner(tool_call, status, cx);
808 rx
809 }
810
811 pub fn authorize_tool_call(
812 &mut self,
813 id: acp::ToolCallId,
814 option: acp::PermissionOption,
815 cx: &mut Context<Self>,
816 ) {
817 let Some((ix, call)) = self.tool_call_mut(&id) else {
818 return;
819 };
820
821 let new_status = match option.kind {
822 acp::PermissionOptionKind::RejectOnce | acp::PermissionOptionKind::RejectAlways => {
823 ToolCallStatus::Rejected
824 }
825 acp::PermissionOptionKind::AllowOnce | acp::PermissionOptionKind::AllowAlways => {
826 ToolCallStatus::Allowed {
827 status: acp::ToolCallStatus::InProgress,
828 }
829 }
830 };
831
832 let curr_status = mem::replace(&mut call.status, new_status);
833
834 if let ToolCallStatus::WaitingForConfirmation { respond_tx, .. } = curr_status {
835 respond_tx.send(option.id).log_err();
836 } else if cfg!(debug_assertions) {
837 panic!("tried to authorize an already authorized tool call");
838 }
839
840 cx.emit(AcpThreadEvent::EntryUpdated(ix));
841 }
842
843 pub fn plan(&self) -> &Plan {
844 &self.plan
845 }
846
847 pub fn update_plan(&mut self, request: acp::Plan, cx: &mut Context<Self>) {
848 self.plan = Plan {
849 entries: request
850 .entries
851 .into_iter()
852 .map(|entry| PlanEntry::from_acp(entry, cx))
853 .collect(),
854 };
855
856 cx.notify();
857 }
858
859 pub fn clear_completed_plan_entries(&mut self, cx: &mut Context<Self>) {
860 self.plan
861 .entries
862 .retain(|entry| !matches!(entry.status, acp::PlanEntryStatus::Completed));
863 cx.notify();
864 }
865
866 pub fn set_project_location(&self, location: acp::ToolCallLocation, cx: &mut Context<Self>) {
867 self.project.update(cx, |project, cx| {
868 let Some(path) = project.project_path_for_absolute_path(&location.path, cx) else {
869 return;
870 };
871 let buffer = project.open_buffer(path, cx);
872 cx.spawn(async move |project, cx| {
873 let buffer = buffer.await?;
874
875 project.update(cx, |project, cx| {
876 let position = if let Some(line) = location.line {
877 let snapshot = buffer.read(cx).snapshot();
878 let point = snapshot.clip_point(Point::new(line, 0), Bias::Left);
879 snapshot.anchor_before(point)
880 } else {
881 Anchor::MIN
882 };
883
884 project.set_agent_location(
885 Some(AgentLocation {
886 buffer: buffer.downgrade(),
887 position,
888 }),
889 cx,
890 );
891 })
892 })
893 .detach_and_log_err(cx);
894 });
895 }
896
897 /// Returns true if the last turn is awaiting tool authorization
898 pub fn waiting_for_tool_confirmation(&self) -> bool {
899 for entry in self.entries.iter().rev() {
900 match &entry {
901 AgentThreadEntry::ToolCall(call) => match call.status {
902 ToolCallStatus::WaitingForConfirmation { .. } => return true,
903 ToolCallStatus::Allowed { .. }
904 | ToolCallStatus::Rejected
905 | ToolCallStatus::Canceled => continue,
906 },
907 AgentThreadEntry::UserMessage(_) | AgentThreadEntry::AssistantMessage(_) => {
908 // Reached the beginning of the turn
909 return false;
910 }
911 }
912 }
913 false
914 }
915
916 pub fn authenticate(&self) -> impl use<> + Future<Output = Result<()>> {
917 self.connection.authenticate()
918 }
919
920 #[cfg(any(test, feature = "test-support"))]
921 pub fn send_raw(
922 &mut self,
923 message: &str,
924 cx: &mut Context<Self>,
925 ) -> BoxFuture<'static, Result<(), acp_old::Error>> {
926 self.send(
927 vec![acp::ContentBlock::Text(acp::TextContent {
928 text: message.to_string(),
929 annotations: None,
930 })],
931 cx,
932 )
933 }
934
935 pub fn send(
936 &mut self,
937 message: Vec<acp::ContentBlock>,
938 cx: &mut Context<Self>,
939 ) -> BoxFuture<'static, Result<(), acp_old::Error>> {
940 let block = ContentBlock::new_combined(
941 message.clone(),
942 self.project.read(cx).languages().clone(),
943 cx,
944 );
945 self.push_entry(
946 AgentThreadEntry::UserMessage(UserMessage { content: block }),
947 cx,
948 );
949
950 let (tx, rx) = oneshot::channel();
951 let cancel = self.cancel(cx);
952
953 self.send_task = Some(cx.spawn(async move |this, cx| {
954 async {
955 cancel.await.log_err();
956
957 let result = this
958 .update(cx, |this, _| {
959 this.connection.prompt(acp::PromptToolArguments {
960 prompt: message,
961 session_id: this.session_id.clone(),
962 })
963 })?
964 .await;
965 tx.send(result).log_err();
966 this.update(cx, |this, _cx| this.send_task.take())?;
967 anyhow::Ok(())
968 }
969 .await
970 .log_err();
971 }));
972
973 async move {
974 match rx.await {
975 Ok(Err(e)) => Err(e)?,
976 _ => Ok(()),
977 }
978 }
979 .boxed()
980 }
981
982 pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<Result<(), acp_old::Error>> {
983 if self.send_task.take().is_some() {
984 let request = self.connection.cancel();
985 cx.spawn(async move |this, cx| {
986 request.await?;
987 this.update(cx, |this, _cx| {
988 for entry in this.entries.iter_mut() {
989 if let AgentThreadEntry::ToolCall(call) = entry {
990 let cancel = matches!(
991 call.status,
992 ToolCallStatus::WaitingForConfirmation { .. }
993 | ToolCallStatus::Allowed {
994 status: acp::ToolCallStatus::InProgress
995 }
996 );
997
998 if cancel {
999 call.status = ToolCallStatus::Canceled;
1000 }
1001 }
1002 }
1003 })?;
1004 Ok(())
1005 })
1006 } else {
1007 Task::ready(Ok(()))
1008 }
1009 }
1010
1011 pub fn read_text_file(
1012 &self,
1013 request: acp::ReadTextFileArguments,
1014 reuse_shared_snapshot: bool,
1015 cx: &mut Context<Self>,
1016 ) -> Task<Result<String>> {
1017 let project = self.project.clone();
1018 let action_log = self.action_log.clone();
1019 cx.spawn(async move |this, cx| {
1020 let load = project.update(cx, |project, cx| {
1021 let path = project
1022 .project_path_for_absolute_path(&request.path, cx)
1023 .context("invalid path")?;
1024 anyhow::Ok(project.open_buffer(path, cx))
1025 });
1026 let buffer = load??.await?;
1027
1028 let snapshot = if reuse_shared_snapshot {
1029 this.read_with(cx, |this, _| {
1030 this.shared_buffers.get(&buffer.clone()).cloned()
1031 })
1032 .log_err()
1033 .flatten()
1034 } else {
1035 None
1036 };
1037
1038 let snapshot = if let Some(snapshot) = snapshot {
1039 snapshot
1040 } else {
1041 action_log.update(cx, |action_log, cx| {
1042 action_log.buffer_read(buffer.clone(), cx);
1043 })?;
1044 project.update(cx, |project, cx| {
1045 let position = buffer
1046 .read(cx)
1047 .snapshot()
1048 .anchor_before(Point::new(request.line.unwrap_or_default(), 0));
1049 project.set_agent_location(
1050 Some(AgentLocation {
1051 buffer: buffer.downgrade(),
1052 position,
1053 }),
1054 cx,
1055 );
1056 })?;
1057
1058 buffer.update(cx, |buffer, _| buffer.snapshot())?
1059 };
1060
1061 this.update(cx, |this, _| {
1062 let text = snapshot.text();
1063 this.shared_buffers.insert(buffer.clone(), snapshot);
1064 if request.line.is_none() && request.limit.is_none() {
1065 return Ok(text);
1066 }
1067 let limit = request.limit.unwrap_or(u32::MAX) as usize;
1068 let Some(line) = request.line else {
1069 return Ok(text.lines().take(limit).collect::<String>());
1070 };
1071
1072 let count = text.lines().count();
1073 if count < line as usize {
1074 anyhow::bail!("There are only {} lines", count);
1075 }
1076 Ok(text
1077 .lines()
1078 .skip(line as usize + 1)
1079 .take(limit)
1080 .collect::<String>())
1081 })?
1082 })
1083 }
1084
1085 pub fn write_text_file(
1086 &self,
1087 request: acp::WriteTextFileToolArguments,
1088 cx: &mut Context<Self>,
1089 ) -> Task<Result<()>> {
1090 let project = self.project.clone();
1091 let action_log = self.action_log.clone();
1092 cx.spawn(async move |this, cx| {
1093 let load = project.update(cx, |project, cx| {
1094 let path = project
1095 .project_path_for_absolute_path(&request.path, cx)
1096 .context("invalid path")?;
1097 anyhow::Ok(project.open_buffer(path, cx))
1098 });
1099 let buffer = load??.await?;
1100 let snapshot = this.update(cx, |this, cx| {
1101 this.shared_buffers
1102 .get(&buffer)
1103 .cloned()
1104 .unwrap_or_else(|| buffer.read(cx).snapshot())
1105 })?;
1106 let edits = cx
1107 .background_executor()
1108 .spawn(async move {
1109 let old_text = snapshot.text();
1110 text_diff(old_text.as_str(), &request.content)
1111 .into_iter()
1112 .map(|(range, replacement)| {
1113 (
1114 snapshot.anchor_after(range.start)
1115 ..snapshot.anchor_before(range.end),
1116 replacement,
1117 )
1118 })
1119 .collect::<Vec<_>>()
1120 })
1121 .await;
1122 cx.update(|cx| {
1123 project.update(cx, |project, cx| {
1124 project.set_agent_location(
1125 Some(AgentLocation {
1126 buffer: buffer.downgrade(),
1127 position: edits
1128 .last()
1129 .map(|(range, _)| range.end)
1130 .unwrap_or(Anchor::MIN),
1131 }),
1132 cx,
1133 );
1134 });
1135
1136 action_log.update(cx, |action_log, cx| {
1137 action_log.buffer_read(buffer.clone(), cx);
1138 });
1139 buffer.update(cx, |buffer, cx| {
1140 buffer.edit(edits, None, cx);
1141 });
1142 action_log.update(cx, |action_log, cx| {
1143 action_log.buffer_edited(buffer.clone(), cx);
1144 });
1145 })?;
1146 project
1147 .update(cx, |project, cx| project.save_buffer(buffer, cx))?
1148 .await
1149 })
1150 }
1151
1152 pub fn child_status(&mut self) -> Option<Task<Result<()>>> {
1153 self.child_status.take()
1154 }
1155
1156 pub fn to_markdown(&self, cx: &App) -> String {
1157 self.entries.iter().map(|e| e.to_markdown(cx)).collect()
1158 }
1159}
1160
1161#[derive(Clone)]
1162pub struct OldAcpClientDelegate {
1163 thread: WeakEntity<AcpThread>,
1164 cx: AsyncApp,
1165 next_tool_call_id: Rc<RefCell<u64>>,
1166 // sent_buffer_versions: HashMap<Entity<Buffer>, HashMap<u64, BufferSnapshot>>,
1167}
1168
1169impl OldAcpClientDelegate {
1170 pub fn new(thread: WeakEntity<AcpThread>, cx: AsyncApp) -> Self {
1171 Self {
1172 thread,
1173 cx,
1174 next_tool_call_id: Rc::new(RefCell::new(0)),
1175 }
1176 }
1177
1178 pub async fn clear_completed_plan_entries(&self) -> Result<()> {
1179 let cx = &mut self.cx.clone();
1180 cx.update(|cx| {
1181 self.thread
1182 .update(cx, |thread, cx| thread.clear_completed_plan_entries(cx))
1183 })?
1184 .context("Failed to update thread")?;
1185
1186 Ok(())
1187 }
1188
1189 pub async fn read_text_file_reusing_snapshot(
1190 &self,
1191 request: acp_old::ReadTextFileParams,
1192 ) -> Result<acp_old::ReadTextFileResponse, acp_old::Error> {
1193 let content = self
1194 .cx
1195 .update(|cx| {
1196 self.thread.update(cx, |thread, cx| {
1197 thread.read_text_file(
1198 acp::ReadTextFileArguments {
1199 path: request.path,
1200 line: request.line,
1201 limit: request.limit,
1202 },
1203 true,
1204 cx,
1205 )
1206 })
1207 })?
1208 .context("Failed to update thread")?
1209 .await?;
1210 Ok(acp_old::ReadTextFileResponse { content })
1211 }
1212}
1213impl acp_old::Client for OldAcpClientDelegate {
1214 async fn stream_assistant_message_chunk(
1215 &self,
1216 params: acp_old::StreamAssistantMessageChunkParams,
1217 ) -> Result<(), acp_old::Error> {
1218 let cx = &mut self.cx.clone();
1219
1220 cx.update(|cx| {
1221 self.thread
1222 .update(cx, |thread, cx| match params.chunk {
1223 acp_old::AssistantMessageChunk::Text { text } => {
1224 thread.push_assistant_chunk(text.into(), false, cx)
1225 }
1226 acp_old::AssistantMessageChunk::Thought { thought } => {
1227 thread.push_assistant_chunk(thought.into(), true, cx)
1228 }
1229 })
1230 .ok();
1231 })?;
1232
1233 Ok(())
1234 }
1235
1236 async fn request_tool_call_confirmation(
1237 &self,
1238 request: acp_old::RequestToolCallConfirmationParams,
1239 ) -> Result<acp_old::RequestToolCallConfirmationResponse, acp_old::Error> {
1240 let cx = &mut self.cx.clone();
1241
1242 let old_acp_id = *self.next_tool_call_id.borrow() + 1;
1243 self.next_tool_call_id.replace(old_acp_id);
1244
1245 let tool_call = into_new_tool_call(
1246 acp::ToolCallId(old_acp_id.to_string().into()),
1247 request.tool_call,
1248 );
1249
1250 let mut options = match request.confirmation {
1251 acp_old::ToolCallConfirmation::Edit { .. } => vec![(
1252 acp_old::ToolCallConfirmationOutcome::AlwaysAllow,
1253 acp::PermissionOptionKind::AllowAlways,
1254 "Always Allow Edits".to_string(),
1255 )],
1256 acp_old::ToolCallConfirmation::Execute { root_command, .. } => vec![(
1257 acp_old::ToolCallConfirmationOutcome::AlwaysAllow,
1258 acp::PermissionOptionKind::AllowAlways,
1259 format!("Always Allow {}", root_command),
1260 )],
1261 acp_old::ToolCallConfirmation::Mcp {
1262 server_name,
1263 tool_name,
1264 ..
1265 } => vec![
1266 (
1267 acp_old::ToolCallConfirmationOutcome::AlwaysAllowMcpServer,
1268 acp::PermissionOptionKind::AllowAlways,
1269 format!("Always Allow {}", server_name),
1270 ),
1271 (
1272 acp_old::ToolCallConfirmationOutcome::AlwaysAllowTool,
1273 acp::PermissionOptionKind::AllowAlways,
1274 format!("Always Allow {}", tool_name),
1275 ),
1276 ],
1277 acp_old::ToolCallConfirmation::Fetch { .. } => vec![(
1278 acp_old::ToolCallConfirmationOutcome::AlwaysAllow,
1279 acp::PermissionOptionKind::AllowAlways,
1280 "Always Allow".to_string(),
1281 )],
1282 acp_old::ToolCallConfirmation::Other { .. } => vec![(
1283 acp_old::ToolCallConfirmationOutcome::AlwaysAllow,
1284 acp::PermissionOptionKind::AllowAlways,
1285 "Always Allow".to_string(),
1286 )],
1287 };
1288
1289 options.extend([
1290 (
1291 acp_old::ToolCallConfirmationOutcome::Allow,
1292 acp::PermissionOptionKind::AllowOnce,
1293 "Allow".to_string(),
1294 ),
1295 (
1296 acp_old::ToolCallConfirmationOutcome::Reject,
1297 acp::PermissionOptionKind::RejectOnce,
1298 "Reject".to_string(),
1299 ),
1300 ]);
1301
1302 let mut outcomes = Vec::with_capacity(options.len());
1303 let mut acp_options = Vec::with_capacity(options.len());
1304
1305 for (index, (outcome, kind, label)) in options.into_iter().enumerate() {
1306 outcomes.push(outcome);
1307 acp_options.push(acp::PermissionOption {
1308 id: acp::PermissionOptionId(index.to_string().into()),
1309 label,
1310 kind,
1311 })
1312 }
1313
1314 let response = cx
1315 .update(|cx| {
1316 self.thread.update(cx, |thread, cx| {
1317 thread.request_tool_call_permission(tool_call, acp_options, cx)
1318 })
1319 })?
1320 .context("Failed to update thread")?
1321 .await;
1322
1323 let outcome = match response {
1324 Ok(option_id) => outcomes[option_id.0.parse::<usize>().unwrap_or(0)].clone(),
1325 Err(oneshot::Canceled) => acp_old::ToolCallConfirmationOutcome::Cancel,
1326 };
1327
1328 Ok(acp_old::RequestToolCallConfirmationResponse {
1329 id: acp_old::ToolCallId(old_acp_id),
1330 outcome: outcome,
1331 })
1332 }
1333
1334 async fn push_tool_call(
1335 &self,
1336 request: acp_old::PushToolCallParams,
1337 ) -> Result<acp_old::PushToolCallResponse, acp_old::Error> {
1338 let cx = &mut self.cx.clone();
1339
1340 let old_acp_id = *self.next_tool_call_id.borrow() + 1;
1341 self.next_tool_call_id.replace(old_acp_id);
1342
1343 cx.update(|cx| {
1344 self.thread.update(cx, |thread, cx| {
1345 thread.update_tool_call(
1346 into_new_tool_call(acp::ToolCallId(old_acp_id.to_string().into()), request),
1347 cx,
1348 )
1349 })
1350 })?
1351 .context("Failed to update thread")??;
1352
1353 Ok(acp_old::PushToolCallResponse {
1354 id: acp_old::ToolCallId(old_acp_id),
1355 })
1356 }
1357
1358 async fn update_tool_call(
1359 &self,
1360 request: acp_old::UpdateToolCallParams,
1361 ) -> Result<(), acp_old::Error> {
1362 let cx = &mut self.cx.clone();
1363
1364 cx.update(|cx| {
1365 self.thread.update(cx, |thread, cx| {
1366 let languages = thread.project.read(cx).languages().clone();
1367
1368 if let Some((ix, tool_call)) = thread
1369 .tool_call_mut(&acp::ToolCallId(request.tool_call_id.0.to_string().into()))
1370 {
1371 tool_call.status = ToolCallStatus::Allowed {
1372 status: into_new_tool_call_status(request.status),
1373 };
1374 tool_call.content = request
1375 .content
1376 .into_iter()
1377 .map(|content| {
1378 ToolCallContent::from_acp(
1379 into_new_tool_call_content(content),
1380 languages.clone(),
1381 cx,
1382 )
1383 })
1384 .collect();
1385
1386 cx.emit(AcpThreadEvent::EntryUpdated(ix));
1387 anyhow::Ok(())
1388 } else {
1389 anyhow::bail!("Tool call not found")
1390 }
1391 })
1392 })?
1393 .context("Failed to update thread")??;
1394
1395 Ok(())
1396 }
1397
1398 async fn update_plan(&self, request: acp_old::UpdatePlanParams) -> Result<(), acp_old::Error> {
1399 let cx = &mut self.cx.clone();
1400
1401 cx.update(|cx| {
1402 self.thread.update(cx, |thread, cx| {
1403 thread.update_plan(
1404 acp::Plan {
1405 entries: request
1406 .entries
1407 .into_iter()
1408 .map(into_new_plan_entry)
1409 .collect(),
1410 },
1411 cx,
1412 )
1413 })
1414 })?
1415 .context("Failed to update thread")?;
1416
1417 Ok(())
1418 }
1419
1420 async fn read_text_file(
1421 &self,
1422 request: acp_old::ReadTextFileParams,
1423 ) -> Result<acp_old::ReadTextFileResponse, acp_old::Error> {
1424 let content = self
1425 .cx
1426 .update(|cx| {
1427 self.thread.update(cx, |thread, cx| {
1428 thread.read_text_file(
1429 acp::ReadTextFileArguments {
1430 path: request.path,
1431 line: request.line,
1432 limit: request.limit,
1433 },
1434 false,
1435 cx,
1436 )
1437 })
1438 })?
1439 .context("Failed to update thread")?
1440 .await?;
1441 Ok(acp_old::ReadTextFileResponse { content })
1442 }
1443
1444 async fn write_text_file(
1445 &self,
1446 request: acp_old::WriteTextFileParams,
1447 ) -> Result<(), acp_old::Error> {
1448 self.cx
1449 .update(|cx| {
1450 self.thread.update(cx, |thread, cx| {
1451 thread.write_text_file(
1452 acp::WriteTextFileToolArguments {
1453 path: request.path,
1454 content: request.content,
1455 },
1456 cx,
1457 )
1458 })
1459 })?
1460 .context("Failed to update thread")?
1461 .await?;
1462
1463 Ok(())
1464 }
1465}
1466
1467fn into_new_tool_call(id: acp::ToolCallId, request: acp_old::PushToolCallParams) -> acp::ToolCall {
1468 acp::ToolCall {
1469 id: id,
1470 label: request.label,
1471 kind: acp_kind_from_old_icon(request.icon),
1472 status: acp::ToolCallStatus::InProgress,
1473 content: request
1474 .content
1475 .into_iter()
1476 .map(into_new_tool_call_content)
1477 .collect(),
1478 locations: request
1479 .locations
1480 .into_iter()
1481 .map(into_new_tool_call_location)
1482 .collect(),
1483 }
1484}
1485
1486fn acp_kind_from_old_icon(icon: acp_old::Icon) -> acp::ToolKind {
1487 match icon {
1488 acp_old::Icon::FileSearch => acp::ToolKind::Search,
1489 acp_old::Icon::Folder => acp::ToolKind::Search,
1490 acp_old::Icon::Globe => acp::ToolKind::Search,
1491 acp_old::Icon::Hammer => acp::ToolKind::Other,
1492 acp_old::Icon::LightBulb => acp::ToolKind::Think,
1493 acp_old::Icon::Pencil => acp::ToolKind::Edit,
1494 acp_old::Icon::Regex => acp::ToolKind::Search,
1495 acp_old::Icon::Terminal => acp::ToolKind::Execute,
1496 }
1497}
1498
1499fn into_new_tool_call_status(status: acp_old::ToolCallStatus) -> acp::ToolCallStatus {
1500 match status {
1501 acp_old::ToolCallStatus::Running => acp::ToolCallStatus::InProgress,
1502 acp_old::ToolCallStatus::Finished => acp::ToolCallStatus::Completed,
1503 acp_old::ToolCallStatus::Error => acp::ToolCallStatus::Failed,
1504 }
1505}
1506
1507fn into_new_tool_call_content(content: acp_old::ToolCallContent) -> acp::ToolCallContent {
1508 match content {
1509 acp_old::ToolCallContent::Markdown { markdown } => acp::ToolCallContent::ContentBlock {
1510 content: acp::ContentBlock::Text(acp::TextContent {
1511 annotations: None,
1512 text: markdown,
1513 }),
1514 },
1515 acp_old::ToolCallContent::Diff { diff } => acp::ToolCallContent::Diff {
1516 diff: into_new_diff(diff),
1517 },
1518 }
1519}
1520
1521fn into_new_diff(diff: acp_old::Diff) -> acp::Diff {
1522 acp::Diff {
1523 path: diff.path,
1524 old_text: diff.old_text,
1525 new_text: diff.new_text,
1526 }
1527}
1528
1529fn into_new_tool_call_location(location: acp_old::ToolCallLocation) -> acp::ToolCallLocation {
1530 acp::ToolCallLocation {
1531 path: location.path,
1532 line: location.line,
1533 }
1534}
1535
1536fn into_new_plan(request: acp_old::UpdatePlanParams) -> acp::Plan {
1537 acp::Plan {
1538 entries: request
1539 .entries
1540 .into_iter()
1541 .map(into_new_plan_entry)
1542 .collect(),
1543 }
1544}
1545
1546fn into_new_plan_entry(entry: acp_old::PlanEntry) -> acp::PlanEntry {
1547 acp::PlanEntry {
1548 content: entry.content,
1549 priority: into_new_plan_priority(entry.priority),
1550 status: into_new_plan_status(entry.status),
1551 }
1552}
1553
1554fn into_new_plan_priority(priority: acp_old::PlanEntryPriority) -> acp::PlanEntryPriority {
1555 match priority {
1556 acp_old::PlanEntryPriority::Low => acp::PlanEntryPriority::Low,
1557 acp_old::PlanEntryPriority::Medium => acp::PlanEntryPriority::Medium,
1558 acp_old::PlanEntryPriority::High => acp::PlanEntryPriority::High,
1559 }
1560}
1561
1562fn into_new_plan_status(status: acp_old::PlanEntryStatus) -> acp::PlanEntryStatus {
1563 match status {
1564 acp_old::PlanEntryStatus::Pending => acp::PlanEntryStatus::Pending,
1565 acp_old::PlanEntryStatus::InProgress => acp::PlanEntryStatus::InProgress,
1566 acp_old::PlanEntryStatus::Completed => acp::PlanEntryStatus::Completed,
1567 }
1568}
1569
1570#[cfg(test)]
1571mod tests {
1572 use super::*;
1573 use anyhow::anyhow;
1574 use async_pipe::{PipeReader, PipeWriter};
1575 use futures::{channel::mpsc, future::LocalBoxFuture, select};
1576 use gpui::{AsyncApp, TestAppContext};
1577 use indoc::indoc;
1578 use project::FakeFs;
1579 use serde_json::json;
1580 use settings::SettingsStore;
1581 use smol::{future::BoxedLocal, stream::StreamExt as _};
1582 use std::{cell::RefCell, rc::Rc, time::Duration};
1583 use util::path;
1584
1585 fn init_test(cx: &mut TestAppContext) {
1586 env_logger::try_init().ok();
1587 cx.update(|cx| {
1588 let settings_store = SettingsStore::test(cx);
1589 cx.set_global(settings_store);
1590 Project::init_settings(cx);
1591 language::init(cx);
1592 });
1593 }
1594
1595 #[gpui::test]
1596 async fn test_thinking_concatenation(cx: &mut TestAppContext) {
1597 init_test(cx);
1598
1599 let fs = FakeFs::new(cx.executor());
1600 let project = Project::test(fs, [], cx).await;
1601 let (thread, fake_server) = fake_acp_thread(project, cx);
1602
1603 fake_server.update(cx, |fake_server, _| {
1604 fake_server.on_user_message(move |_, server, mut cx| async move {
1605 server
1606 .update(&mut cx, |server, _| {
1607 server.send_to_zed(acp_old::StreamAssistantMessageChunkParams {
1608 chunk: acp_old::AssistantMessageChunk::Thought {
1609 thought: "Thinking ".into(),
1610 },
1611 })
1612 })?
1613 .await
1614 .unwrap();
1615 server
1616 .update(&mut cx, |server, _| {
1617 server.send_to_zed(acp_old::StreamAssistantMessageChunkParams {
1618 chunk: acp_old::AssistantMessageChunk::Thought {
1619 thought: "hard!".into(),
1620 },
1621 })
1622 })?
1623 .await
1624 .unwrap();
1625
1626 Ok(())
1627 })
1628 });
1629
1630 thread
1631 .update(cx, |thread, cx| thread.send_raw("Hello from Zed!", cx))
1632 .await
1633 .unwrap();
1634
1635 let output = thread.read_with(cx, |thread, cx| thread.to_markdown(cx));
1636 assert_eq!(
1637 output,
1638 indoc! {r#"
1639 ## User
1640
1641 Hello from Zed!
1642
1643 ## Assistant
1644
1645 <thinking>
1646 Thinking hard!
1647 </thinking>
1648
1649 "#}
1650 );
1651 }
1652
1653 #[gpui::test]
1654 async fn test_edits_concurrently_to_user(cx: &mut TestAppContext) {
1655 init_test(cx);
1656
1657 let fs = FakeFs::new(cx.executor());
1658 fs.insert_tree(path!("/tmp"), json!({"foo": "one\ntwo\nthree\n"}))
1659 .await;
1660 let project = Project::test(fs.clone(), [], cx).await;
1661 let (thread, fake_server) = fake_acp_thread(project.clone(), cx);
1662 let (worktree, pathbuf) = project
1663 .update(cx, |project, cx| {
1664 project.find_or_create_worktree(path!("/tmp/foo"), true, cx)
1665 })
1666 .await
1667 .unwrap();
1668 let buffer = project
1669 .update(cx, |project, cx| {
1670 project.open_buffer((worktree.read(cx).id(), pathbuf), cx)
1671 })
1672 .await
1673 .unwrap();
1674
1675 let (read_file_tx, read_file_rx) = oneshot::channel::<()>();
1676 let read_file_tx = Rc::new(RefCell::new(Some(read_file_tx)));
1677
1678 fake_server.update(cx, |fake_server, _| {
1679 fake_server.on_user_message(move |_, server, mut cx| {
1680 let read_file_tx = read_file_tx.clone();
1681 async move {
1682 let content = server
1683 .update(&mut cx, |server, _| {
1684 server.send_to_zed(acp_old::ReadTextFileParams {
1685 path: path!("/tmp/foo").into(),
1686 line: None,
1687 limit: None,
1688 })
1689 })?
1690 .await
1691 .unwrap();
1692 assert_eq!(content.content, "one\ntwo\nthree\n");
1693 read_file_tx.take().unwrap().send(()).unwrap();
1694 server
1695 .update(&mut cx, |server, _| {
1696 server.send_to_zed(acp_old::WriteTextFileParams {
1697 path: path!("/tmp/foo").into(),
1698 content: "one\ntwo\nthree\nfour\nfive\n".to_string(),
1699 })
1700 })?
1701 .await
1702 .unwrap();
1703 Ok(())
1704 }
1705 })
1706 });
1707
1708 let request = thread.update(cx, |thread, cx| {
1709 thread.send_raw("Extend the count in /tmp/foo", cx)
1710 });
1711 read_file_rx.await.ok();
1712 buffer.update(cx, |buffer, cx| {
1713 buffer.edit([(0..0, "zero\n".to_string())], None, cx);
1714 });
1715 cx.run_until_parked();
1716 assert_eq!(
1717 buffer.read_with(cx, |buffer, _| buffer.text()),
1718 "zero\none\ntwo\nthree\nfour\nfive\n"
1719 );
1720 assert_eq!(
1721 String::from_utf8(fs.read_file_sync(path!("/tmp/foo")).unwrap()).unwrap(),
1722 "zero\none\ntwo\nthree\nfour\nfive\n"
1723 );
1724 request.await.unwrap();
1725 }
1726
1727 #[gpui::test]
1728 async fn test_succeeding_canceled_toolcall(cx: &mut TestAppContext) {
1729 init_test(cx);
1730
1731 let fs = FakeFs::new(cx.executor());
1732 let project = Project::test(fs, [], cx).await;
1733 let (thread, fake_server) = fake_acp_thread(project, cx);
1734
1735 let (end_turn_tx, end_turn_rx) = oneshot::channel::<()>();
1736
1737 let tool_call_id = Rc::new(RefCell::new(None));
1738 let end_turn_rx = Rc::new(RefCell::new(Some(end_turn_rx)));
1739 fake_server.update(cx, |fake_server, _| {
1740 let tool_call_id = tool_call_id.clone();
1741 fake_server.on_user_message(move |_, server, mut cx| {
1742 let end_turn_rx = end_turn_rx.clone();
1743 let tool_call_id = tool_call_id.clone();
1744 async move {
1745 let tool_call_result = server
1746 .update(&mut cx, |server, _| {
1747 server.send_to_zed(acp_old::PushToolCallParams {
1748 label: "Fetch".to_string(),
1749 icon: acp_old::Icon::Globe,
1750 content: None,
1751 locations: vec![],
1752 })
1753 })?
1754 .await
1755 .unwrap();
1756 *tool_call_id.clone().borrow_mut() = Some(tool_call_result.id);
1757 end_turn_rx.take().unwrap().await.ok();
1758
1759 Ok(())
1760 }
1761 })
1762 });
1763
1764 let request = thread.update(cx, |thread, cx| {
1765 thread.send_raw("Fetch https://example.com", cx)
1766 });
1767
1768 run_until_first_tool_call(&thread, cx).await;
1769
1770 thread.read_with(cx, |thread, _| {
1771 assert!(matches!(
1772 thread.entries[1],
1773 AgentThreadEntry::ToolCall(ToolCall {
1774 status: ToolCallStatus::Allowed {
1775 status: acp::ToolCallStatus::InProgress,
1776 ..
1777 },
1778 ..
1779 })
1780 ));
1781 });
1782
1783 cx.run_until_parked();
1784
1785 thread
1786 .update(cx, |thread, cx| thread.cancel(cx))
1787 .await
1788 .unwrap();
1789
1790 thread.read_with(cx, |thread, _| {
1791 assert!(matches!(
1792 &thread.entries[1],
1793 AgentThreadEntry::ToolCall(ToolCall {
1794 status: ToolCallStatus::Canceled,
1795 ..
1796 })
1797 ));
1798 });
1799
1800 fake_server
1801 .update(cx, |fake_server, _| {
1802 fake_server.send_to_zed(acp_old::UpdateToolCallParams {
1803 tool_call_id: tool_call_id.borrow().unwrap(),
1804 status: acp_old::ToolCallStatus::Finished,
1805 content: None,
1806 })
1807 })
1808 .await
1809 .unwrap();
1810
1811 drop(end_turn_tx);
1812 request.await.unwrap();
1813
1814 thread.read_with(cx, |thread, _| {
1815 assert!(matches!(
1816 thread.entries[1],
1817 AgentThreadEntry::ToolCall(ToolCall {
1818 status: ToolCallStatus::Allowed {
1819 status: acp::ToolCallStatus::Completed,
1820 ..
1821 },
1822 ..
1823 })
1824 ));
1825 });
1826 }
1827
1828 async fn run_until_first_tool_call(
1829 thread: &Entity<AcpThread>,
1830 cx: &mut TestAppContext,
1831 ) -> usize {
1832 let (mut tx, mut rx) = mpsc::channel::<usize>(1);
1833
1834 let subscription = cx.update(|cx| {
1835 cx.subscribe(thread, move |thread, _, cx| {
1836 for (ix, entry) in thread.read(cx).entries.iter().enumerate() {
1837 if matches!(entry, AgentThreadEntry::ToolCall(_)) {
1838 return tx.try_send(ix).unwrap();
1839 }
1840 }
1841 })
1842 });
1843
1844 select! {
1845 _ = futures::FutureExt::fuse(smol::Timer::after(Duration::from_secs(10))) => {
1846 panic!("Timeout waiting for tool call")
1847 }
1848 ix = rx.next().fuse() => {
1849 drop(subscription);
1850 ix.unwrap()
1851 }
1852 }
1853 }
1854
1855 pub fn fake_acp_thread(
1856 project: Entity<Project>,
1857 cx: &mut TestAppContext,
1858 ) -> (Entity<AcpThread>, Entity<FakeAcpServer>) {
1859 let (stdin_tx, stdin_rx) = async_pipe::pipe();
1860 let (stdout_tx, stdout_rx) = async_pipe::pipe();
1861
1862 let thread = cx.new(|cx| {
1863 let foreground_executor = cx.foreground_executor().clone();
1864 let (connection, io_fut) = acp_old::AgentConnection::connect_to_agent(
1865 OldAcpClientDelegate::new(cx.entity().downgrade(), cx.to_async()),
1866 stdin_tx,
1867 stdout_rx,
1868 move |fut| {
1869 foreground_executor.spawn(fut).detach();
1870 },
1871 );
1872
1873 let io_task = cx.background_spawn({
1874 async move {
1875 io_fut.await.log_err();
1876 Ok(())
1877 }
1878 });
1879 AcpThread::new(
1880 connection,
1881 "Test".into(),
1882 Some(io_task),
1883 project,
1884 acp::SessionId("test".into()),
1885 cx,
1886 )
1887 });
1888 let agent = cx.update(|cx| cx.new(|cx| FakeAcpServer::new(stdin_rx, stdout_tx, cx)));
1889 (thread, agent)
1890 }
1891
1892 pub struct FakeAcpServer {
1893 connection: acp_old::ClientConnection,
1894
1895 _io_task: Task<()>,
1896 on_user_message: Option<
1897 Rc<
1898 dyn Fn(
1899 acp_old::SendUserMessageParams,
1900 Entity<FakeAcpServer>,
1901 AsyncApp,
1902 ) -> LocalBoxFuture<'static, Result<(), acp_old::Error>>,
1903 >,
1904 >,
1905 }
1906
1907 #[derive(Clone)]
1908 struct FakeAgent {
1909 server: Entity<FakeAcpServer>,
1910 cx: AsyncApp,
1911 }
1912
1913 impl acp_old::Agent for FakeAgent {
1914 async fn initialize(
1915 &self,
1916 params: acp_old::InitializeParams,
1917 ) -> Result<acp_old::InitializeResponse, acp_old::Error> {
1918 Ok(acp_old::InitializeResponse {
1919 protocol_version: params.protocol_version,
1920 is_authenticated: true,
1921 })
1922 }
1923
1924 async fn authenticate(&self) -> Result<(), acp_old::Error> {
1925 Ok(())
1926 }
1927
1928 async fn cancel_send_message(&self) -> Result<(), acp_old::Error> {
1929 Ok(())
1930 }
1931
1932 async fn send_user_message(
1933 &self,
1934 request: acp_old::SendUserMessageParams,
1935 ) -> Result<(), acp_old::Error> {
1936 let mut cx = self.cx.clone();
1937 let handler = self
1938 .server
1939 .update(&mut cx, |server, _| server.on_user_message.clone())
1940 .ok()
1941 .flatten();
1942 if let Some(handler) = handler {
1943 handler(request, self.server.clone(), self.cx.clone()).await
1944 } else {
1945 Err(anyhow::anyhow!("No handler for on_user_message").into())
1946 }
1947 }
1948 }
1949
1950 impl FakeAcpServer {
1951 fn new(stdin: PipeReader, stdout: PipeWriter, cx: &Context<Self>) -> Self {
1952 let agent = FakeAgent {
1953 server: cx.entity(),
1954 cx: cx.to_async(),
1955 };
1956 let foreground_executor = cx.foreground_executor().clone();
1957
1958 let (connection, io_fut) = acp_old::ClientConnection::connect_to_client(
1959 agent.clone(),
1960 stdout,
1961 stdin,
1962 move |fut| {
1963 foreground_executor.spawn(fut).detach();
1964 },
1965 );
1966 FakeAcpServer {
1967 connection: connection,
1968 on_user_message: None,
1969 _io_task: cx.background_spawn(async move {
1970 io_fut.await.log_err();
1971 }),
1972 }
1973 }
1974
1975 fn on_user_message<F>(
1976 &mut self,
1977 handler: impl for<'a> Fn(
1978 acp_old::SendUserMessageParams,
1979 Entity<FakeAcpServer>,
1980 AsyncApp,
1981 ) -> F
1982 + 'static,
1983 ) where
1984 F: Future<Output = Result<(), acp_old::Error>> + 'static,
1985 {
1986 self.on_user_message
1987 .replace(Rc::new(move |request, server, cx| {
1988 handler(request, server, cx).boxed_local()
1989 }));
1990 }
1991
1992 fn send_to_zed<T: acp_old::ClientRequest + 'static>(
1993 &self,
1994 message: T,
1995 ) -> BoxedLocal<Result<T::Response>> {
1996 self.connection
1997 .request(message)
1998 .map(|f| f.map_err(|err| anyhow!(err)))
1999 .boxed_local()
2000 }
2001 }
2002}