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