1mod connection;
2mod diff;
3mod mention;
4mod terminal;
5
6pub use connection::*;
7pub use diff::*;
8pub use mention::*;
9pub use terminal::*;
10
11use action_log::ActionLog;
12use agent_client_protocol as acp;
13use anyhow::{Context as _, Result, anyhow};
14use editor::Bias;
15use futures::{FutureExt, channel::oneshot, future::BoxFuture};
16use gpui::{AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task, WeakEntity};
17use itertools::Itertools;
18use language::{Anchor, Buffer, BufferSnapshot, LanguageRegistry, Point, ToPoint, text_diff};
19use markdown::Markdown;
20use project::{AgentLocation, Project, git_store::GitStoreCheckpoint};
21use std::collections::HashMap;
22use std::error::Error;
23use std::fmt::{Formatter, Write};
24use std::ops::Range;
25use std::process::ExitStatus;
26use std::rc::Rc;
27use std::{fmt::Display, mem, path::PathBuf, sync::Arc};
28use ui::App;
29use util::ResultExt;
30
31#[derive(Debug)]
32pub struct UserMessage {
33 pub id: Option<UserMessageId>,
34 pub content: ContentBlock,
35 pub chunks: Vec<acp::ContentBlock>,
36 pub checkpoint: Option<Checkpoint>,
37}
38
39#[derive(Debug)]
40pub struct Checkpoint {
41 git_checkpoint: GitStoreCheckpoint,
42 pub show: bool,
43}
44
45impl UserMessage {
46 fn to_markdown(&self, cx: &App) -> String {
47 let mut markdown = String::new();
48 if self
49 .checkpoint
50 .as_ref()
51 .map_or(false, |checkpoint| checkpoint.show)
52 {
53 writeln!(markdown, "## User (checkpoint)").unwrap();
54 } else {
55 writeln!(markdown, "## User").unwrap();
56 }
57 writeln!(markdown).unwrap();
58 writeln!(markdown, "{}", self.content.to_markdown(cx)).unwrap();
59 writeln!(markdown).unwrap();
60 markdown
61 }
62}
63
64#[derive(Debug, PartialEq)]
65pub struct AssistantMessage {
66 pub chunks: Vec<AssistantMessageChunk>,
67}
68
69impl AssistantMessage {
70 pub fn to_markdown(&self, cx: &App) -> String {
71 format!(
72 "## Assistant\n\n{}\n\n",
73 self.chunks
74 .iter()
75 .map(|chunk| chunk.to_markdown(cx))
76 .join("\n\n")
77 )
78 }
79}
80
81#[derive(Debug, PartialEq)]
82pub enum AssistantMessageChunk {
83 Message { block: ContentBlock },
84 Thought { block: ContentBlock },
85}
86
87impl AssistantMessageChunk {
88 pub fn from_str(chunk: &str, language_registry: &Arc<LanguageRegistry>, cx: &mut App) -> Self {
89 Self::Message {
90 block: ContentBlock::new(chunk.into(), language_registry, cx),
91 }
92 }
93
94 fn to_markdown(&self, cx: &App) -> String {
95 match self {
96 Self::Message { block } => block.to_markdown(cx).to_string(),
97 Self::Thought { block } => {
98 format!("<thinking>\n{}\n</thinking>", block.to_markdown(cx))
99 }
100 }
101 }
102}
103
104#[derive(Debug)]
105pub enum AgentThreadEntry {
106 UserMessage(UserMessage),
107 AssistantMessage(AssistantMessage),
108 ToolCall(ToolCall),
109}
110
111impl AgentThreadEntry {
112 pub fn to_markdown(&self, cx: &App) -> String {
113 match self {
114 Self::UserMessage(message) => message.to_markdown(cx),
115 Self::AssistantMessage(message) => message.to_markdown(cx),
116 Self::ToolCall(tool_call) => tool_call.to_markdown(cx),
117 }
118 }
119
120 pub fn user_message(&self) -> Option<&UserMessage> {
121 if let AgentThreadEntry::UserMessage(message) = self {
122 Some(message)
123 } else {
124 None
125 }
126 }
127
128 pub fn diffs(&self) -> impl Iterator<Item = &Entity<Diff>> {
129 if let AgentThreadEntry::ToolCall(call) = self {
130 itertools::Either::Left(call.diffs())
131 } else {
132 itertools::Either::Right(std::iter::empty())
133 }
134 }
135
136 pub fn terminals(&self) -> impl Iterator<Item = &Entity<Terminal>> {
137 if let AgentThreadEntry::ToolCall(call) = self {
138 itertools::Either::Left(call.terminals())
139 } else {
140 itertools::Either::Right(std::iter::empty())
141 }
142 }
143
144 pub fn location(&self, ix: usize) -> Option<(acp::ToolCallLocation, AgentLocation)> {
145 if let AgentThreadEntry::ToolCall(ToolCall {
146 locations,
147 resolved_locations,
148 ..
149 }) = self
150 {
151 Some((
152 locations.get(ix)?.clone(),
153 resolved_locations.get(ix)?.clone()?,
154 ))
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 resolved_locations: Vec<Option<AgentLocation>>,
170 pub raw_input: Option<serde_json::Value>,
171 pub raw_output: Option<serde_json::Value>,
172}
173
174impl ToolCall {
175 fn from_acp(
176 tool_call: acp::ToolCall,
177 status: ToolCallStatus,
178 language_registry: Arc<LanguageRegistry>,
179 cx: &mut App,
180 ) -> Self {
181 Self {
182 id: tool_call.id,
183 label: cx.new(|cx| {
184 Markdown::new(
185 tool_call.title.into(),
186 Some(language_registry.clone()),
187 None,
188 cx,
189 )
190 }),
191 kind: tool_call.kind,
192 content: tool_call
193 .content
194 .into_iter()
195 .map(|content| ToolCallContent::from_acp(content, language_registry.clone(), cx))
196 .collect(),
197 locations: tool_call.locations,
198 resolved_locations: Vec::default(),
199 status,
200 raw_input: tool_call.raw_input,
201 raw_output: tool_call.raw_output,
202 }
203 }
204
205 fn update_fields(
206 &mut self,
207 fields: acp::ToolCallUpdateFields,
208 language_registry: Arc<LanguageRegistry>,
209 cx: &mut App,
210 ) {
211 let acp::ToolCallUpdateFields {
212 kind,
213 status,
214 title,
215 content,
216 locations,
217 raw_input,
218 raw_output,
219 } = fields;
220
221 if let Some(kind) = kind {
222 self.kind = kind;
223 }
224
225 if let Some(status) = status {
226 self.status = status.into();
227 }
228
229 if let Some(title) = title {
230 self.label.update(cx, |label, cx| {
231 label.replace(title, cx);
232 });
233 }
234
235 if let Some(content) = content {
236 self.content = content
237 .into_iter()
238 .map(|chunk| ToolCallContent::from_acp(chunk, language_registry.clone(), cx))
239 .collect();
240 }
241
242 if let Some(locations) = locations {
243 self.locations = locations;
244 }
245
246 if let Some(raw_input) = raw_input {
247 self.raw_input = Some(raw_input);
248 }
249
250 if let Some(raw_output) = raw_output {
251 if self.content.is_empty() {
252 if let Some(markdown) = markdown_for_raw_output(&raw_output, &language_registry, cx)
253 {
254 self.content
255 .push(ToolCallContent::ContentBlock(ContentBlock::Markdown {
256 markdown,
257 }));
258 }
259 }
260 self.raw_output = Some(raw_output);
261 }
262 }
263
264 pub fn diffs(&self) -> impl Iterator<Item = &Entity<Diff>> {
265 self.content.iter().filter_map(|content| match content {
266 ToolCallContent::Diff(diff) => Some(diff),
267 ToolCallContent::ContentBlock(_) => None,
268 ToolCallContent::Terminal(_) => None,
269 })
270 }
271
272 pub fn terminals(&self) -> impl Iterator<Item = &Entity<Terminal>> {
273 self.content.iter().filter_map(|content| match content {
274 ToolCallContent::Terminal(terminal) => Some(terminal),
275 ToolCallContent::ContentBlock(_) => None,
276 ToolCallContent::Diff(_) => None,
277 })
278 }
279
280 fn to_markdown(&self, cx: &App) -> String {
281 let mut markdown = format!(
282 "**Tool Call: {}**\nStatus: {}\n\n",
283 self.label.read(cx).source(),
284 self.status
285 );
286 for content in &self.content {
287 markdown.push_str(content.to_markdown(cx).as_str());
288 markdown.push_str("\n\n");
289 }
290 markdown
291 }
292
293 async fn resolve_location(
294 location: acp::ToolCallLocation,
295 project: WeakEntity<Project>,
296 cx: &mut AsyncApp,
297 ) -> Option<AgentLocation> {
298 let buffer = project
299 .update(cx, |project, cx| {
300 if let Some(path) = project.project_path_for_absolute_path(&location.path, cx) {
301 Some(project.open_buffer(path, cx))
302 } else {
303 None
304 }
305 })
306 .ok()??;
307 let buffer = buffer.await.log_err()?;
308 let position = buffer
309 .update(cx, |buffer, _| {
310 if let Some(row) = location.line {
311 let snapshot = buffer.snapshot();
312 let column = snapshot.indent_size_for_line(row).len;
313 let point = snapshot.clip_point(Point::new(row, column), Bias::Left);
314 snapshot.anchor_before(point)
315 } else {
316 Anchor::MIN
317 }
318 })
319 .ok()?;
320
321 Some(AgentLocation {
322 buffer: buffer.downgrade(),
323 position,
324 })
325 }
326
327 fn resolve_locations(
328 &self,
329 project: Entity<Project>,
330 cx: &mut App,
331 ) -> Task<Vec<Option<AgentLocation>>> {
332 let locations = self.locations.clone();
333 project.update(cx, |_, cx| {
334 cx.spawn(async move |project, cx| {
335 let mut new_locations = Vec::new();
336 for location in locations {
337 new_locations.push(Self::resolve_location(location, project.clone(), cx).await);
338 }
339 new_locations
340 })
341 })
342 }
343}
344
345#[derive(Debug)]
346pub enum ToolCallStatus {
347 /// The tool call hasn't started running yet, but we start showing it to
348 /// the user.
349 Pending,
350 /// The tool call is waiting for confirmation from the user.
351 WaitingForConfirmation {
352 options: Vec<acp::PermissionOption>,
353 respond_tx: oneshot::Sender<acp::PermissionOptionId>,
354 },
355 /// The tool call is currently running.
356 InProgress,
357 /// The tool call completed successfully.
358 Completed,
359 /// The tool call failed.
360 Failed,
361 /// The user rejected the tool call.
362 Rejected,
363 /// The user canceled generation so the tool call was canceled.
364 Canceled,
365}
366
367impl From<acp::ToolCallStatus> for ToolCallStatus {
368 fn from(status: acp::ToolCallStatus) -> Self {
369 match status {
370 acp::ToolCallStatus::Pending => Self::Pending,
371 acp::ToolCallStatus::InProgress => Self::InProgress,
372 acp::ToolCallStatus::Completed => Self::Completed,
373 acp::ToolCallStatus::Failed => Self::Failed,
374 }
375 }
376}
377
378impl Display for ToolCallStatus {
379 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
380 write!(
381 f,
382 "{}",
383 match self {
384 ToolCallStatus::Pending => "Pending",
385 ToolCallStatus::WaitingForConfirmation { .. } => "Waiting for confirmation",
386 ToolCallStatus::InProgress => "In Progress",
387 ToolCallStatus::Completed => "Completed",
388 ToolCallStatus::Failed => "Failed",
389 ToolCallStatus::Rejected => "Rejected",
390 ToolCallStatus::Canceled => "Canceled",
391 }
392 )
393 }
394}
395
396#[derive(Debug, PartialEq, Clone)]
397pub enum ContentBlock {
398 Empty,
399 Markdown { markdown: Entity<Markdown> },
400 ResourceLink { resource_link: acp::ResourceLink },
401}
402
403impl ContentBlock {
404 pub fn new(
405 block: acp::ContentBlock,
406 language_registry: &Arc<LanguageRegistry>,
407 cx: &mut App,
408 ) -> Self {
409 let mut this = Self::Empty;
410 this.append(block, language_registry, cx);
411 this
412 }
413
414 pub fn new_combined(
415 blocks: impl IntoIterator<Item = acp::ContentBlock>,
416 language_registry: Arc<LanguageRegistry>,
417 cx: &mut App,
418 ) -> Self {
419 let mut this = Self::Empty;
420 for block in blocks {
421 this.append(block, &language_registry, cx);
422 }
423 this
424 }
425
426 pub fn append(
427 &mut self,
428 block: acp::ContentBlock,
429 language_registry: &Arc<LanguageRegistry>,
430 cx: &mut App,
431 ) {
432 if matches!(self, ContentBlock::Empty) {
433 if let acp::ContentBlock::ResourceLink(resource_link) = block {
434 *self = ContentBlock::ResourceLink { resource_link };
435 return;
436 }
437 }
438
439 let new_content = self.block_string_contents(block);
440
441 match self {
442 ContentBlock::Empty => {
443 *self = Self::create_markdown_block(new_content, language_registry, cx);
444 }
445 ContentBlock::Markdown { markdown } => {
446 markdown.update(cx, |markdown, cx| markdown.append(&new_content, cx));
447 }
448 ContentBlock::ResourceLink { resource_link } => {
449 let existing_content = Self::resource_link_md(&resource_link.uri);
450 let combined = format!("{}\n{}", existing_content, new_content);
451
452 *self = Self::create_markdown_block(combined, language_registry, cx);
453 }
454 }
455 }
456
457 fn create_markdown_block(
458 content: String,
459 language_registry: &Arc<LanguageRegistry>,
460 cx: &mut App,
461 ) -> ContentBlock {
462 ContentBlock::Markdown {
463 markdown: cx
464 .new(|cx| Markdown::new(content.into(), Some(language_registry.clone()), None, cx)),
465 }
466 }
467
468 fn block_string_contents(&self, block: acp::ContentBlock) -> String {
469 match block {
470 acp::ContentBlock::Text(text_content) => text_content.text.clone(),
471 acp::ContentBlock::ResourceLink(resource_link) => {
472 Self::resource_link_md(&resource_link.uri)
473 }
474 acp::ContentBlock::Resource(acp::EmbeddedResource {
475 resource:
476 acp::EmbeddedResourceResource::TextResourceContents(acp::TextResourceContents {
477 uri,
478 ..
479 }),
480 ..
481 }) => Self::resource_link_md(&uri),
482 acp::ContentBlock::Image(image) => Self::image_md(&image),
483 acp::ContentBlock::Audio(_) | acp::ContentBlock::Resource(_) => String::new(),
484 }
485 }
486
487 fn resource_link_md(uri: &str) -> String {
488 if let Some(uri) = MentionUri::parse(&uri).log_err() {
489 uri.as_link().to_string()
490 } else {
491 uri.to_string()
492 }
493 }
494
495 fn image_md(_image: &acp::ImageContent) -> String {
496 "`Image`".into()
497 }
498
499 fn to_markdown<'a>(&'a self, cx: &'a App) -> &'a str {
500 match self {
501 ContentBlock::Empty => "",
502 ContentBlock::Markdown { markdown } => markdown.read(cx).source(),
503 ContentBlock::ResourceLink { resource_link } => &resource_link.uri,
504 }
505 }
506
507 pub fn markdown(&self) -> Option<&Entity<Markdown>> {
508 match self {
509 ContentBlock::Empty => None,
510 ContentBlock::Markdown { markdown } => Some(markdown),
511 ContentBlock::ResourceLink { .. } => None,
512 }
513 }
514
515 pub fn resource_link(&self) -> Option<&acp::ResourceLink> {
516 match self {
517 ContentBlock::ResourceLink { resource_link } => Some(resource_link),
518 _ => None,
519 }
520 }
521}
522
523#[derive(Debug)]
524pub enum ToolCallContent {
525 ContentBlock(ContentBlock),
526 Diff(Entity<Diff>),
527 Terminal(Entity<Terminal>),
528}
529
530impl ToolCallContent {
531 pub fn from_acp(
532 content: acp::ToolCallContent,
533 language_registry: Arc<LanguageRegistry>,
534 cx: &mut App,
535 ) -> Self {
536 match content {
537 acp::ToolCallContent::Content { content } => {
538 Self::ContentBlock(ContentBlock::new(content, &language_registry, cx))
539 }
540 acp::ToolCallContent::Diff { diff } => {
541 Self::Diff(cx.new(|cx| Diff::from_acp(diff, language_registry, cx)))
542 }
543 }
544 }
545
546 pub fn to_markdown(&self, cx: &App) -> String {
547 match self {
548 Self::ContentBlock(content) => content.to_markdown(cx).to_string(),
549 Self::Diff(diff) => diff.read(cx).to_markdown(cx),
550 Self::Terminal(terminal) => terminal.read(cx).to_markdown(cx),
551 }
552 }
553}
554
555#[derive(Debug, PartialEq)]
556pub enum ToolCallUpdate {
557 UpdateFields(acp::ToolCallUpdate),
558 UpdateDiff(ToolCallUpdateDiff),
559 UpdateTerminal(ToolCallUpdateTerminal),
560}
561
562impl ToolCallUpdate {
563 fn id(&self) -> &acp::ToolCallId {
564 match self {
565 Self::UpdateFields(update) => &update.id,
566 Self::UpdateDiff(diff) => &diff.id,
567 Self::UpdateTerminal(terminal) => &terminal.id,
568 }
569 }
570}
571
572impl From<acp::ToolCallUpdate> for ToolCallUpdate {
573 fn from(update: acp::ToolCallUpdate) -> Self {
574 Self::UpdateFields(update)
575 }
576}
577
578impl From<ToolCallUpdateDiff> for ToolCallUpdate {
579 fn from(diff: ToolCallUpdateDiff) -> Self {
580 Self::UpdateDiff(diff)
581 }
582}
583
584#[derive(Debug, PartialEq)]
585pub struct ToolCallUpdateDiff {
586 pub id: acp::ToolCallId,
587 pub diff: Entity<Diff>,
588}
589
590impl From<ToolCallUpdateTerminal> for ToolCallUpdate {
591 fn from(terminal: ToolCallUpdateTerminal) -> Self {
592 Self::UpdateTerminal(terminal)
593 }
594}
595
596#[derive(Debug, PartialEq)]
597pub struct ToolCallUpdateTerminal {
598 pub id: acp::ToolCallId,
599 pub terminal: Entity<Terminal>,
600}
601
602#[derive(Debug, Default)]
603pub struct Plan {
604 pub entries: Vec<PlanEntry>,
605}
606
607#[derive(Debug)]
608pub struct PlanStats<'a> {
609 pub in_progress_entry: Option<&'a PlanEntry>,
610 pub pending: u32,
611 pub completed: u32,
612}
613
614impl Plan {
615 pub fn is_empty(&self) -> bool {
616 self.entries.is_empty()
617 }
618
619 pub fn stats(&self) -> PlanStats<'_> {
620 let mut stats = PlanStats {
621 in_progress_entry: None,
622 pending: 0,
623 completed: 0,
624 };
625
626 for entry in &self.entries {
627 match &entry.status {
628 acp::PlanEntryStatus::Pending => {
629 stats.pending += 1;
630 }
631 acp::PlanEntryStatus::InProgress => {
632 stats.in_progress_entry = stats.in_progress_entry.or(Some(entry));
633 }
634 acp::PlanEntryStatus::Completed => {
635 stats.completed += 1;
636 }
637 }
638 }
639
640 stats
641 }
642}
643
644#[derive(Debug)]
645pub struct PlanEntry {
646 pub content: Entity<Markdown>,
647 pub priority: acp::PlanEntryPriority,
648 pub status: acp::PlanEntryStatus,
649}
650
651impl PlanEntry {
652 pub fn from_acp(entry: acp::PlanEntry, cx: &mut App) -> Self {
653 Self {
654 content: cx.new(|cx| Markdown::new(entry.content.into(), None, None, cx)),
655 priority: entry.priority,
656 status: entry.status,
657 }
658 }
659}
660
661pub struct AcpThread {
662 title: SharedString,
663 entries: Vec<AgentThreadEntry>,
664 plan: Plan,
665 project: Entity<Project>,
666 action_log: Entity<ActionLog>,
667 shared_buffers: HashMap<Entity<Buffer>, BufferSnapshot>,
668 send_task: Option<Task<()>>,
669 connection: Rc<dyn AgentConnection>,
670 session_id: acp::SessionId,
671}
672
673pub enum AcpThreadEvent {
674 NewEntry,
675 EntryUpdated(usize),
676 EntriesRemoved(Range<usize>),
677 ToolAuthorizationRequired,
678 Stopped,
679 Error,
680 ServerExited(ExitStatus),
681}
682
683impl EventEmitter<AcpThreadEvent> for AcpThread {}
684
685#[derive(PartialEq, Eq)]
686pub enum ThreadStatus {
687 Idle,
688 WaitingForToolConfirmation,
689 Generating,
690}
691
692#[derive(Debug, Clone)]
693pub enum LoadError {
694 Unsupported {
695 error_message: SharedString,
696 upgrade_message: SharedString,
697 upgrade_command: String,
698 },
699 Exited(i32),
700 Other(SharedString),
701}
702
703impl Display for LoadError {
704 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
705 match self {
706 LoadError::Unsupported { error_message, .. } => write!(f, "{}", error_message),
707 LoadError::Exited(status) => write!(f, "Server exited with status {}", status),
708 LoadError::Other(msg) => write!(f, "{}", msg),
709 }
710 }
711}
712
713impl Error for LoadError {}
714
715impl AcpThread {
716 pub fn new(
717 title: impl Into<SharedString>,
718 connection: Rc<dyn AgentConnection>,
719 project: Entity<Project>,
720 session_id: acp::SessionId,
721 cx: &mut Context<Self>,
722 ) -> Self {
723 let action_log = cx.new(|_| ActionLog::new(project.clone()));
724
725 Self {
726 action_log,
727 shared_buffers: Default::default(),
728 entries: Default::default(),
729 plan: Default::default(),
730 title: title.into(),
731 project,
732 send_task: None,
733 connection,
734 session_id,
735 }
736 }
737
738 pub fn connection(&self) -> &Rc<dyn AgentConnection> {
739 &self.connection
740 }
741
742 pub fn action_log(&self) -> &Entity<ActionLog> {
743 &self.action_log
744 }
745
746 pub fn project(&self) -> &Entity<Project> {
747 &self.project
748 }
749
750 pub fn title(&self) -> SharedString {
751 self.title.clone()
752 }
753
754 pub fn entries(&self) -> &[AgentThreadEntry] {
755 &self.entries
756 }
757
758 pub fn session_id(&self) -> &acp::SessionId {
759 &self.session_id
760 }
761
762 pub fn status(&self) -> ThreadStatus {
763 if self.send_task.is_some() {
764 if self.waiting_for_tool_confirmation() {
765 ThreadStatus::WaitingForToolConfirmation
766 } else {
767 ThreadStatus::Generating
768 }
769 } else {
770 ThreadStatus::Idle
771 }
772 }
773
774 pub fn has_pending_edit_tool_calls(&self) -> bool {
775 for entry in self.entries.iter().rev() {
776 match entry {
777 AgentThreadEntry::UserMessage(_) => return false,
778 AgentThreadEntry::ToolCall(
779 call @ ToolCall {
780 status: ToolCallStatus::InProgress | ToolCallStatus::Pending,
781 ..
782 },
783 ) if call.diffs().next().is_some() => {
784 return true;
785 }
786 AgentThreadEntry::ToolCall(_) | AgentThreadEntry::AssistantMessage(_) => {}
787 }
788 }
789
790 false
791 }
792
793 pub fn used_tools_since_last_user_message(&self) -> bool {
794 for entry in self.entries.iter().rev() {
795 match entry {
796 AgentThreadEntry::UserMessage(..) => return false,
797 AgentThreadEntry::AssistantMessage(..) => continue,
798 AgentThreadEntry::ToolCall(..) => return true,
799 }
800 }
801
802 false
803 }
804
805 pub fn handle_session_update(
806 &mut self,
807 update: acp::SessionUpdate,
808 cx: &mut Context<Self>,
809 ) -> Result<(), acp::Error> {
810 match update {
811 acp::SessionUpdate::UserMessageChunk { content } => {
812 self.push_user_content_block(None, content, cx);
813 }
814 acp::SessionUpdate::AgentMessageChunk { content } => {
815 self.push_assistant_content_block(content, false, cx);
816 }
817 acp::SessionUpdate::AgentThoughtChunk { content } => {
818 self.push_assistant_content_block(content, true, cx);
819 }
820 acp::SessionUpdate::ToolCall(tool_call) => {
821 self.upsert_tool_call(tool_call, cx)?;
822 }
823 acp::SessionUpdate::ToolCallUpdate(tool_call_update) => {
824 self.update_tool_call(tool_call_update, cx)?;
825 }
826 acp::SessionUpdate::Plan(plan) => {
827 self.update_plan(plan, cx);
828 }
829 }
830 Ok(())
831 }
832
833 pub fn push_user_content_block(
834 &mut self,
835 message_id: Option<UserMessageId>,
836 chunk: acp::ContentBlock,
837 cx: &mut Context<Self>,
838 ) {
839 let language_registry = self.project.read(cx).languages().clone();
840 let entries_len = self.entries.len();
841
842 if let Some(last_entry) = self.entries.last_mut()
843 && let AgentThreadEntry::UserMessage(UserMessage {
844 id,
845 content,
846 chunks,
847 ..
848 }) = last_entry
849 {
850 *id = message_id.or(id.take());
851 content.append(chunk.clone(), &language_registry, cx);
852 chunks.push(chunk);
853 let idx = entries_len - 1;
854 cx.emit(AcpThreadEvent::EntryUpdated(idx));
855 } else {
856 let content = ContentBlock::new(chunk.clone(), &language_registry, cx);
857 self.push_entry(
858 AgentThreadEntry::UserMessage(UserMessage {
859 id: message_id,
860 content,
861 chunks: vec![chunk],
862 checkpoint: None,
863 }),
864 cx,
865 );
866 }
867 }
868
869 pub fn push_assistant_content_block(
870 &mut self,
871 chunk: acp::ContentBlock,
872 is_thought: bool,
873 cx: &mut Context<Self>,
874 ) {
875 let language_registry = self.project.read(cx).languages().clone();
876 let entries_len = self.entries.len();
877 if let Some(last_entry) = self.entries.last_mut()
878 && let AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) = last_entry
879 {
880 let idx = entries_len - 1;
881 cx.emit(AcpThreadEvent::EntryUpdated(idx));
882 match (chunks.last_mut(), is_thought) {
883 (Some(AssistantMessageChunk::Message { block }), false)
884 | (Some(AssistantMessageChunk::Thought { block }), true) => {
885 block.append(chunk, &language_registry, cx)
886 }
887 _ => {
888 let block = ContentBlock::new(chunk, &language_registry, cx);
889 if is_thought {
890 chunks.push(AssistantMessageChunk::Thought { block })
891 } else {
892 chunks.push(AssistantMessageChunk::Message { block })
893 }
894 }
895 }
896 } else {
897 let block = ContentBlock::new(chunk, &language_registry, cx);
898 let chunk = if is_thought {
899 AssistantMessageChunk::Thought { block }
900 } else {
901 AssistantMessageChunk::Message { block }
902 };
903
904 self.push_entry(
905 AgentThreadEntry::AssistantMessage(AssistantMessage {
906 chunks: vec![chunk],
907 }),
908 cx,
909 );
910 }
911 }
912
913 fn push_entry(&mut self, entry: AgentThreadEntry, cx: &mut Context<Self>) {
914 self.entries.push(entry);
915 cx.emit(AcpThreadEvent::NewEntry);
916 }
917
918 pub fn update_tool_call(
919 &mut self,
920 update: impl Into<ToolCallUpdate>,
921 cx: &mut Context<Self>,
922 ) -> Result<()> {
923 let update = update.into();
924 let languages = self.project.read(cx).languages().clone();
925
926 let (ix, current_call) = self
927 .tool_call_mut(update.id())
928 .context("Tool call not found")?;
929 match update {
930 ToolCallUpdate::UpdateFields(update) => {
931 let location_updated = update.fields.locations.is_some();
932 current_call.update_fields(update.fields, languages, cx);
933 if location_updated {
934 self.resolve_locations(update.id.clone(), cx);
935 }
936 }
937 ToolCallUpdate::UpdateDiff(update) => {
938 current_call.content.clear();
939 current_call
940 .content
941 .push(ToolCallContent::Diff(update.diff));
942 }
943 ToolCallUpdate::UpdateTerminal(update) => {
944 current_call.content.clear();
945 current_call
946 .content
947 .push(ToolCallContent::Terminal(update.terminal));
948 }
949 }
950
951 cx.emit(AcpThreadEvent::EntryUpdated(ix));
952
953 Ok(())
954 }
955
956 /// Updates a tool call if id matches an existing entry, otherwise inserts a new one.
957 pub fn upsert_tool_call(
958 &mut self,
959 tool_call: acp::ToolCall,
960 cx: &mut Context<Self>,
961 ) -> Result<(), acp::Error> {
962 let status = tool_call.status.into();
963 self.upsert_tool_call_inner(tool_call.into(), status, cx)
964 }
965
966 /// Fails if id does not match an existing entry.
967 pub fn upsert_tool_call_inner(
968 &mut self,
969 tool_call_update: acp::ToolCallUpdate,
970 status: ToolCallStatus,
971 cx: &mut Context<Self>,
972 ) -> Result<(), acp::Error> {
973 let language_registry = self.project.read(cx).languages().clone();
974 let id = tool_call_update.id.clone();
975
976 if let Some((ix, current_call)) = self.tool_call_mut(&id) {
977 current_call.update_fields(tool_call_update.fields, language_registry, cx);
978 current_call.status = status;
979
980 cx.emit(AcpThreadEvent::EntryUpdated(ix));
981 } else {
982 let call =
983 ToolCall::from_acp(tool_call_update.try_into()?, status, language_registry, cx);
984 self.push_entry(AgentThreadEntry::ToolCall(call), cx);
985 };
986
987 self.resolve_locations(id, cx);
988 Ok(())
989 }
990
991 fn tool_call_mut(&mut self, id: &acp::ToolCallId) -> Option<(usize, &mut ToolCall)> {
992 // The tool call we are looking for is typically the last one, or very close to the end.
993 // At the moment, it doesn't seem like a hashmap would be a good fit for this use case.
994 self.entries
995 .iter_mut()
996 .enumerate()
997 .rev()
998 .find_map(|(index, tool_call)| {
999 if let AgentThreadEntry::ToolCall(tool_call) = tool_call
1000 && &tool_call.id == id
1001 {
1002 Some((index, tool_call))
1003 } else {
1004 None
1005 }
1006 })
1007 }
1008
1009 pub fn resolve_locations(&mut self, id: acp::ToolCallId, cx: &mut Context<Self>) {
1010 let project = self.project.clone();
1011 let Some((_, tool_call)) = self.tool_call_mut(&id) else {
1012 return;
1013 };
1014 let task = tool_call.resolve_locations(project, cx);
1015 cx.spawn(async move |this, cx| {
1016 let resolved_locations = task.await;
1017 this.update(cx, |this, cx| {
1018 let project = this.project.clone();
1019 let Some((ix, tool_call)) = this.tool_call_mut(&id) else {
1020 return;
1021 };
1022 if let Some(Some(location)) = resolved_locations.last() {
1023 project.update(cx, |project, cx| {
1024 if let Some(agent_location) = project.agent_location() {
1025 let should_ignore = agent_location.buffer == location.buffer
1026 && location
1027 .buffer
1028 .update(cx, |buffer, _| {
1029 let snapshot = buffer.snapshot();
1030 let old_position =
1031 agent_location.position.to_point(&snapshot);
1032 let new_position = location.position.to_point(&snapshot);
1033 // ignore this so that when we get updates from the edit tool
1034 // the position doesn't reset to the startof line
1035 old_position.row == new_position.row
1036 && old_position.column > new_position.column
1037 })
1038 .ok()
1039 .unwrap_or_default();
1040 if !should_ignore {
1041 project.set_agent_location(Some(location.clone()), cx);
1042 }
1043 }
1044 });
1045 }
1046 if tool_call.resolved_locations != resolved_locations {
1047 tool_call.resolved_locations = resolved_locations;
1048 cx.emit(AcpThreadEvent::EntryUpdated(ix));
1049 }
1050 })
1051 })
1052 .detach();
1053 }
1054
1055 pub fn request_tool_call_authorization(
1056 &mut self,
1057 tool_call: acp::ToolCallUpdate,
1058 options: Vec<acp::PermissionOption>,
1059 cx: &mut Context<Self>,
1060 ) -> Result<oneshot::Receiver<acp::PermissionOptionId>, acp::Error> {
1061 let (tx, rx) = oneshot::channel();
1062
1063 let status = ToolCallStatus::WaitingForConfirmation {
1064 options,
1065 respond_tx: tx,
1066 };
1067
1068 self.upsert_tool_call_inner(tool_call, status, cx)?;
1069 cx.emit(AcpThreadEvent::ToolAuthorizationRequired);
1070 Ok(rx)
1071 }
1072
1073 pub fn authorize_tool_call(
1074 &mut self,
1075 id: acp::ToolCallId,
1076 option_id: acp::PermissionOptionId,
1077 option_kind: acp::PermissionOptionKind,
1078 cx: &mut Context<Self>,
1079 ) {
1080 let Some((ix, call)) = self.tool_call_mut(&id) else {
1081 return;
1082 };
1083
1084 let new_status = match option_kind {
1085 acp::PermissionOptionKind::RejectOnce | acp::PermissionOptionKind::RejectAlways => {
1086 ToolCallStatus::Rejected
1087 }
1088 acp::PermissionOptionKind::AllowOnce | acp::PermissionOptionKind::AllowAlways => {
1089 ToolCallStatus::InProgress
1090 }
1091 };
1092
1093 let curr_status = mem::replace(&mut call.status, new_status);
1094
1095 if let ToolCallStatus::WaitingForConfirmation { respond_tx, .. } = curr_status {
1096 respond_tx.send(option_id).log_err();
1097 } else if cfg!(debug_assertions) {
1098 panic!("tried to authorize an already authorized tool call");
1099 }
1100
1101 cx.emit(AcpThreadEvent::EntryUpdated(ix));
1102 }
1103
1104 /// Returns true if the last turn is awaiting tool authorization
1105 pub fn waiting_for_tool_confirmation(&self) -> bool {
1106 for entry in self.entries.iter().rev() {
1107 match &entry {
1108 AgentThreadEntry::ToolCall(call) => match call.status {
1109 ToolCallStatus::WaitingForConfirmation { .. } => return true,
1110 ToolCallStatus::Pending
1111 | ToolCallStatus::InProgress
1112 | ToolCallStatus::Completed
1113 | ToolCallStatus::Failed
1114 | ToolCallStatus::Rejected
1115 | ToolCallStatus::Canceled => continue,
1116 },
1117 AgentThreadEntry::UserMessage(_) | AgentThreadEntry::AssistantMessage(_) => {
1118 // Reached the beginning of the turn
1119 return false;
1120 }
1121 }
1122 }
1123 false
1124 }
1125
1126 pub fn plan(&self) -> &Plan {
1127 &self.plan
1128 }
1129
1130 pub fn update_plan(&mut self, request: acp::Plan, cx: &mut Context<Self>) {
1131 let new_entries_len = request.entries.len();
1132 let mut new_entries = request.entries.into_iter();
1133
1134 // Reuse existing markdown to prevent flickering
1135 for (old, new) in self.plan.entries.iter_mut().zip(new_entries.by_ref()) {
1136 let PlanEntry {
1137 content,
1138 priority,
1139 status,
1140 } = old;
1141 content.update(cx, |old, cx| {
1142 old.replace(new.content, cx);
1143 });
1144 *priority = new.priority;
1145 *status = new.status;
1146 }
1147 for new in new_entries {
1148 self.plan.entries.push(PlanEntry::from_acp(new, cx))
1149 }
1150 self.plan.entries.truncate(new_entries_len);
1151
1152 cx.notify();
1153 }
1154
1155 fn clear_completed_plan_entries(&mut self, cx: &mut Context<Self>) {
1156 self.plan
1157 .entries
1158 .retain(|entry| !matches!(entry.status, acp::PlanEntryStatus::Completed));
1159 cx.notify();
1160 }
1161
1162 #[cfg(any(test, feature = "test-support"))]
1163 pub fn send_raw(
1164 &mut self,
1165 message: &str,
1166 cx: &mut Context<Self>,
1167 ) -> BoxFuture<'static, Result<()>> {
1168 self.send(
1169 vec![acp::ContentBlock::Text(acp::TextContent {
1170 text: message.to_string(),
1171 annotations: None,
1172 })],
1173 cx,
1174 )
1175 }
1176
1177 pub fn send(
1178 &mut self,
1179 message: Vec<acp::ContentBlock>,
1180 cx: &mut Context<Self>,
1181 ) -> BoxFuture<'static, Result<()>> {
1182 let block = ContentBlock::new_combined(
1183 message.clone(),
1184 self.project.read(cx).languages().clone(),
1185 cx,
1186 );
1187 let request = acp::PromptRequest {
1188 prompt: message.clone(),
1189 session_id: self.session_id.clone(),
1190 };
1191 let git_store = self.project.read(cx).git_store().clone();
1192
1193 let message_id = if self
1194 .connection
1195 .session_editor(&self.session_id, cx)
1196 .is_some()
1197 {
1198 Some(UserMessageId::new())
1199 } else {
1200 None
1201 };
1202 self.push_entry(
1203 AgentThreadEntry::UserMessage(UserMessage {
1204 id: message_id.clone(),
1205 content: block,
1206 chunks: message,
1207 checkpoint: None,
1208 }),
1209 cx,
1210 );
1211
1212 self.run_turn(cx, async move |this, cx| {
1213 let old_checkpoint = git_store
1214 .update(cx, |git, cx| git.checkpoint(cx))?
1215 .await
1216 .context("failed to get old checkpoint")
1217 .log_err();
1218 this.update(cx, |this, cx| {
1219 if let Some((_ix, message)) = this.last_user_message() {
1220 message.checkpoint = old_checkpoint.map(|git_checkpoint| Checkpoint {
1221 git_checkpoint,
1222 show: false,
1223 });
1224 }
1225 this.connection.prompt(message_id, request, cx)
1226 })?
1227 .await
1228 })
1229 }
1230
1231 pub fn resume(&mut self, cx: &mut Context<Self>) -> BoxFuture<'static, Result<()>> {
1232 self.run_turn(cx, async move |this, cx| {
1233 this.update(cx, |this, cx| {
1234 this.connection
1235 .resume(&this.session_id, cx)
1236 .map(|resume| resume.run(cx))
1237 })?
1238 .context("resuming a session is not supported")?
1239 .await
1240 })
1241 }
1242
1243 fn run_turn(
1244 &mut self,
1245 cx: &mut Context<Self>,
1246 f: impl 'static + AsyncFnOnce(WeakEntity<Self>, &mut AsyncApp) -> Result<acp::PromptResponse>,
1247 ) -> BoxFuture<'static, Result<()>> {
1248 self.clear_completed_plan_entries(cx);
1249
1250 let (tx, rx) = oneshot::channel();
1251 let cancel_task = self.cancel(cx);
1252
1253 self.send_task = Some(cx.spawn(async move |this, cx| {
1254 cancel_task.await;
1255 tx.send(f(this, cx).await).ok();
1256 }));
1257
1258 cx.spawn(async move |this, cx| {
1259 let response = rx.await;
1260
1261 this.update(cx, |this, cx| this.update_last_checkpoint(cx))?
1262 .await?;
1263
1264 this.update(cx, |this, cx| {
1265 match response {
1266 Ok(Err(e)) => {
1267 this.send_task.take();
1268 cx.emit(AcpThreadEvent::Error);
1269 Err(e)
1270 }
1271 result => {
1272 let canceled = matches!(
1273 result,
1274 Ok(Ok(acp::PromptResponse {
1275 stop_reason: acp::StopReason::Canceled
1276 }))
1277 );
1278
1279 // We only take the task if the current prompt wasn't canceled.
1280 //
1281 // This prompt may have been canceled because another one was sent
1282 // while it was still generating. In these cases, dropping `send_task`
1283 // would cause the next generation to be canceled.
1284 if !canceled {
1285 this.send_task.take();
1286 }
1287
1288 cx.emit(AcpThreadEvent::Stopped);
1289 Ok(())
1290 }
1291 }
1292 })?
1293 })
1294 .boxed()
1295 }
1296
1297 pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
1298 let Some(send_task) = self.send_task.take() else {
1299 return Task::ready(());
1300 };
1301
1302 for entry in self.entries.iter_mut() {
1303 if let AgentThreadEntry::ToolCall(call) = entry {
1304 let cancel = matches!(
1305 call.status,
1306 ToolCallStatus::Pending
1307 | ToolCallStatus::WaitingForConfirmation { .. }
1308 | ToolCallStatus::InProgress
1309 );
1310
1311 if cancel {
1312 call.status = ToolCallStatus::Canceled;
1313 }
1314 }
1315 }
1316
1317 self.connection.cancel(&self.session_id, cx);
1318
1319 // Wait for the send task to complete
1320 cx.foreground_executor().spawn(send_task)
1321 }
1322
1323 /// Rewinds this thread to before the entry at `index`, removing it and all
1324 /// subsequent entries while reverting any changes made from that point.
1325 pub fn rewind(&mut self, id: UserMessageId, cx: &mut Context<Self>) -> Task<Result<()>> {
1326 let Some(session_editor) = self.connection.session_editor(&self.session_id, cx) else {
1327 return Task::ready(Err(anyhow!("not supported")));
1328 };
1329 let Some(message) = self.user_message(&id) else {
1330 return Task::ready(Err(anyhow!("message not found")));
1331 };
1332
1333 let checkpoint = message
1334 .checkpoint
1335 .as_ref()
1336 .map(|c| c.git_checkpoint.clone());
1337
1338 let git_store = self.project.read(cx).git_store().clone();
1339 cx.spawn(async move |this, cx| {
1340 if let Some(checkpoint) = checkpoint {
1341 git_store
1342 .update(cx, |git, cx| git.restore_checkpoint(checkpoint, cx))?
1343 .await?;
1344 }
1345
1346 cx.update(|cx| session_editor.truncate(id.clone(), cx))?
1347 .await?;
1348 this.update(cx, |this, cx| {
1349 if let Some((ix, _)) = this.user_message_mut(&id) {
1350 let range = ix..this.entries.len();
1351 this.entries.truncate(ix);
1352 cx.emit(AcpThreadEvent::EntriesRemoved(range));
1353 }
1354 })
1355 })
1356 }
1357
1358 fn update_last_checkpoint(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
1359 let git_store = self.project.read(cx).git_store().clone();
1360
1361 let old_checkpoint = if let Some((_, message)) = self.last_user_message() {
1362 if let Some(checkpoint) = message.checkpoint.as_ref() {
1363 checkpoint.git_checkpoint.clone()
1364 } else {
1365 return Task::ready(Ok(()));
1366 }
1367 } else {
1368 return Task::ready(Ok(()));
1369 };
1370
1371 let new_checkpoint = git_store.update(cx, |git, cx| git.checkpoint(cx));
1372 cx.spawn(async move |this, cx| {
1373 let new_checkpoint = new_checkpoint
1374 .await
1375 .context("failed to get new checkpoint")
1376 .log_err();
1377 if let Some(new_checkpoint) = new_checkpoint {
1378 let equal = git_store
1379 .update(cx, |git, cx| {
1380 git.compare_checkpoints(old_checkpoint.clone(), new_checkpoint, cx)
1381 })?
1382 .await
1383 .unwrap_or(true);
1384 this.update(cx, |this, cx| {
1385 let (ix, message) = this.last_user_message().context("no user message")?;
1386 let checkpoint = message.checkpoint.as_mut().context("no checkpoint")?;
1387 checkpoint.show = !equal;
1388 cx.emit(AcpThreadEvent::EntryUpdated(ix));
1389 anyhow::Ok(())
1390 })??;
1391 }
1392
1393 Ok(())
1394 })
1395 }
1396
1397 fn last_user_message(&mut self) -> Option<(usize, &mut UserMessage)> {
1398 self.entries
1399 .iter_mut()
1400 .enumerate()
1401 .rev()
1402 .find_map(|(ix, entry)| {
1403 if let AgentThreadEntry::UserMessage(message) = entry {
1404 Some((ix, message))
1405 } else {
1406 None
1407 }
1408 })
1409 }
1410
1411 fn user_message(&self, id: &UserMessageId) -> Option<&UserMessage> {
1412 self.entries.iter().find_map(|entry| {
1413 if let AgentThreadEntry::UserMessage(message) = entry {
1414 if message.id.as_ref() == Some(&id) {
1415 Some(message)
1416 } else {
1417 None
1418 }
1419 } else {
1420 None
1421 }
1422 })
1423 }
1424
1425 fn user_message_mut(&mut self, id: &UserMessageId) -> Option<(usize, &mut UserMessage)> {
1426 self.entries.iter_mut().enumerate().find_map(|(ix, entry)| {
1427 if let AgentThreadEntry::UserMessage(message) = entry {
1428 if message.id.as_ref() == Some(&id) {
1429 Some((ix, message))
1430 } else {
1431 None
1432 }
1433 } else {
1434 None
1435 }
1436 })
1437 }
1438
1439 pub fn read_text_file(
1440 &self,
1441 path: PathBuf,
1442 line: Option<u32>,
1443 limit: Option<u32>,
1444 reuse_shared_snapshot: bool,
1445 cx: &mut Context<Self>,
1446 ) -> Task<Result<String>> {
1447 let project = self.project.clone();
1448 let action_log = self.action_log.clone();
1449 cx.spawn(async move |this, cx| {
1450 let load = project.update(cx, |project, cx| {
1451 let path = project
1452 .project_path_for_absolute_path(&path, cx)
1453 .context("invalid path")?;
1454 anyhow::Ok(project.open_buffer(path, cx))
1455 });
1456 let buffer = load??.await?;
1457
1458 let snapshot = if reuse_shared_snapshot {
1459 this.read_with(cx, |this, _| {
1460 this.shared_buffers.get(&buffer.clone()).cloned()
1461 })
1462 .log_err()
1463 .flatten()
1464 } else {
1465 None
1466 };
1467
1468 let snapshot = if let Some(snapshot) = snapshot {
1469 snapshot
1470 } else {
1471 action_log.update(cx, |action_log, cx| {
1472 action_log.buffer_read(buffer.clone(), cx);
1473 })?;
1474 project.update(cx, |project, cx| {
1475 let position = buffer
1476 .read(cx)
1477 .snapshot()
1478 .anchor_before(Point::new(line.unwrap_or_default(), 0));
1479 project.set_agent_location(
1480 Some(AgentLocation {
1481 buffer: buffer.downgrade(),
1482 position,
1483 }),
1484 cx,
1485 );
1486 })?;
1487
1488 buffer.update(cx, |buffer, _| buffer.snapshot())?
1489 };
1490
1491 this.update(cx, |this, _| {
1492 let text = snapshot.text();
1493 this.shared_buffers.insert(buffer.clone(), snapshot);
1494 if line.is_none() && limit.is_none() {
1495 return Ok(text);
1496 }
1497 let limit = limit.unwrap_or(u32::MAX) as usize;
1498 let Some(line) = line else {
1499 return Ok(text.lines().take(limit).collect::<String>());
1500 };
1501
1502 let count = text.lines().count();
1503 if count < line as usize {
1504 anyhow::bail!("There are only {} lines", count);
1505 }
1506 Ok(text
1507 .lines()
1508 .skip(line as usize + 1)
1509 .take(limit)
1510 .collect::<String>())
1511 })?
1512 })
1513 }
1514
1515 pub fn write_text_file(
1516 &self,
1517 path: PathBuf,
1518 content: String,
1519 cx: &mut Context<Self>,
1520 ) -> Task<Result<()>> {
1521 let project = self.project.clone();
1522 let action_log = self.action_log.clone();
1523 cx.spawn(async move |this, cx| {
1524 let load = project.update(cx, |project, cx| {
1525 let path = project
1526 .project_path_for_absolute_path(&path, cx)
1527 .context("invalid path")?;
1528 anyhow::Ok(project.open_buffer(path, cx))
1529 });
1530 let buffer = load??.await?;
1531 let snapshot = this.update(cx, |this, cx| {
1532 this.shared_buffers
1533 .get(&buffer)
1534 .cloned()
1535 .unwrap_or_else(|| buffer.read(cx).snapshot())
1536 })?;
1537 let edits = cx
1538 .background_executor()
1539 .spawn(async move {
1540 let old_text = snapshot.text();
1541 text_diff(old_text.as_str(), &content)
1542 .into_iter()
1543 .map(|(range, replacement)| {
1544 (
1545 snapshot.anchor_after(range.start)
1546 ..snapshot.anchor_before(range.end),
1547 replacement,
1548 )
1549 })
1550 .collect::<Vec<_>>()
1551 })
1552 .await;
1553 cx.update(|cx| {
1554 project.update(cx, |project, cx| {
1555 project.set_agent_location(
1556 Some(AgentLocation {
1557 buffer: buffer.downgrade(),
1558 position: edits
1559 .last()
1560 .map(|(range, _)| range.end)
1561 .unwrap_or(Anchor::MIN),
1562 }),
1563 cx,
1564 );
1565 });
1566
1567 action_log.update(cx, |action_log, cx| {
1568 action_log.buffer_read(buffer.clone(), cx);
1569 });
1570 buffer.update(cx, |buffer, cx| {
1571 buffer.edit(edits, None, cx);
1572 });
1573 action_log.update(cx, |action_log, cx| {
1574 action_log.buffer_edited(buffer.clone(), cx);
1575 });
1576 })?;
1577 project
1578 .update(cx, |project, cx| project.save_buffer(buffer, cx))?
1579 .await
1580 })
1581 }
1582
1583 pub fn to_markdown(&self, cx: &App) -> String {
1584 self.entries.iter().map(|e| e.to_markdown(cx)).collect()
1585 }
1586
1587 pub fn emit_server_exited(&mut self, status: ExitStatus, cx: &mut Context<Self>) {
1588 cx.emit(AcpThreadEvent::ServerExited(status));
1589 }
1590}
1591
1592fn markdown_for_raw_output(
1593 raw_output: &serde_json::Value,
1594 language_registry: &Arc<LanguageRegistry>,
1595 cx: &mut App,
1596) -> Option<Entity<Markdown>> {
1597 match raw_output {
1598 serde_json::Value::Null => None,
1599 serde_json::Value::Bool(value) => Some(cx.new(|cx| {
1600 Markdown::new(
1601 value.to_string().into(),
1602 Some(language_registry.clone()),
1603 None,
1604 cx,
1605 )
1606 })),
1607 serde_json::Value::Number(value) => Some(cx.new(|cx| {
1608 Markdown::new(
1609 value.to_string().into(),
1610 Some(language_registry.clone()),
1611 None,
1612 cx,
1613 )
1614 })),
1615 serde_json::Value::String(value) => Some(cx.new(|cx| {
1616 Markdown::new(
1617 value.clone().into(),
1618 Some(language_registry.clone()),
1619 None,
1620 cx,
1621 )
1622 })),
1623 value => Some(cx.new(|cx| {
1624 Markdown::new(
1625 format!("```json\n{}\n```", value).into(),
1626 Some(language_registry.clone()),
1627 None,
1628 cx,
1629 )
1630 })),
1631 }
1632}
1633
1634#[cfg(test)]
1635mod tests {
1636 use super::*;
1637 use anyhow::anyhow;
1638 use futures::{channel::mpsc, future::LocalBoxFuture, select};
1639 use gpui::{AsyncApp, TestAppContext, WeakEntity};
1640 use indoc::indoc;
1641 use project::{FakeFs, Fs};
1642 use rand::Rng as _;
1643 use serde_json::json;
1644 use settings::SettingsStore;
1645 use smol::stream::StreamExt as _;
1646 use std::{
1647 any::Any,
1648 cell::RefCell,
1649 path::Path,
1650 rc::Rc,
1651 sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
1652 time::Duration,
1653 };
1654 use util::path;
1655
1656 fn init_test(cx: &mut TestAppContext) {
1657 env_logger::try_init().ok();
1658 cx.update(|cx| {
1659 let settings_store = SettingsStore::test(cx);
1660 cx.set_global(settings_store);
1661 Project::init_settings(cx);
1662 language::init(cx);
1663 });
1664 }
1665
1666 #[gpui::test]
1667 async fn test_push_user_content_block(cx: &mut gpui::TestAppContext) {
1668 init_test(cx);
1669
1670 let fs = FakeFs::new(cx.executor());
1671 let project = Project::test(fs, [], cx).await;
1672 let connection = Rc::new(FakeAgentConnection::new());
1673 let thread = cx
1674 .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
1675 .await
1676 .unwrap();
1677
1678 // Test creating a new user message
1679 thread.update(cx, |thread, cx| {
1680 thread.push_user_content_block(
1681 None,
1682 acp::ContentBlock::Text(acp::TextContent {
1683 annotations: None,
1684 text: "Hello, ".to_string(),
1685 }),
1686 cx,
1687 );
1688 });
1689
1690 thread.update(cx, |thread, cx| {
1691 assert_eq!(thread.entries.len(), 1);
1692 if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
1693 assert_eq!(user_msg.id, None);
1694 assert_eq!(user_msg.content.to_markdown(cx), "Hello, ");
1695 } else {
1696 panic!("Expected UserMessage");
1697 }
1698 });
1699
1700 // Test appending to existing user message
1701 let message_1_id = UserMessageId::new();
1702 thread.update(cx, |thread, cx| {
1703 thread.push_user_content_block(
1704 Some(message_1_id.clone()),
1705 acp::ContentBlock::Text(acp::TextContent {
1706 annotations: None,
1707 text: "world!".to_string(),
1708 }),
1709 cx,
1710 );
1711 });
1712
1713 thread.update(cx, |thread, cx| {
1714 assert_eq!(thread.entries.len(), 1);
1715 if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
1716 assert_eq!(user_msg.id, Some(message_1_id));
1717 assert_eq!(user_msg.content.to_markdown(cx), "Hello, world!");
1718 } else {
1719 panic!("Expected UserMessage");
1720 }
1721 });
1722
1723 // Test creating new user message after assistant message
1724 thread.update(cx, |thread, cx| {
1725 thread.push_assistant_content_block(
1726 acp::ContentBlock::Text(acp::TextContent {
1727 annotations: None,
1728 text: "Assistant response".to_string(),
1729 }),
1730 false,
1731 cx,
1732 );
1733 });
1734
1735 let message_2_id = UserMessageId::new();
1736 thread.update(cx, |thread, cx| {
1737 thread.push_user_content_block(
1738 Some(message_2_id.clone()),
1739 acp::ContentBlock::Text(acp::TextContent {
1740 annotations: None,
1741 text: "New user message".to_string(),
1742 }),
1743 cx,
1744 );
1745 });
1746
1747 thread.update(cx, |thread, cx| {
1748 assert_eq!(thread.entries.len(), 3);
1749 if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[2] {
1750 assert_eq!(user_msg.id, Some(message_2_id));
1751 assert_eq!(user_msg.content.to_markdown(cx), "New user message");
1752 } else {
1753 panic!("Expected UserMessage at index 2");
1754 }
1755 });
1756 }
1757
1758 #[gpui::test]
1759 async fn test_thinking_concatenation(cx: &mut gpui::TestAppContext) {
1760 init_test(cx);
1761
1762 let fs = FakeFs::new(cx.executor());
1763 let project = Project::test(fs, [], cx).await;
1764 let connection = Rc::new(FakeAgentConnection::new().on_user_message(
1765 |_, thread, mut cx| {
1766 async move {
1767 thread.update(&mut cx, |thread, cx| {
1768 thread
1769 .handle_session_update(
1770 acp::SessionUpdate::AgentThoughtChunk {
1771 content: "Thinking ".into(),
1772 },
1773 cx,
1774 )
1775 .unwrap();
1776 thread
1777 .handle_session_update(
1778 acp::SessionUpdate::AgentThoughtChunk {
1779 content: "hard!".into(),
1780 },
1781 cx,
1782 )
1783 .unwrap();
1784 })?;
1785 Ok(acp::PromptResponse {
1786 stop_reason: acp::StopReason::EndTurn,
1787 })
1788 }
1789 .boxed_local()
1790 },
1791 ));
1792
1793 let thread = cx
1794 .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
1795 .await
1796 .unwrap();
1797
1798 thread
1799 .update(cx, |thread, cx| thread.send_raw("Hello from Zed!", cx))
1800 .await
1801 .unwrap();
1802
1803 let output = thread.read_with(cx, |thread, cx| thread.to_markdown(cx));
1804 assert_eq!(
1805 output,
1806 indoc! {r#"
1807 ## User
1808
1809 Hello from Zed!
1810
1811 ## Assistant
1812
1813 <thinking>
1814 Thinking hard!
1815 </thinking>
1816
1817 "#}
1818 );
1819 }
1820
1821 #[gpui::test]
1822 async fn test_edits_concurrently_to_user(cx: &mut TestAppContext) {
1823 init_test(cx);
1824
1825 let fs = FakeFs::new(cx.executor());
1826 fs.insert_tree(path!("/tmp"), json!({"foo": "one\ntwo\nthree\n"}))
1827 .await;
1828 let project = Project::test(fs.clone(), [], cx).await;
1829 let (read_file_tx, read_file_rx) = oneshot::channel::<()>();
1830 let read_file_tx = Rc::new(RefCell::new(Some(read_file_tx)));
1831 let connection = Rc::new(FakeAgentConnection::new().on_user_message(
1832 move |_, thread, mut cx| {
1833 let read_file_tx = read_file_tx.clone();
1834 async move {
1835 let content = thread
1836 .update(&mut cx, |thread, cx| {
1837 thread.read_text_file(path!("/tmp/foo").into(), None, None, false, cx)
1838 })
1839 .unwrap()
1840 .await
1841 .unwrap();
1842 assert_eq!(content, "one\ntwo\nthree\n");
1843 read_file_tx.take().unwrap().send(()).unwrap();
1844 thread
1845 .update(&mut cx, |thread, cx| {
1846 thread.write_text_file(
1847 path!("/tmp/foo").into(),
1848 "one\ntwo\nthree\nfour\nfive\n".to_string(),
1849 cx,
1850 )
1851 })
1852 .unwrap()
1853 .await
1854 .unwrap();
1855 Ok(acp::PromptResponse {
1856 stop_reason: acp::StopReason::EndTurn,
1857 })
1858 }
1859 .boxed_local()
1860 },
1861 ));
1862
1863 let (worktree, pathbuf) = project
1864 .update(cx, |project, cx| {
1865 project.find_or_create_worktree(path!("/tmp/foo"), true, cx)
1866 })
1867 .await
1868 .unwrap();
1869 let buffer = project
1870 .update(cx, |project, cx| {
1871 project.open_buffer((worktree.read(cx).id(), pathbuf), cx)
1872 })
1873 .await
1874 .unwrap();
1875
1876 let thread = cx
1877 .update(|cx| connection.new_thread(project, Path::new(path!("/tmp")), cx))
1878 .await
1879 .unwrap();
1880
1881 let request = thread.update(cx, |thread, cx| {
1882 thread.send_raw("Extend the count in /tmp/foo", cx)
1883 });
1884 read_file_rx.await.ok();
1885 buffer.update(cx, |buffer, cx| {
1886 buffer.edit([(0..0, "zero\n".to_string())], None, cx);
1887 });
1888 cx.run_until_parked();
1889 assert_eq!(
1890 buffer.read_with(cx, |buffer, _| buffer.text()),
1891 "zero\none\ntwo\nthree\nfour\nfive\n"
1892 );
1893 assert_eq!(
1894 String::from_utf8(fs.read_file_sync(path!("/tmp/foo")).unwrap()).unwrap(),
1895 "zero\none\ntwo\nthree\nfour\nfive\n"
1896 );
1897 request.await.unwrap();
1898 }
1899
1900 #[gpui::test]
1901 async fn test_succeeding_canceled_toolcall(cx: &mut TestAppContext) {
1902 init_test(cx);
1903
1904 let fs = FakeFs::new(cx.executor());
1905 let project = Project::test(fs, [], cx).await;
1906 let id = acp::ToolCallId("test".into());
1907
1908 let connection = Rc::new(FakeAgentConnection::new().on_user_message({
1909 let id = id.clone();
1910 move |_, thread, mut cx| {
1911 let id = id.clone();
1912 async move {
1913 thread
1914 .update(&mut cx, |thread, cx| {
1915 thread.handle_session_update(
1916 acp::SessionUpdate::ToolCall(acp::ToolCall {
1917 id: id.clone(),
1918 title: "Label".into(),
1919 kind: acp::ToolKind::Fetch,
1920 status: acp::ToolCallStatus::InProgress,
1921 content: vec![],
1922 locations: vec![],
1923 raw_input: None,
1924 raw_output: None,
1925 }),
1926 cx,
1927 )
1928 })
1929 .unwrap()
1930 .unwrap();
1931 Ok(acp::PromptResponse {
1932 stop_reason: acp::StopReason::EndTurn,
1933 })
1934 }
1935 .boxed_local()
1936 }
1937 }));
1938
1939 let thread = cx
1940 .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
1941 .await
1942 .unwrap();
1943
1944 let request = thread.update(cx, |thread, cx| {
1945 thread.send_raw("Fetch https://example.com", cx)
1946 });
1947
1948 run_until_first_tool_call(&thread, cx).await;
1949
1950 thread.read_with(cx, |thread, _| {
1951 assert!(matches!(
1952 thread.entries[1],
1953 AgentThreadEntry::ToolCall(ToolCall {
1954 status: ToolCallStatus::InProgress,
1955 ..
1956 })
1957 ));
1958 });
1959
1960 thread.update(cx, |thread, cx| thread.cancel(cx)).await;
1961
1962 thread.read_with(cx, |thread, _| {
1963 assert!(matches!(
1964 &thread.entries[1],
1965 AgentThreadEntry::ToolCall(ToolCall {
1966 status: ToolCallStatus::Canceled,
1967 ..
1968 })
1969 ));
1970 });
1971
1972 thread
1973 .update(cx, |thread, cx| {
1974 thread.handle_session_update(
1975 acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate {
1976 id,
1977 fields: acp::ToolCallUpdateFields {
1978 status: Some(acp::ToolCallStatus::Completed),
1979 ..Default::default()
1980 },
1981 }),
1982 cx,
1983 )
1984 })
1985 .unwrap();
1986
1987 request.await.unwrap();
1988
1989 thread.read_with(cx, |thread, _| {
1990 assert!(matches!(
1991 thread.entries[1],
1992 AgentThreadEntry::ToolCall(ToolCall {
1993 status: ToolCallStatus::Completed,
1994 ..
1995 })
1996 ));
1997 });
1998 }
1999
2000 #[gpui::test]
2001 async fn test_no_pending_edits_if_tool_calls_are_completed(cx: &mut TestAppContext) {
2002 init_test(cx);
2003 let fs = FakeFs::new(cx.background_executor.clone());
2004 fs.insert_tree(path!("/test"), json!({})).await;
2005 let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
2006
2007 let connection = Rc::new(FakeAgentConnection::new().on_user_message({
2008 move |_, thread, mut cx| {
2009 async move {
2010 thread
2011 .update(&mut cx, |thread, cx| {
2012 thread.handle_session_update(
2013 acp::SessionUpdate::ToolCall(acp::ToolCall {
2014 id: acp::ToolCallId("test".into()),
2015 title: "Label".into(),
2016 kind: acp::ToolKind::Edit,
2017 status: acp::ToolCallStatus::Completed,
2018 content: vec![acp::ToolCallContent::Diff {
2019 diff: acp::Diff {
2020 path: "/test/test.txt".into(),
2021 old_text: None,
2022 new_text: "foo".into(),
2023 },
2024 }],
2025 locations: vec![],
2026 raw_input: None,
2027 raw_output: None,
2028 }),
2029 cx,
2030 )
2031 })
2032 .unwrap()
2033 .unwrap();
2034 Ok(acp::PromptResponse {
2035 stop_reason: acp::StopReason::EndTurn,
2036 })
2037 }
2038 .boxed_local()
2039 }
2040 }));
2041
2042 let thread = cx
2043 .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
2044 .await
2045 .unwrap();
2046
2047 cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["Hi".into()], cx)))
2048 .await
2049 .unwrap();
2050
2051 assert!(cx.read(|cx| !thread.read(cx).has_pending_edit_tool_calls()));
2052 }
2053
2054 #[gpui::test(iterations = 10)]
2055 async fn test_checkpoints(cx: &mut TestAppContext) {
2056 init_test(cx);
2057 let fs = FakeFs::new(cx.background_executor.clone());
2058 fs.insert_tree(
2059 path!("/test"),
2060 json!({
2061 ".git": {}
2062 }),
2063 )
2064 .await;
2065 let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
2066
2067 let simulate_changes = Arc::new(AtomicBool::new(true));
2068 let next_filename = Arc::new(AtomicUsize::new(0));
2069 let connection = Rc::new(FakeAgentConnection::new().on_user_message({
2070 let simulate_changes = simulate_changes.clone();
2071 let next_filename = next_filename.clone();
2072 let fs = fs.clone();
2073 move |request, thread, mut cx| {
2074 let fs = fs.clone();
2075 let simulate_changes = simulate_changes.clone();
2076 let next_filename = next_filename.clone();
2077 async move {
2078 if simulate_changes.load(SeqCst) {
2079 let filename = format!("/test/file-{}", next_filename.fetch_add(1, SeqCst));
2080 fs.write(Path::new(&filename), b"").await?;
2081 }
2082
2083 let acp::ContentBlock::Text(content) = &request.prompt[0] else {
2084 panic!("expected text content block");
2085 };
2086 thread.update(&mut cx, |thread, cx| {
2087 thread
2088 .handle_session_update(
2089 acp::SessionUpdate::AgentMessageChunk {
2090 content: content.text.to_uppercase().into(),
2091 },
2092 cx,
2093 )
2094 .unwrap();
2095 })?;
2096 Ok(acp::PromptResponse {
2097 stop_reason: acp::StopReason::EndTurn,
2098 })
2099 }
2100 .boxed_local()
2101 }
2102 }));
2103 let thread = cx
2104 .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
2105 .await
2106 .unwrap();
2107
2108 cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["Lorem".into()], cx)))
2109 .await
2110 .unwrap();
2111 thread.read_with(cx, |thread, cx| {
2112 assert_eq!(
2113 thread.to_markdown(cx),
2114 indoc! {"
2115 ## User (checkpoint)
2116
2117 Lorem
2118
2119 ## Assistant
2120
2121 LOREM
2122
2123 "}
2124 );
2125 });
2126 assert_eq!(fs.files(), vec![Path::new("/test/file-0")]);
2127
2128 cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["ipsum".into()], cx)))
2129 .await
2130 .unwrap();
2131 thread.read_with(cx, |thread, cx| {
2132 assert_eq!(
2133 thread.to_markdown(cx),
2134 indoc! {"
2135 ## User (checkpoint)
2136
2137 Lorem
2138
2139 ## Assistant
2140
2141 LOREM
2142
2143 ## User (checkpoint)
2144
2145 ipsum
2146
2147 ## Assistant
2148
2149 IPSUM
2150
2151 "}
2152 );
2153 });
2154 assert_eq!(
2155 fs.files(),
2156 vec![Path::new("/test/file-0"), Path::new("/test/file-1")]
2157 );
2158
2159 // Checkpoint isn't stored when there are no changes.
2160 simulate_changes.store(false, SeqCst);
2161 cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["dolor".into()], cx)))
2162 .await
2163 .unwrap();
2164 thread.read_with(cx, |thread, cx| {
2165 assert_eq!(
2166 thread.to_markdown(cx),
2167 indoc! {"
2168 ## User (checkpoint)
2169
2170 Lorem
2171
2172 ## Assistant
2173
2174 LOREM
2175
2176 ## User (checkpoint)
2177
2178 ipsum
2179
2180 ## Assistant
2181
2182 IPSUM
2183
2184 ## User
2185
2186 dolor
2187
2188 ## Assistant
2189
2190 DOLOR
2191
2192 "}
2193 );
2194 });
2195 assert_eq!(
2196 fs.files(),
2197 vec![Path::new("/test/file-0"), Path::new("/test/file-1")]
2198 );
2199
2200 // Rewinding the conversation truncates the history and restores the checkpoint.
2201 thread
2202 .update(cx, |thread, cx| {
2203 let AgentThreadEntry::UserMessage(message) = &thread.entries[2] else {
2204 panic!("unexpected entries {:?}", thread.entries)
2205 };
2206 thread.rewind(message.id.clone().unwrap(), cx)
2207 })
2208 .await
2209 .unwrap();
2210 thread.read_with(cx, |thread, cx| {
2211 assert_eq!(
2212 thread.to_markdown(cx),
2213 indoc! {"
2214 ## User (checkpoint)
2215
2216 Lorem
2217
2218 ## Assistant
2219
2220 LOREM
2221
2222 "}
2223 );
2224 });
2225 assert_eq!(fs.files(), vec![Path::new("/test/file-0")]);
2226 }
2227
2228 async fn run_until_first_tool_call(
2229 thread: &Entity<AcpThread>,
2230 cx: &mut TestAppContext,
2231 ) -> usize {
2232 let (mut tx, mut rx) = mpsc::channel::<usize>(1);
2233
2234 let subscription = cx.update(|cx| {
2235 cx.subscribe(thread, move |thread, _, cx| {
2236 for (ix, entry) in thread.read(cx).entries.iter().enumerate() {
2237 if matches!(entry, AgentThreadEntry::ToolCall(_)) {
2238 return tx.try_send(ix).unwrap();
2239 }
2240 }
2241 })
2242 });
2243
2244 select! {
2245 _ = futures::FutureExt::fuse(smol::Timer::after(Duration::from_secs(10))) => {
2246 panic!("Timeout waiting for tool call")
2247 }
2248 ix = rx.next().fuse() => {
2249 drop(subscription);
2250 ix.unwrap()
2251 }
2252 }
2253 }
2254
2255 #[derive(Clone, Default)]
2256 struct FakeAgentConnection {
2257 auth_methods: Vec<acp::AuthMethod>,
2258 sessions: Arc<parking_lot::Mutex<HashMap<acp::SessionId, WeakEntity<AcpThread>>>>,
2259 on_user_message: Option<
2260 Rc<
2261 dyn Fn(
2262 acp::PromptRequest,
2263 WeakEntity<AcpThread>,
2264 AsyncApp,
2265 ) -> LocalBoxFuture<'static, Result<acp::PromptResponse>>
2266 + 'static,
2267 >,
2268 >,
2269 }
2270
2271 impl FakeAgentConnection {
2272 fn new() -> Self {
2273 Self {
2274 auth_methods: Vec::new(),
2275 on_user_message: None,
2276 sessions: Arc::default(),
2277 }
2278 }
2279
2280 #[expect(unused)]
2281 fn with_auth_methods(mut self, auth_methods: Vec<acp::AuthMethod>) -> Self {
2282 self.auth_methods = auth_methods;
2283 self
2284 }
2285
2286 fn on_user_message(
2287 mut self,
2288 handler: impl Fn(
2289 acp::PromptRequest,
2290 WeakEntity<AcpThread>,
2291 AsyncApp,
2292 ) -> LocalBoxFuture<'static, Result<acp::PromptResponse>>
2293 + 'static,
2294 ) -> Self {
2295 self.on_user_message.replace(Rc::new(handler));
2296 self
2297 }
2298 }
2299
2300 impl AgentConnection for FakeAgentConnection {
2301 fn auth_methods(&self) -> &[acp::AuthMethod] {
2302 &self.auth_methods
2303 }
2304
2305 fn new_thread(
2306 self: Rc<Self>,
2307 project: Entity<Project>,
2308 _cwd: &Path,
2309 cx: &mut gpui::App,
2310 ) -> Task<gpui::Result<Entity<AcpThread>>> {
2311 let session_id = acp::SessionId(
2312 rand::thread_rng()
2313 .sample_iter(&rand::distributions::Alphanumeric)
2314 .take(7)
2315 .map(char::from)
2316 .collect::<String>()
2317 .into(),
2318 );
2319 let thread =
2320 cx.new(|cx| AcpThread::new("Test", self.clone(), project, session_id.clone(), cx));
2321 self.sessions.lock().insert(session_id, thread.downgrade());
2322 Task::ready(Ok(thread))
2323 }
2324
2325 fn authenticate(&self, method: acp::AuthMethodId, _cx: &mut App) -> Task<gpui::Result<()>> {
2326 if self.auth_methods().iter().any(|m| m.id == method) {
2327 Task::ready(Ok(()))
2328 } else {
2329 Task::ready(Err(anyhow!("Invalid Auth Method")))
2330 }
2331 }
2332
2333 fn prompt(
2334 &self,
2335 _id: Option<UserMessageId>,
2336 params: acp::PromptRequest,
2337 cx: &mut App,
2338 ) -> Task<gpui::Result<acp::PromptResponse>> {
2339 let sessions = self.sessions.lock();
2340 let thread = sessions.get(¶ms.session_id).unwrap();
2341 if let Some(handler) = &self.on_user_message {
2342 let handler = handler.clone();
2343 let thread = thread.clone();
2344 cx.spawn(async move |cx| handler(params, thread, cx.clone()).await)
2345 } else {
2346 Task::ready(Ok(acp::PromptResponse {
2347 stop_reason: acp::StopReason::EndTurn,
2348 }))
2349 }
2350 }
2351
2352 fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
2353 let sessions = self.sessions.lock();
2354 let thread = sessions.get(&session_id).unwrap().clone();
2355
2356 cx.spawn(async move |cx| {
2357 thread
2358 .update(cx, |thread, cx| thread.cancel(cx))
2359 .unwrap()
2360 .await
2361 })
2362 .detach();
2363 }
2364
2365 fn session_editor(
2366 &self,
2367 session_id: &acp::SessionId,
2368 _cx: &mut App,
2369 ) -> Option<Rc<dyn AgentSessionEditor>> {
2370 Some(Rc::new(FakeAgentSessionEditor {
2371 _session_id: session_id.clone(),
2372 }))
2373 }
2374
2375 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
2376 self
2377 }
2378 }
2379
2380 struct FakeAgentSessionEditor {
2381 _session_id: acp::SessionId,
2382 }
2383
2384 impl AgentSessionEditor for FakeAgentSessionEditor {
2385 fn truncate(&self, _message_id: UserMessageId, _cx: &mut App) -> Task<Result<()>> {
2386 Task::ready(Ok(()))
2387 }
2388 }
2389}