acp_thread.rs

   1mod connection;
   2mod diff;
   3mod mention;
   4mod terminal;
   5
   6use agent_settings::AgentSettings;
   7use collections::HashSet;
   8pub use connection::*;
   9pub use diff::*;
  10use futures::future::Shared;
  11use language::language_settings::FormatOnSave;
  12pub use mention::*;
  13use project::lsp_store::{FormatTrigger, LspFormatTarget};
  14use serde::{Deserialize, Serialize};
  15use settings::Settings as _;
  16pub use terminal::*;
  17
  18use action_log::ActionLog;
  19use agent_client_protocol::{self as acp};
  20use anyhow::{Context as _, Result, anyhow};
  21use editor::Bias;
  22use futures::{FutureExt, channel::oneshot, future::BoxFuture};
  23use gpui::{AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task, WeakEntity};
  24use itertools::Itertools;
  25use language::{Anchor, Buffer, BufferSnapshot, LanguageRegistry, Point, ToPoint, text_diff};
  26use markdown::Markdown;
  27use project::{AgentLocation, Project, git_store::GitStoreCheckpoint};
  28use std::collections::HashMap;
  29use std::error::Error;
  30use std::fmt::{Formatter, Write};
  31use std::ops::Range;
  32use std::process::ExitStatus;
  33use std::rc::Rc;
  34use std::time::{Duration, Instant};
  35use std::{fmt::Display, mem, path::PathBuf, sync::Arc};
  36use ui::App;
  37use util::{ResultExt, get_system_shell};
  38use uuid::Uuid;
  39
  40#[derive(Debug)]
  41pub struct UserMessage {
  42    pub id: Option<UserMessageId>,
  43    pub content: ContentBlock,
  44    pub chunks: Vec<acp::ContentBlock>,
  45    pub checkpoint: Option<Checkpoint>,
  46}
  47
  48#[derive(Debug)]
  49pub struct Checkpoint {
  50    git_checkpoint: GitStoreCheckpoint,
  51    pub show: bool,
  52}
  53
  54impl UserMessage {
  55    fn to_markdown(&self, cx: &App) -> String {
  56        let mut markdown = String::new();
  57        if self
  58            .checkpoint
  59            .as_ref()
  60            .is_some_and(|checkpoint| checkpoint.show)
  61        {
  62            writeln!(markdown, "## User (checkpoint)").unwrap();
  63        } else {
  64            writeln!(markdown, "## User").unwrap();
  65        }
  66        writeln!(markdown).unwrap();
  67        writeln!(markdown, "{}", self.content.to_markdown(cx)).unwrap();
  68        writeln!(markdown).unwrap();
  69        markdown
  70    }
  71}
  72
  73#[derive(Debug, PartialEq)]
  74pub struct AssistantMessage {
  75    pub chunks: Vec<AssistantMessageChunk>,
  76}
  77
  78impl AssistantMessage {
  79    pub fn to_markdown(&self, cx: &App) -> String {
  80        format!(
  81            "## Assistant\n\n{}\n\n",
  82            self.chunks
  83                .iter()
  84                .map(|chunk| chunk.to_markdown(cx))
  85                .join("\n\n")
  86        )
  87    }
  88}
  89
  90#[derive(Debug, PartialEq)]
  91pub enum AssistantMessageChunk {
  92    Message { block: ContentBlock },
  93    Thought { block: ContentBlock },
  94}
  95
  96impl AssistantMessageChunk {
  97    pub fn from_str(chunk: &str, language_registry: &Arc<LanguageRegistry>, cx: &mut App) -> Self {
  98        Self::Message {
  99            block: ContentBlock::new(chunk.into(), language_registry, cx),
 100        }
 101    }
 102
 103    fn to_markdown(&self, cx: &App) -> String {
 104        match self {
 105            Self::Message { block } => block.to_markdown(cx).to_string(),
 106            Self::Thought { block } => {
 107                format!("<thinking>\n{}\n</thinking>", block.to_markdown(cx))
 108            }
 109        }
 110    }
 111}
 112
 113#[derive(Debug)]
 114pub enum AgentThreadEntry {
 115    UserMessage(UserMessage),
 116    AssistantMessage(AssistantMessage),
 117    ToolCall(ToolCall),
 118}
 119
 120impl AgentThreadEntry {
 121    pub fn to_markdown(&self, cx: &App) -> String {
 122        match self {
 123            Self::UserMessage(message) => message.to_markdown(cx),
 124            Self::AssistantMessage(message) => message.to_markdown(cx),
 125            Self::ToolCall(tool_call) => tool_call.to_markdown(cx),
 126        }
 127    }
 128
 129    pub fn user_message(&self) -> Option<&UserMessage> {
 130        if let AgentThreadEntry::UserMessage(message) = self {
 131            Some(message)
 132        } else {
 133            None
 134        }
 135    }
 136
 137    pub fn diffs(&self) -> impl Iterator<Item = &Entity<Diff>> {
 138        if let AgentThreadEntry::ToolCall(call) = self {
 139            itertools::Either::Left(call.diffs())
 140        } else {
 141            itertools::Either::Right(std::iter::empty())
 142        }
 143    }
 144
 145    pub fn terminals(&self) -> impl Iterator<Item = &Entity<Terminal>> {
 146        if let AgentThreadEntry::ToolCall(call) = self {
 147            itertools::Either::Left(call.terminals())
 148        } else {
 149            itertools::Either::Right(std::iter::empty())
 150        }
 151    }
 152
 153    pub fn location(&self, ix: usize) -> Option<(acp::ToolCallLocation, AgentLocation)> {
 154        if let AgentThreadEntry::ToolCall(ToolCall {
 155            locations,
 156            resolved_locations,
 157            ..
 158        }) = self
 159        {
 160            Some((
 161                locations.get(ix)?.clone(),
 162                resolved_locations.get(ix)?.clone()?,
 163            ))
 164        } else {
 165            None
 166        }
 167    }
 168}
 169
 170#[derive(Debug)]
 171pub struct ToolCall {
 172    pub id: acp::ToolCallId,
 173    pub label: Entity<Markdown>,
 174    pub kind: acp::ToolKind,
 175    pub content: Vec<ToolCallContent>,
 176    pub status: ToolCallStatus,
 177    pub locations: Vec<acp::ToolCallLocation>,
 178    pub resolved_locations: Vec<Option<AgentLocation>>,
 179    pub raw_input: Option<serde_json::Value>,
 180    pub raw_output: Option<serde_json::Value>,
 181}
 182
 183impl ToolCall {
 184    fn from_acp(
 185        tool_call: acp::ToolCall,
 186        status: ToolCallStatus,
 187        language_registry: Arc<LanguageRegistry>,
 188        terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
 189        cx: &mut App,
 190    ) -> Result<Self> {
 191        let title = if let Some((first_line, _)) = tool_call.title.split_once("\n") {
 192            first_line.to_owned() + ""
 193        } else {
 194            tool_call.title
 195        };
 196        let mut content = Vec::with_capacity(tool_call.content.len());
 197        for item in tool_call.content {
 198            content.push(ToolCallContent::from_acp(
 199                item,
 200                language_registry.clone(),
 201                terminals,
 202                cx,
 203            )?);
 204        }
 205
 206        let result = Self {
 207            id: tool_call.id,
 208            label: cx
 209                .new(|cx| Markdown::new(title.into(), Some(language_registry.clone()), None, cx)),
 210            kind: tool_call.kind,
 211            content,
 212            locations: tool_call.locations,
 213            resolved_locations: Vec::default(),
 214            status,
 215            raw_input: tool_call.raw_input,
 216            raw_output: tool_call.raw_output,
 217        };
 218        Ok(result)
 219    }
 220
 221    fn update_fields(
 222        &mut self,
 223        fields: acp::ToolCallUpdateFields,
 224        language_registry: Arc<LanguageRegistry>,
 225        terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
 226        cx: &mut App,
 227    ) -> Result<()> {
 228        let acp::ToolCallUpdateFields {
 229            kind,
 230            status,
 231            title,
 232            content,
 233            locations,
 234            raw_input,
 235            raw_output,
 236        } = fields;
 237
 238        if let Some(kind) = kind {
 239            self.kind = kind;
 240        }
 241
 242        if let Some(status) = status {
 243            self.status = status.into();
 244        }
 245
 246        if let Some(title) = title {
 247            self.label.update(cx, |label, cx| {
 248                if let Some((first_line, _)) = title.split_once("\n") {
 249                    label.replace(first_line.to_owned() + "", cx)
 250                } else {
 251                    label.replace(title, cx);
 252                }
 253            });
 254        }
 255
 256        if let Some(content) = content {
 257            let new_content_len = content.len();
 258            let mut content = content.into_iter();
 259
 260            // Reuse existing content if we can
 261            for (old, new) in self.content.iter_mut().zip(content.by_ref()) {
 262                old.update_from_acp(new, language_registry.clone(), terminals, cx)?;
 263            }
 264            for new in content {
 265                self.content.push(ToolCallContent::from_acp(
 266                    new,
 267                    language_registry.clone(),
 268                    terminals,
 269                    cx,
 270                )?)
 271            }
 272            self.content.truncate(new_content_len);
 273        }
 274
 275        if let Some(locations) = locations {
 276            self.locations = locations;
 277        }
 278
 279        if let Some(raw_input) = raw_input {
 280            self.raw_input = Some(raw_input);
 281        }
 282
 283        if let Some(raw_output) = raw_output {
 284            if self.content.is_empty()
 285                && let Some(markdown) = markdown_for_raw_output(&raw_output, &language_registry, cx)
 286            {
 287                self.content
 288                    .push(ToolCallContent::ContentBlock(ContentBlock::Markdown {
 289                        markdown,
 290                    }));
 291            }
 292            self.raw_output = Some(raw_output);
 293        }
 294        Ok(())
 295    }
 296
 297    pub fn diffs(&self) -> impl Iterator<Item = &Entity<Diff>> {
 298        self.content.iter().filter_map(|content| match content {
 299            ToolCallContent::Diff(diff) => Some(diff),
 300            ToolCallContent::ContentBlock(_) => None,
 301            ToolCallContent::Terminal(_) => None,
 302        })
 303    }
 304
 305    pub fn terminals(&self) -> impl Iterator<Item = &Entity<Terminal>> {
 306        self.content.iter().filter_map(|content| match content {
 307            ToolCallContent::Terminal(terminal) => Some(terminal),
 308            ToolCallContent::ContentBlock(_) => None,
 309            ToolCallContent::Diff(_) => None,
 310        })
 311    }
 312
 313    fn to_markdown(&self, cx: &App) -> String {
 314        let mut markdown = format!(
 315            "**Tool Call: {}**\nStatus: {}\n\n",
 316            self.label.read(cx).source(),
 317            self.status
 318        );
 319        for content in &self.content {
 320            markdown.push_str(content.to_markdown(cx).as_str());
 321            markdown.push_str("\n\n");
 322        }
 323        markdown
 324    }
 325
 326    async fn resolve_location(
 327        location: acp::ToolCallLocation,
 328        project: WeakEntity<Project>,
 329        cx: &mut AsyncApp,
 330    ) -> Option<AgentLocation> {
 331        let buffer = project
 332            .update(cx, |project, cx| {
 333                project
 334                    .project_path_for_absolute_path(&location.path, cx)
 335                    .map(|path| project.open_buffer(path, cx))
 336            })
 337            .ok()??;
 338        let buffer = buffer.await.log_err()?;
 339        let position = buffer
 340            .update(cx, |buffer, _| {
 341                if let Some(row) = location.line {
 342                    let snapshot = buffer.snapshot();
 343                    let column = snapshot.indent_size_for_line(row).len;
 344                    let point = snapshot.clip_point(Point::new(row, column), Bias::Left);
 345                    snapshot.anchor_before(point)
 346                } else {
 347                    Anchor::MIN
 348                }
 349            })
 350            .ok()?;
 351
 352        Some(AgentLocation {
 353            buffer: buffer.downgrade(),
 354            position,
 355        })
 356    }
 357
 358    fn resolve_locations(
 359        &self,
 360        project: Entity<Project>,
 361        cx: &mut App,
 362    ) -> Task<Vec<Option<AgentLocation>>> {
 363        let locations = self.locations.clone();
 364        project.update(cx, |_, cx| {
 365            cx.spawn(async move |project, cx| {
 366                let mut new_locations = Vec::new();
 367                for location in locations {
 368                    new_locations.push(Self::resolve_location(location, project.clone(), cx).await);
 369                }
 370                new_locations
 371            })
 372        })
 373    }
 374}
 375
 376#[derive(Debug)]
 377pub enum ToolCallStatus {
 378    /// The tool call hasn't started running yet, but we start showing it to
 379    /// the user.
 380    Pending,
 381    /// The tool call is waiting for confirmation from the user.
 382    WaitingForConfirmation {
 383        options: Vec<acp::PermissionOption>,
 384        respond_tx: oneshot::Sender<acp::PermissionOptionId>,
 385    },
 386    /// The tool call is currently running.
 387    InProgress,
 388    /// The tool call completed successfully.
 389    Completed,
 390    /// The tool call failed.
 391    Failed,
 392    /// The user rejected the tool call.
 393    Rejected,
 394    /// The user canceled generation so the tool call was canceled.
 395    Canceled,
 396}
 397
 398impl From<acp::ToolCallStatus> for ToolCallStatus {
 399    fn from(status: acp::ToolCallStatus) -> Self {
 400        match status {
 401            acp::ToolCallStatus::Pending => Self::Pending,
 402            acp::ToolCallStatus::InProgress => Self::InProgress,
 403            acp::ToolCallStatus::Completed => Self::Completed,
 404            acp::ToolCallStatus::Failed => Self::Failed,
 405        }
 406    }
 407}
 408
 409impl Display for ToolCallStatus {
 410    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
 411        write!(
 412            f,
 413            "{}",
 414            match self {
 415                ToolCallStatus::Pending => "Pending",
 416                ToolCallStatus::WaitingForConfirmation { .. } => "Waiting for confirmation",
 417                ToolCallStatus::InProgress => "In Progress",
 418                ToolCallStatus::Completed => "Completed",
 419                ToolCallStatus::Failed => "Failed",
 420                ToolCallStatus::Rejected => "Rejected",
 421                ToolCallStatus::Canceled => "Canceled",
 422            }
 423        )
 424    }
 425}
 426
 427#[derive(Debug, PartialEq, Clone)]
 428pub enum ContentBlock {
 429    Empty,
 430    Markdown { markdown: Entity<Markdown> },
 431    ResourceLink { resource_link: acp::ResourceLink },
 432}
 433
 434impl ContentBlock {
 435    pub fn new(
 436        block: acp::ContentBlock,
 437        language_registry: &Arc<LanguageRegistry>,
 438        cx: &mut App,
 439    ) -> Self {
 440        let mut this = Self::Empty;
 441        this.append(block, language_registry, cx);
 442        this
 443    }
 444
 445    pub fn new_combined(
 446        blocks: impl IntoIterator<Item = acp::ContentBlock>,
 447        language_registry: Arc<LanguageRegistry>,
 448        cx: &mut App,
 449    ) -> Self {
 450        let mut this = Self::Empty;
 451        for block in blocks {
 452            this.append(block, &language_registry, cx);
 453        }
 454        this
 455    }
 456
 457    pub fn append(
 458        &mut self,
 459        block: acp::ContentBlock,
 460        language_registry: &Arc<LanguageRegistry>,
 461        cx: &mut App,
 462    ) {
 463        if matches!(self, ContentBlock::Empty)
 464            && let acp::ContentBlock::ResourceLink(resource_link) = block
 465        {
 466            *self = ContentBlock::ResourceLink { resource_link };
 467            return;
 468        }
 469
 470        let new_content = self.block_string_contents(block);
 471
 472        match self {
 473            ContentBlock::Empty => {
 474                *self = Self::create_markdown_block(new_content, language_registry, cx);
 475            }
 476            ContentBlock::Markdown { markdown } => {
 477                markdown.update(cx, |markdown, cx| markdown.append(&new_content, cx));
 478            }
 479            ContentBlock::ResourceLink { resource_link } => {
 480                let existing_content = Self::resource_link_md(&resource_link.uri);
 481                let combined = format!("{}\n{}", existing_content, new_content);
 482
 483                *self = Self::create_markdown_block(combined, language_registry, cx);
 484            }
 485        }
 486    }
 487
 488    fn create_markdown_block(
 489        content: String,
 490        language_registry: &Arc<LanguageRegistry>,
 491        cx: &mut App,
 492    ) -> ContentBlock {
 493        ContentBlock::Markdown {
 494            markdown: cx
 495                .new(|cx| Markdown::new(content.into(), Some(language_registry.clone()), None, cx)),
 496        }
 497    }
 498
 499    fn block_string_contents(&self, block: acp::ContentBlock) -> String {
 500        match block {
 501            acp::ContentBlock::Text(text_content) => text_content.text,
 502            acp::ContentBlock::ResourceLink(resource_link) => {
 503                Self::resource_link_md(&resource_link.uri)
 504            }
 505            acp::ContentBlock::Resource(acp::EmbeddedResource {
 506                resource:
 507                    acp::EmbeddedResourceResource::TextResourceContents(acp::TextResourceContents {
 508                        uri,
 509                        ..
 510                    }),
 511                ..
 512            }) => Self::resource_link_md(&uri),
 513            acp::ContentBlock::Image(image) => Self::image_md(&image),
 514            acp::ContentBlock::Audio(_) | acp::ContentBlock::Resource(_) => String::new(),
 515        }
 516    }
 517
 518    fn resource_link_md(uri: &str) -> String {
 519        if let Some(uri) = MentionUri::parse(uri).log_err() {
 520            uri.as_link().to_string()
 521        } else {
 522            uri.to_string()
 523        }
 524    }
 525
 526    fn image_md(_image: &acp::ImageContent) -> String {
 527        "`Image`".into()
 528    }
 529
 530    pub fn to_markdown<'a>(&'a self, cx: &'a App) -> &'a str {
 531        match self {
 532            ContentBlock::Empty => "",
 533            ContentBlock::Markdown { markdown } => markdown.read(cx).source(),
 534            ContentBlock::ResourceLink { resource_link } => &resource_link.uri,
 535        }
 536    }
 537
 538    pub fn markdown(&self) -> Option<&Entity<Markdown>> {
 539        match self {
 540            ContentBlock::Empty => None,
 541            ContentBlock::Markdown { markdown } => Some(markdown),
 542            ContentBlock::ResourceLink { .. } => None,
 543        }
 544    }
 545
 546    pub fn resource_link(&self) -> Option<&acp::ResourceLink> {
 547        match self {
 548            ContentBlock::ResourceLink { resource_link } => Some(resource_link),
 549            _ => None,
 550        }
 551    }
 552}
 553
 554#[derive(Debug)]
 555pub enum ToolCallContent {
 556    ContentBlock(ContentBlock),
 557    Diff(Entity<Diff>),
 558    Terminal(Entity<Terminal>),
 559}
 560
 561impl ToolCallContent {
 562    pub fn from_acp(
 563        content: acp::ToolCallContent,
 564        language_registry: Arc<LanguageRegistry>,
 565        terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
 566        cx: &mut App,
 567    ) -> Result<Self> {
 568        match content {
 569            acp::ToolCallContent::Content { content } => Ok(Self::ContentBlock(ContentBlock::new(
 570                content,
 571                &language_registry,
 572                cx,
 573            ))),
 574            acp::ToolCallContent::Diff { diff } => Ok(Self::Diff(cx.new(|cx| {
 575                Diff::finalized(
 576                    diff.path,
 577                    diff.old_text,
 578                    diff.new_text,
 579                    language_registry,
 580                    cx,
 581                )
 582            }))),
 583            acp::ToolCallContent::Terminal { terminal_id } => terminals
 584                .get(&terminal_id)
 585                .cloned()
 586                .map(Self::Terminal)
 587                .ok_or_else(|| anyhow::anyhow!("Terminal with id `{}` not found", terminal_id)),
 588        }
 589    }
 590
 591    pub fn update_from_acp(
 592        &mut self,
 593        new: acp::ToolCallContent,
 594        language_registry: Arc<LanguageRegistry>,
 595        terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
 596        cx: &mut App,
 597    ) -> Result<()> {
 598        let needs_update = match (&self, &new) {
 599            (Self::Diff(old_diff), acp::ToolCallContent::Diff { diff: new_diff }) => {
 600                old_diff.read(cx).needs_update(
 601                    new_diff.old_text.as_deref().unwrap_or(""),
 602                    &new_diff.new_text,
 603                    cx,
 604                )
 605            }
 606            _ => true,
 607        };
 608
 609        if needs_update {
 610            *self = Self::from_acp(new, language_registry, terminals, cx)?;
 611        }
 612        Ok(())
 613    }
 614
 615    pub fn to_markdown(&self, cx: &App) -> String {
 616        match self {
 617            Self::ContentBlock(content) => content.to_markdown(cx).to_string(),
 618            Self::Diff(diff) => diff.read(cx).to_markdown(cx),
 619            Self::Terminal(terminal) => terminal.read(cx).to_markdown(cx),
 620        }
 621    }
 622}
 623
 624#[derive(Debug, PartialEq)]
 625pub enum ToolCallUpdate {
 626    UpdateFields(acp::ToolCallUpdate),
 627    UpdateDiff(ToolCallUpdateDiff),
 628    UpdateTerminal(ToolCallUpdateTerminal),
 629}
 630
 631impl ToolCallUpdate {
 632    fn id(&self) -> &acp::ToolCallId {
 633        match self {
 634            Self::UpdateFields(update) => &update.id,
 635            Self::UpdateDiff(diff) => &diff.id,
 636            Self::UpdateTerminal(terminal) => &terminal.id,
 637        }
 638    }
 639}
 640
 641impl From<acp::ToolCallUpdate> for ToolCallUpdate {
 642    fn from(update: acp::ToolCallUpdate) -> Self {
 643        Self::UpdateFields(update)
 644    }
 645}
 646
 647impl From<ToolCallUpdateDiff> for ToolCallUpdate {
 648    fn from(diff: ToolCallUpdateDiff) -> Self {
 649        Self::UpdateDiff(diff)
 650    }
 651}
 652
 653#[derive(Debug, PartialEq)]
 654pub struct ToolCallUpdateDiff {
 655    pub id: acp::ToolCallId,
 656    pub diff: Entity<Diff>,
 657}
 658
 659impl From<ToolCallUpdateTerminal> for ToolCallUpdate {
 660    fn from(terminal: ToolCallUpdateTerminal) -> Self {
 661        Self::UpdateTerminal(terminal)
 662    }
 663}
 664
 665#[derive(Debug, PartialEq)]
 666pub struct ToolCallUpdateTerminal {
 667    pub id: acp::ToolCallId,
 668    pub terminal: Entity<Terminal>,
 669}
 670
 671#[derive(Debug, Default)]
 672pub struct Plan {
 673    pub entries: Vec<PlanEntry>,
 674}
 675
 676#[derive(Debug)]
 677pub struct PlanStats<'a> {
 678    pub in_progress_entry: Option<&'a PlanEntry>,
 679    pub pending: u32,
 680    pub completed: u32,
 681}
 682
 683impl Plan {
 684    pub fn is_empty(&self) -> bool {
 685        self.entries.is_empty()
 686    }
 687
 688    pub fn stats(&self) -> PlanStats<'_> {
 689        let mut stats = PlanStats {
 690            in_progress_entry: None,
 691            pending: 0,
 692            completed: 0,
 693        };
 694
 695        for entry in &self.entries {
 696            match &entry.status {
 697                acp::PlanEntryStatus::Pending => {
 698                    stats.pending += 1;
 699                }
 700                acp::PlanEntryStatus::InProgress => {
 701                    stats.in_progress_entry = stats.in_progress_entry.or(Some(entry));
 702                }
 703                acp::PlanEntryStatus::Completed => {
 704                    stats.completed += 1;
 705                }
 706            }
 707        }
 708
 709        stats
 710    }
 711}
 712
 713#[derive(Debug)]
 714pub struct PlanEntry {
 715    pub content: Entity<Markdown>,
 716    pub priority: acp::PlanEntryPriority,
 717    pub status: acp::PlanEntryStatus,
 718}
 719
 720impl PlanEntry {
 721    pub fn from_acp(entry: acp::PlanEntry, cx: &mut App) -> Self {
 722        Self {
 723            content: cx.new(|cx| Markdown::new(entry.content.into(), None, None, cx)),
 724            priority: entry.priority,
 725            status: entry.status,
 726        }
 727    }
 728}
 729
 730#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 731pub struct TokenUsage {
 732    pub max_tokens: u64,
 733    pub used_tokens: u64,
 734}
 735
 736impl TokenUsage {
 737    pub fn ratio(&self) -> TokenUsageRatio {
 738        #[cfg(debug_assertions)]
 739        let warning_threshold: f32 = std::env::var("ZED_THREAD_WARNING_THRESHOLD")
 740            .unwrap_or("0.8".to_string())
 741            .parse()
 742            .unwrap();
 743        #[cfg(not(debug_assertions))]
 744        let warning_threshold: f32 = 0.8;
 745
 746        // When the maximum is unknown because there is no selected model,
 747        // avoid showing the token limit warning.
 748        if self.max_tokens == 0 {
 749            TokenUsageRatio::Normal
 750        } else if self.used_tokens >= self.max_tokens {
 751            TokenUsageRatio::Exceeded
 752        } else if self.used_tokens as f32 / self.max_tokens as f32 >= warning_threshold {
 753            TokenUsageRatio::Warning
 754        } else {
 755            TokenUsageRatio::Normal
 756        }
 757    }
 758}
 759
 760#[derive(Debug, Clone, PartialEq, Eq)]
 761pub enum TokenUsageRatio {
 762    Normal,
 763    Warning,
 764    Exceeded,
 765}
 766
 767#[derive(Debug, Clone)]
 768pub struct RetryStatus {
 769    pub last_error: SharedString,
 770    pub attempt: usize,
 771    pub max_attempts: usize,
 772    pub started_at: Instant,
 773    pub duration: Duration,
 774}
 775
 776pub struct AcpThread {
 777    title: SharedString,
 778    entries: Vec<AgentThreadEntry>,
 779    plan: Plan,
 780    project: Entity<Project>,
 781    action_log: Entity<ActionLog>,
 782    shared_buffers: HashMap<Entity<Buffer>, BufferSnapshot>,
 783    send_task: Option<Task<()>>,
 784    connection: Rc<dyn AgentConnection>,
 785    session_id: acp::SessionId,
 786    token_usage: Option<TokenUsage>,
 787    prompt_capabilities: acp::PromptCapabilities,
 788    _observe_prompt_capabilities: Task<anyhow::Result<()>>,
 789    determine_shell: Shared<Task<String>>,
 790    terminals: HashMap<acp::TerminalId, Entity<Terminal>>,
 791}
 792
 793#[derive(Debug)]
 794pub enum AcpThreadEvent {
 795    NewEntry,
 796    TitleUpdated,
 797    TokenUsageUpdated,
 798    EntryUpdated(usize),
 799    EntriesRemoved(Range<usize>),
 800    ToolAuthorizationRequired,
 801    Retry(RetryStatus),
 802    Stopped,
 803    Error,
 804    LoadError(LoadError),
 805    PromptCapabilitiesUpdated,
 806    Refusal,
 807    AvailableCommandsUpdated(Vec<acp::AvailableCommand>),
 808}
 809
 810impl EventEmitter<AcpThreadEvent> for AcpThread {}
 811
 812#[derive(PartialEq, Eq, Debug)]
 813pub enum ThreadStatus {
 814    Idle,
 815    WaitingForToolConfirmation,
 816    Generating,
 817}
 818
 819#[derive(Debug, Clone)]
 820pub enum LoadError {
 821    Unsupported {
 822        command: SharedString,
 823        current_version: SharedString,
 824        minimum_version: SharedString,
 825    },
 826    FailedToInstall(SharedString),
 827    Exited {
 828        status: ExitStatus,
 829    },
 830    Other(SharedString),
 831}
 832
 833impl Display for LoadError {
 834    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
 835        match self {
 836            LoadError::Unsupported {
 837                command: path,
 838                current_version,
 839                minimum_version,
 840            } => {
 841                write!(
 842                    f,
 843                    "version {current_version} from {path} is not supported (need at least {minimum_version})"
 844                )
 845            }
 846            LoadError::FailedToInstall(msg) => write!(f, "Failed to install: {msg}"),
 847            LoadError::Exited { status } => write!(f, "Server exited with status {status}"),
 848            LoadError::Other(msg) => write!(f, "{msg}"),
 849        }
 850    }
 851}
 852
 853impl Error for LoadError {}
 854
 855impl AcpThread {
 856    pub fn new(
 857        title: impl Into<SharedString>,
 858        connection: Rc<dyn AgentConnection>,
 859        project: Entity<Project>,
 860        action_log: Entity<ActionLog>,
 861        session_id: acp::SessionId,
 862        mut prompt_capabilities_rx: watch::Receiver<acp::PromptCapabilities>,
 863        cx: &mut Context<Self>,
 864    ) -> Self {
 865        let prompt_capabilities = *prompt_capabilities_rx.borrow();
 866        let task = cx.spawn::<_, anyhow::Result<()>>(async move |this, cx| {
 867            loop {
 868                let caps = prompt_capabilities_rx.recv().await?;
 869                this.update(cx, |this, cx| {
 870                    this.prompt_capabilities = caps;
 871                    cx.emit(AcpThreadEvent::PromptCapabilitiesUpdated);
 872                })?;
 873            }
 874        });
 875
 876        let determine_shell = cx
 877            .background_spawn(async move {
 878                if cfg!(windows) {
 879                    return get_system_shell();
 880                }
 881
 882                if which::which("bash").is_ok() {
 883                    "bash".into()
 884                } else {
 885                    get_system_shell()
 886                }
 887            })
 888            .shared();
 889
 890        Self {
 891            action_log,
 892            shared_buffers: Default::default(),
 893            entries: Default::default(),
 894            plan: Default::default(),
 895            title: title.into(),
 896            project,
 897            send_task: None,
 898            connection,
 899            session_id,
 900            token_usage: None,
 901            prompt_capabilities,
 902            _observe_prompt_capabilities: task,
 903            terminals: HashMap::default(),
 904            determine_shell,
 905        }
 906    }
 907
 908    pub fn prompt_capabilities(&self) -> acp::PromptCapabilities {
 909        self.prompt_capabilities
 910    }
 911
 912    pub fn connection(&self) -> &Rc<dyn AgentConnection> {
 913        &self.connection
 914    }
 915
 916    pub fn action_log(&self) -> &Entity<ActionLog> {
 917        &self.action_log
 918    }
 919
 920    pub fn project(&self) -> &Entity<Project> {
 921        &self.project
 922    }
 923
 924    pub fn title(&self) -> SharedString {
 925        self.title.clone()
 926    }
 927
 928    pub fn entries(&self) -> &[AgentThreadEntry] {
 929        &self.entries
 930    }
 931
 932    pub fn session_id(&self) -> &acp::SessionId {
 933        &self.session_id
 934    }
 935
 936    pub fn status(&self) -> ThreadStatus {
 937        if self.send_task.is_some() {
 938            if self.waiting_for_tool_confirmation() {
 939                ThreadStatus::WaitingForToolConfirmation
 940            } else {
 941                ThreadStatus::Generating
 942            }
 943        } else {
 944            ThreadStatus::Idle
 945        }
 946    }
 947
 948    pub fn token_usage(&self) -> Option<&TokenUsage> {
 949        self.token_usage.as_ref()
 950    }
 951
 952    pub fn has_pending_edit_tool_calls(&self) -> bool {
 953        for entry in self.entries.iter().rev() {
 954            match entry {
 955                AgentThreadEntry::UserMessage(_) => return false,
 956                AgentThreadEntry::ToolCall(
 957                    call @ ToolCall {
 958                        status: ToolCallStatus::InProgress | ToolCallStatus::Pending,
 959                        ..
 960                    },
 961                ) if call.diffs().next().is_some() => {
 962                    return true;
 963                }
 964                AgentThreadEntry::ToolCall(_) | AgentThreadEntry::AssistantMessage(_) => {}
 965            }
 966        }
 967
 968        false
 969    }
 970
 971    pub fn used_tools_since_last_user_message(&self) -> bool {
 972        for entry in self.entries.iter().rev() {
 973            match entry {
 974                AgentThreadEntry::UserMessage(..) => return false,
 975                AgentThreadEntry::AssistantMessage(..) => continue,
 976                AgentThreadEntry::ToolCall(..) => return true,
 977            }
 978        }
 979
 980        false
 981    }
 982
 983    pub fn handle_session_update(
 984        &mut self,
 985        update: acp::SessionUpdate,
 986        cx: &mut Context<Self>,
 987    ) -> Result<(), acp::Error> {
 988        match update {
 989            acp::SessionUpdate::UserMessageChunk { content } => {
 990                self.push_user_content_block(None, content, cx);
 991            }
 992            acp::SessionUpdate::AgentMessageChunk { content } => {
 993                self.push_assistant_content_block(content, false, cx);
 994            }
 995            acp::SessionUpdate::AgentThoughtChunk { content } => {
 996                self.push_assistant_content_block(content, true, cx);
 997            }
 998            acp::SessionUpdate::ToolCall(tool_call) => {
 999                self.upsert_tool_call(tool_call, cx)?;
1000            }
1001            acp::SessionUpdate::ToolCallUpdate(tool_call_update) => {
1002                self.update_tool_call(tool_call_update, cx)?;
1003            }
1004            acp::SessionUpdate::Plan(plan) => {
1005                self.update_plan(plan, cx);
1006            }
1007            acp::SessionUpdate::AvailableCommandsUpdate { available_commands } => {
1008                cx.emit(AcpThreadEvent::AvailableCommandsUpdated(available_commands))
1009            }
1010        }
1011        Ok(())
1012    }
1013
1014    pub fn push_user_content_block(
1015        &mut self,
1016        message_id: Option<UserMessageId>,
1017        chunk: acp::ContentBlock,
1018        cx: &mut Context<Self>,
1019    ) {
1020        let language_registry = self.project.read(cx).languages().clone();
1021        let entries_len = self.entries.len();
1022
1023        if let Some(last_entry) = self.entries.last_mut()
1024            && let AgentThreadEntry::UserMessage(UserMessage {
1025                id,
1026                content,
1027                chunks,
1028                ..
1029            }) = last_entry
1030        {
1031            *id = message_id.or(id.take());
1032            content.append(chunk.clone(), &language_registry, cx);
1033            chunks.push(chunk);
1034            let idx = entries_len - 1;
1035            cx.emit(AcpThreadEvent::EntryUpdated(idx));
1036        } else {
1037            let content = ContentBlock::new(chunk.clone(), &language_registry, cx);
1038            self.push_entry(
1039                AgentThreadEntry::UserMessage(UserMessage {
1040                    id: message_id,
1041                    content,
1042                    chunks: vec![chunk],
1043                    checkpoint: None,
1044                }),
1045                cx,
1046            );
1047        }
1048    }
1049
1050    pub fn push_assistant_content_block(
1051        &mut self,
1052        chunk: acp::ContentBlock,
1053        is_thought: bool,
1054        cx: &mut Context<Self>,
1055    ) {
1056        let language_registry = self.project.read(cx).languages().clone();
1057        let entries_len = self.entries.len();
1058        if let Some(last_entry) = self.entries.last_mut()
1059            && let AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) = last_entry
1060        {
1061            let idx = entries_len - 1;
1062            cx.emit(AcpThreadEvent::EntryUpdated(idx));
1063            match (chunks.last_mut(), is_thought) {
1064                (Some(AssistantMessageChunk::Message { block }), false)
1065                | (Some(AssistantMessageChunk::Thought { block }), true) => {
1066                    block.append(chunk, &language_registry, cx)
1067                }
1068                _ => {
1069                    let block = ContentBlock::new(chunk, &language_registry, cx);
1070                    if is_thought {
1071                        chunks.push(AssistantMessageChunk::Thought { block })
1072                    } else {
1073                        chunks.push(AssistantMessageChunk::Message { block })
1074                    }
1075                }
1076            }
1077        } else {
1078            let block = ContentBlock::new(chunk, &language_registry, cx);
1079            let chunk = if is_thought {
1080                AssistantMessageChunk::Thought { block }
1081            } else {
1082                AssistantMessageChunk::Message { block }
1083            };
1084
1085            self.push_entry(
1086                AgentThreadEntry::AssistantMessage(AssistantMessage {
1087                    chunks: vec![chunk],
1088                }),
1089                cx,
1090            );
1091        }
1092    }
1093
1094    fn push_entry(&mut self, entry: AgentThreadEntry, cx: &mut Context<Self>) {
1095        self.entries.push(entry);
1096        cx.emit(AcpThreadEvent::NewEntry);
1097    }
1098
1099    pub fn can_set_title(&mut self, cx: &mut Context<Self>) -> bool {
1100        self.connection.set_title(&self.session_id, cx).is_some()
1101    }
1102
1103    pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) -> Task<Result<()>> {
1104        if title != self.title {
1105            self.title = title.clone();
1106            cx.emit(AcpThreadEvent::TitleUpdated);
1107            if let Some(set_title) = self.connection.set_title(&self.session_id, cx) {
1108                return set_title.run(title, cx);
1109            }
1110        }
1111        Task::ready(Ok(()))
1112    }
1113
1114    pub fn update_token_usage(&mut self, usage: Option<TokenUsage>, cx: &mut Context<Self>) {
1115        self.token_usage = usage;
1116        cx.emit(AcpThreadEvent::TokenUsageUpdated);
1117    }
1118
1119    pub fn update_retry_status(&mut self, status: RetryStatus, cx: &mut Context<Self>) {
1120        cx.emit(AcpThreadEvent::Retry(status));
1121    }
1122
1123    pub fn update_tool_call(
1124        &mut self,
1125        update: impl Into<ToolCallUpdate>,
1126        cx: &mut Context<Self>,
1127    ) -> Result<()> {
1128        let update = update.into();
1129        let languages = self.project.read(cx).languages().clone();
1130
1131        let ix = self
1132            .index_for_tool_call(update.id())
1133            .context("Tool call not found")?;
1134        let AgentThreadEntry::ToolCall(call) = &mut self.entries[ix] else {
1135            unreachable!()
1136        };
1137
1138        match update {
1139            ToolCallUpdate::UpdateFields(update) => {
1140                let location_updated = update.fields.locations.is_some();
1141                call.update_fields(update.fields, languages, &self.terminals, cx)?;
1142                if location_updated {
1143                    self.resolve_locations(update.id, cx);
1144                }
1145            }
1146            ToolCallUpdate::UpdateDiff(update) => {
1147                call.content.clear();
1148                call.content.push(ToolCallContent::Diff(update.diff));
1149            }
1150            ToolCallUpdate::UpdateTerminal(update) => {
1151                call.content.clear();
1152                call.content
1153                    .push(ToolCallContent::Terminal(update.terminal));
1154            }
1155        }
1156
1157        cx.emit(AcpThreadEvent::EntryUpdated(ix));
1158
1159        Ok(())
1160    }
1161
1162    /// Updates a tool call if id matches an existing entry, otherwise inserts a new one.
1163    pub fn upsert_tool_call(
1164        &mut self,
1165        tool_call: acp::ToolCall,
1166        cx: &mut Context<Self>,
1167    ) -> Result<(), acp::Error> {
1168        let status = tool_call.status.into();
1169        self.upsert_tool_call_inner(tool_call.into(), status, cx)
1170    }
1171
1172    /// Fails if id does not match an existing entry.
1173    pub fn upsert_tool_call_inner(
1174        &mut self,
1175        update: acp::ToolCallUpdate,
1176        status: ToolCallStatus,
1177        cx: &mut Context<Self>,
1178    ) -> Result<(), acp::Error> {
1179        let language_registry = self.project.read(cx).languages().clone();
1180        let id = update.id.clone();
1181
1182        if let Some(ix) = self.index_for_tool_call(&id) {
1183            let AgentThreadEntry::ToolCall(call) = &mut self.entries[ix] else {
1184                unreachable!()
1185            };
1186
1187            call.update_fields(update.fields, language_registry, &self.terminals, cx)?;
1188            call.status = status;
1189
1190            cx.emit(AcpThreadEvent::EntryUpdated(ix));
1191        } else {
1192            let call = ToolCall::from_acp(
1193                update.try_into()?,
1194                status,
1195                language_registry,
1196                &self.terminals,
1197                cx,
1198            )?;
1199            self.push_entry(AgentThreadEntry::ToolCall(call), cx);
1200        };
1201
1202        self.resolve_locations(id, cx);
1203        Ok(())
1204    }
1205
1206    fn index_for_tool_call(&self, id: &acp::ToolCallId) -> Option<usize> {
1207        self.entries
1208            .iter()
1209            .enumerate()
1210            .rev()
1211            .find_map(|(index, entry)| {
1212                if let AgentThreadEntry::ToolCall(tool_call) = entry
1213                    && &tool_call.id == id
1214                {
1215                    Some(index)
1216                } else {
1217                    None
1218                }
1219            })
1220    }
1221
1222    fn tool_call_mut(&mut self, id: &acp::ToolCallId) -> Option<(usize, &mut ToolCall)> {
1223        // The tool call we are looking for is typically the last one, or very close to the end.
1224        // At the moment, it doesn't seem like a hashmap would be a good fit for this use case.
1225        self.entries
1226            .iter_mut()
1227            .enumerate()
1228            .rev()
1229            .find_map(|(index, tool_call)| {
1230                if let AgentThreadEntry::ToolCall(tool_call) = tool_call
1231                    && &tool_call.id == id
1232                {
1233                    Some((index, tool_call))
1234                } else {
1235                    None
1236                }
1237            })
1238    }
1239
1240    pub fn tool_call(&mut self, id: &acp::ToolCallId) -> Option<(usize, &ToolCall)> {
1241        self.entries
1242            .iter()
1243            .enumerate()
1244            .rev()
1245            .find_map(|(index, tool_call)| {
1246                if let AgentThreadEntry::ToolCall(tool_call) = tool_call
1247                    && &tool_call.id == id
1248                {
1249                    Some((index, tool_call))
1250                } else {
1251                    None
1252                }
1253            })
1254    }
1255
1256    pub fn resolve_locations(&mut self, id: acp::ToolCallId, cx: &mut Context<Self>) {
1257        let project = self.project.clone();
1258        let Some((_, tool_call)) = self.tool_call_mut(&id) else {
1259            return;
1260        };
1261        let task = tool_call.resolve_locations(project, cx);
1262        cx.spawn(async move |this, cx| {
1263            let resolved_locations = task.await;
1264            this.update(cx, |this, cx| {
1265                let project = this.project.clone();
1266                let Some((ix, tool_call)) = this.tool_call_mut(&id) else {
1267                    return;
1268                };
1269                if let Some(Some(location)) = resolved_locations.last() {
1270                    project.update(cx, |project, cx| {
1271                        if let Some(agent_location) = project.agent_location() {
1272                            let should_ignore = agent_location.buffer == location.buffer
1273                                && location
1274                                    .buffer
1275                                    .update(cx, |buffer, _| {
1276                                        let snapshot = buffer.snapshot();
1277                                        let old_position =
1278                                            agent_location.position.to_point(&snapshot);
1279                                        let new_position = location.position.to_point(&snapshot);
1280                                        // ignore this so that when we get updates from the edit tool
1281                                        // the position doesn't reset to the startof line
1282                                        old_position.row == new_position.row
1283                                            && old_position.column > new_position.column
1284                                    })
1285                                    .ok()
1286                                    .unwrap_or_default();
1287                            if !should_ignore {
1288                                project.set_agent_location(Some(location.clone()), cx);
1289                            }
1290                        }
1291                    });
1292                }
1293                if tool_call.resolved_locations != resolved_locations {
1294                    tool_call.resolved_locations = resolved_locations;
1295                    cx.emit(AcpThreadEvent::EntryUpdated(ix));
1296                }
1297            })
1298        })
1299        .detach();
1300    }
1301
1302    pub fn request_tool_call_authorization(
1303        &mut self,
1304        tool_call: acp::ToolCallUpdate,
1305        options: Vec<acp::PermissionOption>,
1306        cx: &mut Context<Self>,
1307    ) -> Result<BoxFuture<'static, acp::RequestPermissionOutcome>> {
1308        let (tx, rx) = oneshot::channel();
1309
1310        if AgentSettings::get_global(cx).always_allow_tool_actions {
1311            // Don't use AllowAlways, because then if you were to turn off always_allow_tool_actions,
1312            // some tools would (incorrectly) continue to auto-accept.
1313            if let Some(allow_once_option) = options.iter().find_map(|option| {
1314                if matches!(option.kind, acp::PermissionOptionKind::AllowOnce) {
1315                    Some(option.id.clone())
1316                } else {
1317                    None
1318                }
1319            }) {
1320                self.upsert_tool_call_inner(tool_call, ToolCallStatus::Pending, cx)?;
1321                return Ok(async {
1322                    acp::RequestPermissionOutcome::Selected {
1323                        option_id: allow_once_option,
1324                    }
1325                }
1326                .boxed());
1327            }
1328        }
1329
1330        let status = ToolCallStatus::WaitingForConfirmation {
1331            options,
1332            respond_tx: tx,
1333        };
1334
1335        self.upsert_tool_call_inner(tool_call, status, cx)?;
1336        cx.emit(AcpThreadEvent::ToolAuthorizationRequired);
1337
1338        let fut = async {
1339            match rx.await {
1340                Ok(option) => acp::RequestPermissionOutcome::Selected { option_id: option },
1341                Err(oneshot::Canceled) => acp::RequestPermissionOutcome::Cancelled,
1342            }
1343        }
1344        .boxed();
1345
1346        Ok(fut)
1347    }
1348
1349    pub fn authorize_tool_call(
1350        &mut self,
1351        id: acp::ToolCallId,
1352        option_id: acp::PermissionOptionId,
1353        option_kind: acp::PermissionOptionKind,
1354        cx: &mut Context<Self>,
1355    ) {
1356        let Some((ix, call)) = self.tool_call_mut(&id) else {
1357            return;
1358        };
1359
1360        let new_status = match option_kind {
1361            acp::PermissionOptionKind::RejectOnce | acp::PermissionOptionKind::RejectAlways => {
1362                ToolCallStatus::Rejected
1363            }
1364            acp::PermissionOptionKind::AllowOnce | acp::PermissionOptionKind::AllowAlways => {
1365                ToolCallStatus::InProgress
1366            }
1367        };
1368
1369        let curr_status = mem::replace(&mut call.status, new_status);
1370
1371        if let ToolCallStatus::WaitingForConfirmation { respond_tx, .. } = curr_status {
1372            respond_tx.send(option_id).log_err();
1373        } else if cfg!(debug_assertions) {
1374            panic!("tried to authorize an already authorized tool call");
1375        }
1376
1377        cx.emit(AcpThreadEvent::EntryUpdated(ix));
1378    }
1379
1380    /// Returns true if the last turn is awaiting tool authorization
1381    pub fn waiting_for_tool_confirmation(&self) -> bool {
1382        for entry in self.entries.iter().rev() {
1383            match &entry {
1384                AgentThreadEntry::ToolCall(call) => match call.status {
1385                    ToolCallStatus::WaitingForConfirmation { .. } => return true,
1386                    ToolCallStatus::Pending
1387                    | ToolCallStatus::InProgress
1388                    | ToolCallStatus::Completed
1389                    | ToolCallStatus::Failed
1390                    | ToolCallStatus::Rejected
1391                    | ToolCallStatus::Canceled => continue,
1392                },
1393                AgentThreadEntry::UserMessage(_) | AgentThreadEntry::AssistantMessage(_) => {
1394                    // Reached the beginning of the turn
1395                    return false;
1396                }
1397            }
1398        }
1399        false
1400    }
1401
1402    pub fn plan(&self) -> &Plan {
1403        &self.plan
1404    }
1405
1406    pub fn update_plan(&mut self, request: acp::Plan, cx: &mut Context<Self>) {
1407        let new_entries_len = request.entries.len();
1408        let mut new_entries = request.entries.into_iter();
1409
1410        // Reuse existing markdown to prevent flickering
1411        for (old, new) in self.plan.entries.iter_mut().zip(new_entries.by_ref()) {
1412            let PlanEntry {
1413                content,
1414                priority,
1415                status,
1416            } = old;
1417            content.update(cx, |old, cx| {
1418                old.replace(new.content, cx);
1419            });
1420            *priority = new.priority;
1421            *status = new.status;
1422        }
1423        for new in new_entries {
1424            self.plan.entries.push(PlanEntry::from_acp(new, cx))
1425        }
1426        self.plan.entries.truncate(new_entries_len);
1427
1428        cx.notify();
1429    }
1430
1431    fn clear_completed_plan_entries(&mut self, cx: &mut Context<Self>) {
1432        self.plan
1433            .entries
1434            .retain(|entry| !matches!(entry.status, acp::PlanEntryStatus::Completed));
1435        cx.notify();
1436    }
1437
1438    #[cfg(any(test, feature = "test-support"))]
1439    pub fn send_raw(
1440        &mut self,
1441        message: &str,
1442        cx: &mut Context<Self>,
1443    ) -> BoxFuture<'static, Result<()>> {
1444        self.send(
1445            vec![acp::ContentBlock::Text(acp::TextContent {
1446                text: message.to_string(),
1447                annotations: None,
1448            })],
1449            cx,
1450        )
1451    }
1452
1453    pub fn send(
1454        &mut self,
1455        message: Vec<acp::ContentBlock>,
1456        cx: &mut Context<Self>,
1457    ) -> BoxFuture<'static, Result<()>> {
1458        let block = ContentBlock::new_combined(
1459            message.clone(),
1460            self.project.read(cx).languages().clone(),
1461            cx,
1462        );
1463        let request = acp::PromptRequest {
1464            prompt: message.clone(),
1465            session_id: self.session_id.clone(),
1466        };
1467        let git_store = self.project.read(cx).git_store().clone();
1468
1469        let message_id = if self.connection.truncate(&self.session_id, cx).is_some() {
1470            Some(UserMessageId::new())
1471        } else {
1472            None
1473        };
1474
1475        self.run_turn(cx, async move |this, cx| {
1476            this.update(cx, |this, cx| {
1477                this.push_entry(
1478                    AgentThreadEntry::UserMessage(UserMessage {
1479                        id: message_id.clone(),
1480                        content: block,
1481                        chunks: message,
1482                        checkpoint: None,
1483                    }),
1484                    cx,
1485                );
1486            })
1487            .ok();
1488
1489            let old_checkpoint = git_store
1490                .update(cx, |git, cx| git.checkpoint(cx))?
1491                .await
1492                .context("failed to get old checkpoint")
1493                .log_err();
1494            this.update(cx, |this, cx| {
1495                if let Some((_ix, message)) = this.last_user_message() {
1496                    message.checkpoint = old_checkpoint.map(|git_checkpoint| Checkpoint {
1497                        git_checkpoint,
1498                        show: false,
1499                    });
1500                }
1501                this.connection.prompt(message_id, request, cx)
1502            })?
1503            .await
1504        })
1505    }
1506
1507    pub fn can_resume(&self, cx: &App) -> bool {
1508        self.connection.resume(&self.session_id, cx).is_some()
1509    }
1510
1511    pub fn resume(&mut self, cx: &mut Context<Self>) -> BoxFuture<'static, Result<()>> {
1512        self.run_turn(cx, async move |this, cx| {
1513            this.update(cx, |this, cx| {
1514                this.connection
1515                    .resume(&this.session_id, cx)
1516                    .map(|resume| resume.run(cx))
1517            })?
1518            .context("resuming a session is not supported")?
1519            .await
1520        })
1521    }
1522
1523    fn run_turn(
1524        &mut self,
1525        cx: &mut Context<Self>,
1526        f: impl 'static + AsyncFnOnce(WeakEntity<Self>, &mut AsyncApp) -> Result<acp::PromptResponse>,
1527    ) -> BoxFuture<'static, Result<()>> {
1528        self.clear_completed_plan_entries(cx);
1529
1530        let (tx, rx) = oneshot::channel();
1531        let cancel_task = self.cancel(cx);
1532
1533        self.send_task = Some(cx.spawn(async move |this, cx| {
1534            cancel_task.await;
1535            tx.send(f(this, cx).await).ok();
1536        }));
1537
1538        cx.spawn(async move |this, cx| {
1539            let response = rx.await;
1540
1541            this.update(cx, |this, cx| this.update_last_checkpoint(cx))?
1542                .await?;
1543
1544            this.update(cx, |this, cx| {
1545                this.project
1546                    .update(cx, |project, cx| project.set_agent_location(None, cx));
1547                match response {
1548                    Ok(Err(e)) => {
1549                        this.send_task.take();
1550                        cx.emit(AcpThreadEvent::Error);
1551                        Err(e)
1552                    }
1553                    result => {
1554                        let canceled = matches!(
1555                            result,
1556                            Ok(Ok(acp::PromptResponse {
1557                                stop_reason: acp::StopReason::Cancelled
1558                            }))
1559                        );
1560
1561                        // We only take the task if the current prompt wasn't canceled.
1562                        //
1563                        // This prompt may have been canceled because another one was sent
1564                        // while it was still generating. In these cases, dropping `send_task`
1565                        // would cause the next generation to be canceled.
1566                        if !canceled {
1567                            this.send_task.take();
1568                        }
1569
1570                        // Handle refusal - distinguish between user prompt and tool call refusals
1571                        if let Ok(Ok(acp::PromptResponse {
1572                            stop_reason: acp::StopReason::Refusal,
1573                        })) = result
1574                        {
1575                            if let Some((user_msg_ix, _)) = this.last_user_message() {
1576                                // Check if there's a completed tool call with results after the last user message
1577                                // This indicates the refusal is in response to tool output, not the user's prompt
1578                                let has_completed_tool_call_after_user_msg =
1579                                    this.entries.iter().skip(user_msg_ix + 1).any(|entry| {
1580                                        if let AgentThreadEntry::ToolCall(tool_call) = entry {
1581                                            // Check if the tool call has completed and has output
1582                                            matches!(tool_call.status, ToolCallStatus::Completed)
1583                                                && tool_call.raw_output.is_some()
1584                                        } else {
1585                                            false
1586                                        }
1587                                    });
1588
1589                                if has_completed_tool_call_after_user_msg {
1590                                    // Refusal is due to tool output - don't truncate, just notify
1591                                    // The model refused based on what the tool returned
1592                                    cx.emit(AcpThreadEvent::Refusal);
1593                                } else {
1594                                    // User prompt was refused - truncate back to before the user message
1595                                    let range = user_msg_ix..this.entries.len();
1596                                    if range.start < range.end {
1597                                        this.entries.truncate(user_msg_ix);
1598                                        cx.emit(AcpThreadEvent::EntriesRemoved(range));
1599                                    }
1600                                    cx.emit(AcpThreadEvent::Refusal);
1601                                }
1602                            } else {
1603                                // No user message found, treat as general refusal
1604                                cx.emit(AcpThreadEvent::Refusal);
1605                            }
1606                        }
1607
1608                        cx.emit(AcpThreadEvent::Stopped);
1609                        Ok(())
1610                    }
1611                }
1612            })?
1613        })
1614        .boxed()
1615    }
1616
1617    pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
1618        let Some(send_task) = self.send_task.take() else {
1619            return Task::ready(());
1620        };
1621
1622        for entry in self.entries.iter_mut() {
1623            if let AgentThreadEntry::ToolCall(call) = entry {
1624                let cancel = matches!(
1625                    call.status,
1626                    ToolCallStatus::Pending
1627                        | ToolCallStatus::WaitingForConfirmation { .. }
1628                        | ToolCallStatus::InProgress
1629                );
1630
1631                if cancel {
1632                    call.status = ToolCallStatus::Canceled;
1633                }
1634            }
1635        }
1636
1637        self.connection.cancel(&self.session_id, cx);
1638
1639        // Wait for the send task to complete
1640        cx.foreground_executor().spawn(send_task)
1641    }
1642
1643    /// Rewinds this thread to before the entry at `index`, removing it and all
1644    /// subsequent entries while reverting any changes made from that point.
1645    pub fn rewind(&mut self, id: UserMessageId, cx: &mut Context<Self>) -> Task<Result<()>> {
1646        let Some(truncate) = self.connection.truncate(&self.session_id, cx) else {
1647            return Task::ready(Err(anyhow!("not supported")));
1648        };
1649        let Some(message) = self.user_message(&id) else {
1650            return Task::ready(Err(anyhow!("message not found")));
1651        };
1652
1653        let checkpoint = message
1654            .checkpoint
1655            .as_ref()
1656            .map(|c| c.git_checkpoint.clone());
1657
1658        let git_store = self.project.read(cx).git_store().clone();
1659        cx.spawn(async move |this, cx| {
1660            if let Some(checkpoint) = checkpoint {
1661                git_store
1662                    .update(cx, |git, cx| git.restore_checkpoint(checkpoint, cx))?
1663                    .await?;
1664            }
1665
1666            cx.update(|cx| truncate.run(id.clone(), cx))?.await?;
1667            this.update(cx, |this, cx| {
1668                if let Some((ix, _)) = this.user_message_mut(&id) {
1669                    let range = ix..this.entries.len();
1670                    this.entries.truncate(ix);
1671                    cx.emit(AcpThreadEvent::EntriesRemoved(range));
1672                }
1673            })
1674        })
1675    }
1676
1677    fn update_last_checkpoint(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
1678        let git_store = self.project.read(cx).git_store().clone();
1679
1680        let old_checkpoint = if let Some((_, message)) = self.last_user_message() {
1681            if let Some(checkpoint) = message.checkpoint.as_ref() {
1682                checkpoint.git_checkpoint.clone()
1683            } else {
1684                return Task::ready(Ok(()));
1685            }
1686        } else {
1687            return Task::ready(Ok(()));
1688        };
1689
1690        let new_checkpoint = git_store.update(cx, |git, cx| git.checkpoint(cx));
1691        cx.spawn(async move |this, cx| {
1692            let new_checkpoint = new_checkpoint
1693                .await
1694                .context("failed to get new checkpoint")
1695                .log_err();
1696            if let Some(new_checkpoint) = new_checkpoint {
1697                let equal = git_store
1698                    .update(cx, |git, cx| {
1699                        git.compare_checkpoints(old_checkpoint.clone(), new_checkpoint, cx)
1700                    })?
1701                    .await
1702                    .unwrap_or(true);
1703                this.update(cx, |this, cx| {
1704                    let (ix, message) = this.last_user_message().context("no user message")?;
1705                    let checkpoint = message.checkpoint.as_mut().context("no checkpoint")?;
1706                    checkpoint.show = !equal;
1707                    cx.emit(AcpThreadEvent::EntryUpdated(ix));
1708                    anyhow::Ok(())
1709                })??;
1710            }
1711
1712            Ok(())
1713        })
1714    }
1715
1716    fn last_user_message(&mut self) -> Option<(usize, &mut UserMessage)> {
1717        self.entries
1718            .iter_mut()
1719            .enumerate()
1720            .rev()
1721            .find_map(|(ix, entry)| {
1722                if let AgentThreadEntry::UserMessage(message) = entry {
1723                    Some((ix, message))
1724                } else {
1725                    None
1726                }
1727            })
1728    }
1729
1730    fn user_message(&self, id: &UserMessageId) -> Option<&UserMessage> {
1731        self.entries.iter().find_map(|entry| {
1732            if let AgentThreadEntry::UserMessage(message) = entry {
1733                if message.id.as_ref() == Some(id) {
1734                    Some(message)
1735                } else {
1736                    None
1737                }
1738            } else {
1739                None
1740            }
1741        })
1742    }
1743
1744    fn user_message_mut(&mut self, id: &UserMessageId) -> Option<(usize, &mut UserMessage)> {
1745        self.entries.iter_mut().enumerate().find_map(|(ix, entry)| {
1746            if let AgentThreadEntry::UserMessage(message) = entry {
1747                if message.id.as_ref() == Some(id) {
1748                    Some((ix, message))
1749                } else {
1750                    None
1751                }
1752            } else {
1753                None
1754            }
1755        })
1756    }
1757
1758    pub fn read_text_file(
1759        &self,
1760        path: PathBuf,
1761        line: Option<u32>,
1762        limit: Option<u32>,
1763        reuse_shared_snapshot: bool,
1764        cx: &mut Context<Self>,
1765    ) -> Task<Result<String>> {
1766        let project = self.project.clone();
1767        let action_log = self.action_log.clone();
1768        cx.spawn(async move |this, cx| {
1769            let load = project.update(cx, |project, cx| {
1770                let path = project
1771                    .project_path_for_absolute_path(&path, cx)
1772                    .context("invalid path")?;
1773                anyhow::Ok(project.open_buffer(path, cx))
1774            });
1775            let buffer = load??.await?;
1776
1777            let snapshot = if reuse_shared_snapshot {
1778                this.read_with(cx, |this, _| {
1779                    this.shared_buffers.get(&buffer.clone()).cloned()
1780                })
1781                .log_err()
1782                .flatten()
1783            } else {
1784                None
1785            };
1786
1787            let snapshot = if let Some(snapshot) = snapshot {
1788                snapshot
1789            } else {
1790                action_log.update(cx, |action_log, cx| {
1791                    action_log.buffer_read(buffer.clone(), cx);
1792                })?;
1793                project.update(cx, |project, cx| {
1794                    let position = buffer
1795                        .read(cx)
1796                        .snapshot()
1797                        .anchor_before(Point::new(line.unwrap_or_default(), 0));
1798                    project.set_agent_location(
1799                        Some(AgentLocation {
1800                            buffer: buffer.downgrade(),
1801                            position,
1802                        }),
1803                        cx,
1804                    );
1805                })?;
1806
1807                buffer.update(cx, |buffer, _| buffer.snapshot())?
1808            };
1809
1810            this.update(cx, |this, _| {
1811                let text = snapshot.text();
1812                this.shared_buffers.insert(buffer.clone(), snapshot);
1813                if line.is_none() && limit.is_none() {
1814                    return Ok(text);
1815                }
1816                let limit = limit.unwrap_or(u32::MAX) as usize;
1817                let Some(line) = line else {
1818                    return Ok(text.lines().take(limit).collect::<String>());
1819                };
1820
1821                let count = text.lines().count();
1822                if count < line as usize {
1823                    anyhow::bail!("There are only {} lines", count);
1824                }
1825                Ok(text
1826                    .lines()
1827                    .skip(line as usize + 1)
1828                    .take(limit)
1829                    .collect::<String>())
1830            })?
1831        })
1832    }
1833
1834    pub fn write_text_file(
1835        &self,
1836        path: PathBuf,
1837        content: String,
1838        cx: &mut Context<Self>,
1839    ) -> Task<Result<()>> {
1840        let project = self.project.clone();
1841        let action_log = self.action_log.clone();
1842        cx.spawn(async move |this, cx| {
1843            let load = project.update(cx, |project, cx| {
1844                let path = project
1845                    .project_path_for_absolute_path(&path, cx)
1846                    .context("invalid path")?;
1847                anyhow::Ok(project.open_buffer(path, cx))
1848            });
1849            let buffer = load??.await?;
1850            let snapshot = this.update(cx, |this, cx| {
1851                this.shared_buffers
1852                    .get(&buffer)
1853                    .cloned()
1854                    .unwrap_or_else(|| buffer.read(cx).snapshot())
1855            })?;
1856            let edits = cx
1857                .background_executor()
1858                .spawn(async move {
1859                    let old_text = snapshot.text();
1860                    text_diff(old_text.as_str(), &content)
1861                        .into_iter()
1862                        .map(|(range, replacement)| {
1863                            (
1864                                snapshot.anchor_after(range.start)
1865                                    ..snapshot.anchor_before(range.end),
1866                                replacement,
1867                            )
1868                        })
1869                        .collect::<Vec<_>>()
1870                })
1871                .await;
1872
1873            project.update(cx, |project, cx| {
1874                project.set_agent_location(
1875                    Some(AgentLocation {
1876                        buffer: buffer.downgrade(),
1877                        position: edits
1878                            .last()
1879                            .map(|(range, _)| range.end)
1880                            .unwrap_or(Anchor::MIN),
1881                    }),
1882                    cx,
1883                );
1884            })?;
1885
1886            let format_on_save = cx.update(|cx| {
1887                action_log.update(cx, |action_log, cx| {
1888                    action_log.buffer_read(buffer.clone(), cx);
1889                });
1890
1891                let format_on_save = buffer.update(cx, |buffer, cx| {
1892                    buffer.edit(edits, None, cx);
1893
1894                    let settings = language::language_settings::language_settings(
1895                        buffer.language().map(|l| l.name()),
1896                        buffer.file(),
1897                        cx,
1898                    );
1899
1900                    settings.format_on_save != FormatOnSave::Off
1901                });
1902                action_log.update(cx, |action_log, cx| {
1903                    action_log.buffer_edited(buffer.clone(), cx);
1904                });
1905                format_on_save
1906            })?;
1907
1908            if format_on_save {
1909                let format_task = project.update(cx, |project, cx| {
1910                    project.format(
1911                        HashSet::from_iter([buffer.clone()]),
1912                        LspFormatTarget::Buffers,
1913                        false,
1914                        FormatTrigger::Save,
1915                        cx,
1916                    )
1917                })?;
1918                format_task.await.log_err();
1919
1920                action_log.update(cx, |action_log, cx| {
1921                    action_log.buffer_edited(buffer.clone(), cx);
1922                })?;
1923            }
1924
1925            project
1926                .update(cx, |project, cx| project.save_buffer(buffer, cx))?
1927                .await
1928        })
1929    }
1930
1931    pub fn create_terminal(
1932        &self,
1933        mut command: String,
1934        args: Vec<String>,
1935        extra_env: Vec<acp::EnvVariable>,
1936        cwd: Option<PathBuf>,
1937        output_byte_limit: Option<u64>,
1938        cx: &mut Context<Self>,
1939    ) -> Task<Result<Entity<Terminal>>> {
1940        for arg in args {
1941            command.push(' ');
1942            command.push_str(&arg);
1943        }
1944
1945        let shell_command = if cfg!(windows) {
1946            format!("$null | & {{{}}}", command.replace("\"", "'"))
1947        } else if let Some(cwd) = cwd.as_ref().and_then(|cwd| cwd.as_os_str().to_str()) {
1948            // Make sure once we're *inside* the shell, we cd into `cwd`
1949            format!("(cd {cwd}; {}) </dev/null", command)
1950        } else {
1951            format!("({}) </dev/null", command)
1952        };
1953        let args = vec!["-c".into(), shell_command];
1954
1955        let env = match &cwd {
1956            Some(dir) => self.project.update(cx, |project, cx| {
1957                project.directory_environment(dir.as_path().into(), cx)
1958            }),
1959            None => Task::ready(None).shared(),
1960        };
1961
1962        let env = cx.spawn(async move |_, _| {
1963            let mut env = env.await.unwrap_or_default();
1964            if cfg!(unix) {
1965                env.insert("PAGER".into(), "cat".into());
1966            }
1967            for var in extra_env {
1968                env.insert(var.name, var.value);
1969            }
1970            env
1971        });
1972
1973        let project = self.project.clone();
1974        let language_registry = project.read(cx).languages().clone();
1975        let determine_shell = self.determine_shell.clone();
1976
1977        let terminal_id = acp::TerminalId(Uuid::new_v4().to_string().into());
1978        let terminal_task = cx.spawn({
1979            let terminal_id = terminal_id.clone();
1980            async move |_this, cx| {
1981                let program = determine_shell.await;
1982                let env = env.await;
1983                let terminal = project
1984                    .update(cx, |project, cx| {
1985                        project.create_terminal_task(
1986                            task::SpawnInTerminal {
1987                                command: Some(program),
1988                                args,
1989                                cwd: cwd.clone(),
1990                                env,
1991                                ..Default::default()
1992                            },
1993                            cx,
1994                        )
1995                    })?
1996                    .await?;
1997
1998                cx.new(|cx| {
1999                    Terminal::new(
2000                        terminal_id,
2001                        command,
2002                        cwd,
2003                        output_byte_limit.map(|l| l as usize),
2004                        terminal,
2005                        language_registry,
2006                        cx,
2007                    )
2008                })
2009            }
2010        });
2011
2012        cx.spawn(async move |this, cx| {
2013            let terminal = terminal_task.await?;
2014            this.update(cx, |this, _cx| {
2015                this.terminals.insert(terminal_id, terminal.clone());
2016                terminal
2017            })
2018        })
2019    }
2020
2021    pub fn kill_terminal(
2022        &mut self,
2023        terminal_id: acp::TerminalId,
2024        cx: &mut Context<Self>,
2025    ) -> Result<()> {
2026        self.terminals
2027            .get(&terminal_id)
2028            .context("Terminal not found")?
2029            .update(cx, |terminal, cx| {
2030                terminal.kill(cx);
2031            });
2032
2033        Ok(())
2034    }
2035
2036    pub fn release_terminal(
2037        &mut self,
2038        terminal_id: acp::TerminalId,
2039        cx: &mut Context<Self>,
2040    ) -> Result<()> {
2041        self.terminals
2042            .remove(&terminal_id)
2043            .context("Terminal not found")?
2044            .update(cx, |terminal, cx| {
2045                terminal.kill(cx);
2046            });
2047
2048        Ok(())
2049    }
2050
2051    pub fn terminal(&self, terminal_id: acp::TerminalId) -> Result<Entity<Terminal>> {
2052        self.terminals
2053            .get(&terminal_id)
2054            .context("Terminal not found")
2055            .cloned()
2056    }
2057
2058    pub fn to_markdown(&self, cx: &App) -> String {
2059        self.entries.iter().map(|e| e.to_markdown(cx)).collect()
2060    }
2061
2062    pub fn emit_load_error(&mut self, error: LoadError, cx: &mut Context<Self>) {
2063        cx.emit(AcpThreadEvent::LoadError(error));
2064    }
2065}
2066
2067fn markdown_for_raw_output(
2068    raw_output: &serde_json::Value,
2069    language_registry: &Arc<LanguageRegistry>,
2070    cx: &mut App,
2071) -> Option<Entity<Markdown>> {
2072    match raw_output {
2073        serde_json::Value::Null => None,
2074        serde_json::Value::Bool(value) => Some(cx.new(|cx| {
2075            Markdown::new(
2076                value.to_string().into(),
2077                Some(language_registry.clone()),
2078                None,
2079                cx,
2080            )
2081        })),
2082        serde_json::Value::Number(value) => Some(cx.new(|cx| {
2083            Markdown::new(
2084                value.to_string().into(),
2085                Some(language_registry.clone()),
2086                None,
2087                cx,
2088            )
2089        })),
2090        serde_json::Value::String(value) => Some(cx.new(|cx| {
2091            Markdown::new(
2092                value.clone().into(),
2093                Some(language_registry.clone()),
2094                None,
2095                cx,
2096            )
2097        })),
2098        value => Some(cx.new(|cx| {
2099            Markdown::new(
2100                format!("```json\n{}\n```", value).into(),
2101                Some(language_registry.clone()),
2102                None,
2103                cx,
2104            )
2105        })),
2106    }
2107}
2108
2109#[cfg(test)]
2110mod tests {
2111    use super::*;
2112    use anyhow::anyhow;
2113    use futures::{channel::mpsc, future::LocalBoxFuture, select};
2114    use gpui::{App, AsyncApp, TestAppContext, WeakEntity};
2115    use indoc::indoc;
2116    use project::{FakeFs, Fs};
2117    use rand::{distr, prelude::*};
2118    use serde_json::json;
2119    use settings::SettingsStore;
2120    use smol::stream::StreamExt as _;
2121    use std::{
2122        any::Any,
2123        cell::RefCell,
2124        path::Path,
2125        rc::Rc,
2126        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
2127        time::Duration,
2128    };
2129    use util::path;
2130
2131    fn init_test(cx: &mut TestAppContext) {
2132        env_logger::try_init().ok();
2133        cx.update(|cx| {
2134            let settings_store = SettingsStore::test(cx);
2135            cx.set_global(settings_store);
2136            Project::init_settings(cx);
2137            language::init(cx);
2138        });
2139    }
2140
2141    #[gpui::test]
2142    async fn test_push_user_content_block(cx: &mut gpui::TestAppContext) {
2143        init_test(cx);
2144
2145        let fs = FakeFs::new(cx.executor());
2146        let project = Project::test(fs, [], cx).await;
2147        let connection = Rc::new(FakeAgentConnection::new());
2148        let thread = cx
2149            .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
2150            .await
2151            .unwrap();
2152
2153        // Test creating a new user message
2154        thread.update(cx, |thread, cx| {
2155            thread.push_user_content_block(
2156                None,
2157                acp::ContentBlock::Text(acp::TextContent {
2158                    annotations: None,
2159                    text: "Hello, ".to_string(),
2160                }),
2161                cx,
2162            );
2163        });
2164
2165        thread.update(cx, |thread, cx| {
2166            assert_eq!(thread.entries.len(), 1);
2167            if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
2168                assert_eq!(user_msg.id, None);
2169                assert_eq!(user_msg.content.to_markdown(cx), "Hello, ");
2170            } else {
2171                panic!("Expected UserMessage");
2172            }
2173        });
2174
2175        // Test appending to existing user message
2176        let message_1_id = UserMessageId::new();
2177        thread.update(cx, |thread, cx| {
2178            thread.push_user_content_block(
2179                Some(message_1_id.clone()),
2180                acp::ContentBlock::Text(acp::TextContent {
2181                    annotations: None,
2182                    text: "world!".to_string(),
2183                }),
2184                cx,
2185            );
2186        });
2187
2188        thread.update(cx, |thread, cx| {
2189            assert_eq!(thread.entries.len(), 1);
2190            if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
2191                assert_eq!(user_msg.id, Some(message_1_id));
2192                assert_eq!(user_msg.content.to_markdown(cx), "Hello, world!");
2193            } else {
2194                panic!("Expected UserMessage");
2195            }
2196        });
2197
2198        // Test creating new user message after assistant message
2199        thread.update(cx, |thread, cx| {
2200            thread.push_assistant_content_block(
2201                acp::ContentBlock::Text(acp::TextContent {
2202                    annotations: None,
2203                    text: "Assistant response".to_string(),
2204                }),
2205                false,
2206                cx,
2207            );
2208        });
2209
2210        let message_2_id = UserMessageId::new();
2211        thread.update(cx, |thread, cx| {
2212            thread.push_user_content_block(
2213                Some(message_2_id.clone()),
2214                acp::ContentBlock::Text(acp::TextContent {
2215                    annotations: None,
2216                    text: "New user message".to_string(),
2217                }),
2218                cx,
2219            );
2220        });
2221
2222        thread.update(cx, |thread, cx| {
2223            assert_eq!(thread.entries.len(), 3);
2224            if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[2] {
2225                assert_eq!(user_msg.id, Some(message_2_id));
2226                assert_eq!(user_msg.content.to_markdown(cx), "New user message");
2227            } else {
2228                panic!("Expected UserMessage at index 2");
2229            }
2230        });
2231    }
2232
2233    #[gpui::test]
2234    async fn test_thinking_concatenation(cx: &mut gpui::TestAppContext) {
2235        init_test(cx);
2236
2237        let fs = FakeFs::new(cx.executor());
2238        let project = Project::test(fs, [], cx).await;
2239        let connection = Rc::new(FakeAgentConnection::new().on_user_message(
2240            |_, thread, mut cx| {
2241                async move {
2242                    thread.update(&mut cx, |thread, cx| {
2243                        thread
2244                            .handle_session_update(
2245                                acp::SessionUpdate::AgentThoughtChunk {
2246                                    content: "Thinking ".into(),
2247                                },
2248                                cx,
2249                            )
2250                            .unwrap();
2251                        thread
2252                            .handle_session_update(
2253                                acp::SessionUpdate::AgentThoughtChunk {
2254                                    content: "hard!".into(),
2255                                },
2256                                cx,
2257                            )
2258                            .unwrap();
2259                    })?;
2260                    Ok(acp::PromptResponse {
2261                        stop_reason: acp::StopReason::EndTurn,
2262                    })
2263                }
2264                .boxed_local()
2265            },
2266        ));
2267
2268        let thread = cx
2269            .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
2270            .await
2271            .unwrap();
2272
2273        thread
2274            .update(cx, |thread, cx| thread.send_raw("Hello from Zed!", cx))
2275            .await
2276            .unwrap();
2277
2278        let output = thread.read_with(cx, |thread, cx| thread.to_markdown(cx));
2279        assert_eq!(
2280            output,
2281            indoc! {r#"
2282            ## User
2283
2284            Hello from Zed!
2285
2286            ## Assistant
2287
2288            <thinking>
2289            Thinking hard!
2290            </thinking>
2291
2292            "#}
2293        );
2294    }
2295
2296    #[gpui::test]
2297    async fn test_edits_concurrently_to_user(cx: &mut TestAppContext) {
2298        init_test(cx);
2299
2300        let fs = FakeFs::new(cx.executor());
2301        fs.insert_tree(path!("/tmp"), json!({"foo": "one\ntwo\nthree\n"}))
2302            .await;
2303        let project = Project::test(fs.clone(), [], cx).await;
2304        let (read_file_tx, read_file_rx) = oneshot::channel::<()>();
2305        let read_file_tx = Rc::new(RefCell::new(Some(read_file_tx)));
2306        let connection = Rc::new(FakeAgentConnection::new().on_user_message(
2307            move |_, thread, mut cx| {
2308                let read_file_tx = read_file_tx.clone();
2309                async move {
2310                    let content = thread
2311                        .update(&mut cx, |thread, cx| {
2312                            thread.read_text_file(path!("/tmp/foo").into(), None, None, false, cx)
2313                        })
2314                        .unwrap()
2315                        .await
2316                        .unwrap();
2317                    assert_eq!(content, "one\ntwo\nthree\n");
2318                    read_file_tx.take().unwrap().send(()).unwrap();
2319                    thread
2320                        .update(&mut cx, |thread, cx| {
2321                            thread.write_text_file(
2322                                path!("/tmp/foo").into(),
2323                                "one\ntwo\nthree\nfour\nfive\n".to_string(),
2324                                cx,
2325                            )
2326                        })
2327                        .unwrap()
2328                        .await
2329                        .unwrap();
2330                    Ok(acp::PromptResponse {
2331                        stop_reason: acp::StopReason::EndTurn,
2332                    })
2333                }
2334                .boxed_local()
2335            },
2336        ));
2337
2338        let (worktree, pathbuf) = project
2339            .update(cx, |project, cx| {
2340                project.find_or_create_worktree(path!("/tmp/foo"), true, cx)
2341            })
2342            .await
2343            .unwrap();
2344        let buffer = project
2345            .update(cx, |project, cx| {
2346                project.open_buffer((worktree.read(cx).id(), pathbuf), cx)
2347            })
2348            .await
2349            .unwrap();
2350
2351        let thread = cx
2352            .update(|cx| connection.new_thread(project, Path::new(path!("/tmp")), cx))
2353            .await
2354            .unwrap();
2355
2356        let request = thread.update(cx, |thread, cx| {
2357            thread.send_raw("Extend the count in /tmp/foo", cx)
2358        });
2359        read_file_rx.await.ok();
2360        buffer.update(cx, |buffer, cx| {
2361            buffer.edit([(0..0, "zero\n".to_string())], None, cx);
2362        });
2363        cx.run_until_parked();
2364        assert_eq!(
2365            buffer.read_with(cx, |buffer, _| buffer.text()),
2366            "zero\none\ntwo\nthree\nfour\nfive\n"
2367        );
2368        assert_eq!(
2369            String::from_utf8(fs.read_file_sync(path!("/tmp/foo")).unwrap()).unwrap(),
2370            "zero\none\ntwo\nthree\nfour\nfive\n"
2371        );
2372        request.await.unwrap();
2373    }
2374
2375    #[gpui::test]
2376    async fn test_succeeding_canceled_toolcall(cx: &mut TestAppContext) {
2377        init_test(cx);
2378
2379        let fs = FakeFs::new(cx.executor());
2380        let project = Project::test(fs, [], cx).await;
2381        let id = acp::ToolCallId("test".into());
2382
2383        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
2384            let id = id.clone();
2385            move |_, thread, mut cx| {
2386                let id = id.clone();
2387                async move {
2388                    thread
2389                        .update(&mut cx, |thread, cx| {
2390                            thread.handle_session_update(
2391                                acp::SessionUpdate::ToolCall(acp::ToolCall {
2392                                    id: id.clone(),
2393                                    title: "Label".into(),
2394                                    kind: acp::ToolKind::Fetch,
2395                                    status: acp::ToolCallStatus::InProgress,
2396                                    content: vec![],
2397                                    locations: vec![],
2398                                    raw_input: None,
2399                                    raw_output: None,
2400                                }),
2401                                cx,
2402                            )
2403                        })
2404                        .unwrap()
2405                        .unwrap();
2406                    Ok(acp::PromptResponse {
2407                        stop_reason: acp::StopReason::EndTurn,
2408                    })
2409                }
2410                .boxed_local()
2411            }
2412        }));
2413
2414        let thread = cx
2415            .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
2416            .await
2417            .unwrap();
2418
2419        let request = thread.update(cx, |thread, cx| {
2420            thread.send_raw("Fetch https://example.com", cx)
2421        });
2422
2423        run_until_first_tool_call(&thread, cx).await;
2424
2425        thread.read_with(cx, |thread, _| {
2426            assert!(matches!(
2427                thread.entries[1],
2428                AgentThreadEntry::ToolCall(ToolCall {
2429                    status: ToolCallStatus::InProgress,
2430                    ..
2431                })
2432            ));
2433        });
2434
2435        thread.update(cx, |thread, cx| thread.cancel(cx)).await;
2436
2437        thread.read_with(cx, |thread, _| {
2438            assert!(matches!(
2439                &thread.entries[1],
2440                AgentThreadEntry::ToolCall(ToolCall {
2441                    status: ToolCallStatus::Canceled,
2442                    ..
2443                })
2444            ));
2445        });
2446
2447        thread
2448            .update(cx, |thread, cx| {
2449                thread.handle_session_update(
2450                    acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate {
2451                        id,
2452                        fields: acp::ToolCallUpdateFields {
2453                            status: Some(acp::ToolCallStatus::Completed),
2454                            ..Default::default()
2455                        },
2456                    }),
2457                    cx,
2458                )
2459            })
2460            .unwrap();
2461
2462        request.await.unwrap();
2463
2464        thread.read_with(cx, |thread, _| {
2465            assert!(matches!(
2466                thread.entries[1],
2467                AgentThreadEntry::ToolCall(ToolCall {
2468                    status: ToolCallStatus::Completed,
2469                    ..
2470                })
2471            ));
2472        });
2473    }
2474
2475    #[gpui::test]
2476    async fn test_no_pending_edits_if_tool_calls_are_completed(cx: &mut TestAppContext) {
2477        init_test(cx);
2478        let fs = FakeFs::new(cx.background_executor.clone());
2479        fs.insert_tree(path!("/test"), json!({})).await;
2480        let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
2481
2482        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
2483            move |_, thread, mut cx| {
2484                async move {
2485                    thread
2486                        .update(&mut cx, |thread, cx| {
2487                            thread.handle_session_update(
2488                                acp::SessionUpdate::ToolCall(acp::ToolCall {
2489                                    id: acp::ToolCallId("test".into()),
2490                                    title: "Label".into(),
2491                                    kind: acp::ToolKind::Edit,
2492                                    status: acp::ToolCallStatus::Completed,
2493                                    content: vec![acp::ToolCallContent::Diff {
2494                                        diff: acp::Diff {
2495                                            path: "/test/test.txt".into(),
2496                                            old_text: None,
2497                                            new_text: "foo".into(),
2498                                        },
2499                                    }],
2500                                    locations: vec![],
2501                                    raw_input: None,
2502                                    raw_output: None,
2503                                }),
2504                                cx,
2505                            )
2506                        })
2507                        .unwrap()
2508                        .unwrap();
2509                    Ok(acp::PromptResponse {
2510                        stop_reason: acp::StopReason::EndTurn,
2511                    })
2512                }
2513                .boxed_local()
2514            }
2515        }));
2516
2517        let thread = cx
2518            .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
2519            .await
2520            .unwrap();
2521
2522        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["Hi".into()], cx)))
2523            .await
2524            .unwrap();
2525
2526        assert!(cx.read(|cx| !thread.read(cx).has_pending_edit_tool_calls()));
2527    }
2528
2529    #[gpui::test(iterations = 10)]
2530    async fn test_checkpoints(cx: &mut TestAppContext) {
2531        init_test(cx);
2532        let fs = FakeFs::new(cx.background_executor.clone());
2533        fs.insert_tree(
2534            path!("/test"),
2535            json!({
2536                ".git": {}
2537            }),
2538        )
2539        .await;
2540        let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
2541
2542        let simulate_changes = Arc::new(AtomicBool::new(true));
2543        let next_filename = Arc::new(AtomicUsize::new(0));
2544        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
2545            let simulate_changes = simulate_changes.clone();
2546            let next_filename = next_filename.clone();
2547            let fs = fs.clone();
2548            move |request, thread, mut cx| {
2549                let fs = fs.clone();
2550                let simulate_changes = simulate_changes.clone();
2551                let next_filename = next_filename.clone();
2552                async move {
2553                    if simulate_changes.load(SeqCst) {
2554                        let filename = format!("/test/file-{}", next_filename.fetch_add(1, SeqCst));
2555                        fs.write(Path::new(&filename), b"").await?;
2556                    }
2557
2558                    let acp::ContentBlock::Text(content) = &request.prompt[0] else {
2559                        panic!("expected text content block");
2560                    };
2561                    thread.update(&mut cx, |thread, cx| {
2562                        thread
2563                            .handle_session_update(
2564                                acp::SessionUpdate::AgentMessageChunk {
2565                                    content: content.text.to_uppercase().into(),
2566                                },
2567                                cx,
2568                            )
2569                            .unwrap();
2570                    })?;
2571                    Ok(acp::PromptResponse {
2572                        stop_reason: acp::StopReason::EndTurn,
2573                    })
2574                }
2575                .boxed_local()
2576            }
2577        }));
2578        let thread = cx
2579            .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
2580            .await
2581            .unwrap();
2582
2583        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["Lorem".into()], cx)))
2584            .await
2585            .unwrap();
2586        thread.read_with(cx, |thread, cx| {
2587            assert_eq!(
2588                thread.to_markdown(cx),
2589                indoc! {"
2590                    ## User (checkpoint)
2591
2592                    Lorem
2593
2594                    ## Assistant
2595
2596                    LOREM
2597
2598                "}
2599            );
2600        });
2601        assert_eq!(fs.files(), vec![Path::new(path!("/test/file-0"))]);
2602
2603        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["ipsum".into()], cx)))
2604            .await
2605            .unwrap();
2606        thread.read_with(cx, |thread, cx| {
2607            assert_eq!(
2608                thread.to_markdown(cx),
2609                indoc! {"
2610                    ## User (checkpoint)
2611
2612                    Lorem
2613
2614                    ## Assistant
2615
2616                    LOREM
2617
2618                    ## User (checkpoint)
2619
2620                    ipsum
2621
2622                    ## Assistant
2623
2624                    IPSUM
2625
2626                "}
2627            );
2628        });
2629        assert_eq!(
2630            fs.files(),
2631            vec![
2632                Path::new(path!("/test/file-0")),
2633                Path::new(path!("/test/file-1"))
2634            ]
2635        );
2636
2637        // Checkpoint isn't stored when there are no changes.
2638        simulate_changes.store(false, SeqCst);
2639        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["dolor".into()], cx)))
2640            .await
2641            .unwrap();
2642        thread.read_with(cx, |thread, cx| {
2643            assert_eq!(
2644                thread.to_markdown(cx),
2645                indoc! {"
2646                    ## User (checkpoint)
2647
2648                    Lorem
2649
2650                    ## Assistant
2651
2652                    LOREM
2653
2654                    ## User (checkpoint)
2655
2656                    ipsum
2657
2658                    ## Assistant
2659
2660                    IPSUM
2661
2662                    ## User
2663
2664                    dolor
2665
2666                    ## Assistant
2667
2668                    DOLOR
2669
2670                "}
2671            );
2672        });
2673        assert_eq!(
2674            fs.files(),
2675            vec![
2676                Path::new(path!("/test/file-0")),
2677                Path::new(path!("/test/file-1"))
2678            ]
2679        );
2680
2681        // Rewinding the conversation truncates the history and restores the checkpoint.
2682        thread
2683            .update(cx, |thread, cx| {
2684                let AgentThreadEntry::UserMessage(message) = &thread.entries[2] else {
2685                    panic!("unexpected entries {:?}", thread.entries)
2686                };
2687                thread.rewind(message.id.clone().unwrap(), cx)
2688            })
2689            .await
2690            .unwrap();
2691        thread.read_with(cx, |thread, cx| {
2692            assert_eq!(
2693                thread.to_markdown(cx),
2694                indoc! {"
2695                    ## User (checkpoint)
2696
2697                    Lorem
2698
2699                    ## Assistant
2700
2701                    LOREM
2702
2703                "}
2704            );
2705        });
2706        assert_eq!(fs.files(), vec![Path::new(path!("/test/file-0"))]);
2707    }
2708
2709    #[gpui::test]
2710    async fn test_tool_result_refusal(cx: &mut TestAppContext) {
2711        use std::sync::atomic::AtomicUsize;
2712        init_test(cx);
2713
2714        let fs = FakeFs::new(cx.executor());
2715        let project = Project::test(fs, None, cx).await;
2716
2717        // Create a connection that simulates refusal after tool result
2718        let prompt_count = Arc::new(AtomicUsize::new(0));
2719        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
2720            let prompt_count = prompt_count.clone();
2721            move |_request, thread, mut cx| {
2722                let count = prompt_count.fetch_add(1, SeqCst);
2723                async move {
2724                    if count == 0 {
2725                        // First prompt: Generate a tool call with result
2726                        thread.update(&mut cx, |thread, cx| {
2727                            thread
2728                                .handle_session_update(
2729                                    acp::SessionUpdate::ToolCall(acp::ToolCall {
2730                                        id: acp::ToolCallId("tool1".into()),
2731                                        title: "Test Tool".into(),
2732                                        kind: acp::ToolKind::Fetch,
2733                                        status: acp::ToolCallStatus::Completed,
2734                                        content: vec![],
2735                                        locations: vec![],
2736                                        raw_input: Some(serde_json::json!({"query": "test"})),
2737                                        raw_output: Some(
2738                                            serde_json::json!({"result": "inappropriate content"}),
2739                                        ),
2740                                    }),
2741                                    cx,
2742                                )
2743                                .unwrap();
2744                        })?;
2745
2746                        // Now return refusal because of the tool result
2747                        Ok(acp::PromptResponse {
2748                            stop_reason: acp::StopReason::Refusal,
2749                        })
2750                    } else {
2751                        Ok(acp::PromptResponse {
2752                            stop_reason: acp::StopReason::EndTurn,
2753                        })
2754                    }
2755                }
2756                .boxed_local()
2757            }
2758        }));
2759
2760        let thread = cx
2761            .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
2762            .await
2763            .unwrap();
2764
2765        // Track if we see a Refusal event
2766        let saw_refusal_event = Arc::new(std::sync::Mutex::new(false));
2767        let saw_refusal_event_captured = saw_refusal_event.clone();
2768        thread.update(cx, |_thread, cx| {
2769            cx.subscribe(
2770                &thread,
2771                move |_thread, _event_thread, event: &AcpThreadEvent, _cx| {
2772                    if matches!(event, AcpThreadEvent::Refusal) {
2773                        *saw_refusal_event_captured.lock().unwrap() = true;
2774                    }
2775                },
2776            )
2777            .detach();
2778        });
2779
2780        // Send a user message - this will trigger tool call and then refusal
2781        let send_task = thread.update(cx, |thread, cx| {
2782            thread.send(
2783                vec![acp::ContentBlock::Text(acp::TextContent {
2784                    text: "Hello".into(),
2785                    annotations: None,
2786                })],
2787                cx,
2788            )
2789        });
2790        cx.background_executor.spawn(send_task).detach();
2791        cx.run_until_parked();
2792
2793        // Verify that:
2794        // 1. A Refusal event WAS emitted (because it's a tool result refusal, not user prompt)
2795        // 2. The user message was NOT truncated
2796        assert!(
2797            *saw_refusal_event.lock().unwrap(),
2798            "Refusal event should be emitted for tool result refusals"
2799        );
2800
2801        thread.read_with(cx, |thread, _| {
2802            let entries = thread.entries();
2803            assert!(entries.len() >= 2, "Should have user message and tool call");
2804
2805            // Verify user message is still there
2806            assert!(
2807                matches!(entries[0], AgentThreadEntry::UserMessage(_)),
2808                "User message should not be truncated"
2809            );
2810
2811            // Verify tool call is there with result
2812            if let AgentThreadEntry::ToolCall(tool_call) = &entries[1] {
2813                assert!(
2814                    tool_call.raw_output.is_some(),
2815                    "Tool call should have output"
2816                );
2817            } else {
2818                panic!("Expected tool call at index 1");
2819            }
2820        });
2821    }
2822
2823    #[gpui::test]
2824    async fn test_user_prompt_refusal_emits_event(cx: &mut TestAppContext) {
2825        init_test(cx);
2826
2827        let fs = FakeFs::new(cx.executor());
2828        let project = Project::test(fs, None, cx).await;
2829
2830        let refuse_next = Arc::new(AtomicBool::new(false));
2831        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
2832            let refuse_next = refuse_next.clone();
2833            move |_request, _thread, _cx| {
2834                if refuse_next.load(SeqCst) {
2835                    async move {
2836                        Ok(acp::PromptResponse {
2837                            stop_reason: acp::StopReason::Refusal,
2838                        })
2839                    }
2840                    .boxed_local()
2841                } else {
2842                    async move {
2843                        Ok(acp::PromptResponse {
2844                            stop_reason: acp::StopReason::EndTurn,
2845                        })
2846                    }
2847                    .boxed_local()
2848                }
2849            }
2850        }));
2851
2852        let thread = cx
2853            .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
2854            .await
2855            .unwrap();
2856
2857        // Track if we see a Refusal event
2858        let saw_refusal_event = Arc::new(std::sync::Mutex::new(false));
2859        let saw_refusal_event_captured = saw_refusal_event.clone();
2860        thread.update(cx, |_thread, cx| {
2861            cx.subscribe(
2862                &thread,
2863                move |_thread, _event_thread, event: &AcpThreadEvent, _cx| {
2864                    if matches!(event, AcpThreadEvent::Refusal) {
2865                        *saw_refusal_event_captured.lock().unwrap() = true;
2866                    }
2867                },
2868            )
2869            .detach();
2870        });
2871
2872        // Send a message that will be refused
2873        refuse_next.store(true, SeqCst);
2874        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["hello".into()], cx)))
2875            .await
2876            .unwrap();
2877
2878        // Verify that a Refusal event WAS emitted for user prompt refusal
2879        assert!(
2880            *saw_refusal_event.lock().unwrap(),
2881            "Refusal event should be emitted for user prompt refusals"
2882        );
2883
2884        // Verify the message was truncated (user prompt refusal)
2885        thread.read_with(cx, |thread, cx| {
2886            assert_eq!(thread.to_markdown(cx), "");
2887        });
2888    }
2889
2890    #[gpui::test]
2891    async fn test_refusal(cx: &mut TestAppContext) {
2892        init_test(cx);
2893        let fs = FakeFs::new(cx.background_executor.clone());
2894        fs.insert_tree(path!("/"), json!({})).await;
2895        let project = Project::test(fs.clone(), [path!("/").as_ref()], cx).await;
2896
2897        let refuse_next = Arc::new(AtomicBool::new(false));
2898        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
2899            let refuse_next = refuse_next.clone();
2900            move |request, thread, mut cx| {
2901                let refuse_next = refuse_next.clone();
2902                async move {
2903                    if refuse_next.load(SeqCst) {
2904                        return Ok(acp::PromptResponse {
2905                            stop_reason: acp::StopReason::Refusal,
2906                        });
2907                    }
2908
2909                    let acp::ContentBlock::Text(content) = &request.prompt[0] else {
2910                        panic!("expected text content block");
2911                    };
2912                    thread.update(&mut cx, |thread, cx| {
2913                        thread
2914                            .handle_session_update(
2915                                acp::SessionUpdate::AgentMessageChunk {
2916                                    content: content.text.to_uppercase().into(),
2917                                },
2918                                cx,
2919                            )
2920                            .unwrap();
2921                    })?;
2922                    Ok(acp::PromptResponse {
2923                        stop_reason: acp::StopReason::EndTurn,
2924                    })
2925                }
2926                .boxed_local()
2927            }
2928        }));
2929        let thread = cx
2930            .update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
2931            .await
2932            .unwrap();
2933
2934        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["hello".into()], cx)))
2935            .await
2936            .unwrap();
2937        thread.read_with(cx, |thread, cx| {
2938            assert_eq!(
2939                thread.to_markdown(cx),
2940                indoc! {"
2941                    ## User
2942
2943                    hello
2944
2945                    ## Assistant
2946
2947                    HELLO
2948
2949                "}
2950            );
2951        });
2952
2953        // Simulate refusing the second message. The message should be truncated
2954        // when a user prompt is refused.
2955        refuse_next.store(true, SeqCst);
2956        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["world".into()], cx)))
2957            .await
2958            .unwrap();
2959        thread.read_with(cx, |thread, cx| {
2960            assert_eq!(
2961                thread.to_markdown(cx),
2962                indoc! {"
2963                    ## User
2964
2965                    hello
2966
2967                    ## Assistant
2968
2969                    HELLO
2970
2971                "}
2972            );
2973        });
2974    }
2975
2976    async fn run_until_first_tool_call(
2977        thread: &Entity<AcpThread>,
2978        cx: &mut TestAppContext,
2979    ) -> usize {
2980        let (mut tx, mut rx) = mpsc::channel::<usize>(1);
2981
2982        let subscription = cx.update(|cx| {
2983            cx.subscribe(thread, move |thread, _, cx| {
2984                for (ix, entry) in thread.read(cx).entries.iter().enumerate() {
2985                    if matches!(entry, AgentThreadEntry::ToolCall(_)) {
2986                        return tx.try_send(ix).unwrap();
2987                    }
2988                }
2989            })
2990        });
2991
2992        select! {
2993            _ = futures::FutureExt::fuse(smol::Timer::after(Duration::from_secs(10))) => {
2994                panic!("Timeout waiting for tool call")
2995            }
2996            ix = rx.next().fuse() => {
2997                drop(subscription);
2998                ix.unwrap()
2999            }
3000        }
3001    }
3002
3003    #[derive(Clone, Default)]
3004    struct FakeAgentConnection {
3005        auth_methods: Vec<acp::AuthMethod>,
3006        sessions: Arc<parking_lot::Mutex<HashMap<acp::SessionId, WeakEntity<AcpThread>>>>,
3007        on_user_message: Option<
3008            Rc<
3009                dyn Fn(
3010                        acp::PromptRequest,
3011                        WeakEntity<AcpThread>,
3012                        AsyncApp,
3013                    ) -> LocalBoxFuture<'static, Result<acp::PromptResponse>>
3014                    + 'static,
3015            >,
3016        >,
3017    }
3018
3019    impl FakeAgentConnection {
3020        fn new() -> Self {
3021            Self {
3022                auth_methods: Vec::new(),
3023                on_user_message: None,
3024                sessions: Arc::default(),
3025            }
3026        }
3027
3028        #[expect(unused)]
3029        fn with_auth_methods(mut self, auth_methods: Vec<acp::AuthMethod>) -> Self {
3030            self.auth_methods = auth_methods;
3031            self
3032        }
3033
3034        fn on_user_message(
3035            mut self,
3036            handler: impl Fn(
3037                acp::PromptRequest,
3038                WeakEntity<AcpThread>,
3039                AsyncApp,
3040            ) -> LocalBoxFuture<'static, Result<acp::PromptResponse>>
3041            + 'static,
3042        ) -> Self {
3043            self.on_user_message.replace(Rc::new(handler));
3044            self
3045        }
3046    }
3047
3048    impl AgentConnection for FakeAgentConnection {
3049        fn auth_methods(&self) -> &[acp::AuthMethod] {
3050            &self.auth_methods
3051        }
3052
3053        fn new_thread(
3054            self: Rc<Self>,
3055            project: Entity<Project>,
3056            _cwd: &Path,
3057            cx: &mut App,
3058        ) -> Task<gpui::Result<Entity<AcpThread>>> {
3059            let session_id = acp::SessionId(
3060                rand::rng()
3061                    .sample_iter(&distr::Alphanumeric)
3062                    .take(7)
3063                    .map(char::from)
3064                    .collect::<String>()
3065                    .into(),
3066            );
3067            let action_log = cx.new(|_| ActionLog::new(project.clone()));
3068            let thread = cx.new(|cx| {
3069                AcpThread::new(
3070                    "Test",
3071                    self.clone(),
3072                    project,
3073                    action_log,
3074                    session_id.clone(),
3075                    watch::Receiver::constant(acp::PromptCapabilities {
3076                        image: true,
3077                        audio: true,
3078                        embedded_context: true,
3079                    }),
3080                    cx,
3081                )
3082            });
3083            self.sessions.lock().insert(session_id, thread.downgrade());
3084            Task::ready(Ok(thread))
3085        }
3086
3087        fn authenticate(&self, method: acp::AuthMethodId, _cx: &mut App) -> Task<gpui::Result<()>> {
3088            if self.auth_methods().iter().any(|m| m.id == method) {
3089                Task::ready(Ok(()))
3090            } else {
3091                Task::ready(Err(anyhow!("Invalid Auth Method")))
3092            }
3093        }
3094
3095        fn prompt(
3096            &self,
3097            _id: Option<UserMessageId>,
3098            params: acp::PromptRequest,
3099            cx: &mut App,
3100        ) -> Task<gpui::Result<acp::PromptResponse>> {
3101            let sessions = self.sessions.lock();
3102            let thread = sessions.get(&params.session_id).unwrap();
3103            if let Some(handler) = &self.on_user_message {
3104                let handler = handler.clone();
3105                let thread = thread.clone();
3106                cx.spawn(async move |cx| handler(params, thread, cx.clone()).await)
3107            } else {
3108                Task::ready(Ok(acp::PromptResponse {
3109                    stop_reason: acp::StopReason::EndTurn,
3110                }))
3111            }
3112        }
3113
3114        fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
3115            let sessions = self.sessions.lock();
3116            let thread = sessions.get(session_id).unwrap().clone();
3117
3118            cx.spawn(async move |cx| {
3119                thread
3120                    .update(cx, |thread, cx| thread.cancel(cx))
3121                    .unwrap()
3122                    .await
3123            })
3124            .detach();
3125        }
3126
3127        fn truncate(
3128            &self,
3129            session_id: &acp::SessionId,
3130            _cx: &App,
3131        ) -> Option<Rc<dyn AgentSessionTruncate>> {
3132            Some(Rc::new(FakeAgentSessionEditor {
3133                _session_id: session_id.clone(),
3134            }))
3135        }
3136
3137        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3138            self
3139        }
3140    }
3141
3142    struct FakeAgentSessionEditor {
3143        _session_id: acp::SessionId,
3144    }
3145
3146    impl AgentSessionTruncate for FakeAgentSessionEditor {
3147        fn run(&self, _message_id: UserMessageId, _cx: &mut App) -> Task<Result<()>> {
3148            Task::ready(Ok(()))
3149        }
3150    }
3151}