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