acp_thread.rs

   1mod connection;
   2mod diff;
   3mod mention;
   4mod terminal;
   5
   6pub use connection::*;
   7pub use diff::*;
   8pub use mention::*;
   9pub use terminal::*;
  10
  11use action_log::ActionLog;
  12use agent_client_protocol as acp;
  13use anyhow::{Context as _, Result, anyhow};
  14use editor::Bias;
  15use futures::{FutureExt, channel::oneshot, future::BoxFuture};
  16use gpui::{AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task, WeakEntity};
  17use itertools::Itertools;
  18use language::{Anchor, Buffer, BufferSnapshot, LanguageRegistry, Point, ToPoint, text_diff};
  19use markdown::Markdown;
  20use project::{AgentLocation, Project, git_store::GitStoreCheckpoint};
  21use std::collections::HashMap;
  22use std::error::Error;
  23use std::fmt::{Formatter, Write};
  24use std::ops::Range;
  25use std::process::ExitStatus;
  26use std::rc::Rc;
  27use std::{fmt::Display, mem, path::PathBuf, sync::Arc};
  28use ui::App;
  29use util::ResultExt;
  30
  31#[derive(Debug)]
  32pub struct UserMessage {
  33    pub id: Option<UserMessageId>,
  34    pub content: ContentBlock,
  35    pub chunks: Vec<acp::ContentBlock>,
  36    pub checkpoint: Option<Checkpoint>,
  37}
  38
  39#[derive(Debug)]
  40pub struct Checkpoint {
  41    git_checkpoint: GitStoreCheckpoint,
  42    pub show: bool,
  43}
  44
  45impl UserMessage {
  46    fn to_markdown(&self, cx: &App) -> String {
  47        let mut markdown = String::new();
  48        if self
  49            .checkpoint
  50            .as_ref()
  51            .map_or(false, |checkpoint| checkpoint.show)
  52        {
  53            writeln!(markdown, "## User (checkpoint)").unwrap();
  54        } else {
  55            writeln!(markdown, "## User").unwrap();
  56        }
  57        writeln!(markdown).unwrap();
  58        writeln!(markdown, "{}", self.content.to_markdown(cx)).unwrap();
  59        writeln!(markdown).unwrap();
  60        markdown
  61    }
  62}
  63
  64#[derive(Debug, PartialEq)]
  65pub struct AssistantMessage {
  66    pub chunks: Vec<AssistantMessageChunk>,
  67}
  68
  69impl AssistantMessage {
  70    pub fn to_markdown(&self, cx: &App) -> String {
  71        format!(
  72            "## Assistant\n\n{}\n\n",
  73            self.chunks
  74                .iter()
  75                .map(|chunk| chunk.to_markdown(cx))
  76                .join("\n\n")
  77        )
  78    }
  79}
  80
  81#[derive(Debug, PartialEq)]
  82pub enum AssistantMessageChunk {
  83    Message { block: ContentBlock },
  84    Thought { block: ContentBlock },
  85}
  86
  87impl AssistantMessageChunk {
  88    pub fn from_str(chunk: &str, language_registry: &Arc<LanguageRegistry>, cx: &mut App) -> Self {
  89        Self::Message {
  90            block: ContentBlock::new(chunk.into(), language_registry, cx),
  91        }
  92    }
  93
  94    fn to_markdown(&self, cx: &App) -> String {
  95        match self {
  96            Self::Message { block } => block.to_markdown(cx).to_string(),
  97            Self::Thought { block } => {
  98                format!("<thinking>\n{}\n</thinking>", block.to_markdown(cx))
  99            }
 100        }
 101    }
 102}
 103
 104#[derive(Debug)]
 105pub enum AgentThreadEntry {
 106    UserMessage(UserMessage),
 107    AssistantMessage(AssistantMessage),
 108    ToolCall(ToolCall),
 109}
 110
 111impl AgentThreadEntry {
 112    pub fn to_markdown(&self, cx: &App) -> String {
 113        match self {
 114            Self::UserMessage(message) => message.to_markdown(cx),
 115            Self::AssistantMessage(message) => message.to_markdown(cx),
 116            Self::ToolCall(tool_call) => tool_call.to_markdown(cx),
 117        }
 118    }
 119
 120    pub fn user_message(&self) -> Option<&UserMessage> {
 121        if let AgentThreadEntry::UserMessage(message) = self {
 122            Some(message)
 123        } else {
 124            None
 125        }
 126    }
 127
 128    pub fn diffs(&self) -> impl Iterator<Item = &Entity<Diff>> {
 129        if let AgentThreadEntry::ToolCall(call) = self {
 130            itertools::Either::Left(call.diffs())
 131        } else {
 132            itertools::Either::Right(std::iter::empty())
 133        }
 134    }
 135
 136    pub fn terminals(&self) -> impl Iterator<Item = &Entity<Terminal>> {
 137        if let AgentThreadEntry::ToolCall(call) = self {
 138            itertools::Either::Left(call.terminals())
 139        } else {
 140            itertools::Either::Right(std::iter::empty())
 141        }
 142    }
 143
 144    pub fn location(&self, ix: usize) -> Option<(acp::ToolCallLocation, AgentLocation)> {
 145        if let AgentThreadEntry::ToolCall(ToolCall {
 146            locations,
 147            resolved_locations,
 148            ..
 149        }) = self
 150        {
 151            Some((
 152                locations.get(ix)?.clone(),
 153                resolved_locations.get(ix)?.clone()?,
 154            ))
 155        } else {
 156            None
 157        }
 158    }
 159}
 160
 161#[derive(Debug)]
 162pub struct ToolCall {
 163    pub id: acp::ToolCallId,
 164    pub label: Entity<Markdown>,
 165    pub kind: acp::ToolKind,
 166    pub content: Vec<ToolCallContent>,
 167    pub status: ToolCallStatus,
 168    pub locations: Vec<acp::ToolCallLocation>,
 169    pub resolved_locations: Vec<Option<AgentLocation>>,
 170    pub raw_input: Option<serde_json::Value>,
 171    pub raw_output: Option<serde_json::Value>,
 172}
 173
 174impl ToolCall {
 175    fn from_acp(
 176        tool_call: acp::ToolCall,
 177        status: ToolCallStatus,
 178        language_registry: Arc<LanguageRegistry>,
 179        cx: &mut App,
 180    ) -> Self {
 181        Self {
 182            id: tool_call.id,
 183            label: cx.new(|cx| {
 184                Markdown::new(
 185                    tool_call.title.into(),
 186                    Some(language_registry.clone()),
 187                    None,
 188                    cx,
 189                )
 190            }),
 191            kind: tool_call.kind,
 192            content: tool_call
 193                .content
 194                .into_iter()
 195                .map(|content| ToolCallContent::from_acp(content, language_registry.clone(), cx))
 196                .collect(),
 197            locations: tool_call.locations,
 198            resolved_locations: Vec::default(),
 199            status,
 200            raw_input: tool_call.raw_input,
 201            raw_output: tool_call.raw_output,
 202        }
 203    }
 204
 205    fn update_fields(
 206        &mut self,
 207        fields: acp::ToolCallUpdateFields,
 208        language_registry: Arc<LanguageRegistry>,
 209        cx: &mut App,
 210    ) {
 211        let acp::ToolCallUpdateFields {
 212            kind,
 213            status,
 214            title,
 215            content,
 216            locations,
 217            raw_input,
 218            raw_output,
 219        } = fields;
 220
 221        if let Some(kind) = kind {
 222            self.kind = kind;
 223        }
 224
 225        if let Some(status) = status {
 226            self.status = status.into();
 227        }
 228
 229        if let Some(title) = title {
 230            self.label.update(cx, |label, cx| {
 231                label.replace(title, cx);
 232            });
 233        }
 234
 235        if let Some(content) = content {
 236            self.content = content
 237                .into_iter()
 238                .map(|chunk| ToolCallContent::from_acp(chunk, language_registry.clone(), cx))
 239                .collect();
 240        }
 241
 242        if let Some(locations) = locations {
 243            self.locations = locations;
 244        }
 245
 246        if let Some(raw_input) = raw_input {
 247            self.raw_input = Some(raw_input);
 248        }
 249
 250        if let Some(raw_output) = raw_output {
 251            if self.content.is_empty() {
 252                if let Some(markdown) = markdown_for_raw_output(&raw_output, &language_registry, cx)
 253                {
 254                    self.content
 255                        .push(ToolCallContent::ContentBlock(ContentBlock::Markdown {
 256                            markdown,
 257                        }));
 258                }
 259            }
 260            self.raw_output = Some(raw_output);
 261        }
 262    }
 263
 264    pub fn diffs(&self) -> impl Iterator<Item = &Entity<Diff>> {
 265        self.content.iter().filter_map(|content| match content {
 266            ToolCallContent::Diff(diff) => Some(diff),
 267            ToolCallContent::ContentBlock(_) => None,
 268            ToolCallContent::Terminal(_) => None,
 269        })
 270    }
 271
 272    pub fn terminals(&self) -> impl Iterator<Item = &Entity<Terminal>> {
 273        self.content.iter().filter_map(|content| match content {
 274            ToolCallContent::Terminal(terminal) => Some(terminal),
 275            ToolCallContent::ContentBlock(_) => None,
 276            ToolCallContent::Diff(_) => None,
 277        })
 278    }
 279
 280    fn to_markdown(&self, cx: &App) -> String {
 281        let mut markdown = format!(
 282            "**Tool Call: {}**\nStatus: {}\n\n",
 283            self.label.read(cx).source(),
 284            self.status
 285        );
 286        for content in &self.content {
 287            markdown.push_str(content.to_markdown(cx).as_str());
 288            markdown.push_str("\n\n");
 289        }
 290        markdown
 291    }
 292
 293    async fn resolve_location(
 294        location: acp::ToolCallLocation,
 295        project: WeakEntity<Project>,
 296        cx: &mut AsyncApp,
 297    ) -> Option<AgentLocation> {
 298        let buffer = project
 299            .update(cx, |project, cx| {
 300                if let Some(path) = project.project_path_for_absolute_path(&location.path, cx) {
 301                    Some(project.open_buffer(path, cx))
 302                } else {
 303                    None
 304                }
 305            })
 306            .ok()??;
 307        let buffer = buffer.await.log_err()?;
 308        let position = buffer
 309            .update(cx, |buffer, _| {
 310                if let Some(row) = location.line {
 311                    let snapshot = buffer.snapshot();
 312                    let column = snapshot.indent_size_for_line(row).len;
 313                    let point = snapshot.clip_point(Point::new(row, column), Bias::Left);
 314                    snapshot.anchor_before(point)
 315                } else {
 316                    Anchor::MIN
 317                }
 318            })
 319            .ok()?;
 320
 321        Some(AgentLocation {
 322            buffer: buffer.downgrade(),
 323            position,
 324        })
 325    }
 326
 327    fn resolve_locations(
 328        &self,
 329        project: Entity<Project>,
 330        cx: &mut App,
 331    ) -> Task<Vec<Option<AgentLocation>>> {
 332        let locations = self.locations.clone();
 333        project.update(cx, |_, cx| {
 334            cx.spawn(async move |project, cx| {
 335                let mut new_locations = Vec::new();
 336                for location in locations {
 337                    new_locations.push(Self::resolve_location(location, project.clone(), cx).await);
 338                }
 339                new_locations
 340            })
 341        })
 342    }
 343}
 344
 345#[derive(Debug)]
 346pub enum ToolCallStatus {
 347    /// The tool call hasn't started running yet, but we start showing it to
 348    /// the user.
 349    Pending,
 350    /// The tool call is waiting for confirmation from the user.
 351    WaitingForConfirmation {
 352        options: Vec<acp::PermissionOption>,
 353        respond_tx: oneshot::Sender<acp::PermissionOptionId>,
 354    },
 355    /// The tool call is currently running.
 356    InProgress,
 357    /// The tool call completed successfully.
 358    Completed,
 359    /// The tool call failed.
 360    Failed,
 361    /// The user rejected the tool call.
 362    Rejected,
 363    /// The user canceled generation so the tool call was canceled.
 364    Canceled,
 365}
 366
 367impl From<acp::ToolCallStatus> for ToolCallStatus {
 368    fn from(status: acp::ToolCallStatus) -> Self {
 369        match status {
 370            acp::ToolCallStatus::Pending => Self::Pending,
 371            acp::ToolCallStatus::InProgress => Self::InProgress,
 372            acp::ToolCallStatus::Completed => Self::Completed,
 373            acp::ToolCallStatus::Failed => Self::Failed,
 374        }
 375    }
 376}
 377
 378impl Display for ToolCallStatus {
 379    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
 380        write!(
 381            f,
 382            "{}",
 383            match self {
 384                ToolCallStatus::Pending => "Pending",
 385                ToolCallStatus::WaitingForConfirmation { .. } => "Waiting for confirmation",
 386                ToolCallStatus::InProgress => "In Progress",
 387                ToolCallStatus::Completed => "Completed",
 388                ToolCallStatus::Failed => "Failed",
 389                ToolCallStatus::Rejected => "Rejected",
 390                ToolCallStatus::Canceled => "Canceled",
 391            }
 392        )
 393    }
 394}
 395
 396#[derive(Debug, PartialEq, Clone)]
 397pub enum ContentBlock {
 398    Empty,
 399    Markdown { markdown: Entity<Markdown> },
 400    ResourceLink { resource_link: acp::ResourceLink },
 401}
 402
 403impl ContentBlock {
 404    pub fn new(
 405        block: acp::ContentBlock,
 406        language_registry: &Arc<LanguageRegistry>,
 407        cx: &mut App,
 408    ) -> Self {
 409        let mut this = Self::Empty;
 410        this.append(block, language_registry, cx);
 411        this
 412    }
 413
 414    pub fn new_combined(
 415        blocks: impl IntoIterator<Item = acp::ContentBlock>,
 416        language_registry: Arc<LanguageRegistry>,
 417        cx: &mut App,
 418    ) -> Self {
 419        let mut this = Self::Empty;
 420        for block in blocks {
 421            this.append(block, &language_registry, cx);
 422        }
 423        this
 424    }
 425
 426    pub fn append(
 427        &mut self,
 428        block: acp::ContentBlock,
 429        language_registry: &Arc<LanguageRegistry>,
 430        cx: &mut App,
 431    ) {
 432        if matches!(self, ContentBlock::Empty) {
 433            if let acp::ContentBlock::ResourceLink(resource_link) = block {
 434                *self = ContentBlock::ResourceLink { resource_link };
 435                return;
 436            }
 437        }
 438
 439        let new_content = self.block_string_contents(block);
 440
 441        match self {
 442            ContentBlock::Empty => {
 443                *self = Self::create_markdown_block(new_content, language_registry, cx);
 444            }
 445            ContentBlock::Markdown { markdown } => {
 446                markdown.update(cx, |markdown, cx| markdown.append(&new_content, cx));
 447            }
 448            ContentBlock::ResourceLink { resource_link } => {
 449                let existing_content = Self::resource_link_md(&resource_link.uri);
 450                let combined = format!("{}\n{}", existing_content, new_content);
 451
 452                *self = Self::create_markdown_block(combined, language_registry, cx);
 453            }
 454        }
 455    }
 456
 457    fn create_markdown_block(
 458        content: String,
 459        language_registry: &Arc<LanguageRegistry>,
 460        cx: &mut App,
 461    ) -> ContentBlock {
 462        ContentBlock::Markdown {
 463            markdown: cx
 464                .new(|cx| Markdown::new(content.into(), Some(language_registry.clone()), None, cx)),
 465        }
 466    }
 467
 468    fn block_string_contents(&self, block: acp::ContentBlock) -> String {
 469        match block {
 470            acp::ContentBlock::Text(text_content) => text_content.text.clone(),
 471            acp::ContentBlock::ResourceLink(resource_link) => {
 472                Self::resource_link_md(&resource_link.uri)
 473            }
 474            acp::ContentBlock::Resource(acp::EmbeddedResource {
 475                resource:
 476                    acp::EmbeddedResourceResource::TextResourceContents(acp::TextResourceContents {
 477                        uri,
 478                        ..
 479                    }),
 480                ..
 481            }) => Self::resource_link_md(&uri),
 482            acp::ContentBlock::Image(image) => Self::image_md(&image),
 483            acp::ContentBlock::Audio(_) | acp::ContentBlock::Resource(_) => String::new(),
 484        }
 485    }
 486
 487    fn resource_link_md(uri: &str) -> String {
 488        if let Some(uri) = MentionUri::parse(&uri).log_err() {
 489            uri.as_link().to_string()
 490        } else {
 491            uri.to_string()
 492        }
 493    }
 494
 495    fn image_md(_image: &acp::ImageContent) -> String {
 496        "`Image`".into()
 497    }
 498
 499    fn to_markdown<'a>(&'a self, cx: &'a App) -> &'a str {
 500        match self {
 501            ContentBlock::Empty => "",
 502            ContentBlock::Markdown { markdown } => markdown.read(cx).source(),
 503            ContentBlock::ResourceLink { resource_link } => &resource_link.uri,
 504        }
 505    }
 506
 507    pub fn markdown(&self) -> Option<&Entity<Markdown>> {
 508        match self {
 509            ContentBlock::Empty => None,
 510            ContentBlock::Markdown { markdown } => Some(markdown),
 511            ContentBlock::ResourceLink { .. } => None,
 512        }
 513    }
 514
 515    pub fn resource_link(&self) -> Option<&acp::ResourceLink> {
 516        match self {
 517            ContentBlock::ResourceLink { resource_link } => Some(resource_link),
 518            _ => None,
 519        }
 520    }
 521}
 522
 523#[derive(Debug)]
 524pub enum ToolCallContent {
 525    ContentBlock(ContentBlock),
 526    Diff(Entity<Diff>),
 527    Terminal(Entity<Terminal>),
 528}
 529
 530impl ToolCallContent {
 531    pub fn from_acp(
 532        content: acp::ToolCallContent,
 533        language_registry: Arc<LanguageRegistry>,
 534        cx: &mut App,
 535    ) -> Self {
 536        match content {
 537            acp::ToolCallContent::Content { content } => {
 538                Self::ContentBlock(ContentBlock::new(content, &language_registry, cx))
 539            }
 540            acp::ToolCallContent::Diff { diff } => {
 541                Self::Diff(cx.new(|cx| Diff::from_acp(diff, language_registry, cx)))
 542            }
 543        }
 544    }
 545
 546    pub fn to_markdown(&self, cx: &App) -> String {
 547        match self {
 548            Self::ContentBlock(content) => content.to_markdown(cx).to_string(),
 549            Self::Diff(diff) => diff.read(cx).to_markdown(cx),
 550            Self::Terminal(terminal) => terminal.read(cx).to_markdown(cx),
 551        }
 552    }
 553}
 554
 555#[derive(Debug, PartialEq)]
 556pub enum ToolCallUpdate {
 557    UpdateFields(acp::ToolCallUpdate),
 558    UpdateDiff(ToolCallUpdateDiff),
 559    UpdateTerminal(ToolCallUpdateTerminal),
 560}
 561
 562impl ToolCallUpdate {
 563    fn id(&self) -> &acp::ToolCallId {
 564        match self {
 565            Self::UpdateFields(update) => &update.id,
 566            Self::UpdateDiff(diff) => &diff.id,
 567            Self::UpdateTerminal(terminal) => &terminal.id,
 568        }
 569    }
 570}
 571
 572impl From<acp::ToolCallUpdate> for ToolCallUpdate {
 573    fn from(update: acp::ToolCallUpdate) -> Self {
 574        Self::UpdateFields(update)
 575    }
 576}
 577
 578impl From<ToolCallUpdateDiff> for ToolCallUpdate {
 579    fn from(diff: ToolCallUpdateDiff) -> Self {
 580        Self::UpdateDiff(diff)
 581    }
 582}
 583
 584#[derive(Debug, PartialEq)]
 585pub struct ToolCallUpdateDiff {
 586    pub id: acp::ToolCallId,
 587    pub diff: Entity<Diff>,
 588}
 589
 590impl From<ToolCallUpdateTerminal> for ToolCallUpdate {
 591    fn from(terminal: ToolCallUpdateTerminal) -> Self {
 592        Self::UpdateTerminal(terminal)
 593    }
 594}
 595
 596#[derive(Debug, PartialEq)]
 597pub struct ToolCallUpdateTerminal {
 598    pub id: acp::ToolCallId,
 599    pub terminal: Entity<Terminal>,
 600}
 601
 602#[derive(Debug, Default)]
 603pub struct Plan {
 604    pub entries: Vec<PlanEntry>,
 605}
 606
 607#[derive(Debug)]
 608pub struct PlanStats<'a> {
 609    pub in_progress_entry: Option<&'a PlanEntry>,
 610    pub pending: u32,
 611    pub completed: u32,
 612}
 613
 614impl Plan {
 615    pub fn is_empty(&self) -> bool {
 616        self.entries.is_empty()
 617    }
 618
 619    pub fn stats(&self) -> PlanStats<'_> {
 620        let mut stats = PlanStats {
 621            in_progress_entry: None,
 622            pending: 0,
 623            completed: 0,
 624        };
 625
 626        for entry in &self.entries {
 627            match &entry.status {
 628                acp::PlanEntryStatus::Pending => {
 629                    stats.pending += 1;
 630                }
 631                acp::PlanEntryStatus::InProgress => {
 632                    stats.in_progress_entry = stats.in_progress_entry.or(Some(entry));
 633                }
 634                acp::PlanEntryStatus::Completed => {
 635                    stats.completed += 1;
 636                }
 637            }
 638        }
 639
 640        stats
 641    }
 642}
 643
 644#[derive(Debug)]
 645pub struct PlanEntry {
 646    pub content: Entity<Markdown>,
 647    pub priority: acp::PlanEntryPriority,
 648    pub status: acp::PlanEntryStatus,
 649}
 650
 651impl PlanEntry {
 652    pub fn from_acp(entry: acp::PlanEntry, cx: &mut App) -> Self {
 653        Self {
 654            content: cx.new(|cx| Markdown::new(entry.content.into(), None, None, cx)),
 655            priority: entry.priority,
 656            status: entry.status,
 657        }
 658    }
 659}
 660
 661pub struct AcpThread {
 662    title: SharedString,
 663    entries: Vec<AgentThreadEntry>,
 664    plan: Plan,
 665    project: Entity<Project>,
 666    action_log: Entity<ActionLog>,
 667    shared_buffers: HashMap<Entity<Buffer>, BufferSnapshot>,
 668    send_task: Option<Task<()>>,
 669    connection: Rc<dyn AgentConnection>,
 670    session_id: acp::SessionId,
 671}
 672
 673#[derive(Debug)]
 674pub enum AcpThreadEvent {
 675    NewEntry,
 676    EntryUpdated(usize),
 677    EntriesRemoved(Range<usize>),
 678    ToolAuthorizationRequired,
 679    Stopped,
 680    Error,
 681    ServerExited(ExitStatus),
 682}
 683
 684impl EventEmitter<AcpThreadEvent> for AcpThread {}
 685
 686#[derive(PartialEq, Eq)]
 687pub enum ThreadStatus {
 688    Idle,
 689    WaitingForToolConfirmation,
 690    Generating,
 691}
 692
 693#[derive(Debug, Clone)]
 694pub enum LoadError {
 695    Unsupported {
 696        error_message: SharedString,
 697        upgrade_message: SharedString,
 698        upgrade_command: String,
 699    },
 700    Exited(i32),
 701    Other(SharedString),
 702}
 703
 704impl Display for LoadError {
 705    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
 706        match self {
 707            LoadError::Unsupported { error_message, .. } => write!(f, "{}", error_message),
 708            LoadError::Exited(status) => write!(f, "Server exited with status {}", status),
 709            LoadError::Other(msg) => write!(f, "{}", msg),
 710        }
 711    }
 712}
 713
 714impl Error for LoadError {}
 715
 716impl AcpThread {
 717    pub fn new(
 718        title: impl Into<SharedString>,
 719        connection: Rc<dyn AgentConnection>,
 720        project: Entity<Project>,
 721        session_id: acp::SessionId,
 722        cx: &mut Context<Self>,
 723    ) -> Self {
 724        let action_log = cx.new(|_| ActionLog::new(project.clone()));
 725
 726        Self {
 727            action_log,
 728            shared_buffers: Default::default(),
 729            entries: Default::default(),
 730            plan: Default::default(),
 731            title: title.into(),
 732            project,
 733            send_task: None,
 734            connection,
 735            session_id,
 736        }
 737    }
 738
 739    pub fn connection(&self) -> &Rc<dyn AgentConnection> {
 740        &self.connection
 741    }
 742
 743    pub fn action_log(&self) -> &Entity<ActionLog> {
 744        &self.action_log
 745    }
 746
 747    pub fn project(&self) -> &Entity<Project> {
 748        &self.project
 749    }
 750
 751    pub fn title(&self) -> SharedString {
 752        self.title.clone()
 753    }
 754
 755    pub fn entries(&self) -> &[AgentThreadEntry] {
 756        &self.entries
 757    }
 758
 759    pub fn session_id(&self) -> &acp::SessionId {
 760        &self.session_id
 761    }
 762
 763    pub fn status(&self) -> ThreadStatus {
 764        if self.send_task.is_some() {
 765            if self.waiting_for_tool_confirmation() {
 766                ThreadStatus::WaitingForToolConfirmation
 767            } else {
 768                ThreadStatus::Generating
 769            }
 770        } else {
 771            ThreadStatus::Idle
 772        }
 773    }
 774
 775    pub fn has_pending_edit_tool_calls(&self) -> bool {
 776        for entry in self.entries.iter().rev() {
 777            match entry {
 778                AgentThreadEntry::UserMessage(_) => return false,
 779                AgentThreadEntry::ToolCall(
 780                    call @ ToolCall {
 781                        status: ToolCallStatus::InProgress | ToolCallStatus::Pending,
 782                        ..
 783                    },
 784                ) if call.diffs().next().is_some() => {
 785                    return true;
 786                }
 787                AgentThreadEntry::ToolCall(_) | AgentThreadEntry::AssistantMessage(_) => {}
 788            }
 789        }
 790
 791        false
 792    }
 793
 794    pub fn used_tools_since_last_user_message(&self) -> bool {
 795        for entry in self.entries.iter().rev() {
 796            match entry {
 797                AgentThreadEntry::UserMessage(..) => return false,
 798                AgentThreadEntry::AssistantMessage(..) => continue,
 799                AgentThreadEntry::ToolCall(..) => return true,
 800            }
 801        }
 802
 803        false
 804    }
 805
 806    pub fn handle_session_update(
 807        &mut self,
 808        update: acp::SessionUpdate,
 809        cx: &mut Context<Self>,
 810    ) -> Result<(), acp::Error> {
 811        match update {
 812            acp::SessionUpdate::UserMessageChunk { content } => {
 813                self.push_user_content_block(None, content, cx);
 814            }
 815            acp::SessionUpdate::AgentMessageChunk { content } => {
 816                self.push_assistant_content_block(content, false, cx);
 817            }
 818            acp::SessionUpdate::AgentThoughtChunk { content } => {
 819                self.push_assistant_content_block(content, true, cx);
 820            }
 821            acp::SessionUpdate::ToolCall(tool_call) => {
 822                self.upsert_tool_call(tool_call, cx)?;
 823            }
 824            acp::SessionUpdate::ToolCallUpdate(tool_call_update) => {
 825                self.update_tool_call(tool_call_update, cx)?;
 826            }
 827            acp::SessionUpdate::Plan(plan) => {
 828                self.update_plan(plan, cx);
 829            }
 830        }
 831        Ok(())
 832    }
 833
 834    pub fn push_user_content_block(
 835        &mut self,
 836        message_id: Option<UserMessageId>,
 837        chunk: acp::ContentBlock,
 838        cx: &mut Context<Self>,
 839    ) {
 840        let language_registry = self.project.read(cx).languages().clone();
 841        let entries_len = self.entries.len();
 842
 843        if let Some(last_entry) = self.entries.last_mut()
 844            && let AgentThreadEntry::UserMessage(UserMessage {
 845                id,
 846                content,
 847                chunks,
 848                ..
 849            }) = last_entry
 850        {
 851            *id = message_id.or(id.take());
 852            content.append(chunk.clone(), &language_registry, cx);
 853            chunks.push(chunk);
 854            let idx = entries_len - 1;
 855            cx.emit(AcpThreadEvent::EntryUpdated(idx));
 856        } else {
 857            let content = ContentBlock::new(chunk.clone(), &language_registry, cx);
 858            self.push_entry(
 859                AgentThreadEntry::UserMessage(UserMessage {
 860                    id: message_id,
 861                    content,
 862                    chunks: vec![chunk],
 863                    checkpoint: None,
 864                }),
 865                cx,
 866            );
 867        }
 868    }
 869
 870    pub fn push_assistant_content_block(
 871        &mut self,
 872        chunk: acp::ContentBlock,
 873        is_thought: bool,
 874        cx: &mut Context<Self>,
 875    ) {
 876        let language_registry = self.project.read(cx).languages().clone();
 877        let entries_len = self.entries.len();
 878        if let Some(last_entry) = self.entries.last_mut()
 879            && let AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) = last_entry
 880        {
 881            let idx = entries_len - 1;
 882            cx.emit(AcpThreadEvent::EntryUpdated(idx));
 883            match (chunks.last_mut(), is_thought) {
 884                (Some(AssistantMessageChunk::Message { block }), false)
 885                | (Some(AssistantMessageChunk::Thought { block }), true) => {
 886                    block.append(chunk, &language_registry, cx)
 887                }
 888                _ => {
 889                    let block = ContentBlock::new(chunk, &language_registry, cx);
 890                    if is_thought {
 891                        chunks.push(AssistantMessageChunk::Thought { block })
 892                    } else {
 893                        chunks.push(AssistantMessageChunk::Message { block })
 894                    }
 895                }
 896            }
 897        } else {
 898            let block = ContentBlock::new(chunk, &language_registry, cx);
 899            let chunk = if is_thought {
 900                AssistantMessageChunk::Thought { block }
 901            } else {
 902                AssistantMessageChunk::Message { block }
 903            };
 904
 905            self.push_entry(
 906                AgentThreadEntry::AssistantMessage(AssistantMessage {
 907                    chunks: vec![chunk],
 908                }),
 909                cx,
 910            );
 911        }
 912    }
 913
 914    fn push_entry(&mut self, entry: AgentThreadEntry, cx: &mut Context<Self>) {
 915        self.entries.push(entry);
 916        cx.emit(AcpThreadEvent::NewEntry);
 917    }
 918
 919    pub fn update_tool_call(
 920        &mut self,
 921        update: impl Into<ToolCallUpdate>,
 922        cx: &mut Context<Self>,
 923    ) -> Result<()> {
 924        let update = update.into();
 925        let languages = self.project.read(cx).languages().clone();
 926
 927        let (ix, current_call) = self
 928            .tool_call_mut(update.id())
 929            .context("Tool call not found")?;
 930        match update {
 931            ToolCallUpdate::UpdateFields(update) => {
 932                let location_updated = update.fields.locations.is_some();
 933                current_call.update_fields(update.fields, languages, cx);
 934                if location_updated {
 935                    self.resolve_locations(update.id.clone(), cx);
 936                }
 937            }
 938            ToolCallUpdate::UpdateDiff(update) => {
 939                current_call.content.clear();
 940                current_call
 941                    .content
 942                    .push(ToolCallContent::Diff(update.diff));
 943            }
 944            ToolCallUpdate::UpdateTerminal(update) => {
 945                current_call.content.clear();
 946                current_call
 947                    .content
 948                    .push(ToolCallContent::Terminal(update.terminal));
 949            }
 950        }
 951
 952        cx.emit(AcpThreadEvent::EntryUpdated(ix));
 953
 954        Ok(())
 955    }
 956
 957    /// Updates a tool call if id matches an existing entry, otherwise inserts a new one.
 958    pub fn upsert_tool_call(
 959        &mut self,
 960        tool_call: acp::ToolCall,
 961        cx: &mut Context<Self>,
 962    ) -> Result<(), acp::Error> {
 963        let status = tool_call.status.into();
 964        self.upsert_tool_call_inner(tool_call.into(), status, cx)
 965    }
 966
 967    /// Fails if id does not match an existing entry.
 968    pub fn upsert_tool_call_inner(
 969        &mut self,
 970        tool_call_update: acp::ToolCallUpdate,
 971        status: ToolCallStatus,
 972        cx: &mut Context<Self>,
 973    ) -> Result<(), acp::Error> {
 974        let language_registry = self.project.read(cx).languages().clone();
 975        let id = tool_call_update.id.clone();
 976
 977        if let Some((ix, current_call)) = self.tool_call_mut(&id) {
 978            current_call.update_fields(tool_call_update.fields, language_registry, cx);
 979            current_call.status = status;
 980
 981            cx.emit(AcpThreadEvent::EntryUpdated(ix));
 982        } else {
 983            let call =
 984                ToolCall::from_acp(tool_call_update.try_into()?, status, language_registry, cx);
 985            self.push_entry(AgentThreadEntry::ToolCall(call), cx);
 986        };
 987
 988        self.resolve_locations(id, cx);
 989        Ok(())
 990    }
 991
 992    fn tool_call_mut(&mut self, id: &acp::ToolCallId) -> Option<(usize, &mut ToolCall)> {
 993        // The tool call we are looking for is typically the last one, or very close to the end.
 994        // At the moment, it doesn't seem like a hashmap would be a good fit for this use case.
 995        self.entries
 996            .iter_mut()
 997            .enumerate()
 998            .rev()
 999            .find_map(|(index, tool_call)| {
1000                if let AgentThreadEntry::ToolCall(tool_call) = tool_call
1001                    && &tool_call.id == id
1002                {
1003                    Some((index, tool_call))
1004                } else {
1005                    None
1006                }
1007            })
1008    }
1009
1010    pub fn resolve_locations(&mut self, id: acp::ToolCallId, cx: &mut Context<Self>) {
1011        let project = self.project.clone();
1012        let Some((_, tool_call)) = self.tool_call_mut(&id) else {
1013            return;
1014        };
1015        let task = tool_call.resolve_locations(project, cx);
1016        cx.spawn(async move |this, cx| {
1017            let resolved_locations = task.await;
1018            this.update(cx, |this, cx| {
1019                let project = this.project.clone();
1020                let Some((ix, tool_call)) = this.tool_call_mut(&id) else {
1021                    return;
1022                };
1023                if let Some(Some(location)) = resolved_locations.last() {
1024                    project.update(cx, |project, cx| {
1025                        if let Some(agent_location) = project.agent_location() {
1026                            let should_ignore = agent_location.buffer == location.buffer
1027                                && location
1028                                    .buffer
1029                                    .update(cx, |buffer, _| {
1030                                        let snapshot = buffer.snapshot();
1031                                        let old_position =
1032                                            agent_location.position.to_point(&snapshot);
1033                                        let new_position = location.position.to_point(&snapshot);
1034                                        // ignore this so that when we get updates from the edit tool
1035                                        // the position doesn't reset to the startof line
1036                                        old_position.row == new_position.row
1037                                            && old_position.column > new_position.column
1038                                    })
1039                                    .ok()
1040                                    .unwrap_or_default();
1041                            if !should_ignore {
1042                                project.set_agent_location(Some(location.clone()), cx);
1043                            }
1044                        }
1045                    });
1046                }
1047                if tool_call.resolved_locations != resolved_locations {
1048                    tool_call.resolved_locations = resolved_locations;
1049                    cx.emit(AcpThreadEvent::EntryUpdated(ix));
1050                }
1051            })
1052        })
1053        .detach();
1054    }
1055
1056    pub fn request_tool_call_authorization(
1057        &mut self,
1058        tool_call: acp::ToolCallUpdate,
1059        options: Vec<acp::PermissionOption>,
1060        cx: &mut Context<Self>,
1061    ) -> Result<oneshot::Receiver<acp::PermissionOptionId>, acp::Error> {
1062        let (tx, rx) = oneshot::channel();
1063
1064        let status = ToolCallStatus::WaitingForConfirmation {
1065            options,
1066            respond_tx: tx,
1067        };
1068
1069        self.upsert_tool_call_inner(tool_call, status, cx)?;
1070        cx.emit(AcpThreadEvent::ToolAuthorizationRequired);
1071        Ok(rx)
1072    }
1073
1074    pub fn authorize_tool_call(
1075        &mut self,
1076        id: acp::ToolCallId,
1077        option_id: acp::PermissionOptionId,
1078        option_kind: acp::PermissionOptionKind,
1079        cx: &mut Context<Self>,
1080    ) {
1081        let Some((ix, call)) = self.tool_call_mut(&id) else {
1082            return;
1083        };
1084
1085        let new_status = match option_kind {
1086            acp::PermissionOptionKind::RejectOnce | acp::PermissionOptionKind::RejectAlways => {
1087                ToolCallStatus::Rejected
1088            }
1089            acp::PermissionOptionKind::AllowOnce | acp::PermissionOptionKind::AllowAlways => {
1090                ToolCallStatus::InProgress
1091            }
1092        };
1093
1094        let curr_status = mem::replace(&mut call.status, new_status);
1095
1096        if let ToolCallStatus::WaitingForConfirmation { respond_tx, .. } = curr_status {
1097            respond_tx.send(option_id).log_err();
1098        } else if cfg!(debug_assertions) {
1099            panic!("tried to authorize an already authorized tool call");
1100        }
1101
1102        cx.emit(AcpThreadEvent::EntryUpdated(ix));
1103    }
1104
1105    /// Returns true if the last turn is awaiting tool authorization
1106    pub fn waiting_for_tool_confirmation(&self) -> bool {
1107        for entry in self.entries.iter().rev() {
1108            match &entry {
1109                AgentThreadEntry::ToolCall(call) => match call.status {
1110                    ToolCallStatus::WaitingForConfirmation { .. } => return true,
1111                    ToolCallStatus::Pending
1112                    | ToolCallStatus::InProgress
1113                    | ToolCallStatus::Completed
1114                    | ToolCallStatus::Failed
1115                    | ToolCallStatus::Rejected
1116                    | ToolCallStatus::Canceled => continue,
1117                },
1118                AgentThreadEntry::UserMessage(_) | AgentThreadEntry::AssistantMessage(_) => {
1119                    // Reached the beginning of the turn
1120                    return false;
1121                }
1122            }
1123        }
1124        false
1125    }
1126
1127    pub fn plan(&self) -> &Plan {
1128        &self.plan
1129    }
1130
1131    pub fn update_plan(&mut self, request: acp::Plan, cx: &mut Context<Self>) {
1132        let new_entries_len = request.entries.len();
1133        let mut new_entries = request.entries.into_iter();
1134
1135        // Reuse existing markdown to prevent flickering
1136        for (old, new) in self.plan.entries.iter_mut().zip(new_entries.by_ref()) {
1137            let PlanEntry {
1138                content,
1139                priority,
1140                status,
1141            } = old;
1142            content.update(cx, |old, cx| {
1143                old.replace(new.content, cx);
1144            });
1145            *priority = new.priority;
1146            *status = new.status;
1147        }
1148        for new in new_entries {
1149            self.plan.entries.push(PlanEntry::from_acp(new, cx))
1150        }
1151        self.plan.entries.truncate(new_entries_len);
1152
1153        cx.notify();
1154    }
1155
1156    fn clear_completed_plan_entries(&mut self, cx: &mut Context<Self>) {
1157        self.plan
1158            .entries
1159            .retain(|entry| !matches!(entry.status, acp::PlanEntryStatus::Completed));
1160        cx.notify();
1161    }
1162
1163    #[cfg(any(test, feature = "test-support"))]
1164    pub fn send_raw(
1165        &mut self,
1166        message: &str,
1167        cx: &mut Context<Self>,
1168    ) -> BoxFuture<'static, Result<()>> {
1169        self.send(
1170            vec![acp::ContentBlock::Text(acp::TextContent {
1171                text: message.to_string(),
1172                annotations: None,
1173            })],
1174            cx,
1175        )
1176    }
1177
1178    pub fn send(
1179        &mut self,
1180        message: Vec<acp::ContentBlock>,
1181        cx: &mut Context<Self>,
1182    ) -> BoxFuture<'static, Result<()>> {
1183        let block = ContentBlock::new_combined(
1184            message.clone(),
1185            self.project.read(cx).languages().clone(),
1186            cx,
1187        );
1188        let request = acp::PromptRequest {
1189            prompt: message.clone(),
1190            session_id: self.session_id.clone(),
1191        };
1192        let git_store = self.project.read(cx).git_store().clone();
1193
1194        let message_id = if self
1195            .connection
1196            .session_editor(&self.session_id, cx)
1197            .is_some()
1198        {
1199            Some(UserMessageId::new())
1200        } else {
1201            None
1202        };
1203        self.push_entry(
1204            AgentThreadEntry::UserMessage(UserMessage {
1205                id: message_id.clone(),
1206                content: block,
1207                chunks: message,
1208                checkpoint: None,
1209            }),
1210            cx,
1211        );
1212
1213        self.run_turn(cx, async move |this, cx| {
1214            let old_checkpoint = git_store
1215                .update(cx, |git, cx| git.checkpoint(cx))?
1216                .await
1217                .context("failed to get old checkpoint")
1218                .log_err();
1219            this.update(cx, |this, cx| {
1220                if let Some((_ix, message)) = this.last_user_message() {
1221                    message.checkpoint = old_checkpoint.map(|git_checkpoint| Checkpoint {
1222                        git_checkpoint,
1223                        show: false,
1224                    });
1225                }
1226                this.connection.prompt(message_id, request, cx)
1227            })?
1228            .await
1229        })
1230    }
1231
1232    pub fn resume(&mut self, cx: &mut Context<Self>) -> BoxFuture<'static, Result<()>> {
1233        self.run_turn(cx, async move |this, cx| {
1234            this.update(cx, |this, cx| {
1235                this.connection
1236                    .resume(&this.session_id, cx)
1237                    .map(|resume| resume.run(cx))
1238            })?
1239            .context("resuming a session is not supported")?
1240            .await
1241        })
1242    }
1243
1244    fn run_turn(
1245        &mut self,
1246        cx: &mut Context<Self>,
1247        f: impl 'static + AsyncFnOnce(WeakEntity<Self>, &mut AsyncApp) -> Result<acp::PromptResponse>,
1248    ) -> BoxFuture<'static, Result<()>> {
1249        self.clear_completed_plan_entries(cx);
1250
1251        let (tx, rx) = oneshot::channel();
1252        let cancel_task = self.cancel(cx);
1253
1254        self.send_task = Some(cx.spawn(async move |this, cx| {
1255            cancel_task.await;
1256            tx.send(f(this, cx).await).ok();
1257        }));
1258
1259        cx.spawn(async move |this, cx| {
1260            let response = rx.await;
1261
1262            this.update(cx, |this, cx| this.update_last_checkpoint(cx))?
1263                .await?;
1264
1265            this.update(cx, |this, cx| {
1266                match response {
1267                    Ok(Err(e)) => {
1268                        this.send_task.take();
1269                        cx.emit(AcpThreadEvent::Error);
1270                        Err(e)
1271                    }
1272                    result => {
1273                        let canceled = matches!(
1274                            result,
1275                            Ok(Ok(acp::PromptResponse {
1276                                stop_reason: acp::StopReason::Canceled
1277                            }))
1278                        );
1279
1280                        // We only take the task if the current prompt wasn't canceled.
1281                        //
1282                        // This prompt may have been canceled because another one was sent
1283                        // while it was still generating. In these cases, dropping `send_task`
1284                        // would cause the next generation to be canceled.
1285                        if !canceled {
1286                            this.send_task.take();
1287                        }
1288
1289                        cx.emit(AcpThreadEvent::Stopped);
1290                        Ok(())
1291                    }
1292                }
1293            })?
1294        })
1295        .boxed()
1296    }
1297
1298    pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
1299        let Some(send_task) = self.send_task.take() else {
1300            return Task::ready(());
1301        };
1302
1303        for entry in self.entries.iter_mut() {
1304            if let AgentThreadEntry::ToolCall(call) = entry {
1305                let cancel = matches!(
1306                    call.status,
1307                    ToolCallStatus::Pending
1308                        | ToolCallStatus::WaitingForConfirmation { .. }
1309                        | ToolCallStatus::InProgress
1310                );
1311
1312                if cancel {
1313                    call.status = ToolCallStatus::Canceled;
1314                }
1315            }
1316        }
1317
1318        self.connection.cancel(&self.session_id, cx);
1319
1320        // Wait for the send task to complete
1321        cx.foreground_executor().spawn(send_task)
1322    }
1323
1324    /// Rewinds this thread to before the entry at `index`, removing it and all
1325    /// subsequent entries while reverting any changes made from that point.
1326    pub fn rewind(&mut self, id: UserMessageId, cx: &mut Context<Self>) -> Task<Result<()>> {
1327        let Some(session_editor) = self.connection.session_editor(&self.session_id, cx) else {
1328            return Task::ready(Err(anyhow!("not supported")));
1329        };
1330        let Some(message) = self.user_message(&id) else {
1331            return Task::ready(Err(anyhow!("message not found")));
1332        };
1333
1334        let checkpoint = message
1335            .checkpoint
1336            .as_ref()
1337            .map(|c| c.git_checkpoint.clone());
1338
1339        let git_store = self.project.read(cx).git_store().clone();
1340        cx.spawn(async move |this, cx| {
1341            if let Some(checkpoint) = checkpoint {
1342                git_store
1343                    .update(cx, |git, cx| git.restore_checkpoint(checkpoint, cx))?
1344                    .await?;
1345            }
1346
1347            cx.update(|cx| session_editor.truncate(id.clone(), cx))?
1348                .await?;
1349            this.update(cx, |this, cx| {
1350                if let Some((ix, _)) = this.user_message_mut(&id) {
1351                    let range = ix..this.entries.len();
1352                    this.entries.truncate(ix);
1353                    cx.emit(AcpThreadEvent::EntriesRemoved(range));
1354                }
1355            })
1356        })
1357    }
1358
1359    fn update_last_checkpoint(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
1360        let git_store = self.project.read(cx).git_store().clone();
1361
1362        let old_checkpoint = if let Some((_, message)) = self.last_user_message() {
1363            if let Some(checkpoint) = message.checkpoint.as_ref() {
1364                checkpoint.git_checkpoint.clone()
1365            } else {
1366                return Task::ready(Ok(()));
1367            }
1368        } else {
1369            return Task::ready(Ok(()));
1370        };
1371
1372        let new_checkpoint = git_store.update(cx, |git, cx| git.checkpoint(cx));
1373        cx.spawn(async move |this, cx| {
1374            let new_checkpoint = new_checkpoint
1375                .await
1376                .context("failed to get new checkpoint")
1377                .log_err();
1378            if let Some(new_checkpoint) = new_checkpoint {
1379                let equal = git_store
1380                    .update(cx, |git, cx| {
1381                        git.compare_checkpoints(old_checkpoint.clone(), new_checkpoint, cx)
1382                    })?
1383                    .await
1384                    .unwrap_or(true);
1385                this.update(cx, |this, cx| {
1386                    let (ix, message) = this.last_user_message().context("no user message")?;
1387                    let checkpoint = message.checkpoint.as_mut().context("no checkpoint")?;
1388                    checkpoint.show = !equal;
1389                    cx.emit(AcpThreadEvent::EntryUpdated(ix));
1390                    anyhow::Ok(())
1391                })??;
1392            }
1393
1394            Ok(())
1395        })
1396    }
1397
1398    fn last_user_message(&mut self) -> Option<(usize, &mut UserMessage)> {
1399        self.entries
1400            .iter_mut()
1401            .enumerate()
1402            .rev()
1403            .find_map(|(ix, entry)| {
1404                if let AgentThreadEntry::UserMessage(message) = entry {
1405                    Some((ix, message))
1406                } else {
1407                    None
1408                }
1409            })
1410    }
1411
1412    fn user_message(&self, id: &UserMessageId) -> Option<&UserMessage> {
1413        self.entries.iter().find_map(|entry| {
1414            if let AgentThreadEntry::UserMessage(message) = entry {
1415                if message.id.as_ref() == Some(&id) {
1416                    Some(message)
1417                } else {
1418                    None
1419                }
1420            } else {
1421                None
1422            }
1423        })
1424    }
1425
1426    fn user_message_mut(&mut self, id: &UserMessageId) -> Option<(usize, &mut UserMessage)> {
1427        self.entries.iter_mut().enumerate().find_map(|(ix, entry)| {
1428            if let AgentThreadEntry::UserMessage(message) = entry {
1429                if message.id.as_ref() == Some(&id) {
1430                    Some((ix, message))
1431                } else {
1432                    None
1433                }
1434            } else {
1435                None
1436            }
1437        })
1438    }
1439
1440    pub fn read_text_file(
1441        &self,
1442        path: PathBuf,
1443        line: Option<u32>,
1444        limit: Option<u32>,
1445        reuse_shared_snapshot: bool,
1446        cx: &mut Context<Self>,
1447    ) -> Task<Result<String>> {
1448        let project = self.project.clone();
1449        let action_log = self.action_log.clone();
1450        cx.spawn(async move |this, cx| {
1451            let load = project.update(cx, |project, cx| {
1452                let path = project
1453                    .project_path_for_absolute_path(&path, cx)
1454                    .context("invalid path")?;
1455                anyhow::Ok(project.open_buffer(path, cx))
1456            });
1457            let buffer = load??.await?;
1458
1459            let snapshot = if reuse_shared_snapshot {
1460                this.read_with(cx, |this, _| {
1461                    this.shared_buffers.get(&buffer.clone()).cloned()
1462                })
1463                .log_err()
1464                .flatten()
1465            } else {
1466                None
1467            };
1468
1469            let snapshot = if let Some(snapshot) = snapshot {
1470                snapshot
1471            } else {
1472                action_log.update(cx, |action_log, cx| {
1473                    action_log.buffer_read(buffer.clone(), cx);
1474                })?;
1475                project.update(cx, |project, cx| {
1476                    let position = buffer
1477                        .read(cx)
1478                        .snapshot()
1479                        .anchor_before(Point::new(line.unwrap_or_default(), 0));
1480                    project.set_agent_location(
1481                        Some(AgentLocation {
1482                            buffer: buffer.downgrade(),
1483                            position,
1484                        }),
1485                        cx,
1486                    );
1487                })?;
1488
1489                buffer.update(cx, |buffer, _| buffer.snapshot())?
1490            };
1491
1492            this.update(cx, |this, _| {
1493                let text = snapshot.text();
1494                this.shared_buffers.insert(buffer.clone(), snapshot);
1495                if line.is_none() && limit.is_none() {
1496                    return Ok(text);
1497                }
1498                let limit = limit.unwrap_or(u32::MAX) as usize;
1499                let Some(line) = line else {
1500                    return Ok(text.lines().take(limit).collect::<String>());
1501                };
1502
1503                let count = text.lines().count();
1504                if count < line as usize {
1505                    anyhow::bail!("There are only {} lines", count);
1506                }
1507                Ok(text
1508                    .lines()
1509                    .skip(line as usize + 1)
1510                    .take(limit)
1511                    .collect::<String>())
1512            })?
1513        })
1514    }
1515
1516    pub fn write_text_file(
1517        &self,
1518        path: PathBuf,
1519        content: String,
1520        cx: &mut Context<Self>,
1521    ) -> Task<Result<()>> {
1522        let project = self.project.clone();
1523        let action_log = self.action_log.clone();
1524        cx.spawn(async move |this, cx| {
1525            let load = project.update(cx, |project, cx| {
1526                let path = project
1527                    .project_path_for_absolute_path(&path, cx)
1528                    .context("invalid path")?;
1529                anyhow::Ok(project.open_buffer(path, cx))
1530            });
1531            let buffer = load??.await?;
1532            let snapshot = this.update(cx, |this, cx| {
1533                this.shared_buffers
1534                    .get(&buffer)
1535                    .cloned()
1536                    .unwrap_or_else(|| buffer.read(cx).snapshot())
1537            })?;
1538            let edits = cx
1539                .background_executor()
1540                .spawn(async move {
1541                    let old_text = snapshot.text();
1542                    text_diff(old_text.as_str(), &content)
1543                        .into_iter()
1544                        .map(|(range, replacement)| {
1545                            (
1546                                snapshot.anchor_after(range.start)
1547                                    ..snapshot.anchor_before(range.end),
1548                                replacement,
1549                            )
1550                        })
1551                        .collect::<Vec<_>>()
1552                })
1553                .await;
1554            cx.update(|cx| {
1555                project.update(cx, |project, cx| {
1556                    project.set_agent_location(
1557                        Some(AgentLocation {
1558                            buffer: buffer.downgrade(),
1559                            position: edits
1560                                .last()
1561                                .map(|(range, _)| range.end)
1562                                .unwrap_or(Anchor::MIN),
1563                        }),
1564                        cx,
1565                    );
1566                });
1567
1568                action_log.update(cx, |action_log, cx| {
1569                    action_log.buffer_read(buffer.clone(), cx);
1570                });
1571                buffer.update(cx, |buffer, cx| {
1572                    buffer.edit(edits, None, cx);
1573                });
1574                action_log.update(cx, |action_log, cx| {
1575                    action_log.buffer_edited(buffer.clone(), cx);
1576                });
1577            })?;
1578            project
1579                .update(cx, |project, cx| project.save_buffer(buffer, cx))?
1580                .await
1581        })
1582    }
1583
1584    pub fn to_markdown(&self, cx: &App) -> String {
1585        self.entries.iter().map(|e| e.to_markdown(cx)).collect()
1586    }
1587
1588    pub fn emit_server_exited(&mut self, status: ExitStatus, cx: &mut Context<Self>) {
1589        cx.emit(AcpThreadEvent::ServerExited(status));
1590    }
1591}
1592
1593fn markdown_for_raw_output(
1594    raw_output: &serde_json::Value,
1595    language_registry: &Arc<LanguageRegistry>,
1596    cx: &mut App,
1597) -> Option<Entity<Markdown>> {
1598    match raw_output {
1599        serde_json::Value::Null => None,
1600        serde_json::Value::Bool(value) => Some(cx.new(|cx| {
1601            Markdown::new(
1602                value.to_string().into(),
1603                Some(language_registry.clone()),
1604                None,
1605                cx,
1606            )
1607        })),
1608        serde_json::Value::Number(value) => Some(cx.new(|cx| {
1609            Markdown::new(
1610                value.to_string().into(),
1611                Some(language_registry.clone()),
1612                None,
1613                cx,
1614            )
1615        })),
1616        serde_json::Value::String(value) => Some(cx.new(|cx| {
1617            Markdown::new(
1618                value.clone().into(),
1619                Some(language_registry.clone()),
1620                None,
1621                cx,
1622            )
1623        })),
1624        value => Some(cx.new(|cx| {
1625            Markdown::new(
1626                format!("```json\n{}\n```", value).into(),
1627                Some(language_registry.clone()),
1628                None,
1629                cx,
1630            )
1631        })),
1632    }
1633}
1634
1635#[cfg(test)]
1636mod tests {
1637    use super::*;
1638    use anyhow::anyhow;
1639    use futures::{channel::mpsc, future::LocalBoxFuture, select};
1640    use gpui::{AsyncApp, TestAppContext, WeakEntity};
1641    use indoc::indoc;
1642    use project::{FakeFs, Fs};
1643    use rand::Rng as _;
1644    use serde_json::json;
1645    use settings::SettingsStore;
1646    use smol::stream::StreamExt as _;
1647    use std::{
1648        any::Any,
1649        cell::RefCell,
1650        path::Path,
1651        rc::Rc,
1652        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
1653        time::Duration,
1654    };
1655    use util::path;
1656
1657    fn init_test(cx: &mut TestAppContext) {
1658        env_logger::try_init().ok();
1659        cx.update(|cx| {
1660            let settings_store = SettingsStore::test(cx);
1661            cx.set_global(settings_store);
1662            Project::init_settings(cx);
1663            language::init(cx);
1664        });
1665    }
1666
1667    #[gpui::test]
1668    async fn test_push_user_content_block(cx: &mut gpui::TestAppContext) {
1669        init_test(cx);
1670
1671        let fs = FakeFs::new(cx.executor());
1672        let project = Project::test(fs, [], cx).await;
1673        let connection = Rc::new(FakeAgentConnection::new());
1674        let thread = cx
1675            .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
1676            .await
1677            .unwrap();
1678
1679        // Test creating a new user message
1680        thread.update(cx, |thread, cx| {
1681            thread.push_user_content_block(
1682                None,
1683                acp::ContentBlock::Text(acp::TextContent {
1684                    annotations: None,
1685                    text: "Hello, ".to_string(),
1686                }),
1687                cx,
1688            );
1689        });
1690
1691        thread.update(cx, |thread, cx| {
1692            assert_eq!(thread.entries.len(), 1);
1693            if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
1694                assert_eq!(user_msg.id, None);
1695                assert_eq!(user_msg.content.to_markdown(cx), "Hello, ");
1696            } else {
1697                panic!("Expected UserMessage");
1698            }
1699        });
1700
1701        // Test appending to existing user message
1702        let message_1_id = UserMessageId::new();
1703        thread.update(cx, |thread, cx| {
1704            thread.push_user_content_block(
1705                Some(message_1_id.clone()),
1706                acp::ContentBlock::Text(acp::TextContent {
1707                    annotations: None,
1708                    text: "world!".to_string(),
1709                }),
1710                cx,
1711            );
1712        });
1713
1714        thread.update(cx, |thread, cx| {
1715            assert_eq!(thread.entries.len(), 1);
1716            if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
1717                assert_eq!(user_msg.id, Some(message_1_id));
1718                assert_eq!(user_msg.content.to_markdown(cx), "Hello, world!");
1719            } else {
1720                panic!("Expected UserMessage");
1721            }
1722        });
1723
1724        // Test creating new user message after assistant message
1725        thread.update(cx, |thread, cx| {
1726            thread.push_assistant_content_block(
1727                acp::ContentBlock::Text(acp::TextContent {
1728                    annotations: None,
1729                    text: "Assistant response".to_string(),
1730                }),
1731                false,
1732                cx,
1733            );
1734        });
1735
1736        let message_2_id = UserMessageId::new();
1737        thread.update(cx, |thread, cx| {
1738            thread.push_user_content_block(
1739                Some(message_2_id.clone()),
1740                acp::ContentBlock::Text(acp::TextContent {
1741                    annotations: None,
1742                    text: "New user message".to_string(),
1743                }),
1744                cx,
1745            );
1746        });
1747
1748        thread.update(cx, |thread, cx| {
1749            assert_eq!(thread.entries.len(), 3);
1750            if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[2] {
1751                assert_eq!(user_msg.id, Some(message_2_id));
1752                assert_eq!(user_msg.content.to_markdown(cx), "New user message");
1753            } else {
1754                panic!("Expected UserMessage at index 2");
1755            }
1756        });
1757    }
1758
1759    #[gpui::test]
1760    async fn test_thinking_concatenation(cx: &mut gpui::TestAppContext) {
1761        init_test(cx);
1762
1763        let fs = FakeFs::new(cx.executor());
1764        let project = Project::test(fs, [], cx).await;
1765        let connection = Rc::new(FakeAgentConnection::new().on_user_message(
1766            |_, thread, mut cx| {
1767                async move {
1768                    thread.update(&mut cx, |thread, cx| {
1769                        thread
1770                            .handle_session_update(
1771                                acp::SessionUpdate::AgentThoughtChunk {
1772                                    content: "Thinking ".into(),
1773                                },
1774                                cx,
1775                            )
1776                            .unwrap();
1777                        thread
1778                            .handle_session_update(
1779                                acp::SessionUpdate::AgentThoughtChunk {
1780                                    content: "hard!".into(),
1781                                },
1782                                cx,
1783                            )
1784                            .unwrap();
1785                    })?;
1786                    Ok(acp::PromptResponse {
1787                        stop_reason: acp::StopReason::EndTurn,
1788                    })
1789                }
1790                .boxed_local()
1791            },
1792        ));
1793
1794        let thread = cx
1795            .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
1796            .await
1797            .unwrap();
1798
1799        thread
1800            .update(cx, |thread, cx| thread.send_raw("Hello from Zed!", cx))
1801            .await
1802            .unwrap();
1803
1804        let output = thread.read_with(cx, |thread, cx| thread.to_markdown(cx));
1805        assert_eq!(
1806            output,
1807            indoc! {r#"
1808            ## User
1809
1810            Hello from Zed!
1811
1812            ## Assistant
1813
1814            <thinking>
1815            Thinking hard!
1816            </thinking>
1817
1818            "#}
1819        );
1820    }
1821
1822    #[gpui::test]
1823    async fn test_edits_concurrently_to_user(cx: &mut TestAppContext) {
1824        init_test(cx);
1825
1826        let fs = FakeFs::new(cx.executor());
1827        fs.insert_tree(path!("/tmp"), json!({"foo": "one\ntwo\nthree\n"}))
1828            .await;
1829        let project = Project::test(fs.clone(), [], cx).await;
1830        let (read_file_tx, read_file_rx) = oneshot::channel::<()>();
1831        let read_file_tx = Rc::new(RefCell::new(Some(read_file_tx)));
1832        let connection = Rc::new(FakeAgentConnection::new().on_user_message(
1833            move |_, thread, mut cx| {
1834                let read_file_tx = read_file_tx.clone();
1835                async move {
1836                    let content = thread
1837                        .update(&mut cx, |thread, cx| {
1838                            thread.read_text_file(path!("/tmp/foo").into(), None, None, false, cx)
1839                        })
1840                        .unwrap()
1841                        .await
1842                        .unwrap();
1843                    assert_eq!(content, "one\ntwo\nthree\n");
1844                    read_file_tx.take().unwrap().send(()).unwrap();
1845                    thread
1846                        .update(&mut cx, |thread, cx| {
1847                            thread.write_text_file(
1848                                path!("/tmp/foo").into(),
1849                                "one\ntwo\nthree\nfour\nfive\n".to_string(),
1850                                cx,
1851                            )
1852                        })
1853                        .unwrap()
1854                        .await
1855                        .unwrap();
1856                    Ok(acp::PromptResponse {
1857                        stop_reason: acp::StopReason::EndTurn,
1858                    })
1859                }
1860                .boxed_local()
1861            },
1862        ));
1863
1864        let (worktree, pathbuf) = project
1865            .update(cx, |project, cx| {
1866                project.find_or_create_worktree(path!("/tmp/foo"), true, cx)
1867            })
1868            .await
1869            .unwrap();
1870        let buffer = project
1871            .update(cx, |project, cx| {
1872                project.open_buffer((worktree.read(cx).id(), pathbuf), cx)
1873            })
1874            .await
1875            .unwrap();
1876
1877        let thread = cx
1878            .update(|cx| connection.new_thread(project, Path::new(path!("/tmp")), cx))
1879            .await
1880            .unwrap();
1881
1882        let request = thread.update(cx, |thread, cx| {
1883            thread.send_raw("Extend the count in /tmp/foo", cx)
1884        });
1885        read_file_rx.await.ok();
1886        buffer.update(cx, |buffer, cx| {
1887            buffer.edit([(0..0, "zero\n".to_string())], None, cx);
1888        });
1889        cx.run_until_parked();
1890        assert_eq!(
1891            buffer.read_with(cx, |buffer, _| buffer.text()),
1892            "zero\none\ntwo\nthree\nfour\nfive\n"
1893        );
1894        assert_eq!(
1895            String::from_utf8(fs.read_file_sync(path!("/tmp/foo")).unwrap()).unwrap(),
1896            "zero\none\ntwo\nthree\nfour\nfive\n"
1897        );
1898        request.await.unwrap();
1899    }
1900
1901    #[gpui::test]
1902    async fn test_succeeding_canceled_toolcall(cx: &mut TestAppContext) {
1903        init_test(cx);
1904
1905        let fs = FakeFs::new(cx.executor());
1906        let project = Project::test(fs, [], cx).await;
1907        let id = acp::ToolCallId("test".into());
1908
1909        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
1910            let id = id.clone();
1911            move |_, thread, mut cx| {
1912                let id = id.clone();
1913                async move {
1914                    thread
1915                        .update(&mut cx, |thread, cx| {
1916                            thread.handle_session_update(
1917                                acp::SessionUpdate::ToolCall(acp::ToolCall {
1918                                    id: id.clone(),
1919                                    title: "Label".into(),
1920                                    kind: acp::ToolKind::Fetch,
1921                                    status: acp::ToolCallStatus::InProgress,
1922                                    content: vec![],
1923                                    locations: vec![],
1924                                    raw_input: None,
1925                                    raw_output: None,
1926                                }),
1927                                cx,
1928                            )
1929                        })
1930                        .unwrap()
1931                        .unwrap();
1932                    Ok(acp::PromptResponse {
1933                        stop_reason: acp::StopReason::EndTurn,
1934                    })
1935                }
1936                .boxed_local()
1937            }
1938        }));
1939
1940        let thread = cx
1941            .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
1942            .await
1943            .unwrap();
1944
1945        let request = thread.update(cx, |thread, cx| {
1946            thread.send_raw("Fetch https://example.com", cx)
1947        });
1948
1949        run_until_first_tool_call(&thread, cx).await;
1950
1951        thread.read_with(cx, |thread, _| {
1952            assert!(matches!(
1953                thread.entries[1],
1954                AgentThreadEntry::ToolCall(ToolCall {
1955                    status: ToolCallStatus::InProgress,
1956                    ..
1957                })
1958            ));
1959        });
1960
1961        thread.update(cx, |thread, cx| thread.cancel(cx)).await;
1962
1963        thread.read_with(cx, |thread, _| {
1964            assert!(matches!(
1965                &thread.entries[1],
1966                AgentThreadEntry::ToolCall(ToolCall {
1967                    status: ToolCallStatus::Canceled,
1968                    ..
1969                })
1970            ));
1971        });
1972
1973        thread
1974            .update(cx, |thread, cx| {
1975                thread.handle_session_update(
1976                    acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate {
1977                        id,
1978                        fields: acp::ToolCallUpdateFields {
1979                            status: Some(acp::ToolCallStatus::Completed),
1980                            ..Default::default()
1981                        },
1982                    }),
1983                    cx,
1984                )
1985            })
1986            .unwrap();
1987
1988        request.await.unwrap();
1989
1990        thread.read_with(cx, |thread, _| {
1991            assert!(matches!(
1992                thread.entries[1],
1993                AgentThreadEntry::ToolCall(ToolCall {
1994                    status: ToolCallStatus::Completed,
1995                    ..
1996                })
1997            ));
1998        });
1999    }
2000
2001    #[gpui::test]
2002    async fn test_no_pending_edits_if_tool_calls_are_completed(cx: &mut TestAppContext) {
2003        init_test(cx);
2004        let fs = FakeFs::new(cx.background_executor.clone());
2005        fs.insert_tree(path!("/test"), json!({})).await;
2006        let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
2007
2008        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
2009            move |_, thread, mut cx| {
2010                async move {
2011                    thread
2012                        .update(&mut cx, |thread, cx| {
2013                            thread.handle_session_update(
2014                                acp::SessionUpdate::ToolCall(acp::ToolCall {
2015                                    id: acp::ToolCallId("test".into()),
2016                                    title: "Label".into(),
2017                                    kind: acp::ToolKind::Edit,
2018                                    status: acp::ToolCallStatus::Completed,
2019                                    content: vec![acp::ToolCallContent::Diff {
2020                                        diff: acp::Diff {
2021                                            path: "/test/test.txt".into(),
2022                                            old_text: None,
2023                                            new_text: "foo".into(),
2024                                        },
2025                                    }],
2026                                    locations: vec![],
2027                                    raw_input: None,
2028                                    raw_output: None,
2029                                }),
2030                                cx,
2031                            )
2032                        })
2033                        .unwrap()
2034                        .unwrap();
2035                    Ok(acp::PromptResponse {
2036                        stop_reason: acp::StopReason::EndTurn,
2037                    })
2038                }
2039                .boxed_local()
2040            }
2041        }));
2042
2043        let thread = cx
2044            .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
2045            .await
2046            .unwrap();
2047
2048        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["Hi".into()], cx)))
2049            .await
2050            .unwrap();
2051
2052        assert!(cx.read(|cx| !thread.read(cx).has_pending_edit_tool_calls()));
2053    }
2054
2055    #[gpui::test(iterations = 10)]
2056    async fn test_checkpoints(cx: &mut TestAppContext) {
2057        init_test(cx);
2058        let fs = FakeFs::new(cx.background_executor.clone());
2059        fs.insert_tree(
2060            path!("/test"),
2061            json!({
2062                ".git": {}
2063            }),
2064        )
2065        .await;
2066        let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
2067
2068        let simulate_changes = Arc::new(AtomicBool::new(true));
2069        let next_filename = Arc::new(AtomicUsize::new(0));
2070        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
2071            let simulate_changes = simulate_changes.clone();
2072            let next_filename = next_filename.clone();
2073            let fs = fs.clone();
2074            move |request, thread, mut cx| {
2075                let fs = fs.clone();
2076                let simulate_changes = simulate_changes.clone();
2077                let next_filename = next_filename.clone();
2078                async move {
2079                    if simulate_changes.load(SeqCst) {
2080                        let filename = format!("/test/file-{}", next_filename.fetch_add(1, SeqCst));
2081                        fs.write(Path::new(&filename), b"").await?;
2082                    }
2083
2084                    let acp::ContentBlock::Text(content) = &request.prompt[0] else {
2085                        panic!("expected text content block");
2086                    };
2087                    thread.update(&mut cx, |thread, cx| {
2088                        thread
2089                            .handle_session_update(
2090                                acp::SessionUpdate::AgentMessageChunk {
2091                                    content: content.text.to_uppercase().into(),
2092                                },
2093                                cx,
2094                            )
2095                            .unwrap();
2096                    })?;
2097                    Ok(acp::PromptResponse {
2098                        stop_reason: acp::StopReason::EndTurn,
2099                    })
2100                }
2101                .boxed_local()
2102            }
2103        }));
2104        let thread = cx
2105            .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
2106            .await
2107            .unwrap();
2108
2109        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["Lorem".into()], cx)))
2110            .await
2111            .unwrap();
2112        thread.read_with(cx, |thread, cx| {
2113            assert_eq!(
2114                thread.to_markdown(cx),
2115                indoc! {"
2116                    ## User (checkpoint)
2117
2118                    Lorem
2119
2120                    ## Assistant
2121
2122                    LOREM
2123
2124                "}
2125            );
2126        });
2127        assert_eq!(fs.files(), vec![Path::new("/test/file-0")]);
2128
2129        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["ipsum".into()], cx)))
2130            .await
2131            .unwrap();
2132        thread.read_with(cx, |thread, cx| {
2133            assert_eq!(
2134                thread.to_markdown(cx),
2135                indoc! {"
2136                    ## User (checkpoint)
2137
2138                    Lorem
2139
2140                    ## Assistant
2141
2142                    LOREM
2143
2144                    ## User (checkpoint)
2145
2146                    ipsum
2147
2148                    ## Assistant
2149
2150                    IPSUM
2151
2152                "}
2153            );
2154        });
2155        assert_eq!(
2156            fs.files(),
2157            vec![Path::new("/test/file-0"), Path::new("/test/file-1")]
2158        );
2159
2160        // Checkpoint isn't stored when there are no changes.
2161        simulate_changes.store(false, SeqCst);
2162        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["dolor".into()], cx)))
2163            .await
2164            .unwrap();
2165        thread.read_with(cx, |thread, cx| {
2166            assert_eq!(
2167                thread.to_markdown(cx),
2168                indoc! {"
2169                    ## User (checkpoint)
2170
2171                    Lorem
2172
2173                    ## Assistant
2174
2175                    LOREM
2176
2177                    ## User (checkpoint)
2178
2179                    ipsum
2180
2181                    ## Assistant
2182
2183                    IPSUM
2184
2185                    ## User
2186
2187                    dolor
2188
2189                    ## Assistant
2190
2191                    DOLOR
2192
2193                "}
2194            );
2195        });
2196        assert_eq!(
2197            fs.files(),
2198            vec![Path::new("/test/file-0"), Path::new("/test/file-1")]
2199        );
2200
2201        // Rewinding the conversation truncates the history and restores the checkpoint.
2202        thread
2203            .update(cx, |thread, cx| {
2204                let AgentThreadEntry::UserMessage(message) = &thread.entries[2] else {
2205                    panic!("unexpected entries {:?}", thread.entries)
2206                };
2207                thread.rewind(message.id.clone().unwrap(), cx)
2208            })
2209            .await
2210            .unwrap();
2211        thread.read_with(cx, |thread, cx| {
2212            assert_eq!(
2213                thread.to_markdown(cx),
2214                indoc! {"
2215                    ## User (checkpoint)
2216
2217                    Lorem
2218
2219                    ## Assistant
2220
2221                    LOREM
2222
2223                "}
2224            );
2225        });
2226        assert_eq!(fs.files(), vec![Path::new("/test/file-0")]);
2227    }
2228
2229    async fn run_until_first_tool_call(
2230        thread: &Entity<AcpThread>,
2231        cx: &mut TestAppContext,
2232    ) -> usize {
2233        let (mut tx, mut rx) = mpsc::channel::<usize>(1);
2234
2235        let subscription = cx.update(|cx| {
2236            cx.subscribe(thread, move |thread, _, cx| {
2237                for (ix, entry) in thread.read(cx).entries.iter().enumerate() {
2238                    if matches!(entry, AgentThreadEntry::ToolCall(_)) {
2239                        return tx.try_send(ix).unwrap();
2240                    }
2241                }
2242            })
2243        });
2244
2245        select! {
2246            _ = futures::FutureExt::fuse(smol::Timer::after(Duration::from_secs(10))) => {
2247                panic!("Timeout waiting for tool call")
2248            }
2249            ix = rx.next().fuse() => {
2250                drop(subscription);
2251                ix.unwrap()
2252            }
2253        }
2254    }
2255
2256    #[derive(Clone, Default)]
2257    struct FakeAgentConnection {
2258        auth_methods: Vec<acp::AuthMethod>,
2259        sessions: Arc<parking_lot::Mutex<HashMap<acp::SessionId, WeakEntity<AcpThread>>>>,
2260        on_user_message: Option<
2261            Rc<
2262                dyn Fn(
2263                        acp::PromptRequest,
2264                        WeakEntity<AcpThread>,
2265                        AsyncApp,
2266                    ) -> LocalBoxFuture<'static, Result<acp::PromptResponse>>
2267                    + 'static,
2268            >,
2269        >,
2270    }
2271
2272    impl FakeAgentConnection {
2273        fn new() -> Self {
2274            Self {
2275                auth_methods: Vec::new(),
2276                on_user_message: None,
2277                sessions: Arc::default(),
2278            }
2279        }
2280
2281        #[expect(unused)]
2282        fn with_auth_methods(mut self, auth_methods: Vec<acp::AuthMethod>) -> Self {
2283            self.auth_methods = auth_methods;
2284            self
2285        }
2286
2287        fn on_user_message(
2288            mut self,
2289            handler: impl Fn(
2290                acp::PromptRequest,
2291                WeakEntity<AcpThread>,
2292                AsyncApp,
2293            ) -> LocalBoxFuture<'static, Result<acp::PromptResponse>>
2294            + 'static,
2295        ) -> Self {
2296            self.on_user_message.replace(Rc::new(handler));
2297            self
2298        }
2299    }
2300
2301    impl AgentConnection for FakeAgentConnection {
2302        fn auth_methods(&self) -> &[acp::AuthMethod] {
2303            &self.auth_methods
2304        }
2305
2306        fn new_thread(
2307            self: Rc<Self>,
2308            project: Entity<Project>,
2309            _cwd: &Path,
2310            cx: &mut gpui::App,
2311        ) -> Task<gpui::Result<Entity<AcpThread>>> {
2312            let session_id = acp::SessionId(
2313                rand::thread_rng()
2314                    .sample_iter(&rand::distributions::Alphanumeric)
2315                    .take(7)
2316                    .map(char::from)
2317                    .collect::<String>()
2318                    .into(),
2319            );
2320            let thread =
2321                cx.new(|cx| AcpThread::new("Test", self.clone(), project, session_id.clone(), cx));
2322            self.sessions.lock().insert(session_id, thread.downgrade());
2323            Task::ready(Ok(thread))
2324        }
2325
2326        fn authenticate(&self, method: acp::AuthMethodId, _cx: &mut App) -> Task<gpui::Result<()>> {
2327            if self.auth_methods().iter().any(|m| m.id == method) {
2328                Task::ready(Ok(()))
2329            } else {
2330                Task::ready(Err(anyhow!("Invalid Auth Method")))
2331            }
2332        }
2333
2334        fn prompt(
2335            &self,
2336            _id: Option<UserMessageId>,
2337            params: acp::PromptRequest,
2338            cx: &mut App,
2339        ) -> Task<gpui::Result<acp::PromptResponse>> {
2340            let sessions = self.sessions.lock();
2341            let thread = sessions.get(&params.session_id).unwrap();
2342            if let Some(handler) = &self.on_user_message {
2343                let handler = handler.clone();
2344                let thread = thread.clone();
2345                cx.spawn(async move |cx| handler(params, thread, cx.clone()).await)
2346            } else {
2347                Task::ready(Ok(acp::PromptResponse {
2348                    stop_reason: acp::StopReason::EndTurn,
2349                }))
2350            }
2351        }
2352
2353        fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
2354            let sessions = self.sessions.lock();
2355            let thread = sessions.get(&session_id).unwrap().clone();
2356
2357            cx.spawn(async move |cx| {
2358                thread
2359                    .update(cx, |thread, cx| thread.cancel(cx))
2360                    .unwrap()
2361                    .await
2362            })
2363            .detach();
2364        }
2365
2366        fn session_editor(
2367            &self,
2368            session_id: &acp::SessionId,
2369            _cx: &mut App,
2370        ) -> Option<Rc<dyn AgentSessionEditor>> {
2371            Some(Rc::new(FakeAgentSessionEditor {
2372                _session_id: session_id.clone(),
2373            }))
2374        }
2375
2376        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
2377            self
2378        }
2379    }
2380
2381    struct FakeAgentSessionEditor {
2382        _session_id: acp::SessionId,
2383    }
2384
2385    impl AgentSessionEditor for FakeAgentSessionEditor {
2386        fn truncate(&self, _message_id: UserMessageId, _cx: &mut App) -> Task<Result<()>> {
2387            Task::ready(Ok(()))
2388        }
2389    }
2390}