acp_thread.rs

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