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