acp_thread.rs

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