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