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