acp_thread.rs

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