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