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 session_id(&self) -> &acp::SessionId {
 660        &self.session_id
 661    }
 662
 663    pub fn status(&self) -> ThreadStatus {
 664        if self.send_task.is_some() {
 665            if self.waiting_for_tool_confirmation() {
 666                ThreadStatus::WaitingForToolConfirmation
 667            } else {
 668                ThreadStatus::Generating
 669            }
 670        } else {
 671            ThreadStatus::Idle
 672        }
 673    }
 674
 675    pub fn has_pending_edit_tool_calls(&self) -> bool {
 676        for entry in self.entries.iter().rev() {
 677            match entry {
 678                AgentThreadEntry::UserMessage(_) => return false,
 679                AgentThreadEntry::ToolCall(call) if call.diffs().next().is_some() => return true,
 680                AgentThreadEntry::ToolCall(_) | AgentThreadEntry::AssistantMessage(_) => {}
 681            }
 682        }
 683
 684        false
 685    }
 686
 687    pub fn used_tools_since_last_user_message(&self) -> bool {
 688        for entry in self.entries.iter().rev() {
 689            match entry {
 690                AgentThreadEntry::UserMessage(..) => return false,
 691                AgentThreadEntry::AssistantMessage(..) => continue,
 692                AgentThreadEntry::ToolCall(..) => return true,
 693            }
 694        }
 695
 696        false
 697    }
 698
 699    pub fn handle_session_update(
 700        &mut self,
 701        update: acp::SessionUpdate,
 702        cx: &mut Context<Self>,
 703    ) -> Result<()> {
 704        match update {
 705            acp::SessionUpdate::UserMessageChunk { content } => {
 706                self.push_user_content_block(content, cx);
 707            }
 708            acp::SessionUpdate::AgentMessageChunk { content } => {
 709                self.push_assistant_content_block(content, false, cx);
 710            }
 711            acp::SessionUpdate::AgentThoughtChunk { content } => {
 712                self.push_assistant_content_block(content, true, cx);
 713            }
 714            acp::SessionUpdate::ToolCall(tool_call) => {
 715                self.upsert_tool_call(tool_call, cx);
 716            }
 717            acp::SessionUpdate::ToolCallUpdate(tool_call_update) => {
 718                self.update_tool_call(tool_call_update, cx)?;
 719            }
 720            acp::SessionUpdate::Plan(plan) => {
 721                self.update_plan(plan, cx);
 722            }
 723        }
 724        Ok(())
 725    }
 726
 727    pub fn push_user_content_block(&mut self, chunk: acp::ContentBlock, cx: &mut Context<Self>) {
 728        let language_registry = self.project.read(cx).languages().clone();
 729        let entries_len = self.entries.len();
 730
 731        if let Some(last_entry) = self.entries.last_mut()
 732            && let AgentThreadEntry::UserMessage(UserMessage { content }) = last_entry
 733        {
 734            content.append(chunk, &language_registry, cx);
 735            cx.emit(AcpThreadEvent::EntryUpdated(entries_len - 1));
 736        } else {
 737            let content = ContentBlock::new(chunk, &language_registry, cx);
 738            self.push_entry(AgentThreadEntry::UserMessage(UserMessage { content }), cx);
 739        }
 740    }
 741
 742    pub fn push_assistant_content_block(
 743        &mut self,
 744        chunk: acp::ContentBlock,
 745        is_thought: bool,
 746        cx: &mut Context<Self>,
 747    ) {
 748        let language_registry = self.project.read(cx).languages().clone();
 749        let entries_len = self.entries.len();
 750        if let Some(last_entry) = self.entries.last_mut()
 751            && let AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) = last_entry
 752        {
 753            cx.emit(AcpThreadEvent::EntryUpdated(entries_len - 1));
 754            match (chunks.last_mut(), is_thought) {
 755                (Some(AssistantMessageChunk::Message { block }), false)
 756                | (Some(AssistantMessageChunk::Thought { block }), true) => {
 757                    block.append(chunk, &language_registry, cx)
 758                }
 759                _ => {
 760                    let block = ContentBlock::new(chunk, &language_registry, cx);
 761                    if is_thought {
 762                        chunks.push(AssistantMessageChunk::Thought { block })
 763                    } else {
 764                        chunks.push(AssistantMessageChunk::Message { block })
 765                    }
 766                }
 767            }
 768        } else {
 769            let block = ContentBlock::new(chunk, &language_registry, cx);
 770            let chunk = if is_thought {
 771                AssistantMessageChunk::Thought { block }
 772            } else {
 773                AssistantMessageChunk::Message { block }
 774            };
 775
 776            self.push_entry(
 777                AgentThreadEntry::AssistantMessage(AssistantMessage {
 778                    chunks: vec![chunk],
 779                }),
 780                cx,
 781            );
 782        }
 783    }
 784
 785    fn push_entry(&mut self, entry: AgentThreadEntry, cx: &mut Context<Self>) {
 786        self.entries.push(entry);
 787        cx.emit(AcpThreadEvent::NewEntry);
 788    }
 789
 790    pub fn update_tool_call(
 791        &mut self,
 792        update: acp::ToolCallUpdate,
 793        cx: &mut Context<Self>,
 794    ) -> Result<()> {
 795        let languages = self.project.read(cx).languages().clone();
 796
 797        let (ix, current_call) = self
 798            .tool_call_mut(&update.id)
 799            .context("Tool call not found")?;
 800        current_call.update(update.fields, languages, cx);
 801
 802        cx.emit(AcpThreadEvent::EntryUpdated(ix));
 803
 804        Ok(())
 805    }
 806
 807    /// Updates a tool call if id matches an existing entry, otherwise inserts a new one.
 808    pub fn upsert_tool_call(&mut self, tool_call: acp::ToolCall, cx: &mut Context<Self>) {
 809        let status = ToolCallStatus::Allowed {
 810            status: tool_call.status,
 811        };
 812        self.upsert_tool_call_inner(tool_call, status, cx)
 813    }
 814
 815    pub fn upsert_tool_call_inner(
 816        &mut self,
 817        tool_call: acp::ToolCall,
 818        status: ToolCallStatus,
 819        cx: &mut Context<Self>,
 820    ) {
 821        let language_registry = self.project.read(cx).languages().clone();
 822        let call = ToolCall::from_acp(tool_call, status, language_registry, cx);
 823
 824        let location = call.locations.last().cloned();
 825
 826        if let Some((ix, current_call)) = self.tool_call_mut(&call.id) {
 827            *current_call = call;
 828
 829            cx.emit(AcpThreadEvent::EntryUpdated(ix));
 830        } else {
 831            self.push_entry(AgentThreadEntry::ToolCall(call), cx);
 832        }
 833
 834        if let Some(location) = location {
 835            self.set_project_location(location, cx)
 836        }
 837    }
 838
 839    fn tool_call_mut(&mut self, id: &acp::ToolCallId) -> Option<(usize, &mut ToolCall)> {
 840        // The tool call we are looking for is typically the last one, or very close to the end.
 841        // At the moment, it doesn't seem like a hashmap would be a good fit for this use case.
 842        self.entries
 843            .iter_mut()
 844            .enumerate()
 845            .rev()
 846            .find_map(|(index, tool_call)| {
 847                if let AgentThreadEntry::ToolCall(tool_call) = tool_call
 848                    && &tool_call.id == id
 849                {
 850                    Some((index, tool_call))
 851                } else {
 852                    None
 853                }
 854            })
 855    }
 856
 857    pub fn set_project_location(&self, location: acp::ToolCallLocation, cx: &mut Context<Self>) {
 858        self.project.update(cx, |project, cx| {
 859            let Some(path) = project.project_path_for_absolute_path(&location.path, cx) else {
 860                return;
 861            };
 862            let buffer = project.open_buffer(path, cx);
 863            cx.spawn(async move |project, cx| {
 864                let buffer = buffer.await?;
 865
 866                project.update(cx, |project, cx| {
 867                    let position = if let Some(line) = location.line {
 868                        let snapshot = buffer.read(cx).snapshot();
 869                        let point = snapshot.clip_point(Point::new(line, 0), Bias::Left);
 870                        snapshot.anchor_before(point)
 871                    } else {
 872                        Anchor::MIN
 873                    };
 874
 875                    project.set_agent_location(
 876                        Some(AgentLocation {
 877                            buffer: buffer.downgrade(),
 878                            position,
 879                        }),
 880                        cx,
 881                    );
 882                })
 883            })
 884            .detach_and_log_err(cx);
 885        });
 886    }
 887
 888    pub fn request_tool_call_permission(
 889        &mut self,
 890        tool_call: acp::ToolCall,
 891        options: Vec<acp::PermissionOption>,
 892        cx: &mut Context<Self>,
 893    ) -> oneshot::Receiver<acp::PermissionOptionId> {
 894        let (tx, rx) = oneshot::channel();
 895
 896        let status = ToolCallStatus::WaitingForConfirmation {
 897            options,
 898            respond_tx: tx,
 899        };
 900
 901        self.upsert_tool_call_inner(tool_call, status, cx);
 902        cx.emit(AcpThreadEvent::ToolAuthorizationRequired);
 903        rx
 904    }
 905
 906    pub fn authorize_tool_call(
 907        &mut self,
 908        id: acp::ToolCallId,
 909        option_id: acp::PermissionOptionId,
 910        option_kind: acp::PermissionOptionKind,
 911        cx: &mut Context<Self>,
 912    ) {
 913        let Some((ix, call)) = self.tool_call_mut(&id) else {
 914            return;
 915        };
 916
 917        let new_status = match option_kind {
 918            acp::PermissionOptionKind::RejectOnce | acp::PermissionOptionKind::RejectAlways => {
 919                ToolCallStatus::Rejected
 920            }
 921            acp::PermissionOptionKind::AllowOnce | acp::PermissionOptionKind::AllowAlways => {
 922                ToolCallStatus::Allowed {
 923                    status: acp::ToolCallStatus::InProgress,
 924                }
 925            }
 926        };
 927
 928        let curr_status = mem::replace(&mut call.status, new_status);
 929
 930        if let ToolCallStatus::WaitingForConfirmation { respond_tx, .. } = curr_status {
 931            respond_tx.send(option_id).log_err();
 932        } else if cfg!(debug_assertions) {
 933            panic!("tried to authorize an already authorized tool call");
 934        }
 935
 936        cx.emit(AcpThreadEvent::EntryUpdated(ix));
 937    }
 938
 939    /// Returns true if the last turn is awaiting tool authorization
 940    pub fn waiting_for_tool_confirmation(&self) -> bool {
 941        for entry in self.entries.iter().rev() {
 942            match &entry {
 943                AgentThreadEntry::ToolCall(call) => match call.status {
 944                    ToolCallStatus::WaitingForConfirmation { .. } => return true,
 945                    ToolCallStatus::Allowed { .. }
 946                    | ToolCallStatus::Rejected
 947                    | ToolCallStatus::Canceled => continue,
 948                },
 949                AgentThreadEntry::UserMessage(_) | AgentThreadEntry::AssistantMessage(_) => {
 950                    // Reached the beginning of the turn
 951                    return false;
 952                }
 953            }
 954        }
 955        false
 956    }
 957
 958    pub fn plan(&self) -> &Plan {
 959        &self.plan
 960    }
 961
 962    pub fn update_plan(&mut self, request: acp::Plan, cx: &mut Context<Self>) {
 963        self.plan = Plan {
 964            entries: request
 965                .entries
 966                .into_iter()
 967                .map(|entry| PlanEntry::from_acp(entry, cx))
 968                .collect(),
 969        };
 970
 971        cx.notify();
 972    }
 973
 974    fn clear_completed_plan_entries(&mut self, cx: &mut Context<Self>) {
 975        self.plan
 976            .entries
 977            .retain(|entry| !matches!(entry.status, acp::PlanEntryStatus::Completed));
 978        cx.notify();
 979    }
 980
 981    #[cfg(any(test, feature = "test-support"))]
 982    pub fn send_raw(
 983        &mut self,
 984        message: &str,
 985        cx: &mut Context<Self>,
 986    ) -> BoxFuture<'static, Result<()>> {
 987        self.send(
 988            vec![acp::ContentBlock::Text(acp::TextContent {
 989                text: message.to_string(),
 990                annotations: None,
 991            })],
 992            cx,
 993        )
 994    }
 995
 996    pub fn send(
 997        &mut self,
 998        message: Vec<acp::ContentBlock>,
 999        cx: &mut Context<Self>,
1000    ) -> BoxFuture<'static, Result<()>> {
1001        let block = ContentBlock::new_combined(
1002            message.clone(),
1003            self.project.read(cx).languages().clone(),
1004            cx,
1005        );
1006        self.push_entry(
1007            AgentThreadEntry::UserMessage(UserMessage { content: block }),
1008            cx,
1009        );
1010        self.clear_completed_plan_entries(cx);
1011
1012        let (tx, rx) = oneshot::channel();
1013        let cancel_task = self.cancel(cx);
1014
1015        self.send_task = Some(cx.spawn(async move |this, cx| {
1016            async {
1017                cancel_task.await;
1018
1019                let result = this
1020                    .update(cx, |this, cx| {
1021                        this.connection.prompt(
1022                            acp::PromptRequest {
1023                                prompt: message,
1024                                session_id: this.session_id.clone(),
1025                            },
1026                            cx,
1027                        )
1028                    })?
1029                    .await;
1030                tx.send(result).log_err();
1031                this.update(cx, |this, _cx| this.send_task.take())?;
1032                anyhow::Ok(())
1033            }
1034            .await
1035            .log_err();
1036        }));
1037
1038        cx.spawn(async move |this, cx| match rx.await {
1039            Ok(Err(e)) => {
1040                this.update(cx, |_, cx| cx.emit(AcpThreadEvent::Error))
1041                    .log_err();
1042                Err(e)?
1043            }
1044            _ => {
1045                this.update(cx, |_, cx| cx.emit(AcpThreadEvent::Stopped))
1046                    .log_err();
1047                Ok(())
1048            }
1049        })
1050        .boxed()
1051    }
1052
1053    pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
1054        let Some(send_task) = self.send_task.take() else {
1055            return Task::ready(());
1056        };
1057
1058        for entry in self.entries.iter_mut() {
1059            if let AgentThreadEntry::ToolCall(call) = entry {
1060                let cancel = matches!(
1061                    call.status,
1062                    ToolCallStatus::WaitingForConfirmation { .. }
1063                        | ToolCallStatus::Allowed {
1064                            status: acp::ToolCallStatus::InProgress
1065                        }
1066                );
1067
1068                if cancel {
1069                    call.status = ToolCallStatus::Canceled;
1070                }
1071            }
1072        }
1073
1074        self.connection.cancel(&self.session_id, cx);
1075
1076        // Wait for the send task to complete
1077        cx.foreground_executor().spawn(send_task)
1078    }
1079
1080    pub fn read_text_file(
1081        &self,
1082        path: PathBuf,
1083        line: Option<u32>,
1084        limit: Option<u32>,
1085        reuse_shared_snapshot: bool,
1086        cx: &mut Context<Self>,
1087    ) -> Task<Result<String>> {
1088        let project = self.project.clone();
1089        let action_log = self.action_log.clone();
1090        cx.spawn(async move |this, cx| {
1091            let load = project.update(cx, |project, cx| {
1092                let path = project
1093                    .project_path_for_absolute_path(&path, cx)
1094                    .context("invalid path")?;
1095                anyhow::Ok(project.open_buffer(path, cx))
1096            });
1097            let buffer = load??.await?;
1098
1099            let snapshot = if reuse_shared_snapshot {
1100                this.read_with(cx, |this, _| {
1101                    this.shared_buffers.get(&buffer.clone()).cloned()
1102                })
1103                .log_err()
1104                .flatten()
1105            } else {
1106                None
1107            };
1108
1109            let snapshot = if let Some(snapshot) = snapshot {
1110                snapshot
1111            } else {
1112                action_log.update(cx, |action_log, cx| {
1113                    action_log.buffer_read(buffer.clone(), cx);
1114                })?;
1115                project.update(cx, |project, cx| {
1116                    let position = buffer
1117                        .read(cx)
1118                        .snapshot()
1119                        .anchor_before(Point::new(line.unwrap_or_default(), 0));
1120                    project.set_agent_location(
1121                        Some(AgentLocation {
1122                            buffer: buffer.downgrade(),
1123                            position,
1124                        }),
1125                        cx,
1126                    );
1127                })?;
1128
1129                buffer.update(cx, |buffer, _| buffer.snapshot())?
1130            };
1131
1132            this.update(cx, |this, _| {
1133                let text = snapshot.text();
1134                this.shared_buffers.insert(buffer.clone(), snapshot);
1135                if line.is_none() && limit.is_none() {
1136                    return Ok(text);
1137                }
1138                let limit = limit.unwrap_or(u32::MAX) as usize;
1139                let Some(line) = line else {
1140                    return Ok(text.lines().take(limit).collect::<String>());
1141                };
1142
1143                let count = text.lines().count();
1144                if count < line as usize {
1145                    anyhow::bail!("There are only {} lines", count);
1146                }
1147                Ok(text
1148                    .lines()
1149                    .skip(line as usize + 1)
1150                    .take(limit)
1151                    .collect::<String>())
1152            })?
1153        })
1154    }
1155
1156    pub fn write_text_file(
1157        &self,
1158        path: PathBuf,
1159        content: String,
1160        cx: &mut Context<Self>,
1161    ) -> Task<Result<()>> {
1162        let project = self.project.clone();
1163        let action_log = self.action_log.clone();
1164        cx.spawn(async move |this, cx| {
1165            let load = project.update(cx, |project, cx| {
1166                let path = project
1167                    .project_path_for_absolute_path(&path, cx)
1168                    .context("invalid path")?;
1169                anyhow::Ok(project.open_buffer(path, cx))
1170            });
1171            let buffer = load??.await?;
1172            let snapshot = this.update(cx, |this, cx| {
1173                this.shared_buffers
1174                    .get(&buffer)
1175                    .cloned()
1176                    .unwrap_or_else(|| buffer.read(cx).snapshot())
1177            })?;
1178            let edits = cx
1179                .background_executor()
1180                .spawn(async move {
1181                    let old_text = snapshot.text();
1182                    text_diff(old_text.as_str(), &content)
1183                        .into_iter()
1184                        .map(|(range, replacement)| {
1185                            (
1186                                snapshot.anchor_after(range.start)
1187                                    ..snapshot.anchor_before(range.end),
1188                                replacement,
1189                            )
1190                        })
1191                        .collect::<Vec<_>>()
1192                })
1193                .await;
1194            cx.update(|cx| {
1195                project.update(cx, |project, cx| {
1196                    project.set_agent_location(
1197                        Some(AgentLocation {
1198                            buffer: buffer.downgrade(),
1199                            position: edits
1200                                .last()
1201                                .map(|(range, _)| range.end)
1202                                .unwrap_or(Anchor::MIN),
1203                        }),
1204                        cx,
1205                    );
1206                });
1207
1208                action_log.update(cx, |action_log, cx| {
1209                    action_log.buffer_read(buffer.clone(), cx);
1210                });
1211                buffer.update(cx, |buffer, cx| {
1212                    buffer.edit(edits, None, cx);
1213                });
1214                action_log.update(cx, |action_log, cx| {
1215                    action_log.buffer_edited(buffer.clone(), cx);
1216                });
1217            })?;
1218            project
1219                .update(cx, |project, cx| project.save_buffer(buffer, cx))?
1220                .await
1221        })
1222    }
1223
1224    pub fn to_markdown(&self, cx: &App) -> String {
1225        self.entries.iter().map(|e| e.to_markdown(cx)).collect()
1226    }
1227}
1228
1229#[cfg(test)]
1230mod tests {
1231    use super::*;
1232    use agentic_coding_protocol as acp_old;
1233    use anyhow::anyhow;
1234    use async_pipe::{PipeReader, PipeWriter};
1235    use futures::{channel::mpsc, future::LocalBoxFuture, select};
1236    use gpui::{AsyncApp, TestAppContext};
1237    use indoc::indoc;
1238    use project::FakeFs;
1239    use serde_json::json;
1240    use settings::SettingsStore;
1241    use smol::{future::BoxedLocal, stream::StreamExt as _};
1242    use std::{cell::RefCell, rc::Rc, time::Duration};
1243
1244    use util::path;
1245
1246    fn init_test(cx: &mut TestAppContext) {
1247        env_logger::try_init().ok();
1248        cx.update(|cx| {
1249            let settings_store = SettingsStore::test(cx);
1250            cx.set_global(settings_store);
1251            Project::init_settings(cx);
1252            language::init(cx);
1253        });
1254    }
1255
1256    #[gpui::test]
1257    async fn test_push_user_content_block(cx: &mut gpui::TestAppContext) {
1258        init_test(cx);
1259
1260        let fs = FakeFs::new(cx.executor());
1261        let project = Project::test(fs, [], cx).await;
1262        let (thread, _fake_server) = fake_acp_thread(project, cx);
1263
1264        // Test creating a new user message
1265        thread.update(cx, |thread, cx| {
1266            thread.push_user_content_block(
1267                acp::ContentBlock::Text(acp::TextContent {
1268                    annotations: None,
1269                    text: "Hello, ".to_string(),
1270                }),
1271                cx,
1272            );
1273        });
1274
1275        thread.update(cx, |thread, cx| {
1276            assert_eq!(thread.entries.len(), 1);
1277            if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
1278                assert_eq!(user_msg.content.to_markdown(cx), "Hello, ");
1279            } else {
1280                panic!("Expected UserMessage");
1281            }
1282        });
1283
1284        // Test appending to existing user message
1285        thread.update(cx, |thread, cx| {
1286            thread.push_user_content_block(
1287                acp::ContentBlock::Text(acp::TextContent {
1288                    annotations: None,
1289                    text: "world!".to_string(),
1290                }),
1291                cx,
1292            );
1293        });
1294
1295        thread.update(cx, |thread, cx| {
1296            assert_eq!(thread.entries.len(), 1);
1297            if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
1298                assert_eq!(user_msg.content.to_markdown(cx), "Hello, world!");
1299            } else {
1300                panic!("Expected UserMessage");
1301            }
1302        });
1303
1304        // Test creating new user message after assistant message
1305        thread.update(cx, |thread, cx| {
1306            thread.push_assistant_content_block(
1307                acp::ContentBlock::Text(acp::TextContent {
1308                    annotations: None,
1309                    text: "Assistant response".to_string(),
1310                }),
1311                false,
1312                cx,
1313            );
1314        });
1315
1316        thread.update(cx, |thread, cx| {
1317            thread.push_user_content_block(
1318                acp::ContentBlock::Text(acp::TextContent {
1319                    annotations: None,
1320                    text: "New user message".to_string(),
1321                }),
1322                cx,
1323            );
1324        });
1325
1326        thread.update(cx, |thread, cx| {
1327            assert_eq!(thread.entries.len(), 3);
1328            if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[2] {
1329                assert_eq!(user_msg.content.to_markdown(cx), "New user message");
1330            } else {
1331                panic!("Expected UserMessage at index 2");
1332            }
1333        });
1334    }
1335
1336    #[gpui::test]
1337    async fn test_thinking_concatenation(cx: &mut gpui::TestAppContext) {
1338        init_test(cx);
1339
1340        let fs = FakeFs::new(cx.executor());
1341        let project = Project::test(fs, [], cx).await;
1342        let (thread, fake_server) = fake_acp_thread(project, cx);
1343
1344        fake_server.update(cx, |fake_server, _| {
1345            fake_server.on_user_message(move |_, server, mut cx| async move {
1346                server
1347                    .update(&mut cx, |server, _| {
1348                        server.send_to_zed(acp_old::StreamAssistantMessageChunkParams {
1349                            chunk: acp_old::AssistantMessageChunk::Thought {
1350                                thought: "Thinking ".into(),
1351                            },
1352                        })
1353                    })?
1354                    .await
1355                    .unwrap();
1356                server
1357                    .update(&mut cx, |server, _| {
1358                        server.send_to_zed(acp_old::StreamAssistantMessageChunkParams {
1359                            chunk: acp_old::AssistantMessageChunk::Thought {
1360                                thought: "hard!".into(),
1361                            },
1362                        })
1363                    })?
1364                    .await
1365                    .unwrap();
1366
1367                Ok(())
1368            })
1369        });
1370
1371        thread
1372            .update(cx, |thread, cx| thread.send_raw("Hello from Zed!", cx))
1373            .await
1374            .unwrap();
1375
1376        let output = thread.read_with(cx, |thread, cx| thread.to_markdown(cx));
1377        assert_eq!(
1378            output,
1379            indoc! {r#"
1380            ## User
1381
1382            Hello from Zed!
1383
1384            ## Assistant
1385
1386            <thinking>
1387            Thinking hard!
1388            </thinking>
1389
1390            "#}
1391        );
1392    }
1393
1394    #[gpui::test]
1395    async fn test_edits_concurrently_to_user(cx: &mut TestAppContext) {
1396        init_test(cx);
1397
1398        let fs = FakeFs::new(cx.executor());
1399        fs.insert_tree(path!("/tmp"), json!({"foo": "one\ntwo\nthree\n"}))
1400            .await;
1401        let project = Project::test(fs.clone(), [], cx).await;
1402        let (thread, fake_server) = fake_acp_thread(project.clone(), cx);
1403        let (worktree, pathbuf) = project
1404            .update(cx, |project, cx| {
1405                project.find_or_create_worktree(path!("/tmp/foo"), true, cx)
1406            })
1407            .await
1408            .unwrap();
1409        let buffer = project
1410            .update(cx, |project, cx| {
1411                project.open_buffer((worktree.read(cx).id(), pathbuf), cx)
1412            })
1413            .await
1414            .unwrap();
1415
1416        let (read_file_tx, read_file_rx) = oneshot::channel::<()>();
1417        let read_file_tx = Rc::new(RefCell::new(Some(read_file_tx)));
1418
1419        fake_server.update(cx, |fake_server, _| {
1420            fake_server.on_user_message(move |_, server, mut cx| {
1421                let read_file_tx = read_file_tx.clone();
1422                async move {
1423                    let content = server
1424                        .update(&mut cx, |server, _| {
1425                            server.send_to_zed(acp_old::ReadTextFileParams {
1426                                path: path!("/tmp/foo").into(),
1427                                line: None,
1428                                limit: None,
1429                            })
1430                        })?
1431                        .await
1432                        .unwrap();
1433                    assert_eq!(content.content, "one\ntwo\nthree\n");
1434                    read_file_tx.take().unwrap().send(()).unwrap();
1435                    server
1436                        .update(&mut cx, |server, _| {
1437                            server.send_to_zed(acp_old::WriteTextFileParams {
1438                                path: path!("/tmp/foo").into(),
1439                                content: "one\ntwo\nthree\nfour\nfive\n".to_string(),
1440                            })
1441                        })?
1442                        .await
1443                        .unwrap();
1444                    Ok(())
1445                }
1446            })
1447        });
1448
1449        let request = thread.update(cx, |thread, cx| {
1450            thread.send_raw("Extend the count in /tmp/foo", cx)
1451        });
1452        read_file_rx.await.ok();
1453        buffer.update(cx, |buffer, cx| {
1454            buffer.edit([(0..0, "zero\n".to_string())], None, cx);
1455        });
1456        cx.run_until_parked();
1457        assert_eq!(
1458            buffer.read_with(cx, |buffer, _| buffer.text()),
1459            "zero\none\ntwo\nthree\nfour\nfive\n"
1460        );
1461        assert_eq!(
1462            String::from_utf8(fs.read_file_sync(path!("/tmp/foo")).unwrap()).unwrap(),
1463            "zero\none\ntwo\nthree\nfour\nfive\n"
1464        );
1465        request.await.unwrap();
1466    }
1467
1468    #[gpui::test]
1469    async fn test_succeeding_canceled_toolcall(cx: &mut TestAppContext) {
1470        init_test(cx);
1471
1472        let fs = FakeFs::new(cx.executor());
1473        let project = Project::test(fs, [], cx).await;
1474        let (thread, fake_server) = fake_acp_thread(project, cx);
1475
1476        let (end_turn_tx, end_turn_rx) = oneshot::channel::<()>();
1477
1478        let tool_call_id = Rc::new(RefCell::new(None));
1479        let end_turn_rx = Rc::new(RefCell::new(Some(end_turn_rx)));
1480        fake_server.update(cx, |fake_server, _| {
1481            let tool_call_id = tool_call_id.clone();
1482            fake_server.on_user_message(move |_, server, mut cx| {
1483                let end_turn_rx = end_turn_rx.clone();
1484                let tool_call_id = tool_call_id.clone();
1485                async move {
1486                    let tool_call_result = server
1487                        .update(&mut cx, |server, _| {
1488                            server.send_to_zed(acp_old::PushToolCallParams {
1489                                label: "Fetch".to_string(),
1490                                icon: acp_old::Icon::Globe,
1491                                content: None,
1492                                locations: vec![],
1493                            })
1494                        })?
1495                        .await
1496                        .unwrap();
1497                    *tool_call_id.clone().borrow_mut() = Some(tool_call_result.id);
1498                    end_turn_rx.take().unwrap().await.ok();
1499
1500                    Ok(())
1501                }
1502            })
1503        });
1504
1505        let request = thread.update(cx, |thread, cx| {
1506            thread.send_raw("Fetch https://example.com", cx)
1507        });
1508
1509        run_until_first_tool_call(&thread, cx).await;
1510
1511        thread.read_with(cx, |thread, _| {
1512            assert!(matches!(
1513                thread.entries[1],
1514                AgentThreadEntry::ToolCall(ToolCall {
1515                    status: ToolCallStatus::Allowed {
1516                        status: acp::ToolCallStatus::InProgress,
1517                        ..
1518                    },
1519                    ..
1520                })
1521            ));
1522        });
1523
1524        cx.run_until_parked();
1525
1526        thread.update(cx, |thread, cx| thread.cancel(cx)).await;
1527
1528        thread.read_with(cx, |thread, _| {
1529            assert!(matches!(
1530                &thread.entries[1],
1531                AgentThreadEntry::ToolCall(ToolCall {
1532                    status: ToolCallStatus::Canceled,
1533                    ..
1534                })
1535            ));
1536        });
1537
1538        fake_server
1539            .update(cx, |fake_server, _| {
1540                fake_server.send_to_zed(acp_old::UpdateToolCallParams {
1541                    tool_call_id: tool_call_id.borrow().unwrap(),
1542                    status: acp_old::ToolCallStatus::Finished,
1543                    content: None,
1544                })
1545            })
1546            .await
1547            .unwrap();
1548
1549        drop(end_turn_tx);
1550        assert!(request.await.unwrap_err().to_string().contains("canceled"));
1551
1552        thread.read_with(cx, |thread, _| {
1553            assert!(matches!(
1554                thread.entries[1],
1555                AgentThreadEntry::ToolCall(ToolCall {
1556                    status: ToolCallStatus::Allowed {
1557                        status: acp::ToolCallStatus::Completed,
1558                        ..
1559                    },
1560                    ..
1561                })
1562            ));
1563        });
1564    }
1565
1566    async fn run_until_first_tool_call(
1567        thread: &Entity<AcpThread>,
1568        cx: &mut TestAppContext,
1569    ) -> usize {
1570        let (mut tx, mut rx) = mpsc::channel::<usize>(1);
1571
1572        let subscription = cx.update(|cx| {
1573            cx.subscribe(thread, move |thread, _, cx| {
1574                for (ix, entry) in thread.read(cx).entries.iter().enumerate() {
1575                    if matches!(entry, AgentThreadEntry::ToolCall(_)) {
1576                        return tx.try_send(ix).unwrap();
1577                    }
1578                }
1579            })
1580        });
1581
1582        select! {
1583            _ = futures::FutureExt::fuse(smol::Timer::after(Duration::from_secs(10))) => {
1584                panic!("Timeout waiting for tool call")
1585            }
1586            ix = rx.next().fuse() => {
1587                drop(subscription);
1588                ix.unwrap()
1589            }
1590        }
1591    }
1592
1593    pub fn fake_acp_thread(
1594        project: Entity<Project>,
1595        cx: &mut TestAppContext,
1596    ) -> (Entity<AcpThread>, Entity<FakeAcpServer>) {
1597        let (stdin_tx, stdin_rx) = async_pipe::pipe();
1598        let (stdout_tx, stdout_rx) = async_pipe::pipe();
1599
1600        let thread = cx.new(|cx| {
1601            let foreground_executor = cx.foreground_executor().clone();
1602            let thread_rc = Rc::new(RefCell::new(cx.entity().downgrade()));
1603
1604            let (connection, io_fut) = acp_old::AgentConnection::connect_to_agent(
1605                OldAcpClientDelegate::new(thread_rc.clone(), cx.to_async()),
1606                stdin_tx,
1607                stdout_rx,
1608                move |fut| {
1609                    foreground_executor.spawn(fut).detach();
1610                },
1611            );
1612
1613            let io_task = cx.background_spawn({
1614                async move {
1615                    io_fut.await.log_err();
1616                    Ok(())
1617                }
1618            });
1619            let connection = OldAcpAgentConnection {
1620                name: "test",
1621                connection,
1622                child_status: io_task,
1623                current_thread: thread_rc,
1624                auth_methods: [acp::AuthMethod {
1625                    id: acp::AuthMethodId("acp-old-no-id".into()),
1626                    label: "Log in".into(),
1627                    description: None,
1628                }],
1629            };
1630
1631            AcpThread::new(
1632                "test",
1633                Rc::new(connection),
1634                project,
1635                acp::SessionId("test".into()),
1636                cx,
1637            )
1638        });
1639        let agent = cx.update(|cx| cx.new(|cx| FakeAcpServer::new(stdin_rx, stdout_tx, cx)));
1640        (thread, agent)
1641    }
1642
1643    pub struct FakeAcpServer {
1644        connection: acp_old::ClientConnection,
1645
1646        _io_task: Task<()>,
1647        on_user_message: Option<
1648            Rc<
1649                dyn Fn(
1650                    acp_old::SendUserMessageParams,
1651                    Entity<FakeAcpServer>,
1652                    AsyncApp,
1653                ) -> LocalBoxFuture<'static, Result<(), acp_old::Error>>,
1654            >,
1655        >,
1656    }
1657
1658    #[derive(Clone)]
1659    struct FakeAgent {
1660        server: Entity<FakeAcpServer>,
1661        cx: AsyncApp,
1662        cancel_tx: Rc<RefCell<Option<oneshot::Sender<()>>>>,
1663    }
1664
1665    impl acp_old::Agent for FakeAgent {
1666        async fn initialize(
1667            &self,
1668            params: acp_old::InitializeParams,
1669        ) -> Result<acp_old::InitializeResponse, acp_old::Error> {
1670            Ok(acp_old::InitializeResponse {
1671                protocol_version: params.protocol_version,
1672                is_authenticated: true,
1673            })
1674        }
1675
1676        async fn authenticate(&self) -> Result<(), acp_old::Error> {
1677            Ok(())
1678        }
1679
1680        async fn cancel_send_message(&self) -> Result<(), acp_old::Error> {
1681            if let Some(cancel_tx) = self.cancel_tx.take() {
1682                cancel_tx.send(()).log_err();
1683            }
1684            Ok(())
1685        }
1686
1687        async fn send_user_message(
1688            &self,
1689            request: acp_old::SendUserMessageParams,
1690        ) -> Result<(), acp_old::Error> {
1691            let (cancel_tx, cancel_rx) = oneshot::channel();
1692            self.cancel_tx.replace(Some(cancel_tx));
1693
1694            let mut cx = self.cx.clone();
1695            let handler = self
1696                .server
1697                .update(&mut cx, |server, _| server.on_user_message.clone())
1698                .ok()
1699                .flatten();
1700            if let Some(handler) = handler {
1701                select! {
1702                    _ = cancel_rx.fuse() => Err(anyhow::anyhow!("Message sending canceled").into()),
1703                    _ = handler(request, self.server.clone(), self.cx.clone()).fuse() => Ok(()),
1704                }
1705            } else {
1706                Err(anyhow::anyhow!("No handler for on_user_message").into())
1707            }
1708        }
1709    }
1710
1711    impl FakeAcpServer {
1712        fn new(stdin: PipeReader, stdout: PipeWriter, cx: &Context<Self>) -> Self {
1713            let agent = FakeAgent {
1714                server: cx.entity(),
1715                cx: cx.to_async(),
1716                cancel_tx: Default::default(),
1717            };
1718            let foreground_executor = cx.foreground_executor().clone();
1719
1720            let (connection, io_fut) = acp_old::ClientConnection::connect_to_client(
1721                agent.clone(),
1722                stdout,
1723                stdin,
1724                move |fut| {
1725                    foreground_executor.spawn(fut).detach();
1726                },
1727            );
1728            FakeAcpServer {
1729                connection: connection,
1730                on_user_message: None,
1731                _io_task: cx.background_spawn(async move {
1732                    io_fut.await.log_err();
1733                }),
1734            }
1735        }
1736
1737        fn on_user_message<F>(
1738            &mut self,
1739            handler: impl for<'a> Fn(
1740                acp_old::SendUserMessageParams,
1741                Entity<FakeAcpServer>,
1742                AsyncApp,
1743            ) -> F
1744            + 'static,
1745        ) where
1746            F: Future<Output = Result<(), acp_old::Error>> + 'static,
1747        {
1748            self.on_user_message
1749                .replace(Rc::new(move |request, server, cx| {
1750                    handler(request, server, cx).boxed_local()
1751                }));
1752        }
1753
1754        fn send_to_zed<T: acp_old::ClientRequest + 'static>(
1755            &self,
1756            message: T,
1757        ) -> BoxedLocal<Result<T::Response>> {
1758            self.connection
1759                .request(message)
1760                .map(|f| f.map_err(|err| anyhow!(err)))
1761                .boxed_local()
1762        }
1763    }
1764}