acp_thread.rs

   1mod connection;
   2mod diff;
   3mod mention;
   4mod terminal;
   5use action_log::{ActionLog, ActionLogTelemetry};
   6use agent_client_protocol::{self as acp};
   7use anyhow::{Context as _, Result, anyhow};
   8use collections::HashSet;
   9pub use connection::*;
  10pub use diff::*;
  11use futures::{FutureExt, channel::oneshot, future::BoxFuture};
  12use gpui::{AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task, WeakEntity};
  13use itertools::Itertools;
  14use language::language_settings::FormatOnSave;
  15use language::{Anchor, Buffer, BufferSnapshot, LanguageRegistry, Point, ToPoint, text_diff};
  16use markdown::Markdown;
  17pub use mention::*;
  18use project::lsp_store::{FormatTrigger, LspFormatTarget};
  19use project::{AgentLocation, Project, git_store::GitStoreCheckpoint};
  20use serde::{Deserialize, Serialize};
  21use serde_json::to_string_pretty;
  22use std::collections::HashMap;
  23use std::error::Error;
  24use std::fmt::{Formatter, Write};
  25use std::ops::Range;
  26use std::process::ExitStatus;
  27use std::rc::Rc;
  28use std::time::{Duration, Instant};
  29use std::{fmt::Display, mem, path::PathBuf, sync::Arc};
  30use task::{Shell, ShellBuilder};
  31pub use terminal::*;
  32use text::Bias;
  33use ui::App;
  34use util::markdown::MarkdownEscaped;
  35use util::path_list::PathList;
  36use util::{ResultExt, get_default_system_shell_preferring_bash, paths::PathStyle};
  37use uuid::Uuid;
  38
  39/// Returned when the model stops because it exhausted its output token budget.
  40#[derive(Debug)]
  41pub struct MaxOutputTokensError;
  42
  43impl std::fmt::Display for MaxOutputTokensError {
  44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  45        write!(f, "output token limit reached")
  46    }
  47}
  48
  49impl std::error::Error for MaxOutputTokensError {}
  50
  51/// Key used in ACP ToolCall meta to store the tool's programmatic name.
  52/// This is a workaround since ACP's ToolCall doesn't have a dedicated name field.
  53pub const TOOL_NAME_META_KEY: &str = "tool_name";
  54
  55/// Helper to extract tool name from ACP meta
  56pub fn tool_name_from_meta(meta: &Option<acp::Meta>) -> Option<SharedString> {
  57    meta.as_ref()
  58        .and_then(|m| m.get(TOOL_NAME_META_KEY))
  59        .and_then(|v| v.as_str())
  60        .map(|s| SharedString::from(s.to_owned()))
  61}
  62
  63/// Helper to create meta with tool name
  64pub fn meta_with_tool_name(tool_name: &str) -> acp::Meta {
  65    acp::Meta::from_iter([(TOOL_NAME_META_KEY.into(), tool_name.into())])
  66}
  67
  68/// Key used in ACP ToolCall meta to store the session id and message indexes
  69pub const SUBAGENT_SESSION_INFO_META_KEY: &str = "subagent_session_info";
  70
  71#[derive(Clone, Debug, Deserialize, Serialize)]
  72pub struct SubagentSessionInfo {
  73    /// The session id of the subagent sessiont that was spawned
  74    pub session_id: acp::SessionId,
  75    /// The index of the message of the start of the "turn" run by this tool call
  76    pub message_start_index: usize,
  77    /// The index of the output of the message that the subagent has returned
  78    #[serde(skip_serializing_if = "Option::is_none")]
  79    pub message_end_index: Option<usize>,
  80}
  81
  82/// Helper to extract subagent session id from ACP meta
  83pub fn subagent_session_info_from_meta(meta: &Option<acp::Meta>) -> Option<SubagentSessionInfo> {
  84    meta.as_ref()
  85        .and_then(|m| m.get(SUBAGENT_SESSION_INFO_META_KEY))
  86        .and_then(|v| serde_json::from_value(v.clone()).ok())
  87}
  88
  89#[derive(Debug)]
  90pub struct UserMessage {
  91    pub id: Option<UserMessageId>,
  92    pub content: ContentBlock,
  93    pub chunks: Vec<acp::ContentBlock>,
  94    pub checkpoint: Option<Checkpoint>,
  95    pub indented: bool,
  96}
  97
  98#[derive(Debug)]
  99pub struct Checkpoint {
 100    git_checkpoint: GitStoreCheckpoint,
 101    pub show: bool,
 102}
 103
 104impl UserMessage {
 105    fn to_markdown(&self, cx: &App) -> String {
 106        let mut markdown = String::new();
 107        if self
 108            .checkpoint
 109            .as_ref()
 110            .is_some_and(|checkpoint| checkpoint.show)
 111        {
 112            writeln!(markdown, "## User (checkpoint)").unwrap();
 113        } else {
 114            writeln!(markdown, "## User").unwrap();
 115        }
 116        writeln!(markdown).unwrap();
 117        writeln!(markdown, "{}", self.content.to_markdown(cx)).unwrap();
 118        writeln!(markdown).unwrap();
 119        markdown
 120    }
 121}
 122
 123#[derive(Debug, PartialEq)]
 124pub struct AssistantMessage {
 125    pub chunks: Vec<AssistantMessageChunk>,
 126    pub indented: bool,
 127    pub is_subagent_output: bool,
 128}
 129
 130impl AssistantMessage {
 131    pub fn to_markdown(&self, cx: &App) -> String {
 132        format!(
 133            "## Assistant\n\n{}\n\n",
 134            self.chunks
 135                .iter()
 136                .map(|chunk| chunk.to_markdown(cx))
 137                .join("\n\n")
 138        )
 139    }
 140}
 141
 142#[derive(Debug, PartialEq)]
 143pub enum AssistantMessageChunk {
 144    Message { block: ContentBlock },
 145    Thought { block: ContentBlock },
 146}
 147
 148impl AssistantMessageChunk {
 149    pub fn from_str(
 150        chunk: &str,
 151        language_registry: &Arc<LanguageRegistry>,
 152        path_style: PathStyle,
 153        cx: &mut App,
 154    ) -> Self {
 155        Self::Message {
 156            block: ContentBlock::new(chunk.into(), language_registry, path_style, cx),
 157        }
 158    }
 159
 160    fn to_markdown(&self, cx: &App) -> String {
 161        match self {
 162            Self::Message { block } => block.to_markdown(cx).to_string(),
 163            Self::Thought { block } => {
 164                format!("<thinking>\n{}\n</thinking>", block.to_markdown(cx))
 165            }
 166        }
 167    }
 168}
 169
 170#[derive(Debug)]
 171pub enum AgentThreadEntry {
 172    UserMessage(UserMessage),
 173    AssistantMessage(AssistantMessage),
 174    ToolCall(ToolCall),
 175    CompletedPlan(Vec<PlanEntry>),
 176}
 177
 178impl AgentThreadEntry {
 179    pub fn is_indented(&self) -> bool {
 180        match self {
 181            Self::UserMessage(message) => message.indented,
 182            Self::AssistantMessage(message) => message.indented,
 183            Self::ToolCall(_) => false,
 184            Self::CompletedPlan(_) => false,
 185        }
 186    }
 187
 188    pub fn to_markdown(&self, cx: &App) -> String {
 189        match self {
 190            Self::UserMessage(message) => message.to_markdown(cx),
 191            Self::AssistantMessage(message) => message.to_markdown(cx),
 192            Self::ToolCall(tool_call) => tool_call.to_markdown(cx),
 193            Self::CompletedPlan(entries) => {
 194                let mut md = String::from("## Plan\n\n");
 195                for entry in entries {
 196                    let source = entry.content.read(cx).source().to_string();
 197                    md.push_str(&format!("- [x] {}\n", source));
 198                }
 199                md
 200            }
 201        }
 202    }
 203
 204    pub fn user_message(&self) -> Option<&UserMessage> {
 205        if let AgentThreadEntry::UserMessage(message) = self {
 206            Some(message)
 207        } else {
 208            None
 209        }
 210    }
 211
 212    pub fn diffs(&self) -> impl Iterator<Item = &Entity<Diff>> {
 213        if let AgentThreadEntry::ToolCall(call) = self {
 214            itertools::Either::Left(call.diffs())
 215        } else {
 216            itertools::Either::Right(std::iter::empty())
 217        }
 218    }
 219
 220    pub fn terminals(&self) -> impl Iterator<Item = &Entity<Terminal>> {
 221        if let AgentThreadEntry::ToolCall(call) = self {
 222            itertools::Either::Left(call.terminals())
 223        } else {
 224            itertools::Either::Right(std::iter::empty())
 225        }
 226    }
 227
 228    pub fn location(&self, ix: usize) -> Option<(acp::ToolCallLocation, AgentLocation)> {
 229        if let AgentThreadEntry::ToolCall(ToolCall {
 230            locations,
 231            resolved_locations,
 232            ..
 233        }) = self
 234        {
 235            Some((
 236                locations.get(ix)?.clone(),
 237                resolved_locations.get(ix)?.clone()?,
 238            ))
 239        } else {
 240            None
 241        }
 242    }
 243}
 244
 245#[derive(Debug)]
 246pub struct ToolCall {
 247    pub id: acp::ToolCallId,
 248    pub label: Entity<Markdown>,
 249    pub kind: acp::ToolKind,
 250    pub content: Vec<ToolCallContent>,
 251    pub status: ToolCallStatus,
 252    pub locations: Vec<acp::ToolCallLocation>,
 253    pub resolved_locations: Vec<Option<AgentLocation>>,
 254    pub raw_input: Option<serde_json::Value>,
 255    pub raw_input_markdown: Option<Entity<Markdown>>,
 256    pub raw_output: Option<serde_json::Value>,
 257    pub tool_name: Option<SharedString>,
 258    pub subagent_session_info: Option<SubagentSessionInfo>,
 259}
 260
 261impl ToolCall {
 262    fn from_acp(
 263        tool_call: acp::ToolCall,
 264        status: ToolCallStatus,
 265        language_registry: Arc<LanguageRegistry>,
 266        path_style: PathStyle,
 267        terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
 268        cx: &mut App,
 269    ) -> Result<Self> {
 270        let title = if tool_call.kind == acp::ToolKind::Execute {
 271            tool_call.title
 272        } else if tool_call.kind == acp::ToolKind::Edit {
 273            MarkdownEscaped(tool_call.title.as_str()).to_string()
 274        } else if let Some((first_line, _)) = tool_call.title.split_once("\n") {
 275            first_line.to_owned() + ""
 276        } else {
 277            tool_call.title
 278        };
 279        let mut content = Vec::with_capacity(tool_call.content.len());
 280        for item in tool_call.content {
 281            if let Some(item) = ToolCallContent::from_acp(
 282                item,
 283                language_registry.clone(),
 284                path_style,
 285                terminals,
 286                cx,
 287            )? {
 288                content.push(item);
 289            }
 290        }
 291
 292        let raw_input_markdown = tool_call
 293            .raw_input
 294            .as_ref()
 295            .and_then(|input| markdown_for_raw_output(input, &language_registry, cx));
 296
 297        let tool_name = tool_name_from_meta(&tool_call.meta);
 298
 299        let subagent_session_info = subagent_session_info_from_meta(&tool_call.meta);
 300
 301        let result = Self {
 302            id: tool_call.tool_call_id,
 303            label: cx
 304                .new(|cx| Markdown::new(title.into(), Some(language_registry.clone()), None, cx)),
 305            kind: tool_call.kind,
 306            content,
 307            locations: tool_call.locations,
 308            resolved_locations: Vec::default(),
 309            status,
 310            raw_input: tool_call.raw_input,
 311            raw_input_markdown,
 312            raw_output: tool_call.raw_output,
 313            tool_name,
 314            subagent_session_info,
 315        };
 316        Ok(result)
 317    }
 318
 319    fn update_fields(
 320        &mut self,
 321        fields: acp::ToolCallUpdateFields,
 322        meta: Option<acp::Meta>,
 323        language_registry: Arc<LanguageRegistry>,
 324        path_style: PathStyle,
 325        terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
 326        cx: &mut App,
 327    ) -> Result<()> {
 328        let acp::ToolCallUpdateFields {
 329            kind,
 330            status,
 331            title,
 332            content,
 333            locations,
 334            raw_input,
 335            raw_output,
 336            ..
 337        } = fields;
 338
 339        if let Some(kind) = kind {
 340            self.kind = kind;
 341        }
 342
 343        if let Some(status) = status {
 344            self.status = status.into();
 345        }
 346
 347        if let Some(subagent_session_info) = subagent_session_info_from_meta(&meta) {
 348            self.subagent_session_info = Some(subagent_session_info);
 349        }
 350
 351        if let Some(title) = title {
 352            if self.kind == acp::ToolKind::Execute {
 353                for terminal in self.terminals() {
 354                    terminal.update(cx, |terminal, cx| {
 355                        terminal.update_command_label(&title, cx);
 356                    });
 357                }
 358            }
 359            self.label.update(cx, |label, cx| {
 360                if self.kind == acp::ToolKind::Execute {
 361                    label.replace(title, cx);
 362                } else if self.kind == acp::ToolKind::Edit {
 363                    label.replace(MarkdownEscaped(&title).to_string(), cx)
 364                } else if let Some((first_line, _)) = title.split_once("\n") {
 365                    label.replace(first_line.to_owned() + "", cx);
 366                } else {
 367                    label.replace(title, cx);
 368                }
 369            });
 370        }
 371
 372        if let Some(content) = content {
 373            let mut new_content_len = content.len();
 374            let mut content = content.into_iter();
 375
 376            // Reuse existing content if we can
 377            for (old, new) in self.content.iter_mut().zip(content.by_ref()) {
 378                let valid_content =
 379                    old.update_from_acp(new, language_registry.clone(), path_style, terminals, cx)?;
 380                if !valid_content {
 381                    new_content_len -= 1;
 382                }
 383            }
 384            for new in content {
 385                if let Some(new) = ToolCallContent::from_acp(
 386                    new,
 387                    language_registry.clone(),
 388                    path_style,
 389                    terminals,
 390                    cx,
 391                )? {
 392                    self.content.push(new);
 393                } else {
 394                    new_content_len -= 1;
 395                }
 396            }
 397            self.content.truncate(new_content_len);
 398        }
 399
 400        if let Some(locations) = locations {
 401            self.locations = locations;
 402        }
 403
 404        if let Some(raw_input) = raw_input {
 405            self.raw_input_markdown = markdown_for_raw_output(&raw_input, &language_registry, cx);
 406            self.raw_input = Some(raw_input);
 407        }
 408
 409        if let Some(raw_output) = raw_output {
 410            if self.content.is_empty()
 411                && let Some(markdown) = markdown_for_raw_output(&raw_output, &language_registry, cx)
 412            {
 413                self.content
 414                    .push(ToolCallContent::ContentBlock(ContentBlock::Markdown {
 415                        markdown,
 416                    }));
 417            }
 418            self.raw_output = Some(raw_output);
 419        }
 420        Ok(())
 421    }
 422
 423    pub fn diffs(&self) -> impl Iterator<Item = &Entity<Diff>> {
 424        self.content.iter().filter_map(|content| match content {
 425            ToolCallContent::Diff(diff) => Some(diff),
 426            ToolCallContent::ContentBlock(_) => None,
 427            ToolCallContent::Terminal(_) => None,
 428        })
 429    }
 430
 431    pub fn terminals(&self) -> impl Iterator<Item = &Entity<Terminal>> {
 432        self.content.iter().filter_map(|content| match content {
 433            ToolCallContent::Terminal(terminal) => Some(terminal),
 434            ToolCallContent::ContentBlock(_) => None,
 435            ToolCallContent::Diff(_) => None,
 436        })
 437    }
 438
 439    pub fn is_subagent(&self) -> bool {
 440        self.tool_name.as_ref().is_some_and(|s| s == "spawn_agent")
 441            || self.subagent_session_info.is_some()
 442    }
 443
 444    pub fn to_markdown(&self, cx: &App) -> String {
 445        let mut markdown = format!(
 446            "**Tool Call: {}**\nStatus: {}\n\n",
 447            self.label.read(cx).source(),
 448            self.status
 449        );
 450        for content in &self.content {
 451            markdown.push_str(content.to_markdown(cx).as_str());
 452            markdown.push_str("\n\n");
 453        }
 454        markdown
 455    }
 456
 457    async fn resolve_location(
 458        location: acp::ToolCallLocation,
 459        project: WeakEntity<Project>,
 460        cx: &mut AsyncApp,
 461    ) -> Option<ResolvedLocation> {
 462        let buffer = project
 463            .update(cx, |project, cx| {
 464                project
 465                    .project_path_for_absolute_path(&location.path, cx)
 466                    .map(|path| project.open_buffer(path, cx))
 467            })
 468            .ok()??;
 469        let buffer = buffer.await.log_err()?;
 470        let position = buffer.update(cx, |buffer, _| {
 471            let snapshot = buffer.snapshot();
 472            if let Some(row) = location.line {
 473                let column = snapshot.indent_size_for_line(row).len;
 474                let point = snapshot.clip_point(Point::new(row, column), Bias::Left);
 475                snapshot.anchor_before(point)
 476            } else {
 477                Anchor::min_for_buffer(snapshot.remote_id())
 478            }
 479        });
 480
 481        Some(ResolvedLocation { buffer, position })
 482    }
 483
 484    fn resolve_locations(
 485        &self,
 486        project: Entity<Project>,
 487        cx: &mut App,
 488    ) -> Task<Vec<Option<ResolvedLocation>>> {
 489        let locations = self.locations.clone();
 490        project.update(cx, |_, cx| {
 491            cx.spawn(async move |project, cx| {
 492                let mut new_locations = Vec::new();
 493                for location in locations {
 494                    new_locations.push(Self::resolve_location(location, project.clone(), cx).await);
 495                }
 496                new_locations
 497            })
 498        })
 499    }
 500}
 501
 502// Separate so we can hold a strong reference to the buffer
 503// for saving on the thread
 504#[derive(Clone, Debug, PartialEq, Eq)]
 505struct ResolvedLocation {
 506    buffer: Entity<Buffer>,
 507    position: Anchor,
 508}
 509
 510impl From<&ResolvedLocation> for AgentLocation {
 511    fn from(value: &ResolvedLocation) -> Self {
 512        Self {
 513            buffer: value.buffer.downgrade(),
 514            position: value.position,
 515        }
 516    }
 517}
 518
 519#[derive(Debug, Clone)]
 520pub enum SelectedPermissionParams {
 521    Terminal { patterns: Vec<String> },
 522}
 523
 524#[derive(Debug)]
 525pub struct SelectedPermissionOutcome {
 526    pub option_id: acp::PermissionOptionId,
 527    pub option_kind: acp::PermissionOptionKind,
 528    pub params: Option<SelectedPermissionParams>,
 529}
 530
 531impl SelectedPermissionOutcome {
 532    pub fn new(option_id: acp::PermissionOptionId, option_kind: acp::PermissionOptionKind) -> Self {
 533        Self {
 534            option_id,
 535            option_kind,
 536            params: None,
 537        }
 538    }
 539
 540    pub fn params(mut self, params: Option<SelectedPermissionParams>) -> Self {
 541        self.params = params;
 542        self
 543    }
 544}
 545
 546impl From<SelectedPermissionOutcome> for acp::SelectedPermissionOutcome {
 547    fn from(value: SelectedPermissionOutcome) -> Self {
 548        Self::new(value.option_id)
 549    }
 550}
 551
 552#[derive(Debug)]
 553pub enum RequestPermissionOutcome {
 554    Cancelled,
 555    Selected(SelectedPermissionOutcome),
 556}
 557
 558impl From<RequestPermissionOutcome> for acp::RequestPermissionOutcome {
 559    fn from(value: RequestPermissionOutcome) -> Self {
 560        match value {
 561            RequestPermissionOutcome::Cancelled => Self::Cancelled,
 562            RequestPermissionOutcome::Selected(outcome) => Self::Selected(outcome.into()),
 563        }
 564    }
 565}
 566
 567#[derive(Debug)]
 568pub enum ToolCallStatus {
 569    /// The tool call hasn't started running yet, but we start showing it to
 570    /// the user.
 571    Pending,
 572    /// The tool call is waiting for confirmation from the user.
 573    WaitingForConfirmation {
 574        options: PermissionOptions,
 575        respond_tx: oneshot::Sender<SelectedPermissionOutcome>,
 576    },
 577    /// The tool call is currently running.
 578    InProgress,
 579    /// The tool call completed successfully.
 580    Completed,
 581    /// The tool call failed.
 582    Failed,
 583    /// The user rejected the tool call.
 584    Rejected,
 585    /// The user canceled generation so the tool call was canceled.
 586    Canceled,
 587}
 588
 589impl From<acp::ToolCallStatus> for ToolCallStatus {
 590    fn from(status: acp::ToolCallStatus) -> Self {
 591        match status {
 592            acp::ToolCallStatus::Pending => Self::Pending,
 593            acp::ToolCallStatus::InProgress => Self::InProgress,
 594            acp::ToolCallStatus::Completed => Self::Completed,
 595            acp::ToolCallStatus::Failed => Self::Failed,
 596            _ => Self::Pending,
 597        }
 598    }
 599}
 600
 601impl Display for ToolCallStatus {
 602    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
 603        write!(
 604            f,
 605            "{}",
 606            match self {
 607                ToolCallStatus::Pending => "Pending",
 608                ToolCallStatus::WaitingForConfirmation { .. } => "Waiting for confirmation",
 609                ToolCallStatus::InProgress => "In Progress",
 610                ToolCallStatus::Completed => "Completed",
 611                ToolCallStatus::Failed => "Failed",
 612                ToolCallStatus::Rejected => "Rejected",
 613                ToolCallStatus::Canceled => "Canceled",
 614            }
 615        )
 616    }
 617}
 618
 619#[derive(Debug, PartialEq, Clone)]
 620pub enum ContentBlock {
 621    Empty,
 622    Markdown { markdown: Entity<Markdown> },
 623    ResourceLink { resource_link: acp::ResourceLink },
 624    Image { image: Arc<gpui::Image> },
 625}
 626
 627impl ContentBlock {
 628    pub fn new(
 629        block: acp::ContentBlock,
 630        language_registry: &Arc<LanguageRegistry>,
 631        path_style: PathStyle,
 632        cx: &mut App,
 633    ) -> Self {
 634        let mut this = Self::Empty;
 635        this.append(block, language_registry, path_style, cx);
 636        this
 637    }
 638
 639    pub fn new_combined(
 640        blocks: impl IntoIterator<Item = acp::ContentBlock>,
 641        language_registry: Arc<LanguageRegistry>,
 642        path_style: PathStyle,
 643        cx: &mut App,
 644    ) -> Self {
 645        let mut this = Self::Empty;
 646        for block in blocks {
 647            this.append(block, &language_registry, path_style, cx);
 648        }
 649        this
 650    }
 651
 652    pub fn append(
 653        &mut self,
 654        block: acp::ContentBlock,
 655        language_registry: &Arc<LanguageRegistry>,
 656        path_style: PathStyle,
 657        cx: &mut App,
 658    ) {
 659        match (&mut *self, &block) {
 660            (ContentBlock::Empty, acp::ContentBlock::ResourceLink(resource_link)) => {
 661                *self = ContentBlock::ResourceLink {
 662                    resource_link: resource_link.clone(),
 663                };
 664            }
 665            (ContentBlock::Empty, acp::ContentBlock::Image(image_content)) => {
 666                if let Some(image) = Self::decode_image(image_content) {
 667                    *self = ContentBlock::Image { image };
 668                } else {
 669                    let new_content = Self::image_md(image_content);
 670                    *self = Self::create_markdown_block(new_content, language_registry, cx);
 671                }
 672            }
 673            (ContentBlock::Empty, _) => {
 674                let new_content = Self::block_string_contents(&block, path_style);
 675                *self = Self::create_markdown_block(new_content, language_registry, cx);
 676            }
 677            (ContentBlock::Markdown { markdown }, _) => {
 678                let new_content = Self::block_string_contents(&block, path_style);
 679                markdown.update(cx, |markdown, cx| markdown.append(&new_content, cx));
 680            }
 681            (ContentBlock::ResourceLink { resource_link }, _) => {
 682                let existing_content = Self::resource_link_md(&resource_link.uri, path_style);
 683                let new_content = Self::block_string_contents(&block, path_style);
 684                let combined = format!("{}\n{}", existing_content, new_content);
 685                *self = Self::create_markdown_block(combined, language_registry, cx);
 686            }
 687            (ContentBlock::Image { .. }, _) => {
 688                let new_content = Self::block_string_contents(&block, path_style);
 689                let combined = format!("`Image`\n{}", new_content);
 690                *self = Self::create_markdown_block(combined, language_registry, cx);
 691            }
 692        }
 693    }
 694
 695    fn decode_image(image_content: &acp::ImageContent) -> Option<Arc<gpui::Image>> {
 696        use base64::Engine as _;
 697
 698        let bytes = base64::engine::general_purpose::STANDARD
 699            .decode(image_content.data.as_bytes())
 700            .ok()?;
 701        let format = gpui::ImageFormat::from_mime_type(&image_content.mime_type)?;
 702        Some(Arc::new(gpui::Image::from_bytes(format, bytes)))
 703    }
 704
 705    fn create_markdown_block(
 706        content: String,
 707        language_registry: &Arc<LanguageRegistry>,
 708        cx: &mut App,
 709    ) -> ContentBlock {
 710        ContentBlock::Markdown {
 711            markdown: cx
 712                .new(|cx| Markdown::new(content.into(), Some(language_registry.clone()), None, cx)),
 713        }
 714    }
 715
 716    fn block_string_contents(block: &acp::ContentBlock, path_style: PathStyle) -> String {
 717        match block {
 718            acp::ContentBlock::Text(text_content) => text_content.text.clone(),
 719            acp::ContentBlock::ResourceLink(resource_link) => {
 720                Self::resource_link_md(&resource_link.uri, path_style)
 721            }
 722            acp::ContentBlock::Resource(acp::EmbeddedResource {
 723                resource:
 724                    acp::EmbeddedResourceResource::TextResourceContents(acp::TextResourceContents {
 725                        uri,
 726                        ..
 727                    }),
 728                ..
 729            }) => Self::resource_link_md(uri, path_style),
 730            acp::ContentBlock::Image(image) => Self::image_md(image),
 731            _ => String::new(),
 732        }
 733    }
 734
 735    fn resource_link_md(uri: &str, path_style: PathStyle) -> String {
 736        if let Some(uri) = MentionUri::parse(uri, path_style).log_err() {
 737            uri.as_link().to_string()
 738        } else {
 739            uri.to_string()
 740        }
 741    }
 742
 743    fn image_md(_image: &acp::ImageContent) -> String {
 744        "`Image`".into()
 745    }
 746
 747    pub fn to_markdown<'a>(&'a self, cx: &'a App) -> &'a str {
 748        match self {
 749            ContentBlock::Empty => "",
 750            ContentBlock::Markdown { markdown } => markdown.read(cx).source(),
 751            ContentBlock::ResourceLink { resource_link } => &resource_link.uri,
 752            ContentBlock::Image { .. } => "`Image`",
 753        }
 754    }
 755
 756    pub fn markdown(&self) -> Option<&Entity<Markdown>> {
 757        match self {
 758            ContentBlock::Empty => None,
 759            ContentBlock::Markdown { markdown } => Some(markdown),
 760            ContentBlock::ResourceLink { .. } => None,
 761            ContentBlock::Image { .. } => None,
 762        }
 763    }
 764
 765    pub fn resource_link(&self) -> Option<&acp::ResourceLink> {
 766        match self {
 767            ContentBlock::ResourceLink { resource_link } => Some(resource_link),
 768            _ => None,
 769        }
 770    }
 771
 772    pub fn image(&self) -> Option<&Arc<gpui::Image>> {
 773        match self {
 774            ContentBlock::Image { image } => Some(image),
 775            _ => None,
 776        }
 777    }
 778}
 779
 780#[derive(Debug)]
 781pub enum ToolCallContent {
 782    ContentBlock(ContentBlock),
 783    Diff(Entity<Diff>),
 784    Terminal(Entity<Terminal>),
 785}
 786
 787impl ToolCallContent {
 788    pub fn from_acp(
 789        content: acp::ToolCallContent,
 790        language_registry: Arc<LanguageRegistry>,
 791        path_style: PathStyle,
 792        terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
 793        cx: &mut App,
 794    ) -> Result<Option<Self>> {
 795        match content {
 796            acp::ToolCallContent::Content(acp::Content { content, .. }) => {
 797                Ok(Some(Self::ContentBlock(ContentBlock::new(
 798                    content,
 799                    &language_registry,
 800                    path_style,
 801                    cx,
 802                ))))
 803            }
 804            acp::ToolCallContent::Diff(diff) => Ok(Some(Self::Diff(cx.new(|cx| {
 805                Diff::finalized(
 806                    diff.path.to_string_lossy().into_owned(),
 807                    diff.old_text,
 808                    diff.new_text,
 809                    language_registry,
 810                    cx,
 811                )
 812            })))),
 813            acp::ToolCallContent::Terminal(acp::Terminal { terminal_id, .. }) => terminals
 814                .get(&terminal_id)
 815                .cloned()
 816                .map(|terminal| Some(Self::Terminal(terminal)))
 817                .ok_or_else(|| anyhow::anyhow!("Terminal with id `{}` not found", terminal_id)),
 818            _ => Ok(None),
 819        }
 820    }
 821
 822    pub fn update_from_acp(
 823        &mut self,
 824        new: acp::ToolCallContent,
 825        language_registry: Arc<LanguageRegistry>,
 826        path_style: PathStyle,
 827        terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
 828        cx: &mut App,
 829    ) -> Result<bool> {
 830        let needs_update = match (&self, &new) {
 831            (Self::Diff(old_diff), acp::ToolCallContent::Diff(new_diff)) => {
 832                old_diff.read(cx).needs_update(
 833                    new_diff.old_text.as_deref().unwrap_or(""),
 834                    &new_diff.new_text,
 835                    cx,
 836                )
 837            }
 838            _ => true,
 839        };
 840
 841        if let Some(update) = Self::from_acp(new, language_registry, path_style, terminals, cx)? {
 842            if needs_update {
 843                *self = update;
 844            }
 845            Ok(true)
 846        } else {
 847            Ok(false)
 848        }
 849    }
 850
 851    pub fn to_markdown(&self, cx: &App) -> String {
 852        match self {
 853            Self::ContentBlock(content) => content.to_markdown(cx).to_string(),
 854            Self::Diff(diff) => diff.read(cx).to_markdown(cx),
 855            Self::Terminal(terminal) => terminal.read(cx).to_markdown(cx),
 856        }
 857    }
 858
 859    pub fn image(&self) -> Option<&Arc<gpui::Image>> {
 860        match self {
 861            Self::ContentBlock(content) => content.image(),
 862            _ => None,
 863        }
 864    }
 865}
 866
 867#[derive(Debug, PartialEq)]
 868pub enum ToolCallUpdate {
 869    UpdateFields(acp::ToolCallUpdate),
 870    UpdateDiff(ToolCallUpdateDiff),
 871    UpdateTerminal(ToolCallUpdateTerminal),
 872}
 873
 874impl ToolCallUpdate {
 875    fn id(&self) -> &acp::ToolCallId {
 876        match self {
 877            Self::UpdateFields(update) => &update.tool_call_id,
 878            Self::UpdateDiff(diff) => &diff.id,
 879            Self::UpdateTerminal(terminal) => &terminal.id,
 880        }
 881    }
 882}
 883
 884impl From<acp::ToolCallUpdate> for ToolCallUpdate {
 885    fn from(update: acp::ToolCallUpdate) -> Self {
 886        Self::UpdateFields(update)
 887    }
 888}
 889
 890impl From<ToolCallUpdateDiff> for ToolCallUpdate {
 891    fn from(diff: ToolCallUpdateDiff) -> Self {
 892        Self::UpdateDiff(diff)
 893    }
 894}
 895
 896#[derive(Debug, PartialEq)]
 897pub struct ToolCallUpdateDiff {
 898    pub id: acp::ToolCallId,
 899    pub diff: Entity<Diff>,
 900}
 901
 902impl From<ToolCallUpdateTerminal> for ToolCallUpdate {
 903    fn from(terminal: ToolCallUpdateTerminal) -> Self {
 904        Self::UpdateTerminal(terminal)
 905    }
 906}
 907
 908#[derive(Debug, PartialEq)]
 909pub struct ToolCallUpdateTerminal {
 910    pub id: acp::ToolCallId,
 911    pub terminal: Entity<Terminal>,
 912}
 913
 914#[derive(Debug, Default)]
 915pub struct Plan {
 916    pub entries: Vec<PlanEntry>,
 917}
 918
 919#[derive(Debug)]
 920pub struct PlanStats<'a> {
 921    pub in_progress_entry: Option<&'a PlanEntry>,
 922    pub pending: u32,
 923    pub completed: u32,
 924}
 925
 926impl Plan {
 927    pub fn is_empty(&self) -> bool {
 928        self.entries.is_empty()
 929    }
 930
 931    pub fn stats(&self) -> PlanStats<'_> {
 932        let mut stats = PlanStats {
 933            in_progress_entry: None,
 934            pending: 0,
 935            completed: 0,
 936        };
 937
 938        for entry in &self.entries {
 939            match &entry.status {
 940                acp::PlanEntryStatus::Pending => {
 941                    stats.pending += 1;
 942                }
 943                acp::PlanEntryStatus::InProgress => {
 944                    stats.in_progress_entry = stats.in_progress_entry.or(Some(entry));
 945                    stats.pending += 1;
 946                }
 947                acp::PlanEntryStatus::Completed => {
 948                    stats.completed += 1;
 949                }
 950                _ => {}
 951            }
 952        }
 953
 954        stats
 955    }
 956}
 957
 958#[derive(Debug)]
 959pub struct PlanEntry {
 960    pub content: Entity<Markdown>,
 961    pub priority: acp::PlanEntryPriority,
 962    pub status: acp::PlanEntryStatus,
 963}
 964
 965impl PlanEntry {
 966    pub fn from_acp(entry: acp::PlanEntry, cx: &mut App) -> Self {
 967        Self {
 968            content: cx.new(|cx| Markdown::new(entry.content.into(), None, None, cx)),
 969            priority: entry.priority,
 970            status: entry.status,
 971        }
 972    }
 973}
 974
 975#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 976pub struct TokenUsage {
 977    pub max_tokens: u64,
 978    pub used_tokens: u64,
 979    pub input_tokens: u64,
 980    pub output_tokens: u64,
 981    pub max_output_tokens: Option<u64>,
 982}
 983
 984pub const TOKEN_USAGE_WARNING_THRESHOLD: f32 = 0.8;
 985
 986impl TokenUsage {
 987    pub fn ratio(&self) -> TokenUsageRatio {
 988        #[cfg(debug_assertions)]
 989        let warning_threshold: f32 = std::env::var("ZED_THREAD_WARNING_THRESHOLD")
 990            .unwrap_or(TOKEN_USAGE_WARNING_THRESHOLD.to_string())
 991            .parse()
 992            .unwrap();
 993        #[cfg(not(debug_assertions))]
 994        let warning_threshold: f32 = TOKEN_USAGE_WARNING_THRESHOLD;
 995
 996        // When the maximum is unknown because there is no selected model,
 997        // avoid showing the token limit warning.
 998        if self.max_tokens == 0 {
 999            TokenUsageRatio::Normal
1000        } else if self.used_tokens >= self.max_tokens {
1001            TokenUsageRatio::Exceeded
1002        } else if self.used_tokens as f32 / self.max_tokens as f32 >= warning_threshold {
1003            TokenUsageRatio::Warning
1004        } else {
1005            TokenUsageRatio::Normal
1006        }
1007    }
1008}
1009
1010#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
1011pub enum TokenUsageRatio {
1012    Normal,
1013    Warning,
1014    Exceeded,
1015}
1016
1017#[derive(Debug, Clone)]
1018pub struct RetryStatus {
1019    pub last_error: SharedString,
1020    pub attempt: usize,
1021    pub max_attempts: usize,
1022    pub started_at: Instant,
1023    pub duration: Duration,
1024}
1025
1026struct RunningTurn {
1027    id: u32,
1028    send_task: Task<()>,
1029}
1030
1031pub struct AcpThread {
1032    session_id: acp::SessionId,
1033    work_dirs: Option<PathList>,
1034    parent_session_id: Option<acp::SessionId>,
1035    title: Option<SharedString>,
1036    provisional_title: Option<SharedString>,
1037    entries: Vec<AgentThreadEntry>,
1038    plan: Plan,
1039    project: Entity<Project>,
1040    action_log: Entity<ActionLog>,
1041    shared_buffers: HashMap<Entity<Buffer>, BufferSnapshot>,
1042    turn_id: u32,
1043    running_turn: Option<RunningTurn>,
1044    connection: Rc<dyn AgentConnection>,
1045    token_usage: Option<TokenUsage>,
1046    prompt_capabilities: acp::PromptCapabilities,
1047    available_commands: Vec<acp::AvailableCommand>,
1048    _observe_prompt_capabilities: Task<anyhow::Result<()>>,
1049    terminals: HashMap<acp::TerminalId, Entity<Terminal>>,
1050    pending_terminal_output: HashMap<acp::TerminalId, Vec<Vec<u8>>>,
1051    pending_terminal_exit: HashMap<acp::TerminalId, acp::TerminalExitStatus>,
1052    had_error: bool,
1053    /// The user's unsent prompt text, persisted so it can be restored when reloading the thread.
1054    draft_prompt: Option<Vec<acp::ContentBlock>>,
1055    /// The initial scroll position for the thread view, set during session registration.
1056    ui_scroll_position: Option<gpui::ListOffset>,
1057    /// Buffer for smooth text streaming. Holds text that has been received from
1058    /// the model but not yet revealed in the UI. A timer task drains this buffer
1059    /// gradually to create a fluid typing effect instead of choppy chunk-at-a-time
1060    /// updates.
1061    streaming_text_buffer: Option<StreamingTextBuffer>,
1062}
1063
1064struct StreamingTextBuffer {
1065    /// Text received from the model but not yet appended to the Markdown source.
1066    pending: String,
1067    /// The number of bytes to reveal per timer turn.
1068    bytes_to_reveal_per_tick: usize,
1069    /// The Markdown entity being streamed into.
1070    target: Entity<Markdown>,
1071    /// Timer task that periodically moves text from `pending` into `source`.
1072    _reveal_task: Task<()>,
1073}
1074
1075impl StreamingTextBuffer {
1076    /// The number of milliseconds between each timer tick, controlling how quickly
1077    /// text is revealed.
1078    const TASK_UPDATE_MS: u64 = 16;
1079    /// The time in milliseconds to reveal the entire pending text.
1080    const REVEAL_TARGET: f32 = 200.0;
1081}
1082
1083impl From<&AcpThread> for ActionLogTelemetry {
1084    fn from(value: &AcpThread) -> Self {
1085        Self {
1086            agent_telemetry_id: value.connection().telemetry_id(),
1087            session_id: value.session_id.0.clone(),
1088        }
1089    }
1090}
1091
1092#[derive(Debug)]
1093pub enum AcpThreadEvent {
1094    NewEntry,
1095    TitleUpdated,
1096    TokenUsageUpdated,
1097    EntryUpdated(usize),
1098    EntriesRemoved(Range<usize>),
1099    ToolAuthorizationRequested(acp::ToolCallId),
1100    ToolAuthorizationReceived(acp::ToolCallId),
1101    Retry(RetryStatus),
1102    SubagentSpawned(acp::SessionId),
1103    Stopped(acp::StopReason),
1104    Error,
1105    LoadError(LoadError),
1106    PromptCapabilitiesUpdated,
1107    Refusal,
1108    AvailableCommandsUpdated(Vec<acp::AvailableCommand>),
1109    ModeUpdated(acp::SessionModeId),
1110    ConfigOptionsUpdated(Vec<acp::SessionConfigOption>),
1111    WorkingDirectoriesUpdated,
1112}
1113
1114impl EventEmitter<AcpThreadEvent> for AcpThread {}
1115
1116#[derive(Debug, Clone)]
1117pub enum TerminalProviderEvent {
1118    Created {
1119        terminal_id: acp::TerminalId,
1120        label: String,
1121        cwd: Option<PathBuf>,
1122        output_byte_limit: Option<u64>,
1123        terminal: Entity<::terminal::Terminal>,
1124    },
1125    Output {
1126        terminal_id: acp::TerminalId,
1127        data: Vec<u8>,
1128    },
1129    TitleChanged {
1130        terminal_id: acp::TerminalId,
1131        title: String,
1132    },
1133    Exit {
1134        terminal_id: acp::TerminalId,
1135        status: acp::TerminalExitStatus,
1136    },
1137}
1138
1139#[derive(Debug, Clone)]
1140pub enum TerminalProviderCommand {
1141    WriteInput {
1142        terminal_id: acp::TerminalId,
1143        bytes: Vec<u8>,
1144    },
1145    Resize {
1146        terminal_id: acp::TerminalId,
1147        cols: u16,
1148        rows: u16,
1149    },
1150    Close {
1151        terminal_id: acp::TerminalId,
1152    },
1153}
1154
1155#[derive(PartialEq, Eq, Debug)]
1156pub enum ThreadStatus {
1157    Idle,
1158    Generating,
1159}
1160
1161#[derive(Debug, Clone)]
1162pub enum LoadError {
1163    Unsupported {
1164        command: SharedString,
1165        current_version: SharedString,
1166        minimum_version: SharedString,
1167    },
1168    FailedToInstall(SharedString),
1169    Exited {
1170        status: ExitStatus,
1171    },
1172    Other(SharedString),
1173}
1174
1175impl Display for LoadError {
1176    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1177        match self {
1178            LoadError::Unsupported {
1179                command: path,
1180                current_version,
1181                minimum_version,
1182            } => {
1183                write!(
1184                    f,
1185                    "version {current_version} from {path} is not supported (need at least {minimum_version})"
1186                )
1187            }
1188            LoadError::FailedToInstall(msg) => write!(f, "Failed to install: {msg}"),
1189            LoadError::Exited { status } => write!(f, "Server exited with status {status}"),
1190            LoadError::Other(msg) => write!(f, "{msg}"),
1191        }
1192    }
1193}
1194
1195impl Error for LoadError {}
1196
1197impl AcpThread {
1198    pub fn new(
1199        parent_session_id: Option<acp::SessionId>,
1200        title: Option<SharedString>,
1201        work_dirs: Option<PathList>,
1202        connection: Rc<dyn AgentConnection>,
1203        project: Entity<Project>,
1204        action_log: Entity<ActionLog>,
1205        session_id: acp::SessionId,
1206        mut prompt_capabilities_rx: watch::Receiver<acp::PromptCapabilities>,
1207        cx: &mut Context<Self>,
1208    ) -> Self {
1209        let prompt_capabilities = prompt_capabilities_rx.borrow().clone();
1210        let task = cx.spawn::<_, anyhow::Result<()>>(async move |this, cx| {
1211            loop {
1212                let caps = prompt_capabilities_rx.recv().await?;
1213                this.update(cx, |this, cx| {
1214                    this.prompt_capabilities = caps;
1215                    cx.emit(AcpThreadEvent::PromptCapabilitiesUpdated);
1216                })?;
1217            }
1218        });
1219
1220        Self {
1221            parent_session_id,
1222            work_dirs,
1223            action_log,
1224            shared_buffers: Default::default(),
1225            entries: Default::default(),
1226            plan: Default::default(),
1227            title,
1228            provisional_title: None,
1229            project,
1230            running_turn: None,
1231            turn_id: 0,
1232            connection,
1233            session_id,
1234            token_usage: None,
1235            prompt_capabilities,
1236            available_commands: Vec::new(),
1237            _observe_prompt_capabilities: task,
1238            terminals: HashMap::default(),
1239            pending_terminal_output: HashMap::default(),
1240            pending_terminal_exit: HashMap::default(),
1241            had_error: false,
1242            draft_prompt: None,
1243            ui_scroll_position: None,
1244            streaming_text_buffer: None,
1245        }
1246    }
1247
1248    pub fn parent_session_id(&self) -> Option<&acp::SessionId> {
1249        self.parent_session_id.as_ref()
1250    }
1251
1252    pub fn prompt_capabilities(&self) -> acp::PromptCapabilities {
1253        self.prompt_capabilities.clone()
1254    }
1255
1256    pub fn available_commands(&self) -> &[acp::AvailableCommand] {
1257        &self.available_commands
1258    }
1259
1260    pub fn draft_prompt(&self) -> Option<&[acp::ContentBlock]> {
1261        self.draft_prompt.as_deref()
1262    }
1263
1264    pub fn set_draft_prompt(&mut self, prompt: Option<Vec<acp::ContentBlock>>) {
1265        self.draft_prompt = prompt;
1266    }
1267
1268    pub fn ui_scroll_position(&self) -> Option<gpui::ListOffset> {
1269        self.ui_scroll_position
1270    }
1271
1272    pub fn set_ui_scroll_position(&mut self, position: Option<gpui::ListOffset>) {
1273        self.ui_scroll_position = position;
1274    }
1275
1276    pub fn connection(&self) -> &Rc<dyn AgentConnection> {
1277        &self.connection
1278    }
1279
1280    pub fn action_log(&self) -> &Entity<ActionLog> {
1281        &self.action_log
1282    }
1283
1284    pub fn project(&self) -> &Entity<Project> {
1285        &self.project
1286    }
1287
1288    pub fn title(&self) -> Option<SharedString> {
1289        self.title
1290            .clone()
1291            .or_else(|| self.provisional_title.clone())
1292    }
1293
1294    pub fn has_provisional_title(&self) -> bool {
1295        self.provisional_title.is_some()
1296    }
1297
1298    pub fn entries(&self) -> &[AgentThreadEntry] {
1299        &self.entries
1300    }
1301
1302    pub fn session_id(&self) -> &acp::SessionId {
1303        &self.session_id
1304    }
1305
1306    pub fn work_dirs(&self) -> Option<&PathList> {
1307        self.work_dirs.as_ref()
1308    }
1309
1310    pub fn set_work_dirs(&mut self, work_dirs: PathList, cx: &mut Context<Self>) {
1311        self.work_dirs = Some(work_dirs);
1312        cx.emit(AcpThreadEvent::WorkingDirectoriesUpdated)
1313    }
1314
1315    pub fn status(&self) -> ThreadStatus {
1316        if self.running_turn.is_some() {
1317            ThreadStatus::Generating
1318        } else {
1319            ThreadStatus::Idle
1320        }
1321    }
1322
1323    pub fn had_error(&self) -> bool {
1324        self.had_error
1325    }
1326
1327    pub fn is_waiting_for_confirmation(&self) -> bool {
1328        for entry in self.entries.iter().rev() {
1329            match entry {
1330                AgentThreadEntry::UserMessage(_) => return false,
1331                AgentThreadEntry::ToolCall(ToolCall {
1332                    status: ToolCallStatus::WaitingForConfirmation { .. },
1333                    ..
1334                }) => return true,
1335                AgentThreadEntry::ToolCall(_)
1336                | AgentThreadEntry::AssistantMessage(_)
1337                | AgentThreadEntry::CompletedPlan(_) => {}
1338            }
1339        }
1340        false
1341    }
1342
1343    pub fn token_usage(&self) -> Option<&TokenUsage> {
1344        self.token_usage.as_ref()
1345    }
1346
1347    pub fn has_pending_edit_tool_calls(&self) -> bool {
1348        for entry in self.entries.iter().rev() {
1349            match entry {
1350                AgentThreadEntry::UserMessage(_) => return false,
1351                AgentThreadEntry::ToolCall(
1352                    call @ ToolCall {
1353                        status: ToolCallStatus::InProgress | ToolCallStatus::Pending,
1354                        ..
1355                    },
1356                ) if call.diffs().next().is_some() => {
1357                    return true;
1358                }
1359                AgentThreadEntry::ToolCall(_)
1360                | AgentThreadEntry::AssistantMessage(_)
1361                | AgentThreadEntry::CompletedPlan(_) => {}
1362            }
1363        }
1364
1365        false
1366    }
1367
1368    pub fn has_in_progress_tool_calls(&self) -> bool {
1369        for entry in self.entries.iter().rev() {
1370            match entry {
1371                AgentThreadEntry::UserMessage(_) => return false,
1372                AgentThreadEntry::ToolCall(ToolCall {
1373                    status: ToolCallStatus::InProgress | ToolCallStatus::Pending,
1374                    ..
1375                }) => {
1376                    return true;
1377                }
1378                AgentThreadEntry::ToolCall(_)
1379                | AgentThreadEntry::AssistantMessage(_)
1380                | AgentThreadEntry::CompletedPlan(_) => {}
1381            }
1382        }
1383
1384        false
1385    }
1386
1387    pub fn used_tools_since_last_user_message(&self) -> bool {
1388        for entry in self.entries.iter().rev() {
1389            match entry {
1390                AgentThreadEntry::UserMessage(..) => return false,
1391                AgentThreadEntry::AssistantMessage(..) | AgentThreadEntry::CompletedPlan(..) => {
1392                    continue;
1393                }
1394                AgentThreadEntry::ToolCall(..) => return true,
1395            }
1396        }
1397
1398        false
1399    }
1400
1401    pub fn handle_session_update(
1402        &mut self,
1403        update: acp::SessionUpdate,
1404        cx: &mut Context<Self>,
1405    ) -> Result<(), acp::Error> {
1406        match update {
1407            acp::SessionUpdate::UserMessageChunk(acp::ContentChunk { content, .. }) => {
1408                // We optimistically add the full user prompt before calling `prompt`.
1409                // Some ACP servers echo user chunks back over updates. Skip the chunk if
1410                // it's already present in the current user message to avoid duplicating content.
1411                let already_in_user_message = self
1412                    .entries
1413                    .last()
1414                    .and_then(|entry| entry.user_message())
1415                    .is_some_and(|message| message.chunks.contains(&content));
1416                if !already_in_user_message {
1417                    self.push_user_content_block(None, content, cx);
1418                }
1419            }
1420            acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk { content, .. }) => {
1421                self.push_assistant_content_block(content, false, cx);
1422            }
1423            acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk { content, .. }) => {
1424                self.push_assistant_content_block(content, true, cx);
1425            }
1426            acp::SessionUpdate::ToolCall(tool_call) => {
1427                self.upsert_tool_call(tool_call, cx)?;
1428            }
1429            acp::SessionUpdate::ToolCallUpdate(tool_call_update) => {
1430                self.update_tool_call(tool_call_update, cx)?;
1431            }
1432            acp::SessionUpdate::Plan(plan) => {
1433                self.update_plan(plan, cx);
1434            }
1435            acp::SessionUpdate::SessionInfoUpdate(info_update) => {
1436                if let acp::MaybeUndefined::Value(title) = info_update.title {
1437                    let had_provisional = self.provisional_title.take().is_some();
1438                    let title: SharedString = title.into();
1439                    if self.title.as_ref() != Some(&title) {
1440                        self.title = Some(title);
1441                        cx.emit(AcpThreadEvent::TitleUpdated);
1442                    } else if had_provisional {
1443                        cx.emit(AcpThreadEvent::TitleUpdated);
1444                    }
1445                }
1446            }
1447            acp::SessionUpdate::AvailableCommandsUpdate(acp::AvailableCommandsUpdate {
1448                available_commands,
1449                ..
1450            }) => {
1451                self.available_commands = available_commands.clone();
1452                cx.emit(AcpThreadEvent::AvailableCommandsUpdated(available_commands));
1453            }
1454            acp::SessionUpdate::CurrentModeUpdate(acp::CurrentModeUpdate {
1455                current_mode_id,
1456                ..
1457            }) => cx.emit(AcpThreadEvent::ModeUpdated(current_mode_id)),
1458            acp::SessionUpdate::ConfigOptionUpdate(acp::ConfigOptionUpdate {
1459                config_options,
1460                ..
1461            }) => cx.emit(AcpThreadEvent::ConfigOptionsUpdated(config_options)),
1462            _ => {}
1463        }
1464        Ok(())
1465    }
1466
1467    pub fn push_user_content_block(
1468        &mut self,
1469        message_id: Option<UserMessageId>,
1470        chunk: acp::ContentBlock,
1471        cx: &mut Context<Self>,
1472    ) {
1473        self.push_user_content_block_with_indent(message_id, chunk, false, cx)
1474    }
1475
1476    pub fn push_user_content_block_with_indent(
1477        &mut self,
1478        message_id: Option<UserMessageId>,
1479        chunk: acp::ContentBlock,
1480        indented: bool,
1481        cx: &mut Context<Self>,
1482    ) {
1483        let language_registry = self.project.read(cx).languages().clone();
1484        let path_style = self.project.read(cx).path_style(cx);
1485        let entries_len = self.entries.len();
1486
1487        if let Some(last_entry) = self.entries.last_mut()
1488            && let AgentThreadEntry::UserMessage(UserMessage {
1489                id,
1490                content,
1491                chunks,
1492                indented: existing_indented,
1493                ..
1494            }) = last_entry
1495            && *existing_indented == indented
1496        {
1497            Self::flush_streaming_text(&mut self.streaming_text_buffer, cx);
1498            *id = message_id.or(id.take());
1499            content.append(chunk.clone(), &language_registry, path_style, cx);
1500            chunks.push(chunk);
1501            let idx = entries_len - 1;
1502            cx.emit(AcpThreadEvent::EntryUpdated(idx));
1503        } else {
1504            let content = ContentBlock::new(chunk.clone(), &language_registry, path_style, cx);
1505            self.push_entry(
1506                AgentThreadEntry::UserMessage(UserMessage {
1507                    id: message_id,
1508                    content,
1509                    chunks: vec![chunk],
1510                    checkpoint: None,
1511                    indented,
1512                }),
1513                cx,
1514            );
1515        }
1516    }
1517
1518    pub fn push_assistant_content_block(
1519        &mut self,
1520        chunk: acp::ContentBlock,
1521        is_thought: bool,
1522        cx: &mut Context<Self>,
1523    ) {
1524        self.push_assistant_content_block_with_indent(chunk, is_thought, false, cx)
1525    }
1526
1527    pub fn push_assistant_content_block_with_indent(
1528        &mut self,
1529        chunk: acp::ContentBlock,
1530        is_thought: bool,
1531        indented: bool,
1532        cx: &mut Context<Self>,
1533    ) {
1534        let path_style = self.project.read(cx).path_style(cx);
1535
1536        // For text chunks going to an existing Markdown block, buffer for smooth
1537        // streaming instead of appending all at once which may feel more choppy.
1538        if let acp::ContentBlock::Text(text_content) = &chunk {
1539            if let Some(markdown) = self.streaming_markdown_target(is_thought, indented) {
1540                let entries_len = self.entries.len();
1541                cx.emit(AcpThreadEvent::EntryUpdated(entries_len - 1));
1542                self.buffer_streaming_text(&markdown, text_content.text.clone(), cx);
1543                return;
1544            }
1545        }
1546
1547        let language_registry = self.project.read(cx).languages().clone();
1548        let entries_len = self.entries.len();
1549        if let Some(last_entry) = self.entries.last_mut()
1550            && let AgentThreadEntry::AssistantMessage(AssistantMessage {
1551                chunks,
1552                indented: existing_indented,
1553                is_subagent_output: _,
1554            }) = last_entry
1555            && *existing_indented == indented
1556        {
1557            let idx = entries_len - 1;
1558            Self::flush_streaming_text(&mut self.streaming_text_buffer, cx);
1559            cx.emit(AcpThreadEvent::EntryUpdated(idx));
1560            match (chunks.last_mut(), is_thought) {
1561                (Some(AssistantMessageChunk::Message { block }), false)
1562                | (Some(AssistantMessageChunk::Thought { block }), true) => {
1563                    block.append(chunk, &language_registry, path_style, cx)
1564                }
1565                _ => {
1566                    let block = ContentBlock::new(chunk, &language_registry, path_style, cx);
1567                    if is_thought {
1568                        chunks.push(AssistantMessageChunk::Thought { block })
1569                    } else {
1570                        chunks.push(AssistantMessageChunk::Message { block })
1571                    }
1572                }
1573            }
1574        } else {
1575            let block = ContentBlock::new(chunk, &language_registry, path_style, cx);
1576            let chunk = if is_thought {
1577                AssistantMessageChunk::Thought { block }
1578            } else {
1579                AssistantMessageChunk::Message { block }
1580            };
1581
1582            self.push_entry(
1583                AgentThreadEntry::AssistantMessage(AssistantMessage {
1584                    chunks: vec![chunk],
1585                    indented,
1586                    is_subagent_output: false,
1587                }),
1588                cx,
1589            );
1590        }
1591    }
1592
1593    fn streaming_markdown_target(
1594        &self,
1595        is_thought: bool,
1596        indented: bool,
1597    ) -> Option<Entity<Markdown>> {
1598        let last_entry = self.entries.last()?;
1599        if let AgentThreadEntry::AssistantMessage(AssistantMessage {
1600            chunks,
1601            indented: existing_indented,
1602            ..
1603        }) = last_entry
1604            && *existing_indented == indented
1605            && let [.., chunk] = chunks.as_slice()
1606        {
1607            match (chunk, is_thought) {
1608                (
1609                    AssistantMessageChunk::Message {
1610                        block: ContentBlock::Markdown { markdown },
1611                    },
1612                    false,
1613                )
1614                | (
1615                    AssistantMessageChunk::Thought {
1616                        block: ContentBlock::Markdown { markdown },
1617                    },
1618                    true,
1619                ) => Some(markdown.clone()),
1620                _ => None,
1621            }
1622        } else {
1623            None
1624        }
1625    }
1626
1627    /// Add text to the streaming buffer. If the target changed (e.g. switching
1628    /// from thoughts to message text), flush the old buffer first.
1629    fn buffer_streaming_text(
1630        &mut self,
1631        markdown: &Entity<Markdown>,
1632        text: String,
1633        cx: &mut Context<Self>,
1634    ) {
1635        if let Some(buffer) = &mut self.streaming_text_buffer {
1636            if buffer.target.entity_id() == markdown.entity_id() {
1637                buffer.pending.push_str(&text);
1638
1639                buffer.bytes_to_reveal_per_tick = (buffer.pending.len() as f32
1640                    / StreamingTextBuffer::REVEAL_TARGET
1641                    * StreamingTextBuffer::TASK_UPDATE_MS as f32)
1642                    .ceil() as usize;
1643                return;
1644            }
1645            Self::flush_streaming_text(&mut self.streaming_text_buffer, cx);
1646        }
1647
1648        let target = markdown.clone();
1649        let _reveal_task = self.start_streaming_reveal(cx);
1650        let pending_len = text.len();
1651        let bytes_to_reveal = (pending_len as f32 / StreamingTextBuffer::REVEAL_TARGET
1652            * StreamingTextBuffer::TASK_UPDATE_MS as f32)
1653            .ceil() as usize;
1654        self.streaming_text_buffer = Some(StreamingTextBuffer {
1655            pending: text,
1656            bytes_to_reveal_per_tick: bytes_to_reveal,
1657            target,
1658            _reveal_task,
1659        });
1660    }
1661
1662    /// Flush all buffered streaming text into the Markdown entity immediately.
1663    fn flush_streaming_text(
1664        streaming_text_buffer: &mut Option<StreamingTextBuffer>,
1665        cx: &mut Context<Self>,
1666    ) {
1667        if let Some(buffer) = streaming_text_buffer.take() {
1668            if !buffer.pending.is_empty() {
1669                buffer
1670                    .target
1671                    .update(cx, |markdown, cx| markdown.append(&buffer.pending, cx));
1672            }
1673        }
1674    }
1675
1676    /// Spawns a foreground task that periodically drains
1677    /// `streaming_text_buffer.pending` into the target `Markdown` entity,
1678    /// producing smooth, continuous text output.
1679    fn start_streaming_reveal(&self, cx: &mut Context<Self>) -> Task<()> {
1680        cx.spawn(async move |this, cx| {
1681            loop {
1682                cx.background_executor()
1683                    .timer(Duration::from_millis(StreamingTextBuffer::TASK_UPDATE_MS))
1684                    .await;
1685
1686                let should_continue = this
1687                    .update(cx, |this, cx| {
1688                        let Some(buffer) = &mut this.streaming_text_buffer else {
1689                            return false;
1690                        };
1691
1692                        if buffer.pending.is_empty() {
1693                            return true;
1694                        }
1695
1696                        let pending_len = buffer.pending.len();
1697
1698                        let byte_boundary = buffer
1699                            .pending
1700                            .ceil_char_boundary(buffer.bytes_to_reveal_per_tick)
1701                            .min(pending_len);
1702
1703                        buffer.target.update(cx, |markdown: &mut Markdown, cx| {
1704                            markdown.append(&buffer.pending[..byte_boundary], cx);
1705                            buffer.pending.drain(..byte_boundary);
1706                        });
1707
1708                        true
1709                    })
1710                    .unwrap_or(false);
1711
1712                if !should_continue {
1713                    break;
1714                }
1715            }
1716        })
1717    }
1718
1719    fn push_entry(&mut self, entry: AgentThreadEntry, cx: &mut Context<Self>) {
1720        Self::flush_streaming_text(&mut self.streaming_text_buffer, cx);
1721        self.entries.push(entry);
1722        cx.emit(AcpThreadEvent::NewEntry);
1723    }
1724
1725    pub fn can_set_title(&mut self, cx: &mut Context<Self>) -> bool {
1726        self.connection.set_title(&self.session_id, cx).is_some()
1727    }
1728
1729    pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) -> Task<Result<()>> {
1730        let had_provisional = self.provisional_title.take().is_some();
1731        if self.title.as_ref() != Some(&title) {
1732            self.title = Some(title.clone());
1733            cx.emit(AcpThreadEvent::TitleUpdated);
1734            if let Some(set_title) = self.connection.set_title(&self.session_id, cx) {
1735                return set_title.run(title, cx);
1736            }
1737        } else if had_provisional {
1738            cx.emit(AcpThreadEvent::TitleUpdated);
1739        }
1740        Task::ready(Ok(()))
1741    }
1742
1743    /// Sets a provisional display title without propagating back to the
1744    /// underlying agent connection. This is used for quick preview titles
1745    /// (e.g. first 20 chars of the user message) that should be shown
1746    /// immediately but replaced once the LLM generates a proper title via
1747    /// `set_title`.
1748    pub fn set_provisional_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
1749        self.provisional_title = Some(title);
1750        cx.emit(AcpThreadEvent::TitleUpdated);
1751    }
1752
1753    pub fn subagent_spawned(&mut self, session_id: acp::SessionId, cx: &mut Context<Self>) {
1754        cx.emit(AcpThreadEvent::SubagentSpawned(session_id));
1755    }
1756
1757    pub fn update_token_usage(&mut self, usage: Option<TokenUsage>, cx: &mut Context<Self>) {
1758        self.token_usage = usage;
1759        cx.emit(AcpThreadEvent::TokenUsageUpdated);
1760    }
1761
1762    pub fn update_retry_status(&mut self, status: RetryStatus, cx: &mut Context<Self>) {
1763        cx.emit(AcpThreadEvent::Retry(status));
1764    }
1765
1766    pub fn update_tool_call(
1767        &mut self,
1768        update: impl Into<ToolCallUpdate>,
1769        cx: &mut Context<Self>,
1770    ) -> Result<()> {
1771        let update = update.into();
1772        let languages = self.project.read(cx).languages().clone();
1773        let path_style = self.project.read(cx).path_style(cx);
1774
1775        let ix = match self.index_for_tool_call(update.id()) {
1776            Some(ix) => ix,
1777            None => {
1778                // Tool call not found - create a failed tool call entry
1779                let failed_tool_call = ToolCall {
1780                    id: update.id().clone(),
1781                    label: cx.new(|cx| Markdown::new("Tool call not found".into(), None, None, cx)),
1782                    kind: acp::ToolKind::Fetch,
1783                    content: vec![ToolCallContent::ContentBlock(ContentBlock::new(
1784                        "Tool call not found".into(),
1785                        &languages,
1786                        path_style,
1787                        cx,
1788                    ))],
1789                    status: ToolCallStatus::Failed,
1790                    locations: Vec::new(),
1791                    resolved_locations: Vec::new(),
1792                    raw_input: None,
1793                    raw_input_markdown: None,
1794                    raw_output: None,
1795                    tool_name: None,
1796                    subagent_session_info: None,
1797                };
1798                self.push_entry(AgentThreadEntry::ToolCall(failed_tool_call), cx);
1799                return Ok(());
1800            }
1801        };
1802        let AgentThreadEntry::ToolCall(call) = &mut self.entries[ix] else {
1803            unreachable!()
1804        };
1805
1806        match update {
1807            ToolCallUpdate::UpdateFields(update) => {
1808                let location_updated = update.fields.locations.is_some();
1809                call.update_fields(
1810                    update.fields,
1811                    update.meta,
1812                    languages,
1813                    path_style,
1814                    &self.terminals,
1815                    cx,
1816                )?;
1817                if location_updated {
1818                    self.resolve_locations(update.tool_call_id, cx);
1819                }
1820            }
1821            ToolCallUpdate::UpdateDiff(update) => {
1822                call.content.clear();
1823                call.content.push(ToolCallContent::Diff(update.diff));
1824            }
1825            ToolCallUpdate::UpdateTerminal(update) => {
1826                call.content.clear();
1827                call.content
1828                    .push(ToolCallContent::Terminal(update.terminal));
1829            }
1830        }
1831
1832        cx.emit(AcpThreadEvent::EntryUpdated(ix));
1833
1834        Ok(())
1835    }
1836
1837    /// Updates a tool call if id matches an existing entry, otherwise inserts a new one.
1838    pub fn upsert_tool_call(
1839        &mut self,
1840        tool_call: acp::ToolCall,
1841        cx: &mut Context<Self>,
1842    ) -> Result<(), acp::Error> {
1843        let status = tool_call.status.into();
1844        self.upsert_tool_call_inner(tool_call.into(), status, cx)
1845    }
1846
1847    /// Fails if id does not match an existing entry.
1848    pub fn upsert_tool_call_inner(
1849        &mut self,
1850        update: acp::ToolCallUpdate,
1851        status: ToolCallStatus,
1852        cx: &mut Context<Self>,
1853    ) -> Result<(), acp::Error> {
1854        let language_registry = self.project.read(cx).languages().clone();
1855        let path_style = self.project.read(cx).path_style(cx);
1856        let id = update.tool_call_id.clone();
1857
1858        let agent_telemetry_id = self.connection().telemetry_id();
1859        let session = self.session_id();
1860        let parent_session_id = self.parent_session_id();
1861        if let ToolCallStatus::Completed | ToolCallStatus::Failed = status {
1862            let status = if matches!(status, ToolCallStatus::Completed) {
1863                "completed"
1864            } else {
1865                "failed"
1866            };
1867            telemetry::event!(
1868                "Agent Tool Call Completed",
1869                agent_telemetry_id,
1870                session,
1871                parent_session_id,
1872                status
1873            );
1874        }
1875
1876        if let Some(ix) = self.index_for_tool_call(&id) {
1877            let AgentThreadEntry::ToolCall(call) = &mut self.entries[ix] else {
1878                unreachable!()
1879            };
1880
1881            call.update_fields(
1882                update.fields,
1883                update.meta,
1884                language_registry,
1885                path_style,
1886                &self.terminals,
1887                cx,
1888            )?;
1889            call.status = status;
1890
1891            cx.emit(AcpThreadEvent::EntryUpdated(ix));
1892        } else {
1893            let call = ToolCall::from_acp(
1894                update.try_into()?,
1895                status,
1896                language_registry,
1897                self.project.read(cx).path_style(cx),
1898                &self.terminals,
1899                cx,
1900            )?;
1901            self.push_entry(AgentThreadEntry::ToolCall(call), cx);
1902        };
1903
1904        self.resolve_locations(id, cx);
1905        Ok(())
1906    }
1907
1908    fn index_for_tool_call(&self, id: &acp::ToolCallId) -> Option<usize> {
1909        self.entries
1910            .iter()
1911            .enumerate()
1912            .rev()
1913            .find_map(|(index, entry)| {
1914                if let AgentThreadEntry::ToolCall(tool_call) = entry
1915                    && &tool_call.id == id
1916                {
1917                    Some(index)
1918                } else {
1919                    None
1920                }
1921            })
1922    }
1923
1924    fn tool_call_mut(&mut self, id: &acp::ToolCallId) -> Option<(usize, &mut ToolCall)> {
1925        // The tool call we are looking for is typically the last one, or very close to the end.
1926        // At the moment, it doesn't seem like a hashmap would be a good fit for this use case.
1927        self.entries
1928            .iter_mut()
1929            .enumerate()
1930            .rev()
1931            .find_map(|(index, tool_call)| {
1932                if let AgentThreadEntry::ToolCall(tool_call) = tool_call
1933                    && &tool_call.id == id
1934                {
1935                    Some((index, tool_call))
1936                } else {
1937                    None
1938                }
1939            })
1940    }
1941
1942    pub fn tool_call(&self, id: &acp::ToolCallId) -> Option<(usize, &ToolCall)> {
1943        self.entries
1944            .iter()
1945            .enumerate()
1946            .rev()
1947            .find_map(|(index, tool_call)| {
1948                if let AgentThreadEntry::ToolCall(tool_call) = tool_call
1949                    && &tool_call.id == id
1950                {
1951                    Some((index, tool_call))
1952                } else {
1953                    None
1954                }
1955            })
1956    }
1957
1958    pub fn tool_call_for_subagent(&self, session_id: &acp::SessionId) -> Option<&ToolCall> {
1959        self.entries.iter().find_map(|entry| match entry {
1960            AgentThreadEntry::ToolCall(tool_call) => {
1961                if let Some(subagent_session_info) = &tool_call.subagent_session_info
1962                    && &subagent_session_info.session_id == session_id
1963                {
1964                    Some(tool_call)
1965                } else {
1966                    None
1967                }
1968            }
1969            _ => None,
1970        })
1971    }
1972
1973    pub fn resolve_locations(&mut self, id: acp::ToolCallId, cx: &mut Context<Self>) {
1974        let project = self.project.clone();
1975        let should_update_agent_location = self.parent_session_id.is_none();
1976        let Some((_, tool_call)) = self.tool_call_mut(&id) else {
1977            return;
1978        };
1979        let task = tool_call.resolve_locations(project, cx);
1980        cx.spawn(async move |this, cx| {
1981            let resolved_locations = task.await;
1982
1983            this.update(cx, |this, cx| {
1984                let project = this.project.clone();
1985
1986                for location in resolved_locations.iter().flatten() {
1987                    this.shared_buffers
1988                        .insert(location.buffer.clone(), location.buffer.read(cx).snapshot());
1989                }
1990                let Some((ix, tool_call)) = this.tool_call_mut(&id) else {
1991                    return;
1992                };
1993
1994                if let Some(Some(location)) = resolved_locations.last() {
1995                    project.update(cx, |project, cx| {
1996                        let should_ignore = if let Some(agent_location) = project
1997                            .agent_location()
1998                            .filter(|agent_location| agent_location.buffer == location.buffer)
1999                        {
2000                            let snapshot = location.buffer.read(cx).snapshot();
2001                            let old_position = agent_location.position.to_point(&snapshot);
2002                            let new_position = location.position.to_point(&snapshot);
2003
2004                            // ignore this so that when we get updates from the edit tool
2005                            // the position doesn't reset to the startof line
2006                            old_position.row == new_position.row
2007                                && old_position.column > new_position.column
2008                        } else {
2009                            false
2010                        };
2011                        if !should_ignore && should_update_agent_location {
2012                            project.set_agent_location(Some(location.into()), cx);
2013                        }
2014                    });
2015                }
2016
2017                let resolved_locations = resolved_locations
2018                    .iter()
2019                    .map(|l| l.as_ref().map(|l| AgentLocation::from(l)))
2020                    .collect::<Vec<_>>();
2021
2022                if tool_call.resolved_locations != resolved_locations {
2023                    tool_call.resolved_locations = resolved_locations;
2024                    cx.emit(AcpThreadEvent::EntryUpdated(ix));
2025                }
2026            })
2027        })
2028        .detach();
2029    }
2030
2031    pub fn request_tool_call_authorization(
2032        &mut self,
2033        tool_call: acp::ToolCallUpdate,
2034        options: PermissionOptions,
2035        cx: &mut Context<Self>,
2036    ) -> Result<Task<RequestPermissionOutcome>> {
2037        let (tx, rx) = oneshot::channel();
2038
2039        let status = ToolCallStatus::WaitingForConfirmation {
2040            options,
2041            respond_tx: tx,
2042        };
2043
2044        let tool_call_id = tool_call.tool_call_id.clone();
2045        self.upsert_tool_call_inner(tool_call, status, cx)?;
2046        cx.emit(AcpThreadEvent::ToolAuthorizationRequested(
2047            tool_call_id.clone(),
2048        ));
2049
2050        Ok(cx.spawn(async move |this, cx| {
2051            let outcome = match rx.await {
2052                Ok(outcome) => RequestPermissionOutcome::Selected(outcome),
2053                Err(oneshot::Canceled) => RequestPermissionOutcome::Cancelled,
2054            };
2055            this.update(cx, |_this, cx| {
2056                cx.emit(AcpThreadEvent::ToolAuthorizationReceived(tool_call_id))
2057            })
2058            .ok();
2059            outcome
2060        }))
2061    }
2062
2063    pub fn authorize_tool_call(
2064        &mut self,
2065        id: acp::ToolCallId,
2066        outcome: SelectedPermissionOutcome,
2067        cx: &mut Context<Self>,
2068    ) {
2069        let Some((ix, call)) = self.tool_call_mut(&id) else {
2070            return;
2071        };
2072
2073        let new_status = match outcome.option_kind {
2074            acp::PermissionOptionKind::RejectOnce | acp::PermissionOptionKind::RejectAlways => {
2075                ToolCallStatus::Rejected
2076            }
2077            acp::PermissionOptionKind::AllowOnce | acp::PermissionOptionKind::AllowAlways => {
2078                ToolCallStatus::InProgress
2079            }
2080            _ => ToolCallStatus::InProgress,
2081        };
2082
2083        let curr_status = mem::replace(&mut call.status, new_status);
2084
2085        if let ToolCallStatus::WaitingForConfirmation { respond_tx, .. } = curr_status {
2086            respond_tx.send(outcome).log_err();
2087        } else if cfg!(debug_assertions) {
2088            panic!("tried to authorize an already authorized tool call");
2089        }
2090
2091        cx.emit(AcpThreadEvent::EntryUpdated(ix));
2092    }
2093
2094    pub fn plan(&self) -> &Plan {
2095        &self.plan
2096    }
2097
2098    pub fn update_plan(&mut self, request: acp::Plan, cx: &mut Context<Self>) {
2099        let new_entries_len = request.entries.len();
2100        let mut new_entries = request.entries.into_iter();
2101
2102        // Reuse existing markdown to prevent flickering
2103        for (old, new) in self.plan.entries.iter_mut().zip(new_entries.by_ref()) {
2104            let PlanEntry {
2105                content,
2106                priority,
2107                status,
2108            } = old;
2109            content.update(cx, |old, cx| {
2110                old.replace(new.content, cx);
2111            });
2112            *priority = new.priority;
2113            *status = new.status;
2114        }
2115        for new in new_entries {
2116            self.plan.entries.push(PlanEntry::from_acp(new, cx))
2117        }
2118        self.plan.entries.truncate(new_entries_len);
2119
2120        cx.notify();
2121    }
2122
2123    pub fn snapshot_completed_plan(&mut self, cx: &mut Context<Self>) {
2124        if !self.plan.is_empty() && self.plan.stats().pending == 0 {
2125            let completed_entries = std::mem::take(&mut self.plan.entries);
2126            self.push_entry(AgentThreadEntry::CompletedPlan(completed_entries), cx);
2127        }
2128    }
2129
2130    fn clear_completed_plan_entries(&mut self, cx: &mut Context<Self>) {
2131        self.plan
2132            .entries
2133            .retain(|entry| !matches!(entry.status, acp::PlanEntryStatus::Completed));
2134        cx.notify();
2135    }
2136
2137    pub fn clear_plan(&mut self, cx: &mut Context<Self>) {
2138        self.plan.entries.clear();
2139        cx.notify();
2140    }
2141
2142    #[cfg(any(test, feature = "test-support"))]
2143    pub fn send_raw(
2144        &mut self,
2145        message: &str,
2146        cx: &mut Context<Self>,
2147    ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
2148        self.send(vec![message.into()], cx)
2149    }
2150
2151    pub fn send(
2152        &mut self,
2153        message: Vec<acp::ContentBlock>,
2154        cx: &mut Context<Self>,
2155    ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
2156        let block = ContentBlock::new_combined(
2157            message.clone(),
2158            self.project.read(cx).languages().clone(),
2159            self.project.read(cx).path_style(cx),
2160            cx,
2161        );
2162        let request = acp::PromptRequest::new(self.session_id.clone(), message.clone());
2163        let git_store = self.project.read(cx).git_store().clone();
2164
2165        let message_id = if self.connection.truncate(&self.session_id, cx).is_some() {
2166            Some(UserMessageId::new())
2167        } else {
2168            None
2169        };
2170
2171        self.run_turn(cx, async move |this, cx| {
2172            this.update(cx, |this, cx| {
2173                this.push_entry(
2174                    AgentThreadEntry::UserMessage(UserMessage {
2175                        id: message_id.clone(),
2176                        content: block,
2177                        chunks: message,
2178                        checkpoint: None,
2179                        indented: false,
2180                    }),
2181                    cx,
2182                );
2183            })
2184            .ok();
2185
2186            let old_checkpoint = git_store
2187                .update(cx, |git, cx| git.checkpoint(cx))
2188                .await
2189                .context("failed to get old checkpoint")
2190                .log_err();
2191            this.update(cx, |this, cx| {
2192                if let Some((_ix, message)) = this.last_user_message() {
2193                    message.checkpoint = old_checkpoint.map(|git_checkpoint| Checkpoint {
2194                        git_checkpoint,
2195                        show: false,
2196                    });
2197                }
2198                this.connection.prompt(message_id, request, cx)
2199            })?
2200            .await
2201        })
2202    }
2203
2204    pub fn can_retry(&self, cx: &App) -> bool {
2205        self.connection.retry(&self.session_id, cx).is_some()
2206    }
2207
2208    pub fn retry(
2209        &mut self,
2210        cx: &mut Context<Self>,
2211    ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
2212        self.run_turn(cx, async move |this, cx| {
2213            this.update(cx, |this, cx| {
2214                this.connection
2215                    .retry(&this.session_id, cx)
2216                    .map(|retry| retry.run(cx))
2217            })?
2218            .context("retrying a session is not supported")?
2219            .await
2220        })
2221    }
2222
2223    fn run_turn(
2224        &mut self,
2225        cx: &mut Context<Self>,
2226        f: impl 'static + AsyncFnOnce(WeakEntity<Self>, &mut AsyncApp) -> Result<acp::PromptResponse>,
2227    ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
2228        self.clear_completed_plan_entries(cx);
2229        self.had_error = false;
2230
2231        let (tx, rx) = oneshot::channel();
2232        let cancel_task = self.cancel(cx);
2233
2234        self.turn_id += 1;
2235        let turn_id = self.turn_id;
2236        self.running_turn = Some(RunningTurn {
2237            id: turn_id,
2238            send_task: cx.spawn(async move |this, cx| {
2239                cancel_task.await;
2240                tx.send(f(this, cx).await).ok();
2241            }),
2242        });
2243
2244        cx.spawn(async move |this, cx| {
2245            let response = rx.await;
2246
2247            this.update(cx, |this, cx| this.update_last_checkpoint(cx))?
2248                .await?;
2249
2250            this.update(cx, |this, cx| {
2251                if this.parent_session_id.is_none() {
2252                    this.project
2253                        .update(cx, |project, cx| project.set_agent_location(None, cx));
2254                }
2255                let Ok(response) = response else {
2256                    // tx dropped, just return
2257                    return Ok(None);
2258                };
2259
2260                let is_same_turn = this
2261                    .running_turn
2262                    .as_ref()
2263                    .is_some_and(|turn| turn_id == turn.id);
2264
2265                // If the user submitted a follow up message, running_turn might
2266                // already point to a different turn. Therefore we only want to
2267                // take the task if it's the same turn.
2268                if is_same_turn {
2269                    this.running_turn.take();
2270                }
2271
2272                match response {
2273                    Ok(r) => {
2274                        Self::flush_streaming_text(&mut this.streaming_text_buffer, cx);
2275
2276                        if r.stop_reason == acp::StopReason::MaxTokens {
2277                            this.had_error = true;
2278                            cx.emit(AcpThreadEvent::Error);
2279                            log::error!("Max tokens reached. Usage: {:?}", this.token_usage);
2280
2281                            let exceeded_max_output_tokens =
2282                                this.token_usage.as_ref().is_some_and(|u| {
2283                                    u.max_output_tokens
2284                                        .is_some_and(|max| u.output_tokens >= max)
2285                                });
2286
2287                            if exceeded_max_output_tokens {
2288                                log::error!(
2289                                    "Max output tokens reached. Usage: {:?}",
2290                                    this.token_usage
2291                                );
2292                            } else {
2293                                log::error!("Max tokens reached. Usage: {:?}", this.token_usage);
2294                            }
2295                            return Err(anyhow!(MaxOutputTokensError));
2296                        }
2297
2298                        let canceled = matches!(r.stop_reason, acp::StopReason::Cancelled);
2299                        if canceled {
2300                            this.mark_pending_tools_as_canceled();
2301                        }
2302
2303                        if !canceled {
2304                            this.snapshot_completed_plan(cx);
2305                        }
2306
2307                        // Handle refusal - distinguish between user prompt and tool call refusals
2308                        if let acp::StopReason::Refusal = r.stop_reason {
2309                            this.had_error = true;
2310                            if let Some((user_msg_ix, _)) = this.last_user_message() {
2311                                // Check if there's a completed tool call with results after the last user message
2312                                // This indicates the refusal is in response to tool output, not the user's prompt
2313                                let has_completed_tool_call_after_user_msg =
2314                                    this.entries.iter().skip(user_msg_ix + 1).any(|entry| {
2315                                        if let AgentThreadEntry::ToolCall(tool_call) = entry {
2316                                            // Check if the tool call has completed and has output
2317                                            matches!(tool_call.status, ToolCallStatus::Completed)
2318                                                && tool_call.raw_output.is_some()
2319                                        } else {
2320                                            false
2321                                        }
2322                                    });
2323
2324                                if has_completed_tool_call_after_user_msg {
2325                                    // Refusal is due to tool output - don't truncate, just notify
2326                                    // The model refused based on what the tool returned
2327                                    cx.emit(AcpThreadEvent::Refusal);
2328                                } else {
2329                                    // User prompt was refused - truncate back to before the user message
2330                                    let range = user_msg_ix..this.entries.len();
2331                                    if range.start < range.end {
2332                                        this.entries.truncate(user_msg_ix);
2333                                        cx.emit(AcpThreadEvent::EntriesRemoved(range));
2334                                    }
2335                                    cx.emit(AcpThreadEvent::Refusal);
2336                                }
2337                            } else {
2338                                // No user message found, treat as general refusal
2339                                cx.emit(AcpThreadEvent::Refusal);
2340                            }
2341                        }
2342
2343                        cx.emit(AcpThreadEvent::Stopped(r.stop_reason));
2344                        Ok(Some(r))
2345                    }
2346                    Err(e) => {
2347                        Self::flush_streaming_text(&mut this.streaming_text_buffer, cx);
2348
2349                        this.had_error = true;
2350                        cx.emit(AcpThreadEvent::Error);
2351                        log::error!("Error in run turn: {:?}", e);
2352                        Err(e)
2353                    }
2354                }
2355            })?
2356        })
2357        .boxed()
2358    }
2359
2360    pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
2361        let Some(turn) = self.running_turn.take() else {
2362            return Task::ready(());
2363        };
2364        self.connection.cancel(&self.session_id, cx);
2365
2366        Self::flush_streaming_text(&mut self.streaming_text_buffer, cx);
2367        self.mark_pending_tools_as_canceled();
2368
2369        // Wait for the send task to complete
2370        cx.background_spawn(turn.send_task)
2371    }
2372
2373    fn mark_pending_tools_as_canceled(&mut self) {
2374        for entry in self.entries.iter_mut() {
2375            if let AgentThreadEntry::ToolCall(call) = entry {
2376                let cancel = matches!(
2377                    call.status,
2378                    ToolCallStatus::Pending
2379                        | ToolCallStatus::WaitingForConfirmation { .. }
2380                        | ToolCallStatus::InProgress
2381                );
2382
2383                if cancel {
2384                    call.status = ToolCallStatus::Canceled;
2385                }
2386            }
2387        }
2388    }
2389
2390    /// Restores the git working tree to the state at the given checkpoint (if one exists)
2391    pub fn restore_checkpoint(
2392        &mut self,
2393        id: UserMessageId,
2394        cx: &mut Context<Self>,
2395    ) -> Task<Result<()>> {
2396        let Some((_, message)) = self.user_message_mut(&id) else {
2397            return Task::ready(Err(anyhow!("message not found")));
2398        };
2399
2400        let checkpoint = message
2401            .checkpoint
2402            .as_ref()
2403            .map(|c| c.git_checkpoint.clone());
2404
2405        // Cancel any in-progress generation before restoring
2406        let cancel_task = self.cancel(cx);
2407        let rewind = self.rewind(id.clone(), cx);
2408        let git_store = self.project.read(cx).git_store().clone();
2409
2410        cx.spawn(async move |_, cx| {
2411            cancel_task.await;
2412            rewind.await?;
2413            if let Some(checkpoint) = checkpoint {
2414                git_store
2415                    .update(cx, |git, cx| git.restore_checkpoint(checkpoint, cx))
2416                    .await?;
2417            }
2418
2419            Ok(())
2420        })
2421    }
2422
2423    /// Rewinds this thread to before the entry at `index`, removing it and all
2424    /// subsequent entries while rejecting any action_log changes made from that point.
2425    /// Unlike `restore_checkpoint`, this method does not restore from git.
2426    pub fn rewind(&mut self, id: UserMessageId, cx: &mut Context<Self>) -> Task<Result<()>> {
2427        let Some(truncate) = self.connection.truncate(&self.session_id, cx) else {
2428            return Task::ready(Err(anyhow!("not supported")));
2429        };
2430
2431        Self::flush_streaming_text(&mut self.streaming_text_buffer, cx);
2432        let telemetry = ActionLogTelemetry::from(&*self);
2433        cx.spawn(async move |this, cx| {
2434            cx.update(|cx| truncate.run(id.clone(), cx)).await?;
2435            this.update(cx, |this, cx| {
2436                if let Some((ix, _)) = this.user_message_mut(&id) {
2437                    // Collect all terminals from entries that will be removed
2438                    let terminals_to_remove: Vec<acp::TerminalId> = this.entries[ix..]
2439                        .iter()
2440                        .flat_map(|entry| entry.terminals())
2441                        .filter_map(|terminal| terminal.read(cx).id().clone().into())
2442                        .collect();
2443
2444                    let range = ix..this.entries.len();
2445                    this.entries.truncate(ix);
2446                    cx.emit(AcpThreadEvent::EntriesRemoved(range));
2447
2448                    // Kill and remove the terminals
2449                    for terminal_id in terminals_to_remove {
2450                        if let Some(terminal) = this.terminals.remove(&terminal_id) {
2451                            terminal.update(cx, |terminal, cx| {
2452                                terminal.kill(cx);
2453                            });
2454                        }
2455                    }
2456                }
2457                this.action_log().update(cx, |action_log, cx| {
2458                    action_log.reject_all_edits(Some(telemetry), cx)
2459                })
2460            })?
2461            .await;
2462            Ok(())
2463        })
2464    }
2465
2466    fn update_last_checkpoint(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
2467        let git_store = self.project.read(cx).git_store().clone();
2468
2469        let Some((_, message)) = self.last_user_message() else {
2470            return Task::ready(Ok(()));
2471        };
2472        let Some(user_message_id) = message.id.clone() else {
2473            return Task::ready(Ok(()));
2474        };
2475        let Some(checkpoint) = message.checkpoint.as_ref() else {
2476            return Task::ready(Ok(()));
2477        };
2478        let old_checkpoint = checkpoint.git_checkpoint.clone();
2479
2480        let new_checkpoint = git_store.update(cx, |git, cx| git.checkpoint(cx));
2481        cx.spawn(async move |this, cx| {
2482            let Some(new_checkpoint) = new_checkpoint
2483                .await
2484                .context("failed to get new checkpoint")
2485                .log_err()
2486            else {
2487                return Ok(());
2488            };
2489
2490            let equal = git_store
2491                .update(cx, |git, cx| {
2492                    git.compare_checkpoints(old_checkpoint.clone(), new_checkpoint, cx)
2493                })
2494                .await
2495                .unwrap_or(true);
2496
2497            this.update(cx, |this, cx| {
2498                if let Some((ix, message)) = this.user_message_mut(&user_message_id) {
2499                    if let Some(checkpoint) = message.checkpoint.as_mut() {
2500                        checkpoint.show = !equal;
2501                        cx.emit(AcpThreadEvent::EntryUpdated(ix));
2502                    }
2503                }
2504            })?;
2505
2506            Ok(())
2507        })
2508    }
2509
2510    fn last_user_message(&mut self) -> Option<(usize, &mut UserMessage)> {
2511        self.entries
2512            .iter_mut()
2513            .enumerate()
2514            .rev()
2515            .find_map(|(ix, entry)| {
2516                if let AgentThreadEntry::UserMessage(message) = entry {
2517                    Some((ix, message))
2518                } else {
2519                    None
2520                }
2521            })
2522    }
2523
2524    fn user_message_mut(&mut self, id: &UserMessageId) -> Option<(usize, &mut UserMessage)> {
2525        self.entries.iter_mut().enumerate().find_map(|(ix, entry)| {
2526            if let AgentThreadEntry::UserMessage(message) = entry {
2527                if message.id.as_ref() == Some(id) {
2528                    Some((ix, message))
2529                } else {
2530                    None
2531                }
2532            } else {
2533                None
2534            }
2535        })
2536    }
2537
2538    pub fn read_text_file(
2539        &self,
2540        path: PathBuf,
2541        line: Option<u32>,
2542        limit: Option<u32>,
2543        reuse_shared_snapshot: bool,
2544        cx: &mut Context<Self>,
2545    ) -> Task<Result<String, acp::Error>> {
2546        // Args are 1-based, move to 0-based
2547        let line = line.unwrap_or_default().saturating_sub(1);
2548        let limit = limit.unwrap_or(u32::MAX);
2549        let project = self.project.clone();
2550        let action_log = self.action_log.clone();
2551        let should_update_agent_location = self.parent_session_id.is_none();
2552        cx.spawn(async move |this, cx| {
2553            let load = project.update(cx, |project, cx| {
2554                let path = project
2555                    .project_path_for_absolute_path(&path, cx)
2556                    .ok_or_else(|| {
2557                        acp::Error::resource_not_found(Some(path.display().to_string()))
2558                    })?;
2559                Ok::<_, acp::Error>(project.open_buffer(path, cx))
2560            })?;
2561
2562            let buffer = load.await?;
2563
2564            let snapshot = if reuse_shared_snapshot {
2565                this.read_with(cx, |this, _| {
2566                    this.shared_buffers.get(&buffer.clone()).cloned()
2567                })
2568                .log_err()
2569                .flatten()
2570            } else {
2571                None
2572            };
2573
2574            let snapshot = if let Some(snapshot) = snapshot {
2575                snapshot
2576            } else {
2577                action_log.update(cx, |action_log, cx| {
2578                    action_log.buffer_read(buffer.clone(), cx);
2579                });
2580
2581                let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
2582                this.update(cx, |this, _| {
2583                    this.shared_buffers.insert(buffer.clone(), snapshot.clone());
2584                })?;
2585                snapshot
2586            };
2587
2588            let max_point = snapshot.max_point();
2589            let start_position = Point::new(line, 0);
2590
2591            if start_position > max_point {
2592                return Err(acp::Error::invalid_params().data(format!(
2593                    "Attempting to read beyond the end of the file, line {}:{}",
2594                    max_point.row + 1,
2595                    max_point.column
2596                )));
2597            }
2598
2599            let start = snapshot.anchor_before(start_position);
2600            let end = snapshot.anchor_before(Point::new(line.saturating_add(limit), 0));
2601
2602            if should_update_agent_location {
2603                project.update(cx, |project, cx| {
2604                    project.set_agent_location(
2605                        Some(AgentLocation {
2606                            buffer: buffer.downgrade(),
2607                            position: start,
2608                        }),
2609                        cx,
2610                    );
2611                });
2612            }
2613
2614            Ok(snapshot.text_for_range(start..end).collect::<String>())
2615        })
2616    }
2617
2618    pub fn write_text_file(
2619        &self,
2620        path: PathBuf,
2621        content: String,
2622        cx: &mut Context<Self>,
2623    ) -> Task<Result<()>> {
2624        let project = self.project.clone();
2625        let action_log = self.action_log.clone();
2626        let should_update_agent_location = self.parent_session_id.is_none();
2627        cx.spawn(async move |this, cx| {
2628            let load = project.update(cx, |project, cx| {
2629                let path = project
2630                    .project_path_for_absolute_path(&path, cx)
2631                    .context("invalid path")?;
2632                anyhow::Ok(project.open_buffer(path, cx))
2633            });
2634            let buffer = load?.await?;
2635            let snapshot = this.update(cx, |this, cx| {
2636                this.shared_buffers
2637                    .get(&buffer)
2638                    .cloned()
2639                    .unwrap_or_else(|| buffer.read(cx).snapshot())
2640            })?;
2641            let edits = cx
2642                .background_executor()
2643                .spawn(async move {
2644                    let old_text = snapshot.text();
2645                    text_diff(old_text.as_str(), &content)
2646                        .into_iter()
2647                        .map(|(range, replacement)| {
2648                            (snapshot.anchor_range_inside(range), replacement)
2649                        })
2650                        .collect::<Vec<_>>()
2651                })
2652                .await;
2653
2654            if should_update_agent_location {
2655                project.update(cx, |project, cx| {
2656                    project.set_agent_location(
2657                        Some(AgentLocation {
2658                            buffer: buffer.downgrade(),
2659                            position: edits
2660                                .last()
2661                                .map(|(range, _)| range.end)
2662                                .unwrap_or(Anchor::min_for_buffer(buffer.read(cx).remote_id())),
2663                        }),
2664                        cx,
2665                    );
2666                });
2667            }
2668
2669            let format_on_save = cx.update(|cx| {
2670                action_log.update(cx, |action_log, cx| {
2671                    action_log.buffer_read(buffer.clone(), cx);
2672                });
2673
2674                let format_on_save = buffer.update(cx, |buffer, cx| {
2675                    buffer.edit(edits, None, cx);
2676
2677                    let settings =
2678                        language::language_settings::LanguageSettings::for_buffer(buffer, cx);
2679
2680                    settings.format_on_save != FormatOnSave::Off
2681                });
2682                action_log.update(cx, |action_log, cx| {
2683                    action_log.buffer_edited(buffer.clone(), cx);
2684                });
2685                format_on_save
2686            });
2687
2688            if format_on_save {
2689                let format_task = project.update(cx, |project, cx| {
2690                    project.format(
2691                        HashSet::from_iter([buffer.clone()]),
2692                        LspFormatTarget::Buffers,
2693                        false,
2694                        FormatTrigger::Save,
2695                        cx,
2696                    )
2697                });
2698                format_task.await.log_err();
2699
2700                action_log.update(cx, |action_log, cx| {
2701                    action_log.buffer_edited(buffer.clone(), cx);
2702                });
2703            }
2704
2705            project
2706                .update(cx, |project, cx| project.save_buffer(buffer, cx))
2707                .await
2708        })
2709    }
2710
2711    pub fn create_terminal(
2712        &self,
2713        command: String,
2714        args: Vec<String>,
2715        extra_env: Vec<acp::EnvVariable>,
2716        cwd: Option<PathBuf>,
2717        output_byte_limit: Option<u64>,
2718        cx: &mut Context<Self>,
2719    ) -> Task<Result<Entity<Terminal>>> {
2720        let env = match &cwd {
2721            Some(dir) => self.project.update(cx, |project, cx| {
2722                project.environment().update(cx, |env, cx| {
2723                    env.directory_environment(dir.as_path().into(), cx)
2724                })
2725            }),
2726            None => Task::ready(None).shared(),
2727        };
2728        let env = cx.spawn(async move |_, _| {
2729            let mut env = env.await.unwrap_or_default();
2730            // Disables paging for `git` and hopefully other commands
2731            env.insert("PAGER".into(), "".into());
2732            for var in extra_env {
2733                env.insert(var.name, var.value);
2734            }
2735            env
2736        });
2737
2738        let project = self.project.clone();
2739        let language_registry = project.read(cx).languages().clone();
2740        let is_windows = project.read(cx).path_style(cx).is_windows();
2741
2742        let terminal_id = acp::TerminalId::new(Uuid::new_v4().to_string());
2743        let terminal_task = cx.spawn({
2744            let terminal_id = terminal_id.clone();
2745            async move |_this, cx| {
2746                let env = env.await;
2747                let shell = project
2748                    .update(cx, |project, cx| {
2749                        project
2750                            .remote_client()
2751                            .and_then(|r| r.read(cx).default_system_shell())
2752                    })
2753                    .unwrap_or_else(|| get_default_system_shell_preferring_bash());
2754                let (task_command, task_args) =
2755                    ShellBuilder::new(&Shell::Program(shell), is_windows)
2756                        .redirect_stdin_to_dev_null()
2757                        .build(Some(command.clone()), &args);
2758                let terminal = project
2759                    .update(cx, |project, cx| {
2760                        project.create_terminal_task(
2761                            task::SpawnInTerminal {
2762                                command: Some(task_command),
2763                                args: task_args,
2764                                cwd: cwd.clone(),
2765                                env,
2766                                ..Default::default()
2767                            },
2768                            cx,
2769                        )
2770                    })
2771                    .await?;
2772
2773                anyhow::Ok(cx.new(|cx| {
2774                    Terminal::new(
2775                        terminal_id,
2776                        &format!("{} {}", command, args.join(" ")),
2777                        cwd,
2778                        output_byte_limit.map(|l| l as usize),
2779                        terminal,
2780                        language_registry,
2781                        cx,
2782                    )
2783                }))
2784            }
2785        });
2786
2787        cx.spawn(async move |this, cx| {
2788            let terminal = terminal_task.await?;
2789            this.update(cx, |this, _cx| {
2790                this.terminals.insert(terminal_id, terminal.clone());
2791                terminal
2792            })
2793        })
2794    }
2795
2796    pub fn kill_terminal(
2797        &mut self,
2798        terminal_id: acp::TerminalId,
2799        cx: &mut Context<Self>,
2800    ) -> Result<()> {
2801        self.terminals
2802            .get(&terminal_id)
2803            .context("Terminal not found")?
2804            .update(cx, |terminal, cx| {
2805                terminal.kill(cx);
2806            });
2807
2808        Ok(())
2809    }
2810
2811    pub fn release_terminal(
2812        &mut self,
2813        terminal_id: acp::TerminalId,
2814        cx: &mut Context<Self>,
2815    ) -> Result<()> {
2816        self.terminals
2817            .remove(&terminal_id)
2818            .context("Terminal not found")?
2819            .update(cx, |terminal, cx| {
2820                terminal.kill(cx);
2821            });
2822
2823        Ok(())
2824    }
2825
2826    pub fn terminal(&self, terminal_id: acp::TerminalId) -> Result<Entity<Terminal>> {
2827        self.terminals
2828            .get(&terminal_id)
2829            .context("Terminal not found")
2830            .cloned()
2831    }
2832
2833    pub fn to_markdown(&self, cx: &App) -> String {
2834        self.entries.iter().map(|e| e.to_markdown(cx)).collect()
2835    }
2836
2837    pub fn emit_load_error(&mut self, error: LoadError, cx: &mut Context<Self>) {
2838        cx.emit(AcpThreadEvent::LoadError(error));
2839    }
2840
2841    pub fn register_terminal_created(
2842        &mut self,
2843        terminal_id: acp::TerminalId,
2844        command_label: String,
2845        working_dir: Option<PathBuf>,
2846        output_byte_limit: Option<u64>,
2847        terminal: Entity<::terminal::Terminal>,
2848        cx: &mut Context<Self>,
2849    ) -> Entity<Terminal> {
2850        let language_registry = self.project.read(cx).languages().clone();
2851
2852        let entity = cx.new(|cx| {
2853            Terminal::new(
2854                terminal_id.clone(),
2855                &command_label,
2856                working_dir.clone(),
2857                output_byte_limit.map(|l| l as usize),
2858                terminal,
2859                language_registry,
2860                cx,
2861            )
2862        });
2863        self.terminals.insert(terminal_id.clone(), entity.clone());
2864        entity
2865    }
2866
2867    pub fn mark_as_subagent_output(&mut self, cx: &mut Context<Self>) {
2868        for entry in self.entries.iter_mut().rev() {
2869            if let AgentThreadEntry::AssistantMessage(assistant_message) = entry {
2870                assistant_message.is_subagent_output = true;
2871                cx.notify();
2872                return;
2873            }
2874        }
2875    }
2876
2877    pub fn on_terminal_provider_event(
2878        &mut self,
2879        event: TerminalProviderEvent,
2880        cx: &mut Context<Self>,
2881    ) {
2882        match event {
2883            TerminalProviderEvent::Created {
2884                terminal_id,
2885                label,
2886                cwd,
2887                output_byte_limit,
2888                terminal,
2889            } => {
2890                let entity = self.register_terminal_created(
2891                    terminal_id.clone(),
2892                    label,
2893                    cwd,
2894                    output_byte_limit,
2895                    terminal,
2896                    cx,
2897                );
2898
2899                if let Some(mut chunks) = self.pending_terminal_output.remove(&terminal_id) {
2900                    for data in chunks.drain(..) {
2901                        entity.update(cx, |term, cx| {
2902                            term.inner().update(cx, |inner, cx| {
2903                                inner.write_output(&data, cx);
2904                            })
2905                        });
2906                    }
2907                }
2908
2909                if let Some(_status) = self.pending_terminal_exit.remove(&terminal_id) {
2910                    entity.update(cx, |_term, cx| {
2911                        cx.notify();
2912                    });
2913                }
2914
2915                cx.notify();
2916            }
2917            TerminalProviderEvent::Output { terminal_id, data } => {
2918                if let Some(entity) = self.terminals.get(&terminal_id) {
2919                    entity.update(cx, |term, cx| {
2920                        term.inner().update(cx, |inner, cx| {
2921                            inner.write_output(&data, cx);
2922                        })
2923                    });
2924                } else {
2925                    self.pending_terminal_output
2926                        .entry(terminal_id)
2927                        .or_default()
2928                        .push(data);
2929                }
2930            }
2931            TerminalProviderEvent::TitleChanged { terminal_id, title } => {
2932                if let Some(entity) = self.terminals.get(&terminal_id) {
2933                    entity.update(cx, |term, cx| {
2934                        term.inner().update(cx, |inner, cx| {
2935                            inner.breadcrumb_text = title;
2936                            cx.emit(::terminal::Event::BreadcrumbsChanged);
2937                        })
2938                    });
2939                }
2940            }
2941            TerminalProviderEvent::Exit {
2942                terminal_id,
2943                status,
2944            } => {
2945                if let Some(entity) = self.terminals.get(&terminal_id) {
2946                    entity.update(cx, |_term, cx| {
2947                        cx.notify();
2948                    });
2949                } else {
2950                    self.pending_terminal_exit.insert(terminal_id, status);
2951                }
2952            }
2953        }
2954    }
2955}
2956
2957fn markdown_for_raw_output(
2958    raw_output: &serde_json::Value,
2959    language_registry: &Arc<LanguageRegistry>,
2960    cx: &mut App,
2961) -> Option<Entity<Markdown>> {
2962    match raw_output {
2963        serde_json::Value::Null => None,
2964        serde_json::Value::Bool(value) => Some(cx.new(|cx| {
2965            Markdown::new(
2966                value.to_string().into(),
2967                Some(language_registry.clone()),
2968                None,
2969                cx,
2970            )
2971        })),
2972        serde_json::Value::Number(value) => Some(cx.new(|cx| {
2973            Markdown::new(
2974                value.to_string().into(),
2975                Some(language_registry.clone()),
2976                None,
2977                cx,
2978            )
2979        })),
2980        serde_json::Value::String(value) => Some(cx.new(|cx| {
2981            Markdown::new(
2982                value.clone().into(),
2983                Some(language_registry.clone()),
2984                None,
2985                cx,
2986            )
2987        })),
2988        value => Some(cx.new(|cx| {
2989            let pretty_json = to_string_pretty(value).unwrap_or_else(|_| value.to_string());
2990
2991            Markdown::new(
2992                format!("```json\n{}\n```", pretty_json).into(),
2993                Some(language_registry.clone()),
2994                None,
2995                cx,
2996            )
2997        })),
2998    }
2999}
3000
3001#[cfg(test)]
3002mod tests {
3003    use super::*;
3004    use anyhow::anyhow;
3005    use futures::{channel::mpsc, future::LocalBoxFuture, select};
3006    use gpui::{App, AsyncApp, TestAppContext, WeakEntity};
3007    use indoc::indoc;
3008    use project::{AgentId, FakeFs, Fs};
3009    use rand::{distr, prelude::*};
3010    use serde_json::json;
3011    use settings::SettingsStore;
3012    use smol::stream::StreamExt as _;
3013    use std::{
3014        any::Any,
3015        cell::RefCell,
3016        path::Path,
3017        rc::Rc,
3018        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
3019        time::Duration,
3020    };
3021    use util::{path, path_list::PathList};
3022
3023    fn init_test(cx: &mut TestAppContext) {
3024        env_logger::try_init().ok();
3025        cx.update(|cx| {
3026            let settings_store = SettingsStore::test(cx);
3027            cx.set_global(settings_store);
3028        });
3029    }
3030
3031    #[gpui::test]
3032    async fn test_terminal_output_buffered_before_created_renders(cx: &mut gpui::TestAppContext) {
3033        init_test(cx);
3034
3035        let fs = FakeFs::new(cx.executor());
3036        let project = Project::test(fs, [], cx).await;
3037        let connection = Rc::new(FakeAgentConnection::new());
3038        let thread = cx
3039            .update(|cx| {
3040                connection.new_session(
3041                    project,
3042                    PathList::new(&[std::path::Path::new(path!("/test"))]),
3043                    cx,
3044                )
3045            })
3046            .await
3047            .unwrap();
3048
3049        let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
3050
3051        // Send Output BEFORE Created - should be buffered by acp_thread
3052        thread.update(cx, |thread, cx| {
3053            thread.on_terminal_provider_event(
3054                TerminalProviderEvent::Output {
3055                    terminal_id: terminal_id.clone(),
3056                    data: b"hello buffered".to_vec(),
3057                },
3058                cx,
3059            );
3060        });
3061
3062        // Create a display-only terminal and then send Created
3063        let lower = cx.new(|cx| {
3064            let builder = ::terminal::TerminalBuilder::new_display_only(
3065                ::terminal::terminal_settings::CursorShape::default(),
3066                ::terminal::terminal_settings::AlternateScroll::On,
3067                None,
3068                0,
3069                cx.background_executor(),
3070                PathStyle::local(),
3071            )
3072            .unwrap();
3073            builder.subscribe(cx)
3074        });
3075
3076        thread.update(cx, |thread, cx| {
3077            thread.on_terminal_provider_event(
3078                TerminalProviderEvent::Created {
3079                    terminal_id: terminal_id.clone(),
3080                    label: "Buffered Test".to_string(),
3081                    cwd: None,
3082                    output_byte_limit: None,
3083                    terminal: lower.clone(),
3084                },
3085                cx,
3086            );
3087        });
3088
3089        // After Created, buffered Output should have been flushed into the renderer
3090        let content = thread.read_with(cx, |thread, cx| {
3091            let term = thread.terminal(terminal_id.clone()).unwrap();
3092            term.read_with(cx, |t, cx| t.inner().read(cx).get_content())
3093        });
3094
3095        assert!(
3096            content.contains("hello buffered"),
3097            "expected buffered output to render, got: {content}"
3098        );
3099    }
3100
3101    #[gpui::test]
3102    async fn test_terminal_output_and_exit_buffered_before_created(cx: &mut gpui::TestAppContext) {
3103        init_test(cx);
3104
3105        let fs = FakeFs::new(cx.executor());
3106        let project = Project::test(fs, [], cx).await;
3107        let connection = Rc::new(FakeAgentConnection::new());
3108        let thread = cx
3109            .update(|cx| {
3110                connection.new_session(
3111                    project,
3112                    PathList::new(&[std::path::Path::new(path!("/test"))]),
3113                    cx,
3114                )
3115            })
3116            .await
3117            .unwrap();
3118
3119        let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
3120
3121        // Send Output BEFORE Created
3122        thread.update(cx, |thread, cx| {
3123            thread.on_terminal_provider_event(
3124                TerminalProviderEvent::Output {
3125                    terminal_id: terminal_id.clone(),
3126                    data: b"pre-exit data".to_vec(),
3127                },
3128                cx,
3129            );
3130        });
3131
3132        // Send Exit BEFORE Created
3133        thread.update(cx, |thread, cx| {
3134            thread.on_terminal_provider_event(
3135                TerminalProviderEvent::Exit {
3136                    terminal_id: terminal_id.clone(),
3137                    status: acp::TerminalExitStatus::new().exit_code(0),
3138                },
3139                cx,
3140            );
3141        });
3142
3143        // Now create a display-only lower-level terminal and send Created
3144        let lower = cx.new(|cx| {
3145            let builder = ::terminal::TerminalBuilder::new_display_only(
3146                ::terminal::terminal_settings::CursorShape::default(),
3147                ::terminal::terminal_settings::AlternateScroll::On,
3148                None,
3149                0,
3150                cx.background_executor(),
3151                PathStyle::local(),
3152            )
3153            .unwrap();
3154            builder.subscribe(cx)
3155        });
3156
3157        thread.update(cx, |thread, cx| {
3158            thread.on_terminal_provider_event(
3159                TerminalProviderEvent::Created {
3160                    terminal_id: terminal_id.clone(),
3161                    label: "Buffered Exit Test".to_string(),
3162                    cwd: None,
3163                    output_byte_limit: None,
3164                    terminal: lower.clone(),
3165                },
3166                cx,
3167            );
3168        });
3169
3170        // Output should be present after Created (flushed from buffer)
3171        let content = thread.read_with(cx, |thread, cx| {
3172            let term = thread.terminal(terminal_id.clone()).unwrap();
3173            term.read_with(cx, |t, cx| t.inner().read(cx).get_content())
3174        });
3175
3176        assert!(
3177            content.contains("pre-exit data"),
3178            "expected pre-exit data to render, got: {content}"
3179        );
3180    }
3181
3182    /// Test that killing a terminal via Terminal::kill properly:
3183    /// 1. Causes wait_for_exit to complete (doesn't hang forever)
3184    /// 2. The underlying terminal still has the output that was written before the kill
3185    ///
3186    /// This test verifies that the fix to kill_active_task (which now also kills
3187    /// the shell process in addition to the foreground process) properly allows
3188    /// wait_for_exit to complete instead of hanging indefinitely.
3189    #[cfg(unix)]
3190    #[gpui::test]
3191    async fn test_terminal_kill_allows_wait_for_exit_to_complete(cx: &mut gpui::TestAppContext) {
3192        use std::collections::HashMap;
3193        use task::Shell;
3194        use util::shell_builder::ShellBuilder;
3195
3196        init_test(cx);
3197        cx.executor().allow_parking();
3198
3199        let fs = FakeFs::new(cx.executor());
3200        let project = Project::test(fs, [], cx).await;
3201        let connection = Rc::new(FakeAgentConnection::new());
3202        let thread = cx
3203            .update(|cx| {
3204                connection.new_session(
3205                    project.clone(),
3206                    PathList::new(&[Path::new(path!("/test"))]),
3207                    cx,
3208                )
3209            })
3210            .await
3211            .unwrap();
3212
3213        let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
3214
3215        // Create a real PTY terminal that runs a command which prints output then sleeps
3216        // We use printf instead of echo and chain with && sleep to ensure proper execution
3217        let (completion_tx, _completion_rx) = smol::channel::unbounded();
3218        let (program, args) = ShellBuilder::new(&Shell::System, false).build(
3219            Some("printf 'output_before_kill\\n' && sleep 60".to_owned()),
3220            &[],
3221        );
3222
3223        let builder = cx
3224            .update(|cx| {
3225                ::terminal::TerminalBuilder::new(
3226                    None,
3227                    None,
3228                    task::Shell::WithArguments {
3229                        program,
3230                        args,
3231                        title_override: None,
3232                    },
3233                    HashMap::default(),
3234                    ::terminal::terminal_settings::CursorShape::default(),
3235                    ::terminal::terminal_settings::AlternateScroll::On,
3236                    None,
3237                    vec![],
3238                    0,
3239                    false,
3240                    0,
3241                    Some(completion_tx),
3242                    cx,
3243                    vec![],
3244                    PathStyle::local(),
3245                )
3246            })
3247            .await
3248            .unwrap();
3249
3250        let lower_terminal = cx.new(|cx| builder.subscribe(cx));
3251
3252        // Create the acp_thread Terminal wrapper
3253        thread.update(cx, |thread, cx| {
3254            thread.on_terminal_provider_event(
3255                TerminalProviderEvent::Created {
3256                    terminal_id: terminal_id.clone(),
3257                    label: "printf output_before_kill && sleep 60".to_string(),
3258                    cwd: None,
3259                    output_byte_limit: None,
3260                    terminal: lower_terminal.clone(),
3261                },
3262                cx,
3263            );
3264        });
3265
3266        // Poll until the printf command produces output, rather than using a
3267        // fixed sleep which is flaky on loaded machines.
3268        let deadline = std::time::Instant::now() + Duration::from_secs(10);
3269        loop {
3270            let has_output = thread.read_with(cx, |thread, cx| {
3271                let term = thread
3272                    .terminals
3273                    .get(&terminal_id)
3274                    .expect("terminal not found");
3275                let content = term.read(cx).inner().read(cx).get_content();
3276                content.contains("output_before_kill")
3277            });
3278            if has_output {
3279                break;
3280            }
3281            assert!(
3282                std::time::Instant::now() < deadline,
3283                "Timed out waiting for printf output to appear in terminal",
3284            );
3285            cx.executor().timer(Duration::from_millis(50)).await;
3286        }
3287
3288        // Get the acp_thread Terminal and kill it
3289        let wait_for_exit = thread.update(cx, |thread, cx| {
3290            let term = thread.terminals.get(&terminal_id).unwrap();
3291            let wait_for_exit = term.read(cx).wait_for_exit();
3292            term.update(cx, |term, cx| {
3293                term.kill(cx);
3294            });
3295            wait_for_exit
3296        });
3297
3298        // KEY ASSERTION: wait_for_exit should complete within a reasonable time (not hang).
3299        // Before the fix to kill_active_task, this would hang forever because
3300        // only the foreground process was killed, not the shell, so the PTY
3301        // child never exited and wait_for_completed_task never completed.
3302        let exit_result = futures::select! {
3303            result = futures::FutureExt::fuse(wait_for_exit) => Some(result),
3304            _ = futures::FutureExt::fuse(cx.background_executor.timer(Duration::from_secs(5))) => None,
3305        };
3306
3307        assert!(
3308            exit_result.is_some(),
3309            "wait_for_exit should complete after kill, but it timed out. \
3310            This indicates kill_active_task is not properly killing the shell process."
3311        );
3312
3313        // Give the system a chance to process any pending updates
3314        cx.run_until_parked();
3315
3316        // Verify that the underlying terminal still has the output that was
3317        // written before the kill. This verifies that killing doesn't lose output.
3318        let inner_content = thread.read_with(cx, |thread, cx| {
3319            let term = thread.terminals.get(&terminal_id).unwrap();
3320            term.read(cx).inner().read(cx).get_content()
3321        });
3322
3323        assert!(
3324            inner_content.contains("output_before_kill"),
3325            "Underlying terminal should contain output from before kill, got: {}",
3326            inner_content
3327        );
3328    }
3329
3330    #[gpui::test]
3331    async fn test_push_user_content_block(cx: &mut gpui::TestAppContext) {
3332        init_test(cx);
3333
3334        let fs = FakeFs::new(cx.executor());
3335        let project = Project::test(fs, [], cx).await;
3336        let connection = Rc::new(FakeAgentConnection::new());
3337        let thread = cx
3338            .update(|cx| {
3339                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
3340            })
3341            .await
3342            .unwrap();
3343
3344        // Test creating a new user message
3345        thread.update(cx, |thread, cx| {
3346            thread.push_user_content_block(None, "Hello, ".into(), cx);
3347        });
3348
3349        thread.update(cx, |thread, cx| {
3350            assert_eq!(thread.entries.len(), 1);
3351            if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
3352                assert_eq!(user_msg.id, None);
3353                assert_eq!(user_msg.content.to_markdown(cx), "Hello, ");
3354            } else {
3355                panic!("Expected UserMessage");
3356            }
3357        });
3358
3359        // Test appending to existing user message
3360        let message_1_id = UserMessageId::new();
3361        thread.update(cx, |thread, cx| {
3362            thread.push_user_content_block(Some(message_1_id.clone()), "world!".into(), cx);
3363        });
3364
3365        thread.update(cx, |thread, cx| {
3366            assert_eq!(thread.entries.len(), 1);
3367            if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
3368                assert_eq!(user_msg.id, Some(message_1_id));
3369                assert_eq!(user_msg.content.to_markdown(cx), "Hello, world!");
3370            } else {
3371                panic!("Expected UserMessage");
3372            }
3373        });
3374
3375        // Test creating new user message after assistant message
3376        thread.update(cx, |thread, cx| {
3377            thread.push_assistant_content_block("Assistant response".into(), false, cx);
3378        });
3379
3380        let message_2_id = UserMessageId::new();
3381        thread.update(cx, |thread, cx| {
3382            thread.push_user_content_block(
3383                Some(message_2_id.clone()),
3384                "New user message".into(),
3385                cx,
3386            );
3387        });
3388
3389        thread.update(cx, |thread, cx| {
3390            assert_eq!(thread.entries.len(), 3);
3391            if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[2] {
3392                assert_eq!(user_msg.id, Some(message_2_id));
3393                assert_eq!(user_msg.content.to_markdown(cx), "New user message");
3394            } else {
3395                panic!("Expected UserMessage at index 2");
3396            }
3397        });
3398    }
3399
3400    #[gpui::test]
3401    async fn test_thinking_concatenation(cx: &mut gpui::TestAppContext) {
3402        init_test(cx);
3403
3404        let fs = FakeFs::new(cx.executor());
3405        let project = Project::test(fs, [], cx).await;
3406        let connection = Rc::new(FakeAgentConnection::new().on_user_message(
3407            |_, thread, mut cx| {
3408                async move {
3409                    thread.update(&mut cx, |thread, cx| {
3410                        thread
3411                            .handle_session_update(
3412                                acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk::new(
3413                                    "Thinking ".into(),
3414                                )),
3415                                cx,
3416                            )
3417                            .unwrap();
3418                        thread
3419                            .handle_session_update(
3420                                acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk::new(
3421                                    "hard!".into(),
3422                                )),
3423                                cx,
3424                            )
3425                            .unwrap();
3426                    })?;
3427                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3428                }
3429                .boxed_local()
3430            },
3431        ));
3432
3433        let thread = cx
3434            .update(|cx| {
3435                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
3436            })
3437            .await
3438            .unwrap();
3439
3440        thread
3441            .update(cx, |thread, cx| thread.send_raw("Hello from Zed!", cx))
3442            .await
3443            .unwrap();
3444
3445        let output = thread.read_with(cx, |thread, cx| thread.to_markdown(cx));
3446        assert_eq!(
3447            output,
3448            indoc! {r#"
3449            ## User
3450
3451            Hello from Zed!
3452
3453            ## Assistant
3454
3455            <thinking>
3456            Thinking hard!
3457            </thinking>
3458
3459            "#}
3460        );
3461    }
3462
3463    #[gpui::test]
3464    async fn test_ignore_echoed_user_message_chunks_during_active_turn(
3465        cx: &mut gpui::TestAppContext,
3466    ) {
3467        init_test(cx);
3468
3469        let fs = FakeFs::new(cx.executor());
3470        let project = Project::test(fs, [], cx).await;
3471        let connection = Rc::new(FakeAgentConnection::new().on_user_message(
3472            |request, thread, mut cx| {
3473                async move {
3474                    let prompt = request.prompt.first().cloned().unwrap_or_else(|| "".into());
3475
3476                    thread.update(&mut cx, |thread, cx| {
3477                        thread
3478                            .handle_session_update(
3479                                acp::SessionUpdate::UserMessageChunk(acp::ContentChunk::new(
3480                                    prompt,
3481                                )),
3482                                cx,
3483                            )
3484                            .unwrap();
3485                    })?;
3486
3487                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3488                }
3489                .boxed_local()
3490            },
3491        ));
3492
3493        let thread = cx
3494            .update(|cx| {
3495                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
3496            })
3497            .await
3498            .unwrap();
3499
3500        thread
3501            .update(cx, |thread, cx| thread.send_raw("Hello from Zed!", cx))
3502            .await
3503            .unwrap();
3504
3505        let output = thread.read_with(cx, |thread, cx| thread.to_markdown(cx));
3506        assert_eq!(output.matches("Hello from Zed!").count(), 1);
3507    }
3508
3509    #[gpui::test]
3510    async fn test_edits_concurrently_to_user(cx: &mut TestAppContext) {
3511        init_test(cx);
3512
3513        let fs = FakeFs::new(cx.executor());
3514        fs.insert_tree(path!("/tmp"), json!({"foo": "one\ntwo\nthree\n"}))
3515            .await;
3516        let project = Project::test(fs.clone(), [], cx).await;
3517        let (read_file_tx, read_file_rx) = oneshot::channel::<()>();
3518        let read_file_tx = Rc::new(RefCell::new(Some(read_file_tx)));
3519        let connection = Rc::new(FakeAgentConnection::new().on_user_message(
3520            move |_, thread, mut cx| {
3521                let read_file_tx = read_file_tx.clone();
3522                async move {
3523                    let content = thread
3524                        .update(&mut cx, |thread, cx| {
3525                            thread.read_text_file(path!("/tmp/foo").into(), None, None, false, cx)
3526                        })
3527                        .unwrap()
3528                        .await
3529                        .unwrap();
3530                    assert_eq!(content, "one\ntwo\nthree\n");
3531                    read_file_tx.take().unwrap().send(()).unwrap();
3532                    thread
3533                        .update(&mut cx, |thread, cx| {
3534                            thread.write_text_file(
3535                                path!("/tmp/foo").into(),
3536                                "one\ntwo\nthree\nfour\nfive\n".to_string(),
3537                                cx,
3538                            )
3539                        })
3540                        .unwrap()
3541                        .await
3542                        .unwrap();
3543                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3544                }
3545                .boxed_local()
3546            },
3547        ));
3548
3549        let (worktree, pathbuf) = project
3550            .update(cx, |project, cx| {
3551                project.find_or_create_worktree(path!("/tmp/foo"), true, cx)
3552            })
3553            .await
3554            .unwrap();
3555        let buffer = project
3556            .update(cx, |project, cx| {
3557                project.open_buffer((worktree.read(cx).id(), pathbuf), cx)
3558            })
3559            .await
3560            .unwrap();
3561
3562        let thread = cx
3563            .update(|cx| {
3564                connection.new_session(project, PathList::new(&[Path::new(path!("/tmp"))]), cx)
3565            })
3566            .await
3567            .unwrap();
3568
3569        let request = thread.update(cx, |thread, cx| {
3570            thread.send_raw("Extend the count in /tmp/foo", cx)
3571        });
3572        read_file_rx.await.ok();
3573        buffer.update(cx, |buffer, cx| {
3574            buffer.edit([(0..0, "zero\n".to_string())], None, cx);
3575        });
3576        cx.run_until_parked();
3577        assert_eq!(
3578            buffer.read_with(cx, |buffer, _| buffer.text()),
3579            "zero\none\ntwo\nthree\nfour\nfive\n"
3580        );
3581        assert_eq!(
3582            String::from_utf8(fs.read_file_sync(path!("/tmp/foo")).unwrap()).unwrap(),
3583            "zero\none\ntwo\nthree\nfour\nfive\n"
3584        );
3585        request.await.unwrap();
3586    }
3587
3588    #[gpui::test]
3589    async fn test_reading_from_line(cx: &mut TestAppContext) {
3590        init_test(cx);
3591
3592        let fs = FakeFs::new(cx.executor());
3593        fs.insert_tree(path!("/tmp"), json!({"foo": "one\ntwo\nthree\nfour\n"}))
3594            .await;
3595        let project = Project::test(fs.clone(), [], cx).await;
3596        project
3597            .update(cx, |project, cx| {
3598                project.find_or_create_worktree(path!("/tmp/foo"), true, cx)
3599            })
3600            .await
3601            .unwrap();
3602
3603        let connection = Rc::new(FakeAgentConnection::new());
3604
3605        let thread = cx
3606            .update(|cx| {
3607                connection.new_session(project, PathList::new(&[Path::new(path!("/tmp"))]), cx)
3608            })
3609            .await
3610            .unwrap();
3611
3612        // Whole file
3613        let content = thread
3614            .update(cx, |thread, cx| {
3615                thread.read_text_file(path!("/tmp/foo").into(), None, None, false, cx)
3616            })
3617            .await
3618            .unwrap();
3619
3620        assert_eq!(content, "one\ntwo\nthree\nfour\n");
3621
3622        // Only start line
3623        let content = thread
3624            .update(cx, |thread, cx| {
3625                thread.read_text_file(path!("/tmp/foo").into(), Some(3), None, false, cx)
3626            })
3627            .await
3628            .unwrap();
3629
3630        assert_eq!(content, "three\nfour\n");
3631
3632        // Only limit
3633        let content = thread
3634            .update(cx, |thread, cx| {
3635                thread.read_text_file(path!("/tmp/foo").into(), None, Some(2), false, cx)
3636            })
3637            .await
3638            .unwrap();
3639
3640        assert_eq!(content, "one\ntwo\n");
3641
3642        // Range
3643        let content = thread
3644            .update(cx, |thread, cx| {
3645                thread.read_text_file(path!("/tmp/foo").into(), Some(2), Some(2), false, cx)
3646            })
3647            .await
3648            .unwrap();
3649
3650        assert_eq!(content, "two\nthree\n");
3651
3652        // Invalid
3653        let err = thread
3654            .update(cx, |thread, cx| {
3655                thread.read_text_file(path!("/tmp/foo").into(), Some(6), Some(2), false, cx)
3656            })
3657            .await
3658            .unwrap_err();
3659
3660        assert_eq!(
3661            err.to_string(),
3662            "Invalid params: \"Attempting to read beyond the end of the file, line 5:0\""
3663        );
3664    }
3665
3666    #[gpui::test]
3667    async fn test_reading_empty_file(cx: &mut TestAppContext) {
3668        init_test(cx);
3669
3670        let fs = FakeFs::new(cx.executor());
3671        fs.insert_tree(path!("/tmp"), json!({"foo": ""})).await;
3672        let project = Project::test(fs.clone(), [], cx).await;
3673        project
3674            .update(cx, |project, cx| {
3675                project.find_or_create_worktree(path!("/tmp/foo"), true, cx)
3676            })
3677            .await
3678            .unwrap();
3679
3680        let connection = Rc::new(FakeAgentConnection::new());
3681
3682        let thread = cx
3683            .update(|cx| {
3684                connection.new_session(project, PathList::new(&[Path::new(path!("/tmp"))]), cx)
3685            })
3686            .await
3687            .unwrap();
3688
3689        // Whole file
3690        let content = thread
3691            .update(cx, |thread, cx| {
3692                thread.read_text_file(path!("/tmp/foo").into(), None, None, false, cx)
3693            })
3694            .await
3695            .unwrap();
3696
3697        assert_eq!(content, "");
3698
3699        // Only start line
3700        let content = thread
3701            .update(cx, |thread, cx| {
3702                thread.read_text_file(path!("/tmp/foo").into(), Some(1), None, false, cx)
3703            })
3704            .await
3705            .unwrap();
3706
3707        assert_eq!(content, "");
3708
3709        // Only limit
3710        let content = thread
3711            .update(cx, |thread, cx| {
3712                thread.read_text_file(path!("/tmp/foo").into(), None, Some(2), false, cx)
3713            })
3714            .await
3715            .unwrap();
3716
3717        assert_eq!(content, "");
3718
3719        // Range
3720        let content = thread
3721            .update(cx, |thread, cx| {
3722                thread.read_text_file(path!("/tmp/foo").into(), Some(1), Some(1), false, cx)
3723            })
3724            .await
3725            .unwrap();
3726
3727        assert_eq!(content, "");
3728
3729        // Invalid
3730        let err = thread
3731            .update(cx, |thread, cx| {
3732                thread.read_text_file(path!("/tmp/foo").into(), Some(5), Some(2), false, cx)
3733            })
3734            .await
3735            .unwrap_err();
3736
3737        assert_eq!(
3738            err.to_string(),
3739            "Invalid params: \"Attempting to read beyond the end of the file, line 1:0\""
3740        );
3741    }
3742    #[gpui::test]
3743    async fn test_reading_non_existing_file(cx: &mut TestAppContext) {
3744        init_test(cx);
3745
3746        let fs = FakeFs::new(cx.executor());
3747        fs.insert_tree(path!("/tmp"), json!({})).await;
3748        let project = Project::test(fs.clone(), [], cx).await;
3749        project
3750            .update(cx, |project, cx| {
3751                project.find_or_create_worktree(path!("/tmp"), true, cx)
3752            })
3753            .await
3754            .unwrap();
3755
3756        let connection = Rc::new(FakeAgentConnection::new());
3757
3758        let thread = cx
3759            .update(|cx| {
3760                connection.new_session(project, PathList::new(&[Path::new(path!("/tmp"))]), cx)
3761            })
3762            .await
3763            .unwrap();
3764
3765        // Out of project file
3766        let err = thread
3767            .update(cx, |thread, cx| {
3768                thread.read_text_file(path!("/foo").into(), None, None, false, cx)
3769            })
3770            .await
3771            .unwrap_err();
3772
3773        assert_eq!(err.code, acp::ErrorCode::ResourceNotFound);
3774    }
3775
3776    #[gpui::test]
3777    async fn test_succeeding_canceled_toolcall(cx: &mut TestAppContext) {
3778        init_test(cx);
3779
3780        let fs = FakeFs::new(cx.executor());
3781        let project = Project::test(fs, [], cx).await;
3782        let id = acp::ToolCallId::new("test");
3783
3784        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
3785            let id = id.clone();
3786            move |_, thread, mut cx| {
3787                let id = id.clone();
3788                async move {
3789                    thread
3790                        .update(&mut cx, |thread, cx| {
3791                            thread.handle_session_update(
3792                                acp::SessionUpdate::ToolCall(
3793                                    acp::ToolCall::new(id.clone(), "Label")
3794                                        .kind(acp::ToolKind::Fetch)
3795                                        .status(acp::ToolCallStatus::InProgress),
3796                                ),
3797                                cx,
3798                            )
3799                        })
3800                        .unwrap()
3801                        .unwrap();
3802                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3803                }
3804                .boxed_local()
3805            }
3806        }));
3807
3808        let thread = cx
3809            .update(|cx| {
3810                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
3811            })
3812            .await
3813            .unwrap();
3814
3815        let request = thread.update(cx, |thread, cx| {
3816            thread.send_raw("Fetch https://example.com", cx)
3817        });
3818
3819        run_until_first_tool_call(&thread, cx).await;
3820
3821        thread.read_with(cx, |thread, _| {
3822            assert!(matches!(
3823                thread.entries[1],
3824                AgentThreadEntry::ToolCall(ToolCall {
3825                    status: ToolCallStatus::InProgress,
3826                    ..
3827                })
3828            ));
3829        });
3830
3831        thread.update(cx, |thread, cx| thread.cancel(cx)).await;
3832
3833        thread.read_with(cx, |thread, _| {
3834            assert!(matches!(
3835                &thread.entries[1],
3836                AgentThreadEntry::ToolCall(ToolCall {
3837                    status: ToolCallStatus::Canceled,
3838                    ..
3839                })
3840            ));
3841        });
3842
3843        thread
3844            .update(cx, |thread, cx| {
3845                thread.handle_session_update(
3846                    acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
3847                        id,
3848                        acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::Completed),
3849                    )),
3850                    cx,
3851                )
3852            })
3853            .unwrap();
3854
3855        request.await.unwrap();
3856
3857        thread.read_with(cx, |thread, _| {
3858            assert!(matches!(
3859                thread.entries[1],
3860                AgentThreadEntry::ToolCall(ToolCall {
3861                    status: ToolCallStatus::Completed,
3862                    ..
3863                })
3864            ));
3865        });
3866    }
3867
3868    #[gpui::test]
3869    async fn test_no_pending_edits_if_tool_calls_are_completed(cx: &mut TestAppContext) {
3870        init_test(cx);
3871        let fs = FakeFs::new(cx.background_executor.clone());
3872        fs.insert_tree(path!("/test"), json!({})).await;
3873        let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
3874
3875        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
3876            move |_, thread, mut cx| {
3877                async move {
3878                    thread
3879                        .update(&mut cx, |thread, cx| {
3880                            thread.handle_session_update(
3881                                acp::SessionUpdate::ToolCall(
3882                                    acp::ToolCall::new("test", "Label")
3883                                        .kind(acp::ToolKind::Edit)
3884                                        .status(acp::ToolCallStatus::Completed)
3885                                        .content(vec![acp::ToolCallContent::Diff(acp::Diff::new(
3886                                            "/test/test.txt",
3887                                            "foo",
3888                                        ))]),
3889                                ),
3890                                cx,
3891                            )
3892                        })
3893                        .unwrap()
3894                        .unwrap();
3895                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3896                }
3897                .boxed_local()
3898            }
3899        }));
3900
3901        let thread = cx
3902            .update(|cx| {
3903                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
3904            })
3905            .await
3906            .unwrap();
3907
3908        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["Hi".into()], cx)))
3909            .await
3910            .unwrap();
3911
3912        assert!(cx.read(|cx| !thread.read(cx).has_pending_edit_tool_calls()));
3913    }
3914
3915    #[gpui::test(iterations = 10)]
3916    async fn test_checkpoints(cx: &mut TestAppContext) {
3917        init_test(cx);
3918        let fs = FakeFs::new(cx.background_executor.clone());
3919        fs.insert_tree(
3920            path!("/test"),
3921            json!({
3922                ".git": {}
3923            }),
3924        )
3925        .await;
3926        let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
3927
3928        let simulate_changes = Arc::new(AtomicBool::new(true));
3929        let next_filename = Arc::new(AtomicUsize::new(0));
3930        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
3931            let simulate_changes = simulate_changes.clone();
3932            let next_filename = next_filename.clone();
3933            let fs = fs.clone();
3934            move |request, thread, mut cx| {
3935                let fs = fs.clone();
3936                let simulate_changes = simulate_changes.clone();
3937                let next_filename = next_filename.clone();
3938                async move {
3939                    if simulate_changes.load(SeqCst) {
3940                        let filename = format!("/test/file-{}", next_filename.fetch_add(1, SeqCst));
3941                        fs.write(Path::new(&filename), b"").await?;
3942                    }
3943
3944                    let acp::ContentBlock::Text(content) = &request.prompt[0] else {
3945                        panic!("expected text content block");
3946                    };
3947                    thread.update(&mut cx, |thread, cx| {
3948                        thread
3949                            .handle_session_update(
3950                                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
3951                                    content.text.to_uppercase().into(),
3952                                )),
3953                                cx,
3954                            )
3955                            .unwrap();
3956                    })?;
3957                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3958                }
3959                .boxed_local()
3960            }
3961        }));
3962        let thread = cx
3963            .update(|cx| {
3964                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
3965            })
3966            .await
3967            .unwrap();
3968
3969        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["Lorem".into()], cx)))
3970            .await
3971            .unwrap();
3972        thread.read_with(cx, |thread, cx| {
3973            assert_eq!(
3974                thread.to_markdown(cx),
3975                indoc! {"
3976                    ## User (checkpoint)
3977
3978                    Lorem
3979
3980                    ## Assistant
3981
3982                    LOREM
3983
3984                "}
3985            );
3986        });
3987        assert_eq!(fs.files(), vec![Path::new(path!("/test/file-0"))]);
3988
3989        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["ipsum".into()], cx)))
3990            .await
3991            .unwrap();
3992        thread.read_with(cx, |thread, cx| {
3993            assert_eq!(
3994                thread.to_markdown(cx),
3995                indoc! {"
3996                    ## User (checkpoint)
3997
3998                    Lorem
3999
4000                    ## Assistant
4001
4002                    LOREM
4003
4004                    ## User (checkpoint)
4005
4006                    ipsum
4007
4008                    ## Assistant
4009
4010                    IPSUM
4011
4012                "}
4013            );
4014        });
4015        assert_eq!(
4016            fs.files(),
4017            vec![
4018                Path::new(path!("/test/file-0")),
4019                Path::new(path!("/test/file-1"))
4020            ]
4021        );
4022
4023        // Checkpoint isn't stored when there are no changes.
4024        simulate_changes.store(false, SeqCst);
4025        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["dolor".into()], cx)))
4026            .await
4027            .unwrap();
4028        thread.read_with(cx, |thread, cx| {
4029            assert_eq!(
4030                thread.to_markdown(cx),
4031                indoc! {"
4032                    ## User (checkpoint)
4033
4034                    Lorem
4035
4036                    ## Assistant
4037
4038                    LOREM
4039
4040                    ## User (checkpoint)
4041
4042                    ipsum
4043
4044                    ## Assistant
4045
4046                    IPSUM
4047
4048                    ## User
4049
4050                    dolor
4051
4052                    ## Assistant
4053
4054                    DOLOR
4055
4056                "}
4057            );
4058        });
4059        assert_eq!(
4060            fs.files(),
4061            vec![
4062                Path::new(path!("/test/file-0")),
4063                Path::new(path!("/test/file-1"))
4064            ]
4065        );
4066
4067        // Rewinding the conversation truncates the history and restores the checkpoint.
4068        thread
4069            .update(cx, |thread, cx| {
4070                let AgentThreadEntry::UserMessage(message) = &thread.entries[2] else {
4071                    panic!("unexpected entries {:?}", thread.entries)
4072                };
4073                thread.restore_checkpoint(message.id.clone().unwrap(), cx)
4074            })
4075            .await
4076            .unwrap();
4077        thread.read_with(cx, |thread, cx| {
4078            assert_eq!(
4079                thread.to_markdown(cx),
4080                indoc! {"
4081                    ## User (checkpoint)
4082
4083                    Lorem
4084
4085                    ## Assistant
4086
4087                    LOREM
4088
4089                "}
4090            );
4091        });
4092        assert_eq!(fs.files(), vec![Path::new(path!("/test/file-0"))]);
4093    }
4094
4095    #[gpui::test]
4096    async fn test_tool_result_refusal(cx: &mut TestAppContext) {
4097        use std::sync::atomic::AtomicUsize;
4098        init_test(cx);
4099
4100        let fs = FakeFs::new(cx.executor());
4101        let project = Project::test(fs, None, cx).await;
4102
4103        // Create a connection that simulates refusal after tool result
4104        let prompt_count = Arc::new(AtomicUsize::new(0));
4105        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
4106            let prompt_count = prompt_count.clone();
4107            move |_request, thread, mut cx| {
4108                let count = prompt_count.fetch_add(1, SeqCst);
4109                async move {
4110                    if count == 0 {
4111                        // First prompt: Generate a tool call with result
4112                        thread.update(&mut cx, |thread, cx| {
4113                            thread
4114                                .handle_session_update(
4115                                    acp::SessionUpdate::ToolCall(
4116                                        acp::ToolCall::new("tool1", "Test Tool")
4117                                            .kind(acp::ToolKind::Fetch)
4118                                            .status(acp::ToolCallStatus::Completed)
4119                                            .raw_input(serde_json::json!({"query": "test"}))
4120                                            .raw_output(serde_json::json!({"result": "inappropriate content"})),
4121                                    ),
4122                                    cx,
4123                                )
4124                                .unwrap();
4125                        })?;
4126
4127                        // Now return refusal because of the tool result
4128                        Ok(acp::PromptResponse::new(acp::StopReason::Refusal))
4129                    } else {
4130                        Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
4131                    }
4132                }
4133                .boxed_local()
4134            }
4135        }));
4136
4137        let thread = cx
4138            .update(|cx| {
4139                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
4140            })
4141            .await
4142            .unwrap();
4143
4144        // Track if we see a Refusal event
4145        let saw_refusal_event = Arc::new(std::sync::Mutex::new(false));
4146        let saw_refusal_event_captured = saw_refusal_event.clone();
4147        thread.update(cx, |_thread, cx| {
4148            cx.subscribe(
4149                &thread,
4150                move |_thread, _event_thread, event: &AcpThreadEvent, _cx| {
4151                    if matches!(event, AcpThreadEvent::Refusal) {
4152                        *saw_refusal_event_captured.lock().unwrap() = true;
4153                    }
4154                },
4155            )
4156            .detach();
4157        });
4158
4159        // Send a user message - this will trigger tool call and then refusal
4160        let send_task = thread.update(cx, |thread, cx| thread.send(vec!["Hello".into()], cx));
4161        cx.background_executor.spawn(send_task).detach();
4162        cx.run_until_parked();
4163
4164        // Verify that:
4165        // 1. A Refusal event WAS emitted (because it's a tool result refusal, not user prompt)
4166        // 2. The user message was NOT truncated
4167        assert!(
4168            *saw_refusal_event.lock().unwrap(),
4169            "Refusal event should be emitted for tool result refusals"
4170        );
4171
4172        thread.read_with(cx, |thread, _| {
4173            let entries = thread.entries();
4174            assert!(entries.len() >= 2, "Should have user message and tool call");
4175
4176            // Verify user message is still there
4177            assert!(
4178                matches!(entries[0], AgentThreadEntry::UserMessage(_)),
4179                "User message should not be truncated"
4180            );
4181
4182            // Verify tool call is there with result
4183            if let AgentThreadEntry::ToolCall(tool_call) = &entries[1] {
4184                assert!(
4185                    tool_call.raw_output.is_some(),
4186                    "Tool call should have output"
4187                );
4188            } else {
4189                panic!("Expected tool call at index 1");
4190            }
4191        });
4192    }
4193
4194    #[gpui::test]
4195    async fn test_user_prompt_refusal_emits_event(cx: &mut TestAppContext) {
4196        init_test(cx);
4197
4198        let fs = FakeFs::new(cx.executor());
4199        let project = Project::test(fs, None, cx).await;
4200
4201        let refuse_next = Arc::new(AtomicBool::new(false));
4202        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
4203            let refuse_next = refuse_next.clone();
4204            move |_request, _thread, _cx| {
4205                if refuse_next.load(SeqCst) {
4206                    async move { Ok(acp::PromptResponse::new(acp::StopReason::Refusal)) }
4207                        .boxed_local()
4208                } else {
4209                    async move { Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)) }
4210                        .boxed_local()
4211                }
4212            }
4213        }));
4214
4215        let thread = cx
4216            .update(|cx| {
4217                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
4218            })
4219            .await
4220            .unwrap();
4221
4222        // Track if we see a Refusal event
4223        let saw_refusal_event = Arc::new(std::sync::Mutex::new(false));
4224        let saw_refusal_event_captured = saw_refusal_event.clone();
4225        thread.update(cx, |_thread, cx| {
4226            cx.subscribe(
4227                &thread,
4228                move |_thread, _event_thread, event: &AcpThreadEvent, _cx| {
4229                    if matches!(event, AcpThreadEvent::Refusal) {
4230                        *saw_refusal_event_captured.lock().unwrap() = true;
4231                    }
4232                },
4233            )
4234            .detach();
4235        });
4236
4237        // Send a message that will be refused
4238        refuse_next.store(true, SeqCst);
4239        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["hello".into()], cx)))
4240            .await
4241            .unwrap();
4242
4243        // Verify that a Refusal event WAS emitted for user prompt refusal
4244        assert!(
4245            *saw_refusal_event.lock().unwrap(),
4246            "Refusal event should be emitted for user prompt refusals"
4247        );
4248
4249        // Verify the message was truncated (user prompt refusal)
4250        thread.read_with(cx, |thread, cx| {
4251            assert_eq!(thread.to_markdown(cx), "");
4252        });
4253    }
4254
4255    #[gpui::test]
4256    async fn test_refusal(cx: &mut TestAppContext) {
4257        init_test(cx);
4258        let fs = FakeFs::new(cx.background_executor.clone());
4259        fs.insert_tree(path!("/"), json!({})).await;
4260        let project = Project::test(fs.clone(), [path!("/").as_ref()], cx).await;
4261
4262        let refuse_next = Arc::new(AtomicBool::new(false));
4263        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
4264            let refuse_next = refuse_next.clone();
4265            move |request, thread, mut cx| {
4266                let refuse_next = refuse_next.clone();
4267                async move {
4268                    if refuse_next.load(SeqCst) {
4269                        return Ok(acp::PromptResponse::new(acp::StopReason::Refusal));
4270                    }
4271
4272                    let acp::ContentBlock::Text(content) = &request.prompt[0] else {
4273                        panic!("expected text content block");
4274                    };
4275                    thread.update(&mut cx, |thread, cx| {
4276                        thread
4277                            .handle_session_update(
4278                                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
4279                                    content.text.to_uppercase().into(),
4280                                )),
4281                                cx,
4282                            )
4283                            .unwrap();
4284                    })?;
4285                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
4286                }
4287                .boxed_local()
4288            }
4289        }));
4290        let thread = cx
4291            .update(|cx| {
4292                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
4293            })
4294            .await
4295            .unwrap();
4296
4297        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["hello".into()], cx)))
4298            .await
4299            .unwrap();
4300        thread.read_with(cx, |thread, cx| {
4301            assert_eq!(
4302                thread.to_markdown(cx),
4303                indoc! {"
4304                    ## User
4305
4306                    hello
4307
4308                    ## Assistant
4309
4310                    HELLO
4311
4312                "}
4313            );
4314        });
4315
4316        // Simulate refusing the second message. The message should be truncated
4317        // when a user prompt is refused.
4318        refuse_next.store(true, SeqCst);
4319        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["world".into()], cx)))
4320            .await
4321            .unwrap();
4322        thread.read_with(cx, |thread, cx| {
4323            assert_eq!(
4324                thread.to_markdown(cx),
4325                indoc! {"
4326                    ## User
4327
4328                    hello
4329
4330                    ## Assistant
4331
4332                    HELLO
4333
4334                "}
4335            );
4336        });
4337    }
4338
4339    async fn run_until_first_tool_call(
4340        thread: &Entity<AcpThread>,
4341        cx: &mut TestAppContext,
4342    ) -> usize {
4343        let (mut tx, mut rx) = mpsc::channel::<usize>(1);
4344
4345        let subscription = cx.update(|cx| {
4346            cx.subscribe(thread, move |thread, _, cx| {
4347                for (ix, entry) in thread.read(cx).entries.iter().enumerate() {
4348                    if matches!(entry, AgentThreadEntry::ToolCall(_)) {
4349                        return tx.try_send(ix).unwrap();
4350                    }
4351                }
4352            })
4353        });
4354
4355        select! {
4356            _ = futures::FutureExt::fuse(cx.background_executor.timer(Duration::from_secs(10))) => {
4357                panic!("Timeout waiting for tool call")
4358            }
4359            ix = rx.next().fuse() => {
4360                drop(subscription);
4361                ix.unwrap()
4362            }
4363        }
4364    }
4365
4366    #[derive(Clone, Default)]
4367    struct FakeAgentConnection {
4368        auth_methods: Vec<acp::AuthMethod>,
4369        sessions: Arc<parking_lot::Mutex<HashMap<acp::SessionId, WeakEntity<AcpThread>>>>,
4370        set_title_calls: Rc<RefCell<Vec<SharedString>>>,
4371        on_user_message: Option<
4372            Rc<
4373                dyn Fn(
4374                        acp::PromptRequest,
4375                        WeakEntity<AcpThread>,
4376                        AsyncApp,
4377                    ) -> LocalBoxFuture<'static, Result<acp::PromptResponse>>
4378                    + 'static,
4379            >,
4380        >,
4381    }
4382
4383    impl FakeAgentConnection {
4384        fn new() -> Self {
4385            Self {
4386                auth_methods: Vec::new(),
4387                on_user_message: None,
4388                sessions: Arc::default(),
4389                set_title_calls: Default::default(),
4390            }
4391        }
4392
4393        #[expect(unused)]
4394        fn with_auth_methods(mut self, auth_methods: Vec<acp::AuthMethod>) -> Self {
4395            self.auth_methods = auth_methods;
4396            self
4397        }
4398
4399        fn on_user_message(
4400            mut self,
4401            handler: impl Fn(
4402                acp::PromptRequest,
4403                WeakEntity<AcpThread>,
4404                AsyncApp,
4405            ) -> LocalBoxFuture<'static, Result<acp::PromptResponse>>
4406            + 'static,
4407        ) -> Self {
4408            self.on_user_message.replace(Rc::new(handler));
4409            self
4410        }
4411    }
4412
4413    impl AgentConnection for FakeAgentConnection {
4414        fn agent_id(&self) -> AgentId {
4415            AgentId::new("fake")
4416        }
4417
4418        fn telemetry_id(&self) -> SharedString {
4419            "fake".into()
4420        }
4421
4422        fn auth_methods(&self) -> &[acp::AuthMethod] {
4423            &self.auth_methods
4424        }
4425
4426        fn new_session(
4427            self: Rc<Self>,
4428            project: Entity<Project>,
4429            work_dirs: PathList,
4430            cx: &mut App,
4431        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4432            let session_id = acp::SessionId::new(
4433                rand::rng()
4434                    .sample_iter(&distr::Alphanumeric)
4435                    .take(7)
4436                    .map(char::from)
4437                    .collect::<String>(),
4438            );
4439            let action_log = cx.new(|_| ActionLog::new(project.clone()));
4440            let thread = cx.new(|cx| {
4441                AcpThread::new(
4442                    None,
4443                    None,
4444                    Some(work_dirs),
4445                    self.clone(),
4446                    project,
4447                    action_log,
4448                    session_id.clone(),
4449                    watch::Receiver::constant(
4450                        acp::PromptCapabilities::new()
4451                            .image(true)
4452                            .audio(true)
4453                            .embedded_context(true),
4454                    ),
4455                    cx,
4456                )
4457            });
4458            self.sessions.lock().insert(session_id, thread.downgrade());
4459            Task::ready(Ok(thread))
4460        }
4461
4462        fn authenticate(&self, method: acp::AuthMethodId, _cx: &mut App) -> Task<gpui::Result<()>> {
4463            if self.auth_methods().iter().any(|m| m.id() == &method) {
4464                Task::ready(Ok(()))
4465            } else {
4466                Task::ready(Err(anyhow!("Invalid Auth Method")))
4467            }
4468        }
4469
4470        fn prompt(
4471            &self,
4472            _id: Option<UserMessageId>,
4473            params: acp::PromptRequest,
4474            cx: &mut App,
4475        ) -> Task<gpui::Result<acp::PromptResponse>> {
4476            let sessions = self.sessions.lock();
4477            let thread = sessions.get(&params.session_id).unwrap();
4478            if let Some(handler) = &self.on_user_message {
4479                let handler = handler.clone();
4480                let thread = thread.clone();
4481                cx.spawn(async move |cx| handler(params, thread, cx.clone()).await)
4482            } else {
4483                Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
4484            }
4485        }
4486
4487        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
4488
4489        fn truncate(
4490            &self,
4491            session_id: &acp::SessionId,
4492            _cx: &App,
4493        ) -> Option<Rc<dyn AgentSessionTruncate>> {
4494            Some(Rc::new(FakeAgentSessionEditor {
4495                _session_id: session_id.clone(),
4496            }))
4497        }
4498
4499        fn set_title(
4500            &self,
4501            _session_id: &acp::SessionId,
4502            _cx: &App,
4503        ) -> Option<Rc<dyn AgentSessionSetTitle>> {
4504            Some(Rc::new(FakeAgentSessionSetTitle {
4505                calls: self.set_title_calls.clone(),
4506            }))
4507        }
4508
4509        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4510            self
4511        }
4512    }
4513
4514    struct FakeAgentSessionSetTitle {
4515        calls: Rc<RefCell<Vec<SharedString>>>,
4516    }
4517
4518    impl AgentSessionSetTitle for FakeAgentSessionSetTitle {
4519        fn run(&self, title: SharedString, _cx: &mut App) -> Task<Result<()>> {
4520            self.calls.borrow_mut().push(title);
4521            Task::ready(Ok(()))
4522        }
4523    }
4524
4525    struct FakeAgentSessionEditor {
4526        _session_id: acp::SessionId,
4527    }
4528
4529    impl AgentSessionTruncate for FakeAgentSessionEditor {
4530        fn run(&self, _message_id: UserMessageId, _cx: &mut App) -> Task<Result<()>> {
4531            Task::ready(Ok(()))
4532        }
4533    }
4534
4535    #[gpui::test]
4536    async fn test_tool_call_not_found_creates_failed_entry(cx: &mut TestAppContext) {
4537        init_test(cx);
4538
4539        let fs = FakeFs::new(cx.executor());
4540        let project = Project::test(fs, [], cx).await;
4541        let connection = Rc::new(FakeAgentConnection::new());
4542        let thread = cx
4543            .update(|cx| {
4544                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
4545            })
4546            .await
4547            .unwrap();
4548
4549        // Try to update a tool call that doesn't exist
4550        let nonexistent_id = acp::ToolCallId::new("nonexistent-tool-call");
4551        thread.update(cx, |thread, cx| {
4552            let result = thread.handle_session_update(
4553                acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
4554                    nonexistent_id.clone(),
4555                    acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::Completed),
4556                )),
4557                cx,
4558            );
4559
4560            // The update should succeed (not return an error)
4561            assert!(result.is_ok());
4562
4563            // There should now be exactly one entry in the thread
4564            assert_eq!(thread.entries.len(), 1);
4565
4566            // The entry should be a failed tool call
4567            if let AgentThreadEntry::ToolCall(tool_call) = &thread.entries[0] {
4568                assert_eq!(tool_call.id, nonexistent_id);
4569                assert!(matches!(tool_call.status, ToolCallStatus::Failed));
4570                assert_eq!(tool_call.kind, acp::ToolKind::Fetch);
4571
4572                // Check that the content contains the error message
4573                assert_eq!(tool_call.content.len(), 1);
4574                if let ToolCallContent::ContentBlock(content_block) = &tool_call.content[0] {
4575                    match content_block {
4576                        ContentBlock::Markdown { markdown } => {
4577                            let markdown_text = markdown.read(cx).source();
4578                            assert!(markdown_text.contains("Tool call not found"));
4579                        }
4580                        ContentBlock::Empty => panic!("Expected markdown content, got empty"),
4581                        ContentBlock::ResourceLink { .. } => {
4582                            panic!("Expected markdown content, got resource link")
4583                        }
4584                        ContentBlock::Image { .. } => {
4585                            panic!("Expected markdown content, got image")
4586                        }
4587                    }
4588                } else {
4589                    panic!("Expected ContentBlock, got: {:?}", tool_call.content[0]);
4590                }
4591            } else {
4592                panic!("Expected ToolCall entry, got: {:?}", thread.entries[0]);
4593            }
4594        });
4595    }
4596
4597    /// Tests that restoring a checkpoint properly cleans up terminals that were
4598    /// created after that checkpoint, and cancels any in-progress generation.
4599    ///
4600    /// Reproduces issue #35142: When a checkpoint is restored, any terminal processes
4601    /// that were started after that checkpoint should be terminated, and any in-progress
4602    /// AI generation should be canceled.
4603    #[gpui::test]
4604    async fn test_restore_checkpoint_kills_terminal(cx: &mut TestAppContext) {
4605        init_test(cx);
4606
4607        let fs = FakeFs::new(cx.executor());
4608        let project = Project::test(fs, [], cx).await;
4609        let connection = Rc::new(FakeAgentConnection::new());
4610        let thread = cx
4611            .update(|cx| {
4612                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
4613            })
4614            .await
4615            .unwrap();
4616
4617        // Send first user message to create a checkpoint
4618        cx.update(|cx| {
4619            thread.update(cx, |thread, cx| {
4620                thread.send(vec!["first message".into()], cx)
4621            })
4622        })
4623        .await
4624        .unwrap();
4625
4626        // Send second message (creates another checkpoint) - we'll restore to this one
4627        cx.update(|cx| {
4628            thread.update(cx, |thread, cx| {
4629                thread.send(vec!["second message".into()], cx)
4630            })
4631        })
4632        .await
4633        .unwrap();
4634
4635        // Create 2 terminals BEFORE the checkpoint that have completed running
4636        let terminal_id_1 = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
4637        let mock_terminal_1 = cx.new(|cx| {
4638            let builder = ::terminal::TerminalBuilder::new_display_only(
4639                ::terminal::terminal_settings::CursorShape::default(),
4640                ::terminal::terminal_settings::AlternateScroll::On,
4641                None,
4642                0,
4643                cx.background_executor(),
4644                PathStyle::local(),
4645            )
4646            .unwrap();
4647            builder.subscribe(cx)
4648        });
4649
4650        thread.update(cx, |thread, cx| {
4651            thread.on_terminal_provider_event(
4652                TerminalProviderEvent::Created {
4653                    terminal_id: terminal_id_1.clone(),
4654                    label: "echo 'first'".to_string(),
4655                    cwd: Some(PathBuf::from("/test")),
4656                    output_byte_limit: None,
4657                    terminal: mock_terminal_1.clone(),
4658                },
4659                cx,
4660            );
4661        });
4662
4663        thread.update(cx, |thread, cx| {
4664            thread.on_terminal_provider_event(
4665                TerminalProviderEvent::Output {
4666                    terminal_id: terminal_id_1.clone(),
4667                    data: b"first\n".to_vec(),
4668                },
4669                cx,
4670            );
4671        });
4672
4673        thread.update(cx, |thread, cx| {
4674            thread.on_terminal_provider_event(
4675                TerminalProviderEvent::Exit {
4676                    terminal_id: terminal_id_1.clone(),
4677                    status: acp::TerminalExitStatus::new().exit_code(0),
4678                },
4679                cx,
4680            );
4681        });
4682
4683        let terminal_id_2 = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
4684        let mock_terminal_2 = cx.new(|cx| {
4685            let builder = ::terminal::TerminalBuilder::new_display_only(
4686                ::terminal::terminal_settings::CursorShape::default(),
4687                ::terminal::terminal_settings::AlternateScroll::On,
4688                None,
4689                0,
4690                cx.background_executor(),
4691                PathStyle::local(),
4692            )
4693            .unwrap();
4694            builder.subscribe(cx)
4695        });
4696
4697        thread.update(cx, |thread, cx| {
4698            thread.on_terminal_provider_event(
4699                TerminalProviderEvent::Created {
4700                    terminal_id: terminal_id_2.clone(),
4701                    label: "echo 'second'".to_string(),
4702                    cwd: Some(PathBuf::from("/test")),
4703                    output_byte_limit: None,
4704                    terminal: mock_terminal_2.clone(),
4705                },
4706                cx,
4707            );
4708        });
4709
4710        thread.update(cx, |thread, cx| {
4711            thread.on_terminal_provider_event(
4712                TerminalProviderEvent::Output {
4713                    terminal_id: terminal_id_2.clone(),
4714                    data: b"second\n".to_vec(),
4715                },
4716                cx,
4717            );
4718        });
4719
4720        thread.update(cx, |thread, cx| {
4721            thread.on_terminal_provider_event(
4722                TerminalProviderEvent::Exit {
4723                    terminal_id: terminal_id_2.clone(),
4724                    status: acp::TerminalExitStatus::new().exit_code(0),
4725                },
4726                cx,
4727            );
4728        });
4729
4730        // Get the second message ID to restore to
4731        let second_message_id = thread.read_with(cx, |thread, _| {
4732            // At this point we have:
4733            // - Index 0: First user message (with checkpoint)
4734            // - Index 1: Second user message (with checkpoint)
4735            // No assistant responses because FakeAgentConnection just returns EndTurn
4736            let AgentThreadEntry::UserMessage(message) = &thread.entries[1] else {
4737                panic!("expected user message at index 1");
4738            };
4739            message.id.clone().unwrap()
4740        });
4741
4742        // Create a terminal AFTER the checkpoint we'll restore to.
4743        // This simulates the AI agent starting a long-running terminal command.
4744        let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
4745        let mock_terminal = cx.new(|cx| {
4746            let builder = ::terminal::TerminalBuilder::new_display_only(
4747                ::terminal::terminal_settings::CursorShape::default(),
4748                ::terminal::terminal_settings::AlternateScroll::On,
4749                None,
4750                0,
4751                cx.background_executor(),
4752                PathStyle::local(),
4753            )
4754            .unwrap();
4755            builder.subscribe(cx)
4756        });
4757
4758        // Register the terminal as created
4759        thread.update(cx, |thread, cx| {
4760            thread.on_terminal_provider_event(
4761                TerminalProviderEvent::Created {
4762                    terminal_id: terminal_id.clone(),
4763                    label: "sleep 1000".to_string(),
4764                    cwd: Some(PathBuf::from("/test")),
4765                    output_byte_limit: None,
4766                    terminal: mock_terminal.clone(),
4767                },
4768                cx,
4769            );
4770        });
4771
4772        // Simulate the terminal producing output (still running)
4773        thread.update(cx, |thread, cx| {
4774            thread.on_terminal_provider_event(
4775                TerminalProviderEvent::Output {
4776                    terminal_id: terminal_id.clone(),
4777                    data: b"terminal is running...\n".to_vec(),
4778                },
4779                cx,
4780            );
4781        });
4782
4783        // Create a tool call entry that references this terminal
4784        // This represents the agent requesting a terminal command
4785        thread.update(cx, |thread, cx| {
4786            thread
4787                .handle_session_update(
4788                    acp::SessionUpdate::ToolCall(
4789                        acp::ToolCall::new("terminal-tool-1", "Running command")
4790                            .kind(acp::ToolKind::Execute)
4791                            .status(acp::ToolCallStatus::InProgress)
4792                            .content(vec![acp::ToolCallContent::Terminal(acp::Terminal::new(
4793                                terminal_id.clone(),
4794                            ))])
4795                            .raw_input(serde_json::json!({"command": "sleep 1000", "cd": "/test"})),
4796                    ),
4797                    cx,
4798                )
4799                .unwrap();
4800        });
4801
4802        // Verify terminal exists and is in the thread
4803        let terminal_exists_before =
4804            thread.read_with(cx, |thread, _| thread.terminals.contains_key(&terminal_id));
4805        assert!(
4806            terminal_exists_before,
4807            "Terminal should exist before checkpoint restore"
4808        );
4809
4810        // Verify the terminal's underlying task is still running (not completed)
4811        let terminal_running_before = thread.read_with(cx, |thread, _cx| {
4812            let terminal_entity = thread.terminals.get(&terminal_id).unwrap();
4813            terminal_entity.read_with(cx, |term, _cx| {
4814                term.output().is_none() // output is None means it's still running
4815            })
4816        });
4817        assert!(
4818            terminal_running_before,
4819            "Terminal should be running before checkpoint restore"
4820        );
4821
4822        // Verify we have the expected entries before restore
4823        let entry_count_before = thread.read_with(cx, |thread, _| thread.entries.len());
4824        assert!(
4825            entry_count_before > 1,
4826            "Should have multiple entries before restore"
4827        );
4828
4829        // Restore the checkpoint to the second message.
4830        // This should:
4831        // 1. Cancel any in-progress generation (via the cancel() call)
4832        // 2. Remove the terminal that was created after that point
4833        thread
4834            .update(cx, |thread, cx| {
4835                thread.restore_checkpoint(second_message_id, cx)
4836            })
4837            .await
4838            .unwrap();
4839
4840        // Verify that no send_task is in progress after restore
4841        // (cancel() clears the send_task)
4842        let has_send_task_after = thread.read_with(cx, |thread, _| thread.running_turn.is_some());
4843        assert!(
4844            !has_send_task_after,
4845            "Should not have a send_task after restore (cancel should have cleared it)"
4846        );
4847
4848        // Verify the entries were truncated (restoring to index 1 truncates at 1, keeping only index 0)
4849        let entry_count = thread.read_with(cx, |thread, _| thread.entries.len());
4850        assert_eq!(
4851            entry_count, 1,
4852            "Should have 1 entry after restore (only the first user message)"
4853        );
4854
4855        // Verify the 2 completed terminals from before the checkpoint still exist
4856        let terminal_1_exists = thread.read_with(cx, |thread, _| {
4857            thread.terminals.contains_key(&terminal_id_1)
4858        });
4859        assert!(
4860            terminal_1_exists,
4861            "Terminal 1 (from before checkpoint) should still exist"
4862        );
4863
4864        let terminal_2_exists = thread.read_with(cx, |thread, _| {
4865            thread.terminals.contains_key(&terminal_id_2)
4866        });
4867        assert!(
4868            terminal_2_exists,
4869            "Terminal 2 (from before checkpoint) should still exist"
4870        );
4871
4872        // Verify they're still in completed state
4873        let terminal_1_completed = thread.read_with(cx, |thread, _cx| {
4874            let terminal_entity = thread.terminals.get(&terminal_id_1).unwrap();
4875            terminal_entity.read_with(cx, |term, _cx| term.output().is_some())
4876        });
4877        assert!(terminal_1_completed, "Terminal 1 should still be completed");
4878
4879        let terminal_2_completed = thread.read_with(cx, |thread, _cx| {
4880            let terminal_entity = thread.terminals.get(&terminal_id_2).unwrap();
4881            terminal_entity.read_with(cx, |term, _cx| term.output().is_some())
4882        });
4883        assert!(terminal_2_completed, "Terminal 2 should still be completed");
4884
4885        // Verify the running terminal (created after checkpoint) was removed
4886        let terminal_3_exists =
4887            thread.read_with(cx, |thread, _| thread.terminals.contains_key(&terminal_id));
4888        assert!(
4889            !terminal_3_exists,
4890            "Terminal 3 (created after checkpoint) should have been removed"
4891        );
4892
4893        // Verify total count is 2 (the two from before the checkpoint)
4894        let terminal_count = thread.read_with(cx, |thread, _| thread.terminals.len());
4895        assert_eq!(
4896            terminal_count, 2,
4897            "Should have exactly 2 terminals (the completed ones from before checkpoint)"
4898        );
4899    }
4900
4901    /// Tests that update_last_checkpoint correctly updates the original message's checkpoint
4902    /// even when a new user message is added while the async checkpoint comparison is in progress.
4903    ///
4904    /// This is a regression test for a bug where update_last_checkpoint would fail with
4905    /// "no checkpoint" if a new user message (without a checkpoint) was added between when
4906    /// update_last_checkpoint started and when its async closure ran.
4907    #[gpui::test]
4908    async fn test_update_last_checkpoint_with_new_message_added(cx: &mut TestAppContext) {
4909        init_test(cx);
4910
4911        let fs = FakeFs::new(cx.executor());
4912        fs.insert_tree(path!("/test"), json!({".git": {}, "file.txt": "content"}))
4913            .await;
4914        let project = Project::test(fs.clone(), [Path::new(path!("/test"))], cx).await;
4915
4916        let handler_done = Arc::new(AtomicBool::new(false));
4917        let handler_done_clone = handler_done.clone();
4918        let connection = Rc::new(FakeAgentConnection::new().on_user_message(
4919            move |_, _thread, _cx| {
4920                handler_done_clone.store(true, SeqCst);
4921                async move { Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)) }.boxed_local()
4922            },
4923        ));
4924
4925        let thread = cx
4926            .update(|cx| {
4927                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
4928            })
4929            .await
4930            .unwrap();
4931
4932        let send_future = thread.update(cx, |thread, cx| thread.send_raw("First message", cx));
4933        let send_task = cx.background_executor.spawn(send_future);
4934
4935        // Tick until handler completes, then a few more to let update_last_checkpoint start
4936        while !handler_done.load(SeqCst) {
4937            cx.executor().tick();
4938        }
4939        for _ in 0..5 {
4940            cx.executor().tick();
4941        }
4942
4943        thread.update(cx, |thread, cx| {
4944            thread.push_entry(
4945                AgentThreadEntry::UserMessage(UserMessage {
4946                    id: Some(UserMessageId::new()),
4947                    content: ContentBlock::Empty,
4948                    chunks: vec!["Injected message (no checkpoint)".into()],
4949                    checkpoint: None,
4950                    indented: false,
4951                }),
4952                cx,
4953            );
4954        });
4955
4956        cx.run_until_parked();
4957        let result = send_task.await;
4958
4959        assert!(
4960            result.is_ok(),
4961            "send should succeed even when new message added during update_last_checkpoint: {:?}",
4962            result.err()
4963        );
4964    }
4965
4966    /// Tests that when a follow-up message is sent during generation,
4967    /// the first turn completing does NOT clear `running_turn` because
4968    /// it now belongs to the second turn.
4969    #[gpui::test]
4970    async fn test_follow_up_message_during_generation_does_not_clear_turn(cx: &mut TestAppContext) {
4971        init_test(cx);
4972
4973        let fs = FakeFs::new(cx.executor());
4974        let project = Project::test(fs, [], cx).await;
4975
4976        // First handler waits for this signal before completing
4977        let (first_complete_tx, first_complete_rx) = futures::channel::oneshot::channel::<()>();
4978        let first_complete_rx = RefCell::new(Some(first_complete_rx));
4979
4980        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
4981            move |params, _thread, _cx| {
4982                let first_complete_rx = first_complete_rx.borrow_mut().take();
4983                let is_first = params
4984                    .prompt
4985                    .iter()
4986                    .any(|c| matches!(c, acp::ContentBlock::Text(t) if t.text.contains("first")));
4987
4988                async move {
4989                    if is_first {
4990                        // First handler waits until signaled
4991                        if let Some(rx) = first_complete_rx {
4992                            rx.await.ok();
4993                        }
4994                    }
4995                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
4996                }
4997                .boxed_local()
4998            }
4999        }));
5000
5001        let thread = cx
5002            .update(|cx| {
5003                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
5004            })
5005            .await
5006            .unwrap();
5007
5008        // Send first message (turn_id=1) - handler will block
5009        let first_request = thread.update(cx, |thread, cx| thread.send_raw("first", cx));
5010        assert_eq!(thread.read_with(cx, |t, _| t.turn_id), 1);
5011
5012        // Send second message (turn_id=2) while first is still blocked
5013        // This calls cancel() which takes turn 1's running_turn and sets turn 2's
5014        let second_request = thread.update(cx, |thread, cx| thread.send_raw("second", cx));
5015        assert_eq!(thread.read_with(cx, |t, _| t.turn_id), 2);
5016
5017        let running_turn_after_second_send =
5018            thread.read_with(cx, |thread, _| thread.running_turn.as_ref().map(|t| t.id));
5019        assert_eq!(
5020            running_turn_after_second_send,
5021            Some(2),
5022            "running_turn should be set to turn 2 after sending second message"
5023        );
5024
5025        // Now signal first handler to complete
5026        first_complete_tx.send(()).ok();
5027
5028        // First request completes - should NOT clear running_turn
5029        // because running_turn now belongs to turn 2
5030        first_request.await.unwrap();
5031
5032        let running_turn_after_first =
5033            thread.read_with(cx, |thread, _| thread.running_turn.as_ref().map(|t| t.id));
5034        assert_eq!(
5035            running_turn_after_first,
5036            Some(2),
5037            "first turn completing should not clear running_turn (belongs to turn 2)"
5038        );
5039
5040        // Second request completes - SHOULD clear running_turn
5041        second_request.await.unwrap();
5042
5043        let running_turn_after_second =
5044            thread.read_with(cx, |thread, _| thread.running_turn.is_some());
5045        assert!(
5046            !running_turn_after_second,
5047            "second turn completing should clear running_turn"
5048        );
5049    }
5050
5051    #[gpui::test]
5052    async fn test_send_returns_cancelled_response_and_marks_tools_as_cancelled(
5053        cx: &mut TestAppContext,
5054    ) {
5055        init_test(cx);
5056
5057        let fs = FakeFs::new(cx.executor());
5058        let project = Project::test(fs, [], cx).await;
5059
5060        let connection = Rc::new(FakeAgentConnection::new().on_user_message(
5061            move |_params, thread, mut cx| {
5062                async move {
5063                    thread
5064                        .update(&mut cx, |thread, cx| {
5065                            thread.handle_session_update(
5066                                acp::SessionUpdate::ToolCall(
5067                                    acp::ToolCall::new(
5068                                        acp::ToolCallId::new("test-tool"),
5069                                        "Test Tool",
5070                                    )
5071                                    .kind(acp::ToolKind::Fetch)
5072                                    .status(acp::ToolCallStatus::InProgress),
5073                                ),
5074                                cx,
5075                            )
5076                        })
5077                        .unwrap()
5078                        .unwrap();
5079
5080                    Ok(acp::PromptResponse::new(acp::StopReason::Cancelled))
5081                }
5082                .boxed_local()
5083            },
5084        ));
5085
5086        let thread = cx
5087            .update(|cx| {
5088                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
5089            })
5090            .await
5091            .unwrap();
5092
5093        let response = thread
5094            .update(cx, |thread, cx| thread.send_raw("test message", cx))
5095            .await;
5096
5097        let response = response
5098            .expect("send should succeed")
5099            .expect("should have response");
5100        assert_eq!(
5101            response.stop_reason,
5102            acp::StopReason::Cancelled,
5103            "response should have Cancelled stop_reason"
5104        );
5105
5106        thread.read_with(cx, |thread, _| {
5107            let tool_entry = thread
5108                .entries
5109                .iter()
5110                .find_map(|e| {
5111                    if let AgentThreadEntry::ToolCall(call) = e {
5112                        Some(call)
5113                    } else {
5114                        None
5115                    }
5116                })
5117                .expect("should have tool call entry");
5118
5119            assert!(
5120                matches!(tool_entry.status, ToolCallStatus::Canceled),
5121                "tool should be marked as Canceled when response is Cancelled, got {:?}",
5122                tool_entry.status
5123            );
5124        });
5125    }
5126
5127    #[gpui::test]
5128    async fn test_provisional_title_replaced_by_real_title(cx: &mut TestAppContext) {
5129        init_test(cx);
5130
5131        let fs = FakeFs::new(cx.executor());
5132        let project = Project::test(fs, [], cx).await;
5133        let connection = Rc::new(FakeAgentConnection::new());
5134        let set_title_calls = connection.set_title_calls.clone();
5135
5136        let thread = cx
5137            .update(|cx| {
5138                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
5139            })
5140            .await
5141            .unwrap();
5142
5143        // Initial title is the default.
5144        thread.read_with(cx, |thread, _| {
5145            assert_eq!(thread.title(), None);
5146        });
5147
5148        // Setting a provisional title updates the display title.
5149        thread.update(cx, |thread, cx| {
5150            thread.set_provisional_title("Hello, can you help…".into(), cx);
5151        });
5152        thread.read_with(cx, |thread, _| {
5153            assert_eq!(
5154                thread.title().as_ref().map(|s| s.as_str()),
5155                Some("Hello, can you help…")
5156            );
5157        });
5158
5159        // The provisional title should NOT have propagated to the connection.
5160        assert_eq!(
5161            set_title_calls.borrow().len(),
5162            0,
5163            "provisional title should not propagate to the connection"
5164        );
5165
5166        // When the real title arrives via set_title, it replaces the
5167        // provisional title and propagates to the connection.
5168        let task = thread.update(cx, |thread, cx| {
5169            thread.set_title("Helping with Rust question".into(), cx)
5170        });
5171        task.await.expect("set_title should succeed");
5172        thread.read_with(cx, |thread, _| {
5173            assert_eq!(
5174                thread.title().as_ref().map(|s| s.as_str()),
5175                Some("Helping with Rust question")
5176            );
5177        });
5178        assert_eq!(
5179            set_title_calls.borrow().as_slice(),
5180            &[SharedString::from("Helping with Rust question")],
5181            "real title should propagate to the connection"
5182        );
5183    }
5184
5185    #[gpui::test]
5186    async fn test_session_info_update_replaces_provisional_title_and_emits_event(
5187        cx: &mut TestAppContext,
5188    ) {
5189        init_test(cx);
5190
5191        let fs = FakeFs::new(cx.executor());
5192        let project = Project::test(fs, [], cx).await;
5193        let connection = Rc::new(FakeAgentConnection::new());
5194
5195        let thread = cx
5196            .update(|cx| {
5197                connection.clone().new_session(
5198                    project,
5199                    PathList::new(&[Path::new(path!("/test"))]),
5200                    cx,
5201                )
5202            })
5203            .await
5204            .unwrap();
5205
5206        let title_updated_events = Rc::new(RefCell::new(0usize));
5207        let title_updated_events_for_subscription = title_updated_events.clone();
5208        thread.update(cx, |_thread, cx| {
5209            cx.subscribe(
5210                &thread,
5211                move |_thread, _event_thread, event: &AcpThreadEvent, _cx| {
5212                    if matches!(event, AcpThreadEvent::TitleUpdated) {
5213                        *title_updated_events_for_subscription.borrow_mut() += 1;
5214                    }
5215                },
5216            )
5217            .detach();
5218        });
5219
5220        thread.update(cx, |thread, cx| {
5221            thread.set_provisional_title("Hello, can you help…".into(), cx);
5222        });
5223        assert_eq!(
5224            *title_updated_events.borrow(),
5225            1,
5226            "setting a provisional title should emit TitleUpdated"
5227        );
5228
5229        let result = thread.update(cx, |thread, cx| {
5230            thread.handle_session_update(
5231                acp::SessionUpdate::SessionInfoUpdate(
5232                    acp::SessionInfoUpdate::new().title("Helping with Rust question"),
5233                ),
5234                cx,
5235            )
5236        });
5237        result.expect("session info update should succeed");
5238
5239        thread.read_with(cx, |thread, _| {
5240            assert_eq!(
5241                thread.title().as_ref().map(|s| s.as_str()),
5242                Some("Helping with Rust question")
5243            );
5244            assert!(
5245                !thread.has_provisional_title(),
5246                "session info title update should clear provisional title"
5247            );
5248        });
5249
5250        assert_eq!(
5251            *title_updated_events.borrow(),
5252            2,
5253            "session info title update should emit TitleUpdated"
5254        );
5255        assert!(
5256            connection.set_title_calls.borrow().is_empty(),
5257            "session info title update should not propagate back to the connection"
5258        );
5259    }
5260}