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 = language::language_settings::language_settings(
2592                        buffer.language().map(|l| l.name()),
2593                        buffer.file(),
2594                        cx,
2595                    );
2596
2597                    settings.format_on_save != FormatOnSave::Off
2598                });
2599                action_log.update(cx, |action_log, cx| {
2600                    action_log.buffer_edited(buffer.clone(), cx);
2601                });
2602                format_on_save
2603            });
2604
2605            if format_on_save {
2606                let format_task = project.update(cx, |project, cx| {
2607                    project.format(
2608                        HashSet::from_iter([buffer.clone()]),
2609                        LspFormatTarget::Buffers,
2610                        false,
2611                        FormatTrigger::Save,
2612                        cx,
2613                    )
2614                });
2615                format_task.await.log_err();
2616
2617                action_log.update(cx, |action_log, cx| {
2618                    action_log.buffer_edited(buffer.clone(), cx);
2619                });
2620            }
2621
2622            project
2623                .update(cx, |project, cx| project.save_buffer(buffer, cx))
2624                .await
2625        })
2626    }
2627
2628    pub fn create_terminal(
2629        &self,
2630        command: String,
2631        args: Vec<String>,
2632        extra_env: Vec<acp::EnvVariable>,
2633        cwd: Option<PathBuf>,
2634        output_byte_limit: Option<u64>,
2635        cx: &mut Context<Self>,
2636    ) -> Task<Result<Entity<Terminal>>> {
2637        let env = match &cwd {
2638            Some(dir) => self.project.update(cx, |project, cx| {
2639                project.environment().update(cx, |env, cx| {
2640                    env.directory_environment(dir.as_path().into(), cx)
2641                })
2642            }),
2643            None => Task::ready(None).shared(),
2644        };
2645        let env = cx.spawn(async move |_, _| {
2646            let mut env = env.await.unwrap_or_default();
2647            // Disables paging for `git` and hopefully other commands
2648            env.insert("PAGER".into(), "".into());
2649            for var in extra_env {
2650                env.insert(var.name, var.value);
2651            }
2652            env
2653        });
2654
2655        let project = self.project.clone();
2656        let language_registry = project.read(cx).languages().clone();
2657        let is_windows = project.read(cx).path_style(cx).is_windows();
2658
2659        let terminal_id = acp::TerminalId::new(Uuid::new_v4().to_string());
2660        let terminal_task = cx.spawn({
2661            let terminal_id = terminal_id.clone();
2662            async move |_this, cx| {
2663                let env = env.await;
2664                let shell = project
2665                    .update(cx, |project, cx| {
2666                        project
2667                            .remote_client()
2668                            .and_then(|r| r.read(cx).default_system_shell())
2669                    })
2670                    .unwrap_or_else(|| get_default_system_shell_preferring_bash());
2671                let (task_command, task_args) =
2672                    ShellBuilder::new(&Shell::Program(shell), is_windows)
2673                        .redirect_stdin_to_dev_null()
2674                        .build(Some(command.clone()), &args);
2675                let terminal = project
2676                    .update(cx, |project, cx| {
2677                        project.create_terminal_task(
2678                            task::SpawnInTerminal {
2679                                command: Some(task_command),
2680                                args: task_args,
2681                                cwd: cwd.clone(),
2682                                env,
2683                                ..Default::default()
2684                            },
2685                            cx,
2686                        )
2687                    })
2688                    .await?;
2689
2690                anyhow::Ok(cx.new(|cx| {
2691                    Terminal::new(
2692                        terminal_id,
2693                        &format!("{} {}", command, args.join(" ")),
2694                        cwd,
2695                        output_byte_limit.map(|l| l as usize),
2696                        terminal,
2697                        language_registry,
2698                        cx,
2699                    )
2700                }))
2701            }
2702        });
2703
2704        cx.spawn(async move |this, cx| {
2705            let terminal = terminal_task.await?;
2706            this.update(cx, |this, _cx| {
2707                this.terminals.insert(terminal_id, terminal.clone());
2708                terminal
2709            })
2710        })
2711    }
2712
2713    pub fn kill_terminal(
2714        &mut self,
2715        terminal_id: acp::TerminalId,
2716        cx: &mut Context<Self>,
2717    ) -> Result<()> {
2718        self.terminals
2719            .get(&terminal_id)
2720            .context("Terminal not found")?
2721            .update(cx, |terminal, cx| {
2722                terminal.kill(cx);
2723            });
2724
2725        Ok(())
2726    }
2727
2728    pub fn release_terminal(
2729        &mut self,
2730        terminal_id: acp::TerminalId,
2731        cx: &mut Context<Self>,
2732    ) -> Result<()> {
2733        self.terminals
2734            .remove(&terminal_id)
2735            .context("Terminal not found")?
2736            .update(cx, |terminal, cx| {
2737                terminal.kill(cx);
2738            });
2739
2740        Ok(())
2741    }
2742
2743    pub fn terminal(&self, terminal_id: acp::TerminalId) -> Result<Entity<Terminal>> {
2744        self.terminals
2745            .get(&terminal_id)
2746            .context("Terminal not found")
2747            .cloned()
2748    }
2749
2750    pub fn to_markdown(&self, cx: &App) -> String {
2751        self.entries.iter().map(|e| e.to_markdown(cx)).collect()
2752    }
2753
2754    pub fn emit_load_error(&mut self, error: LoadError, cx: &mut Context<Self>) {
2755        cx.emit(AcpThreadEvent::LoadError(error));
2756    }
2757
2758    pub fn register_terminal_created(
2759        &mut self,
2760        terminal_id: acp::TerminalId,
2761        command_label: String,
2762        working_dir: Option<PathBuf>,
2763        output_byte_limit: Option<u64>,
2764        terminal: Entity<::terminal::Terminal>,
2765        cx: &mut Context<Self>,
2766    ) -> Entity<Terminal> {
2767        let language_registry = self.project.read(cx).languages().clone();
2768
2769        let entity = cx.new(|cx| {
2770            Terminal::new(
2771                terminal_id.clone(),
2772                &command_label,
2773                working_dir.clone(),
2774                output_byte_limit.map(|l| l as usize),
2775                terminal,
2776                language_registry,
2777                cx,
2778            )
2779        });
2780        self.terminals.insert(terminal_id.clone(), entity.clone());
2781        entity
2782    }
2783
2784    pub fn mark_as_subagent_output(&mut self, cx: &mut Context<Self>) {
2785        for entry in self.entries.iter_mut().rev() {
2786            if let AgentThreadEntry::AssistantMessage(assistant_message) = entry {
2787                assistant_message.is_subagent_output = true;
2788                cx.notify();
2789                return;
2790            }
2791        }
2792    }
2793
2794    pub fn on_terminal_provider_event(
2795        &mut self,
2796        event: TerminalProviderEvent,
2797        cx: &mut Context<Self>,
2798    ) {
2799        match event {
2800            TerminalProviderEvent::Created {
2801                terminal_id,
2802                label,
2803                cwd,
2804                output_byte_limit,
2805                terminal,
2806            } => {
2807                let entity = self.register_terminal_created(
2808                    terminal_id.clone(),
2809                    label,
2810                    cwd,
2811                    output_byte_limit,
2812                    terminal,
2813                    cx,
2814                );
2815
2816                if let Some(mut chunks) = self.pending_terminal_output.remove(&terminal_id) {
2817                    for data in chunks.drain(..) {
2818                        entity.update(cx, |term, cx| {
2819                            term.inner().update(cx, |inner, cx| {
2820                                inner.write_output(&data, cx);
2821                            })
2822                        });
2823                    }
2824                }
2825
2826                if let Some(_status) = self.pending_terminal_exit.remove(&terminal_id) {
2827                    entity.update(cx, |_term, cx| {
2828                        cx.notify();
2829                    });
2830                }
2831
2832                cx.notify();
2833            }
2834            TerminalProviderEvent::Output { terminal_id, data } => {
2835                if let Some(entity) = self.terminals.get(&terminal_id) {
2836                    entity.update(cx, |term, cx| {
2837                        term.inner().update(cx, |inner, cx| {
2838                            inner.write_output(&data, cx);
2839                        })
2840                    });
2841                } else {
2842                    self.pending_terminal_output
2843                        .entry(terminal_id)
2844                        .or_default()
2845                        .push(data);
2846                }
2847            }
2848            TerminalProviderEvent::TitleChanged { terminal_id, title } => {
2849                if let Some(entity) = self.terminals.get(&terminal_id) {
2850                    entity.update(cx, |term, cx| {
2851                        term.inner().update(cx, |inner, cx| {
2852                            inner.breadcrumb_text = title;
2853                            cx.emit(::terminal::Event::BreadcrumbsChanged);
2854                        })
2855                    });
2856                }
2857            }
2858            TerminalProviderEvent::Exit {
2859                terminal_id,
2860                status,
2861            } => {
2862                if let Some(entity) = self.terminals.get(&terminal_id) {
2863                    entity.update(cx, |_term, cx| {
2864                        cx.notify();
2865                    });
2866                } else {
2867                    self.pending_terminal_exit.insert(terminal_id, status);
2868                }
2869            }
2870        }
2871    }
2872}
2873
2874fn markdown_for_raw_output(
2875    raw_output: &serde_json::Value,
2876    language_registry: &Arc<LanguageRegistry>,
2877    cx: &mut App,
2878) -> Option<Entity<Markdown>> {
2879    match raw_output {
2880        serde_json::Value::Null => None,
2881        serde_json::Value::Bool(value) => Some(cx.new(|cx| {
2882            Markdown::new(
2883                value.to_string().into(),
2884                Some(language_registry.clone()),
2885                None,
2886                cx,
2887            )
2888        })),
2889        serde_json::Value::Number(value) => Some(cx.new(|cx| {
2890            Markdown::new(
2891                value.to_string().into(),
2892                Some(language_registry.clone()),
2893                None,
2894                cx,
2895            )
2896        })),
2897        serde_json::Value::String(value) => Some(cx.new(|cx| {
2898            Markdown::new(
2899                value.clone().into(),
2900                Some(language_registry.clone()),
2901                None,
2902                cx,
2903            )
2904        })),
2905        value => Some(cx.new(|cx| {
2906            let pretty_json = to_string_pretty(value).unwrap_or_else(|_| value.to_string());
2907
2908            Markdown::new(
2909                format!("```json\n{}\n```", pretty_json).into(),
2910                Some(language_registry.clone()),
2911                None,
2912                cx,
2913            )
2914        })),
2915    }
2916}
2917
2918#[cfg(test)]
2919mod tests {
2920    use super::*;
2921    use anyhow::anyhow;
2922    use futures::{channel::mpsc, future::LocalBoxFuture, select};
2923    use gpui::{App, AsyncApp, TestAppContext, WeakEntity};
2924    use indoc::indoc;
2925    use project::{AgentId, FakeFs, Fs};
2926    use rand::{distr, prelude::*};
2927    use serde_json::json;
2928    use settings::SettingsStore;
2929    use smol::stream::StreamExt as _;
2930    use std::{
2931        any::Any,
2932        cell::RefCell,
2933        path::Path,
2934        rc::Rc,
2935        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
2936        time::Duration,
2937    };
2938    use util::{path, path_list::PathList};
2939
2940    fn init_test(cx: &mut TestAppContext) {
2941        env_logger::try_init().ok();
2942        cx.update(|cx| {
2943            let settings_store = SettingsStore::test(cx);
2944            cx.set_global(settings_store);
2945        });
2946    }
2947
2948    #[gpui::test]
2949    async fn test_terminal_output_buffered_before_created_renders(cx: &mut gpui::TestAppContext) {
2950        init_test(cx);
2951
2952        let fs = FakeFs::new(cx.executor());
2953        let project = Project::test(fs, [], cx).await;
2954        let connection = Rc::new(FakeAgentConnection::new());
2955        let thread = cx
2956            .update(|cx| {
2957                connection.new_session(
2958                    project,
2959                    PathList::new(&[std::path::Path::new(path!("/test"))]),
2960                    cx,
2961                )
2962            })
2963            .await
2964            .unwrap();
2965
2966        let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
2967
2968        // Send Output BEFORE Created - should be buffered by acp_thread
2969        thread.update(cx, |thread, cx| {
2970            thread.on_terminal_provider_event(
2971                TerminalProviderEvent::Output {
2972                    terminal_id: terminal_id.clone(),
2973                    data: b"hello buffered".to_vec(),
2974                },
2975                cx,
2976            );
2977        });
2978
2979        // Create a display-only terminal and then send Created
2980        let lower = cx.new(|cx| {
2981            let builder = ::terminal::TerminalBuilder::new_display_only(
2982                ::terminal::terminal_settings::CursorShape::default(),
2983                ::terminal::terminal_settings::AlternateScroll::On,
2984                None,
2985                0,
2986                cx.background_executor(),
2987                PathStyle::local(),
2988            )
2989            .unwrap();
2990            builder.subscribe(cx)
2991        });
2992
2993        thread.update(cx, |thread, cx| {
2994            thread.on_terminal_provider_event(
2995                TerminalProviderEvent::Created {
2996                    terminal_id: terminal_id.clone(),
2997                    label: "Buffered Test".to_string(),
2998                    cwd: None,
2999                    output_byte_limit: None,
3000                    terminal: lower.clone(),
3001                },
3002                cx,
3003            );
3004        });
3005
3006        // After Created, buffered Output should have been flushed into the renderer
3007        let content = thread.read_with(cx, |thread, cx| {
3008            let term = thread.terminal(terminal_id.clone()).unwrap();
3009            term.read_with(cx, |t, cx| t.inner().read(cx).get_content())
3010        });
3011
3012        assert!(
3013            content.contains("hello buffered"),
3014            "expected buffered output to render, got: {content}"
3015        );
3016    }
3017
3018    #[gpui::test]
3019    async fn test_terminal_output_and_exit_buffered_before_created(cx: &mut gpui::TestAppContext) {
3020        init_test(cx);
3021
3022        let fs = FakeFs::new(cx.executor());
3023        let project = Project::test(fs, [], cx).await;
3024        let connection = Rc::new(FakeAgentConnection::new());
3025        let thread = cx
3026            .update(|cx| {
3027                connection.new_session(
3028                    project,
3029                    PathList::new(&[std::path::Path::new(path!("/test"))]),
3030                    cx,
3031                )
3032            })
3033            .await
3034            .unwrap();
3035
3036        let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
3037
3038        // Send Output BEFORE Created
3039        thread.update(cx, |thread, cx| {
3040            thread.on_terminal_provider_event(
3041                TerminalProviderEvent::Output {
3042                    terminal_id: terminal_id.clone(),
3043                    data: b"pre-exit data".to_vec(),
3044                },
3045                cx,
3046            );
3047        });
3048
3049        // Send Exit BEFORE Created
3050        thread.update(cx, |thread, cx| {
3051            thread.on_terminal_provider_event(
3052                TerminalProviderEvent::Exit {
3053                    terminal_id: terminal_id.clone(),
3054                    status: acp::TerminalExitStatus::new().exit_code(0),
3055                },
3056                cx,
3057            );
3058        });
3059
3060        // Now create a display-only lower-level terminal and send Created
3061        let lower = cx.new(|cx| {
3062            let builder = ::terminal::TerminalBuilder::new_display_only(
3063                ::terminal::terminal_settings::CursorShape::default(),
3064                ::terminal::terminal_settings::AlternateScroll::On,
3065                None,
3066                0,
3067                cx.background_executor(),
3068                PathStyle::local(),
3069            )
3070            .unwrap();
3071            builder.subscribe(cx)
3072        });
3073
3074        thread.update(cx, |thread, cx| {
3075            thread.on_terminal_provider_event(
3076                TerminalProviderEvent::Created {
3077                    terminal_id: terminal_id.clone(),
3078                    label: "Buffered Exit Test".to_string(),
3079                    cwd: None,
3080                    output_byte_limit: None,
3081                    terminal: lower.clone(),
3082                },
3083                cx,
3084            );
3085        });
3086
3087        // Output should be present after Created (flushed from buffer)
3088        let content = thread.read_with(cx, |thread, cx| {
3089            let term = thread.terminal(terminal_id.clone()).unwrap();
3090            term.read_with(cx, |t, cx| t.inner().read(cx).get_content())
3091        });
3092
3093        assert!(
3094            content.contains("pre-exit data"),
3095            "expected pre-exit data to render, got: {content}"
3096        );
3097    }
3098
3099    /// Test that killing a terminal via Terminal::kill properly:
3100    /// 1. Causes wait_for_exit to complete (doesn't hang forever)
3101    /// 2. The underlying terminal still has the output that was written before the kill
3102    ///
3103    /// This test verifies that the fix to kill_active_task (which now also kills
3104    /// the shell process in addition to the foreground process) properly allows
3105    /// wait_for_exit to complete instead of hanging indefinitely.
3106    #[cfg(unix)]
3107    #[gpui::test]
3108    async fn test_terminal_kill_allows_wait_for_exit_to_complete(cx: &mut gpui::TestAppContext) {
3109        use std::collections::HashMap;
3110        use task::Shell;
3111        use util::shell_builder::ShellBuilder;
3112
3113        init_test(cx);
3114        cx.executor().allow_parking();
3115
3116        let fs = FakeFs::new(cx.executor());
3117        let project = Project::test(fs, [], cx).await;
3118        let connection = Rc::new(FakeAgentConnection::new());
3119        let thread = cx
3120            .update(|cx| {
3121                connection.new_session(
3122                    project.clone(),
3123                    PathList::new(&[Path::new(path!("/test"))]),
3124                    cx,
3125                )
3126            })
3127            .await
3128            .unwrap();
3129
3130        let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
3131
3132        // Create a real PTY terminal that runs a command which prints output then sleeps
3133        // We use printf instead of echo and chain with && sleep to ensure proper execution
3134        let (completion_tx, _completion_rx) = smol::channel::unbounded();
3135        let (program, args) = ShellBuilder::new(&Shell::System, false).build(
3136            Some("printf 'output_before_kill\\n' && sleep 60".to_owned()),
3137            &[],
3138        );
3139
3140        let builder = cx
3141            .update(|cx| {
3142                ::terminal::TerminalBuilder::new(
3143                    None,
3144                    None,
3145                    task::Shell::WithArguments {
3146                        program,
3147                        args,
3148                        title_override: None,
3149                    },
3150                    HashMap::default(),
3151                    ::terminal::terminal_settings::CursorShape::default(),
3152                    ::terminal::terminal_settings::AlternateScroll::On,
3153                    None,
3154                    vec![],
3155                    0,
3156                    false,
3157                    0,
3158                    Some(completion_tx),
3159                    cx,
3160                    vec![],
3161                    PathStyle::local(),
3162                )
3163            })
3164            .await
3165            .unwrap();
3166
3167        let lower_terminal = cx.new(|cx| builder.subscribe(cx));
3168
3169        // Create the acp_thread Terminal wrapper
3170        thread.update(cx, |thread, cx| {
3171            thread.on_terminal_provider_event(
3172                TerminalProviderEvent::Created {
3173                    terminal_id: terminal_id.clone(),
3174                    label: "printf output_before_kill && sleep 60".to_string(),
3175                    cwd: None,
3176                    output_byte_limit: None,
3177                    terminal: lower_terminal.clone(),
3178                },
3179                cx,
3180            );
3181        });
3182
3183        // Wait for the printf command to execute and produce output
3184        // Use real time since parking is enabled
3185        cx.executor().timer(Duration::from_millis(500)).await;
3186
3187        // Get the acp_thread Terminal and kill it
3188        let wait_for_exit = thread.update(cx, |thread, cx| {
3189            let term = thread.terminals.get(&terminal_id).unwrap();
3190            let wait_for_exit = term.read(cx).wait_for_exit();
3191            term.update(cx, |term, cx| {
3192                term.kill(cx);
3193            });
3194            wait_for_exit
3195        });
3196
3197        // KEY ASSERTION: wait_for_exit should complete within a reasonable time (not hang).
3198        // Before the fix to kill_active_task, this would hang forever because
3199        // only the foreground process was killed, not the shell, so the PTY
3200        // child never exited and wait_for_completed_task never completed.
3201        let exit_result = futures::select! {
3202            result = futures::FutureExt::fuse(wait_for_exit) => Some(result),
3203            _ = futures::FutureExt::fuse(cx.background_executor.timer(Duration::from_secs(5))) => None,
3204        };
3205
3206        assert!(
3207            exit_result.is_some(),
3208            "wait_for_exit should complete after kill, but it timed out. \
3209            This indicates kill_active_task is not properly killing the shell process."
3210        );
3211
3212        // Give the system a chance to process any pending updates
3213        cx.run_until_parked();
3214
3215        // Verify that the underlying terminal still has the output that was
3216        // written before the kill. This verifies that killing doesn't lose output.
3217        let inner_content = thread.read_with(cx, |thread, cx| {
3218            let term = thread.terminals.get(&terminal_id).unwrap();
3219            term.read(cx).inner().read(cx).get_content()
3220        });
3221
3222        assert!(
3223            inner_content.contains("output_before_kill"),
3224            "Underlying terminal should contain output from before kill, got: {}",
3225            inner_content
3226        );
3227    }
3228
3229    #[gpui::test]
3230    async fn test_push_user_content_block(cx: &mut gpui::TestAppContext) {
3231        init_test(cx);
3232
3233        let fs = FakeFs::new(cx.executor());
3234        let project = Project::test(fs, [], cx).await;
3235        let connection = Rc::new(FakeAgentConnection::new());
3236        let thread = cx
3237            .update(|cx| {
3238                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
3239            })
3240            .await
3241            .unwrap();
3242
3243        // Test creating a new user message
3244        thread.update(cx, |thread, cx| {
3245            thread.push_user_content_block(None, "Hello, ".into(), cx);
3246        });
3247
3248        thread.update(cx, |thread, cx| {
3249            assert_eq!(thread.entries.len(), 1);
3250            if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
3251                assert_eq!(user_msg.id, None);
3252                assert_eq!(user_msg.content.to_markdown(cx), "Hello, ");
3253            } else {
3254                panic!("Expected UserMessage");
3255            }
3256        });
3257
3258        // Test appending to existing user message
3259        let message_1_id = UserMessageId::new();
3260        thread.update(cx, |thread, cx| {
3261            thread.push_user_content_block(Some(message_1_id.clone()), "world!".into(), cx);
3262        });
3263
3264        thread.update(cx, |thread, cx| {
3265            assert_eq!(thread.entries.len(), 1);
3266            if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
3267                assert_eq!(user_msg.id, Some(message_1_id));
3268                assert_eq!(user_msg.content.to_markdown(cx), "Hello, world!");
3269            } else {
3270                panic!("Expected UserMessage");
3271            }
3272        });
3273
3274        // Test creating new user message after assistant message
3275        thread.update(cx, |thread, cx| {
3276            thread.push_assistant_content_block("Assistant response".into(), false, cx);
3277        });
3278
3279        let message_2_id = UserMessageId::new();
3280        thread.update(cx, |thread, cx| {
3281            thread.push_user_content_block(
3282                Some(message_2_id.clone()),
3283                "New user message".into(),
3284                cx,
3285            );
3286        });
3287
3288        thread.update(cx, |thread, cx| {
3289            assert_eq!(thread.entries.len(), 3);
3290            if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[2] {
3291                assert_eq!(user_msg.id, Some(message_2_id));
3292                assert_eq!(user_msg.content.to_markdown(cx), "New user message");
3293            } else {
3294                panic!("Expected UserMessage at index 2");
3295            }
3296        });
3297    }
3298
3299    #[gpui::test]
3300    async fn test_thinking_concatenation(cx: &mut gpui::TestAppContext) {
3301        init_test(cx);
3302
3303        let fs = FakeFs::new(cx.executor());
3304        let project = Project::test(fs, [], cx).await;
3305        let connection = Rc::new(FakeAgentConnection::new().on_user_message(
3306            |_, thread, mut cx| {
3307                async move {
3308                    thread.update(&mut cx, |thread, cx| {
3309                        thread
3310                            .handle_session_update(
3311                                acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk::new(
3312                                    "Thinking ".into(),
3313                                )),
3314                                cx,
3315                            )
3316                            .unwrap();
3317                        thread
3318                            .handle_session_update(
3319                                acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk::new(
3320                                    "hard!".into(),
3321                                )),
3322                                cx,
3323                            )
3324                            .unwrap();
3325                    })?;
3326                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3327                }
3328                .boxed_local()
3329            },
3330        ));
3331
3332        let thread = cx
3333            .update(|cx| {
3334                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
3335            })
3336            .await
3337            .unwrap();
3338
3339        thread
3340            .update(cx, |thread, cx| thread.send_raw("Hello from Zed!", cx))
3341            .await
3342            .unwrap();
3343
3344        let output = thread.read_with(cx, |thread, cx| thread.to_markdown(cx));
3345        assert_eq!(
3346            output,
3347            indoc! {r#"
3348            ## User
3349
3350            Hello from Zed!
3351
3352            ## Assistant
3353
3354            <thinking>
3355            Thinking hard!
3356            </thinking>
3357
3358            "#}
3359        );
3360    }
3361
3362    #[gpui::test]
3363    async fn test_edits_concurrently_to_user(cx: &mut TestAppContext) {
3364        init_test(cx);
3365
3366        let fs = FakeFs::new(cx.executor());
3367        fs.insert_tree(path!("/tmp"), json!({"foo": "one\ntwo\nthree\n"}))
3368            .await;
3369        let project = Project::test(fs.clone(), [], cx).await;
3370        let (read_file_tx, read_file_rx) = oneshot::channel::<()>();
3371        let read_file_tx = Rc::new(RefCell::new(Some(read_file_tx)));
3372        let connection = Rc::new(FakeAgentConnection::new().on_user_message(
3373            move |_, thread, mut cx| {
3374                let read_file_tx = read_file_tx.clone();
3375                async move {
3376                    let content = thread
3377                        .update(&mut cx, |thread, cx| {
3378                            thread.read_text_file(path!("/tmp/foo").into(), None, None, false, cx)
3379                        })
3380                        .unwrap()
3381                        .await
3382                        .unwrap();
3383                    assert_eq!(content, "one\ntwo\nthree\n");
3384                    read_file_tx.take().unwrap().send(()).unwrap();
3385                    thread
3386                        .update(&mut cx, |thread, cx| {
3387                            thread.write_text_file(
3388                                path!("/tmp/foo").into(),
3389                                "one\ntwo\nthree\nfour\nfive\n".to_string(),
3390                                cx,
3391                            )
3392                        })
3393                        .unwrap()
3394                        .await
3395                        .unwrap();
3396                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3397                }
3398                .boxed_local()
3399            },
3400        ));
3401
3402        let (worktree, pathbuf) = project
3403            .update(cx, |project, cx| {
3404                project.find_or_create_worktree(path!("/tmp/foo"), true, cx)
3405            })
3406            .await
3407            .unwrap();
3408        let buffer = project
3409            .update(cx, |project, cx| {
3410                project.open_buffer((worktree.read(cx).id(), pathbuf), cx)
3411            })
3412            .await
3413            .unwrap();
3414
3415        let thread = cx
3416            .update(|cx| {
3417                connection.new_session(project, PathList::new(&[Path::new(path!("/tmp"))]), cx)
3418            })
3419            .await
3420            .unwrap();
3421
3422        let request = thread.update(cx, |thread, cx| {
3423            thread.send_raw("Extend the count in /tmp/foo", cx)
3424        });
3425        read_file_rx.await.ok();
3426        buffer.update(cx, |buffer, cx| {
3427            buffer.edit([(0..0, "zero\n".to_string())], None, cx);
3428        });
3429        cx.run_until_parked();
3430        assert_eq!(
3431            buffer.read_with(cx, |buffer, _| buffer.text()),
3432            "zero\none\ntwo\nthree\nfour\nfive\n"
3433        );
3434        assert_eq!(
3435            String::from_utf8(fs.read_file_sync(path!("/tmp/foo")).unwrap()).unwrap(),
3436            "zero\none\ntwo\nthree\nfour\nfive\n"
3437        );
3438        request.await.unwrap();
3439    }
3440
3441    #[gpui::test]
3442    async fn test_reading_from_line(cx: &mut TestAppContext) {
3443        init_test(cx);
3444
3445        let fs = FakeFs::new(cx.executor());
3446        fs.insert_tree(path!("/tmp"), json!({"foo": "one\ntwo\nthree\nfour\n"}))
3447            .await;
3448        let project = Project::test(fs.clone(), [], cx).await;
3449        project
3450            .update(cx, |project, cx| {
3451                project.find_or_create_worktree(path!("/tmp/foo"), true, cx)
3452            })
3453            .await
3454            .unwrap();
3455
3456        let connection = Rc::new(FakeAgentConnection::new());
3457
3458        let thread = cx
3459            .update(|cx| {
3460                connection.new_session(project, PathList::new(&[Path::new(path!("/tmp"))]), cx)
3461            })
3462            .await
3463            .unwrap();
3464
3465        // Whole file
3466        let content = thread
3467            .update(cx, |thread, cx| {
3468                thread.read_text_file(path!("/tmp/foo").into(), None, None, false, cx)
3469            })
3470            .await
3471            .unwrap();
3472
3473        assert_eq!(content, "one\ntwo\nthree\nfour\n");
3474
3475        // Only start line
3476        let content = thread
3477            .update(cx, |thread, cx| {
3478                thread.read_text_file(path!("/tmp/foo").into(), Some(3), None, false, cx)
3479            })
3480            .await
3481            .unwrap();
3482
3483        assert_eq!(content, "three\nfour\n");
3484
3485        // Only limit
3486        let content = thread
3487            .update(cx, |thread, cx| {
3488                thread.read_text_file(path!("/tmp/foo").into(), None, Some(2), false, cx)
3489            })
3490            .await
3491            .unwrap();
3492
3493        assert_eq!(content, "one\ntwo\n");
3494
3495        // Range
3496        let content = thread
3497            .update(cx, |thread, cx| {
3498                thread.read_text_file(path!("/tmp/foo").into(), Some(2), Some(2), false, cx)
3499            })
3500            .await
3501            .unwrap();
3502
3503        assert_eq!(content, "two\nthree\n");
3504
3505        // Invalid
3506        let err = thread
3507            .update(cx, |thread, cx| {
3508                thread.read_text_file(path!("/tmp/foo").into(), Some(6), Some(2), false, cx)
3509            })
3510            .await
3511            .unwrap_err();
3512
3513        assert_eq!(
3514            err.to_string(),
3515            "Invalid params: \"Attempting to read beyond the end of the file, line 5:0\""
3516        );
3517    }
3518
3519    #[gpui::test]
3520    async fn test_reading_empty_file(cx: &mut TestAppContext) {
3521        init_test(cx);
3522
3523        let fs = FakeFs::new(cx.executor());
3524        fs.insert_tree(path!("/tmp"), json!({"foo": ""})).await;
3525        let project = Project::test(fs.clone(), [], cx).await;
3526        project
3527            .update(cx, |project, cx| {
3528                project.find_or_create_worktree(path!("/tmp/foo"), true, cx)
3529            })
3530            .await
3531            .unwrap();
3532
3533        let connection = Rc::new(FakeAgentConnection::new());
3534
3535        let thread = cx
3536            .update(|cx| {
3537                connection.new_session(project, PathList::new(&[Path::new(path!("/tmp"))]), cx)
3538            })
3539            .await
3540            .unwrap();
3541
3542        // Whole file
3543        let content = thread
3544            .update(cx, |thread, cx| {
3545                thread.read_text_file(path!("/tmp/foo").into(), None, None, false, cx)
3546            })
3547            .await
3548            .unwrap();
3549
3550        assert_eq!(content, "");
3551
3552        // Only start line
3553        let content = thread
3554            .update(cx, |thread, cx| {
3555                thread.read_text_file(path!("/tmp/foo").into(), Some(1), None, false, cx)
3556            })
3557            .await
3558            .unwrap();
3559
3560        assert_eq!(content, "");
3561
3562        // Only limit
3563        let content = thread
3564            .update(cx, |thread, cx| {
3565                thread.read_text_file(path!("/tmp/foo").into(), None, Some(2), false, cx)
3566            })
3567            .await
3568            .unwrap();
3569
3570        assert_eq!(content, "");
3571
3572        // Range
3573        let content = thread
3574            .update(cx, |thread, cx| {
3575                thread.read_text_file(path!("/tmp/foo").into(), Some(1), Some(1), false, cx)
3576            })
3577            .await
3578            .unwrap();
3579
3580        assert_eq!(content, "");
3581
3582        // Invalid
3583        let err = thread
3584            .update(cx, |thread, cx| {
3585                thread.read_text_file(path!("/tmp/foo").into(), Some(5), Some(2), false, cx)
3586            })
3587            .await
3588            .unwrap_err();
3589
3590        assert_eq!(
3591            err.to_string(),
3592            "Invalid params: \"Attempting to read beyond the end of the file, line 1:0\""
3593        );
3594    }
3595    #[gpui::test]
3596    async fn test_reading_non_existing_file(cx: &mut TestAppContext) {
3597        init_test(cx);
3598
3599        let fs = FakeFs::new(cx.executor());
3600        fs.insert_tree(path!("/tmp"), json!({})).await;
3601        let project = Project::test(fs.clone(), [], cx).await;
3602        project
3603            .update(cx, |project, cx| {
3604                project.find_or_create_worktree(path!("/tmp"), true, cx)
3605            })
3606            .await
3607            .unwrap();
3608
3609        let connection = Rc::new(FakeAgentConnection::new());
3610
3611        let thread = cx
3612            .update(|cx| {
3613                connection.new_session(project, PathList::new(&[Path::new(path!("/tmp"))]), cx)
3614            })
3615            .await
3616            .unwrap();
3617
3618        // Out of project file
3619        let err = thread
3620            .update(cx, |thread, cx| {
3621                thread.read_text_file(path!("/foo").into(), None, None, false, cx)
3622            })
3623            .await
3624            .unwrap_err();
3625
3626        assert_eq!(err.code, acp::ErrorCode::ResourceNotFound);
3627    }
3628
3629    #[gpui::test]
3630    async fn test_succeeding_canceled_toolcall(cx: &mut TestAppContext) {
3631        init_test(cx);
3632
3633        let fs = FakeFs::new(cx.executor());
3634        let project = Project::test(fs, [], cx).await;
3635        let id = acp::ToolCallId::new("test");
3636
3637        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
3638            let id = id.clone();
3639            move |_, thread, mut cx| {
3640                let id = id.clone();
3641                async move {
3642                    thread
3643                        .update(&mut cx, |thread, cx| {
3644                            thread.handle_session_update(
3645                                acp::SessionUpdate::ToolCall(
3646                                    acp::ToolCall::new(id.clone(), "Label")
3647                                        .kind(acp::ToolKind::Fetch)
3648                                        .status(acp::ToolCallStatus::InProgress),
3649                                ),
3650                                cx,
3651                            )
3652                        })
3653                        .unwrap()
3654                        .unwrap();
3655                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3656                }
3657                .boxed_local()
3658            }
3659        }));
3660
3661        let thread = cx
3662            .update(|cx| {
3663                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
3664            })
3665            .await
3666            .unwrap();
3667
3668        let request = thread.update(cx, |thread, cx| {
3669            thread.send_raw("Fetch https://example.com", cx)
3670        });
3671
3672        run_until_first_tool_call(&thread, cx).await;
3673
3674        thread.read_with(cx, |thread, _| {
3675            assert!(matches!(
3676                thread.entries[1],
3677                AgentThreadEntry::ToolCall(ToolCall {
3678                    status: ToolCallStatus::InProgress,
3679                    ..
3680                })
3681            ));
3682        });
3683
3684        thread.update(cx, |thread, cx| thread.cancel(cx)).await;
3685
3686        thread.read_with(cx, |thread, _| {
3687            assert!(matches!(
3688                &thread.entries[1],
3689                AgentThreadEntry::ToolCall(ToolCall {
3690                    status: ToolCallStatus::Canceled,
3691                    ..
3692                })
3693            ));
3694        });
3695
3696        thread
3697            .update(cx, |thread, cx| {
3698                thread.handle_session_update(
3699                    acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
3700                        id,
3701                        acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::Completed),
3702                    )),
3703                    cx,
3704                )
3705            })
3706            .unwrap();
3707
3708        request.await.unwrap();
3709
3710        thread.read_with(cx, |thread, _| {
3711            assert!(matches!(
3712                thread.entries[1],
3713                AgentThreadEntry::ToolCall(ToolCall {
3714                    status: ToolCallStatus::Completed,
3715                    ..
3716                })
3717            ));
3718        });
3719    }
3720
3721    #[gpui::test]
3722    async fn test_no_pending_edits_if_tool_calls_are_completed(cx: &mut TestAppContext) {
3723        init_test(cx);
3724        let fs = FakeFs::new(cx.background_executor.clone());
3725        fs.insert_tree(path!("/test"), json!({})).await;
3726        let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
3727
3728        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
3729            move |_, thread, mut cx| {
3730                async move {
3731                    thread
3732                        .update(&mut cx, |thread, cx| {
3733                            thread.handle_session_update(
3734                                acp::SessionUpdate::ToolCall(
3735                                    acp::ToolCall::new("test", "Label")
3736                                        .kind(acp::ToolKind::Edit)
3737                                        .status(acp::ToolCallStatus::Completed)
3738                                        .content(vec![acp::ToolCallContent::Diff(acp::Diff::new(
3739                                            "/test/test.txt",
3740                                            "foo",
3741                                        ))]),
3742                                ),
3743                                cx,
3744                            )
3745                        })
3746                        .unwrap()
3747                        .unwrap();
3748                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3749                }
3750                .boxed_local()
3751            }
3752        }));
3753
3754        let thread = cx
3755            .update(|cx| {
3756                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
3757            })
3758            .await
3759            .unwrap();
3760
3761        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["Hi".into()], cx)))
3762            .await
3763            .unwrap();
3764
3765        assert!(cx.read(|cx| !thread.read(cx).has_pending_edit_tool_calls()));
3766    }
3767
3768    #[gpui::test(iterations = 10)]
3769    async fn test_checkpoints(cx: &mut TestAppContext) {
3770        init_test(cx);
3771        let fs = FakeFs::new(cx.background_executor.clone());
3772        fs.insert_tree(
3773            path!("/test"),
3774            json!({
3775                ".git": {}
3776            }),
3777        )
3778        .await;
3779        let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
3780
3781        let simulate_changes = Arc::new(AtomicBool::new(true));
3782        let next_filename = Arc::new(AtomicUsize::new(0));
3783        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
3784            let simulate_changes = simulate_changes.clone();
3785            let next_filename = next_filename.clone();
3786            let fs = fs.clone();
3787            move |request, thread, mut cx| {
3788                let fs = fs.clone();
3789                let simulate_changes = simulate_changes.clone();
3790                let next_filename = next_filename.clone();
3791                async move {
3792                    if simulate_changes.load(SeqCst) {
3793                        let filename = format!("/test/file-{}", next_filename.fetch_add(1, SeqCst));
3794                        fs.write(Path::new(&filename), b"").await?;
3795                    }
3796
3797                    let acp::ContentBlock::Text(content) = &request.prompt[0] else {
3798                        panic!("expected text content block");
3799                    };
3800                    thread.update(&mut cx, |thread, cx| {
3801                        thread
3802                            .handle_session_update(
3803                                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
3804                                    content.text.to_uppercase().into(),
3805                                )),
3806                                cx,
3807                            )
3808                            .unwrap();
3809                    })?;
3810                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3811                }
3812                .boxed_local()
3813            }
3814        }));
3815        let thread = cx
3816            .update(|cx| {
3817                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
3818            })
3819            .await
3820            .unwrap();
3821
3822        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["Lorem".into()], cx)))
3823            .await
3824            .unwrap();
3825        thread.read_with(cx, |thread, cx| {
3826            assert_eq!(
3827                thread.to_markdown(cx),
3828                indoc! {"
3829                    ## User (checkpoint)
3830
3831                    Lorem
3832
3833                    ## Assistant
3834
3835                    LOREM
3836
3837                "}
3838            );
3839        });
3840        assert_eq!(fs.files(), vec![Path::new(path!("/test/file-0"))]);
3841
3842        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["ipsum".into()], cx)))
3843            .await
3844            .unwrap();
3845        thread.read_with(cx, |thread, cx| {
3846            assert_eq!(
3847                thread.to_markdown(cx),
3848                indoc! {"
3849                    ## User (checkpoint)
3850
3851                    Lorem
3852
3853                    ## Assistant
3854
3855                    LOREM
3856
3857                    ## User (checkpoint)
3858
3859                    ipsum
3860
3861                    ## Assistant
3862
3863                    IPSUM
3864
3865                "}
3866            );
3867        });
3868        assert_eq!(
3869            fs.files(),
3870            vec![
3871                Path::new(path!("/test/file-0")),
3872                Path::new(path!("/test/file-1"))
3873            ]
3874        );
3875
3876        // Checkpoint isn't stored when there are no changes.
3877        simulate_changes.store(false, SeqCst);
3878        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["dolor".into()], cx)))
3879            .await
3880            .unwrap();
3881        thread.read_with(cx, |thread, cx| {
3882            assert_eq!(
3883                thread.to_markdown(cx),
3884                indoc! {"
3885                    ## User (checkpoint)
3886
3887                    Lorem
3888
3889                    ## Assistant
3890
3891                    LOREM
3892
3893                    ## User (checkpoint)
3894
3895                    ipsum
3896
3897                    ## Assistant
3898
3899                    IPSUM
3900
3901                    ## User
3902
3903                    dolor
3904
3905                    ## Assistant
3906
3907                    DOLOR
3908
3909                "}
3910            );
3911        });
3912        assert_eq!(
3913            fs.files(),
3914            vec![
3915                Path::new(path!("/test/file-0")),
3916                Path::new(path!("/test/file-1"))
3917            ]
3918        );
3919
3920        // Rewinding the conversation truncates the history and restores the checkpoint.
3921        thread
3922            .update(cx, |thread, cx| {
3923                let AgentThreadEntry::UserMessage(message) = &thread.entries[2] else {
3924                    panic!("unexpected entries {:?}", thread.entries)
3925                };
3926                thread.restore_checkpoint(message.id.clone().unwrap(), cx)
3927            })
3928            .await
3929            .unwrap();
3930        thread.read_with(cx, |thread, cx| {
3931            assert_eq!(
3932                thread.to_markdown(cx),
3933                indoc! {"
3934                    ## User (checkpoint)
3935
3936                    Lorem
3937
3938                    ## Assistant
3939
3940                    LOREM
3941
3942                "}
3943            );
3944        });
3945        assert_eq!(fs.files(), vec![Path::new(path!("/test/file-0"))]);
3946    }
3947
3948    #[gpui::test]
3949    async fn test_tool_result_refusal(cx: &mut TestAppContext) {
3950        use std::sync::atomic::AtomicUsize;
3951        init_test(cx);
3952
3953        let fs = FakeFs::new(cx.executor());
3954        let project = Project::test(fs, None, cx).await;
3955
3956        // Create a connection that simulates refusal after tool result
3957        let prompt_count = Arc::new(AtomicUsize::new(0));
3958        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
3959            let prompt_count = prompt_count.clone();
3960            move |_request, thread, mut cx| {
3961                let count = prompt_count.fetch_add(1, SeqCst);
3962                async move {
3963                    if count == 0 {
3964                        // First prompt: Generate a tool call with result
3965                        thread.update(&mut cx, |thread, cx| {
3966                            thread
3967                                .handle_session_update(
3968                                    acp::SessionUpdate::ToolCall(
3969                                        acp::ToolCall::new("tool1", "Test Tool")
3970                                            .kind(acp::ToolKind::Fetch)
3971                                            .status(acp::ToolCallStatus::Completed)
3972                                            .raw_input(serde_json::json!({"query": "test"}))
3973                                            .raw_output(serde_json::json!({"result": "inappropriate content"})),
3974                                    ),
3975                                    cx,
3976                                )
3977                                .unwrap();
3978                        })?;
3979
3980                        // Now return refusal because of the tool result
3981                        Ok(acp::PromptResponse::new(acp::StopReason::Refusal))
3982                    } else {
3983                        Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3984                    }
3985                }
3986                .boxed_local()
3987            }
3988        }));
3989
3990        let thread = cx
3991            .update(|cx| {
3992                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
3993            })
3994            .await
3995            .unwrap();
3996
3997        // Track if we see a Refusal event
3998        let saw_refusal_event = Arc::new(std::sync::Mutex::new(false));
3999        let saw_refusal_event_captured = saw_refusal_event.clone();
4000        thread.update(cx, |_thread, cx| {
4001            cx.subscribe(
4002                &thread,
4003                move |_thread, _event_thread, event: &AcpThreadEvent, _cx| {
4004                    if matches!(event, AcpThreadEvent::Refusal) {
4005                        *saw_refusal_event_captured.lock().unwrap() = true;
4006                    }
4007                },
4008            )
4009            .detach();
4010        });
4011
4012        // Send a user message - this will trigger tool call and then refusal
4013        let send_task = thread.update(cx, |thread, cx| thread.send(vec!["Hello".into()], cx));
4014        cx.background_executor.spawn(send_task).detach();
4015        cx.run_until_parked();
4016
4017        // Verify that:
4018        // 1. A Refusal event WAS emitted (because it's a tool result refusal, not user prompt)
4019        // 2. The user message was NOT truncated
4020        assert!(
4021            *saw_refusal_event.lock().unwrap(),
4022            "Refusal event should be emitted for tool result refusals"
4023        );
4024
4025        thread.read_with(cx, |thread, _| {
4026            let entries = thread.entries();
4027            assert!(entries.len() >= 2, "Should have user message and tool call");
4028
4029            // Verify user message is still there
4030            assert!(
4031                matches!(entries[0], AgentThreadEntry::UserMessage(_)),
4032                "User message should not be truncated"
4033            );
4034
4035            // Verify tool call is there with result
4036            if let AgentThreadEntry::ToolCall(tool_call) = &entries[1] {
4037                assert!(
4038                    tool_call.raw_output.is_some(),
4039                    "Tool call should have output"
4040                );
4041            } else {
4042                panic!("Expected tool call at index 1");
4043            }
4044        });
4045    }
4046
4047    #[gpui::test]
4048    async fn test_user_prompt_refusal_emits_event(cx: &mut TestAppContext) {
4049        init_test(cx);
4050
4051        let fs = FakeFs::new(cx.executor());
4052        let project = Project::test(fs, None, cx).await;
4053
4054        let refuse_next = Arc::new(AtomicBool::new(false));
4055        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
4056            let refuse_next = refuse_next.clone();
4057            move |_request, _thread, _cx| {
4058                if refuse_next.load(SeqCst) {
4059                    async move { Ok(acp::PromptResponse::new(acp::StopReason::Refusal)) }
4060                        .boxed_local()
4061                } else {
4062                    async move { Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)) }
4063                        .boxed_local()
4064                }
4065            }
4066        }));
4067
4068        let thread = cx
4069            .update(|cx| {
4070                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
4071            })
4072            .await
4073            .unwrap();
4074
4075        // Track if we see a Refusal event
4076        let saw_refusal_event = Arc::new(std::sync::Mutex::new(false));
4077        let saw_refusal_event_captured = saw_refusal_event.clone();
4078        thread.update(cx, |_thread, cx| {
4079            cx.subscribe(
4080                &thread,
4081                move |_thread, _event_thread, event: &AcpThreadEvent, _cx| {
4082                    if matches!(event, AcpThreadEvent::Refusal) {
4083                        *saw_refusal_event_captured.lock().unwrap() = true;
4084                    }
4085                },
4086            )
4087            .detach();
4088        });
4089
4090        // Send a message that will be refused
4091        refuse_next.store(true, SeqCst);
4092        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["hello".into()], cx)))
4093            .await
4094            .unwrap();
4095
4096        // Verify that a Refusal event WAS emitted for user prompt refusal
4097        assert!(
4098            *saw_refusal_event.lock().unwrap(),
4099            "Refusal event should be emitted for user prompt refusals"
4100        );
4101
4102        // Verify the message was truncated (user prompt refusal)
4103        thread.read_with(cx, |thread, cx| {
4104            assert_eq!(thread.to_markdown(cx), "");
4105        });
4106    }
4107
4108    #[gpui::test]
4109    async fn test_refusal(cx: &mut TestAppContext) {
4110        init_test(cx);
4111        let fs = FakeFs::new(cx.background_executor.clone());
4112        fs.insert_tree(path!("/"), json!({})).await;
4113        let project = Project::test(fs.clone(), [path!("/").as_ref()], cx).await;
4114
4115        let refuse_next = Arc::new(AtomicBool::new(false));
4116        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
4117            let refuse_next = refuse_next.clone();
4118            move |request, thread, mut cx| {
4119                let refuse_next = refuse_next.clone();
4120                async move {
4121                    if refuse_next.load(SeqCst) {
4122                        return Ok(acp::PromptResponse::new(acp::StopReason::Refusal));
4123                    }
4124
4125                    let acp::ContentBlock::Text(content) = &request.prompt[0] else {
4126                        panic!("expected text content block");
4127                    };
4128                    thread.update(&mut cx, |thread, cx| {
4129                        thread
4130                            .handle_session_update(
4131                                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
4132                                    content.text.to_uppercase().into(),
4133                                )),
4134                                cx,
4135                            )
4136                            .unwrap();
4137                    })?;
4138                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
4139                }
4140                .boxed_local()
4141            }
4142        }));
4143        let thread = cx
4144            .update(|cx| {
4145                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
4146            })
4147            .await
4148            .unwrap();
4149
4150        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["hello".into()], cx)))
4151            .await
4152            .unwrap();
4153        thread.read_with(cx, |thread, cx| {
4154            assert_eq!(
4155                thread.to_markdown(cx),
4156                indoc! {"
4157                    ## User
4158
4159                    hello
4160
4161                    ## Assistant
4162
4163                    HELLO
4164
4165                "}
4166            );
4167        });
4168
4169        // Simulate refusing the second message. The message should be truncated
4170        // when a user prompt is refused.
4171        refuse_next.store(true, SeqCst);
4172        cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["world".into()], cx)))
4173            .await
4174            .unwrap();
4175        thread.read_with(cx, |thread, cx| {
4176            assert_eq!(
4177                thread.to_markdown(cx),
4178                indoc! {"
4179                    ## User
4180
4181                    hello
4182
4183                    ## Assistant
4184
4185                    HELLO
4186
4187                "}
4188            );
4189        });
4190    }
4191
4192    async fn run_until_first_tool_call(
4193        thread: &Entity<AcpThread>,
4194        cx: &mut TestAppContext,
4195    ) -> usize {
4196        let (mut tx, mut rx) = mpsc::channel::<usize>(1);
4197
4198        let subscription = cx.update(|cx| {
4199            cx.subscribe(thread, move |thread, _, cx| {
4200                for (ix, entry) in thread.read(cx).entries.iter().enumerate() {
4201                    if matches!(entry, AgentThreadEntry::ToolCall(_)) {
4202                        return tx.try_send(ix).unwrap();
4203                    }
4204                }
4205            })
4206        });
4207
4208        select! {
4209            _ = futures::FutureExt::fuse(cx.background_executor.timer(Duration::from_secs(10))) => {
4210                panic!("Timeout waiting for tool call")
4211            }
4212            ix = rx.next().fuse() => {
4213                drop(subscription);
4214                ix.unwrap()
4215            }
4216        }
4217    }
4218
4219    #[derive(Clone, Default)]
4220    struct FakeAgentConnection {
4221        auth_methods: Vec<acp::AuthMethod>,
4222        sessions: Arc<parking_lot::Mutex<HashMap<acp::SessionId, WeakEntity<AcpThread>>>>,
4223        set_title_calls: Rc<RefCell<Vec<SharedString>>>,
4224        on_user_message: Option<
4225            Rc<
4226                dyn Fn(
4227                        acp::PromptRequest,
4228                        WeakEntity<AcpThread>,
4229                        AsyncApp,
4230                    ) -> LocalBoxFuture<'static, Result<acp::PromptResponse>>
4231                    + 'static,
4232            >,
4233        >,
4234    }
4235
4236    impl FakeAgentConnection {
4237        fn new() -> Self {
4238            Self {
4239                auth_methods: Vec::new(),
4240                on_user_message: None,
4241                sessions: Arc::default(),
4242                set_title_calls: Default::default(),
4243            }
4244        }
4245
4246        #[expect(unused)]
4247        fn with_auth_methods(mut self, auth_methods: Vec<acp::AuthMethod>) -> Self {
4248            self.auth_methods = auth_methods;
4249            self
4250        }
4251
4252        fn on_user_message(
4253            mut self,
4254            handler: impl Fn(
4255                acp::PromptRequest,
4256                WeakEntity<AcpThread>,
4257                AsyncApp,
4258            ) -> LocalBoxFuture<'static, Result<acp::PromptResponse>>
4259            + 'static,
4260        ) -> Self {
4261            self.on_user_message.replace(Rc::new(handler));
4262            self
4263        }
4264    }
4265
4266    impl AgentConnection for FakeAgentConnection {
4267        fn agent_id(&self) -> AgentId {
4268            AgentId::new("fake")
4269        }
4270
4271        fn telemetry_id(&self) -> SharedString {
4272            "fake".into()
4273        }
4274
4275        fn auth_methods(&self) -> &[acp::AuthMethod] {
4276            &self.auth_methods
4277        }
4278
4279        fn new_session(
4280            self: Rc<Self>,
4281            project: Entity<Project>,
4282            work_dirs: PathList,
4283            cx: &mut App,
4284        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4285            let session_id = acp::SessionId::new(
4286                rand::rng()
4287                    .sample_iter(&distr::Alphanumeric)
4288                    .take(7)
4289                    .map(char::from)
4290                    .collect::<String>(),
4291            );
4292            let action_log = cx.new(|_| ActionLog::new(project.clone()));
4293            let thread = cx.new(|cx| {
4294                AcpThread::new(
4295                    None,
4296                    None,
4297                    Some(work_dirs),
4298                    self.clone(),
4299                    project,
4300                    action_log,
4301                    session_id.clone(),
4302                    watch::Receiver::constant(
4303                        acp::PromptCapabilities::new()
4304                            .image(true)
4305                            .audio(true)
4306                            .embedded_context(true),
4307                    ),
4308                    cx,
4309                )
4310            });
4311            self.sessions.lock().insert(session_id, thread.downgrade());
4312            Task::ready(Ok(thread))
4313        }
4314
4315        fn authenticate(&self, method: acp::AuthMethodId, _cx: &mut App) -> Task<gpui::Result<()>> {
4316            if self.auth_methods().iter().any(|m| m.id() == &method) {
4317                Task::ready(Ok(()))
4318            } else {
4319                Task::ready(Err(anyhow!("Invalid Auth Method")))
4320            }
4321        }
4322
4323        fn prompt(
4324            &self,
4325            _id: Option<UserMessageId>,
4326            params: acp::PromptRequest,
4327            cx: &mut App,
4328        ) -> Task<gpui::Result<acp::PromptResponse>> {
4329            let sessions = self.sessions.lock();
4330            let thread = sessions.get(&params.session_id).unwrap();
4331            if let Some(handler) = &self.on_user_message {
4332                let handler = handler.clone();
4333                let thread = thread.clone();
4334                cx.spawn(async move |cx| handler(params, thread, cx.clone()).await)
4335            } else {
4336                Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
4337            }
4338        }
4339
4340        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
4341
4342        fn truncate(
4343            &self,
4344            session_id: &acp::SessionId,
4345            _cx: &App,
4346        ) -> Option<Rc<dyn AgentSessionTruncate>> {
4347            Some(Rc::new(FakeAgentSessionEditor {
4348                _session_id: session_id.clone(),
4349            }))
4350        }
4351
4352        fn set_title(
4353            &self,
4354            _session_id: &acp::SessionId,
4355            _cx: &App,
4356        ) -> Option<Rc<dyn AgentSessionSetTitle>> {
4357            Some(Rc::new(FakeAgentSessionSetTitle {
4358                calls: self.set_title_calls.clone(),
4359            }))
4360        }
4361
4362        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4363            self
4364        }
4365    }
4366
4367    struct FakeAgentSessionSetTitle {
4368        calls: Rc<RefCell<Vec<SharedString>>>,
4369    }
4370
4371    impl AgentSessionSetTitle for FakeAgentSessionSetTitle {
4372        fn run(&self, title: SharedString, _cx: &mut App) -> Task<Result<()>> {
4373            self.calls.borrow_mut().push(title);
4374            Task::ready(Ok(()))
4375        }
4376    }
4377
4378    struct FakeAgentSessionEditor {
4379        _session_id: acp::SessionId,
4380    }
4381
4382    impl AgentSessionTruncate for FakeAgentSessionEditor {
4383        fn run(&self, _message_id: UserMessageId, _cx: &mut App) -> Task<Result<()>> {
4384            Task::ready(Ok(()))
4385        }
4386    }
4387
4388    #[gpui::test]
4389    async fn test_tool_call_not_found_creates_failed_entry(cx: &mut TestAppContext) {
4390        init_test(cx);
4391
4392        let fs = FakeFs::new(cx.executor());
4393        let project = Project::test(fs, [], cx).await;
4394        let connection = Rc::new(FakeAgentConnection::new());
4395        let thread = cx
4396            .update(|cx| {
4397                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
4398            })
4399            .await
4400            .unwrap();
4401
4402        // Try to update a tool call that doesn't exist
4403        let nonexistent_id = acp::ToolCallId::new("nonexistent-tool-call");
4404        thread.update(cx, |thread, cx| {
4405            let result = thread.handle_session_update(
4406                acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
4407                    nonexistent_id.clone(),
4408                    acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::Completed),
4409                )),
4410                cx,
4411            );
4412
4413            // The update should succeed (not return an error)
4414            assert!(result.is_ok());
4415
4416            // There should now be exactly one entry in the thread
4417            assert_eq!(thread.entries.len(), 1);
4418
4419            // The entry should be a failed tool call
4420            if let AgentThreadEntry::ToolCall(tool_call) = &thread.entries[0] {
4421                assert_eq!(tool_call.id, nonexistent_id);
4422                assert!(matches!(tool_call.status, ToolCallStatus::Failed));
4423                assert_eq!(tool_call.kind, acp::ToolKind::Fetch);
4424
4425                // Check that the content contains the error message
4426                assert_eq!(tool_call.content.len(), 1);
4427                if let ToolCallContent::ContentBlock(content_block) = &tool_call.content[0] {
4428                    match content_block {
4429                        ContentBlock::Markdown { markdown } => {
4430                            let markdown_text = markdown.read(cx).source();
4431                            assert!(markdown_text.contains("Tool call not found"));
4432                        }
4433                        ContentBlock::Empty => panic!("Expected markdown content, got empty"),
4434                        ContentBlock::ResourceLink { .. } => {
4435                            panic!("Expected markdown content, got resource link")
4436                        }
4437                        ContentBlock::Image { .. } => {
4438                            panic!("Expected markdown content, got image")
4439                        }
4440                    }
4441                } else {
4442                    panic!("Expected ContentBlock, got: {:?}", tool_call.content[0]);
4443                }
4444            } else {
4445                panic!("Expected ToolCall entry, got: {:?}", thread.entries[0]);
4446            }
4447        });
4448    }
4449
4450    /// Tests that restoring a checkpoint properly cleans up terminals that were
4451    /// created after that checkpoint, and cancels any in-progress generation.
4452    ///
4453    /// Reproduces issue #35142: When a checkpoint is restored, any terminal processes
4454    /// that were started after that checkpoint should be terminated, and any in-progress
4455    /// AI generation should be canceled.
4456    #[gpui::test]
4457    async fn test_restore_checkpoint_kills_terminal(cx: &mut TestAppContext) {
4458        init_test(cx);
4459
4460        let fs = FakeFs::new(cx.executor());
4461        let project = Project::test(fs, [], cx).await;
4462        let connection = Rc::new(FakeAgentConnection::new());
4463        let thread = cx
4464            .update(|cx| {
4465                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
4466            })
4467            .await
4468            .unwrap();
4469
4470        // Send first user message to create a checkpoint
4471        cx.update(|cx| {
4472            thread.update(cx, |thread, cx| {
4473                thread.send(vec!["first message".into()], cx)
4474            })
4475        })
4476        .await
4477        .unwrap();
4478
4479        // Send second message (creates another checkpoint) - we'll restore to this one
4480        cx.update(|cx| {
4481            thread.update(cx, |thread, cx| {
4482                thread.send(vec!["second message".into()], cx)
4483            })
4484        })
4485        .await
4486        .unwrap();
4487
4488        // Create 2 terminals BEFORE the checkpoint that have completed running
4489        let terminal_id_1 = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
4490        let mock_terminal_1 = cx.new(|cx| {
4491            let builder = ::terminal::TerminalBuilder::new_display_only(
4492                ::terminal::terminal_settings::CursorShape::default(),
4493                ::terminal::terminal_settings::AlternateScroll::On,
4494                None,
4495                0,
4496                cx.background_executor(),
4497                PathStyle::local(),
4498            )
4499            .unwrap();
4500            builder.subscribe(cx)
4501        });
4502
4503        thread.update(cx, |thread, cx| {
4504            thread.on_terminal_provider_event(
4505                TerminalProviderEvent::Created {
4506                    terminal_id: terminal_id_1.clone(),
4507                    label: "echo 'first'".to_string(),
4508                    cwd: Some(PathBuf::from("/test")),
4509                    output_byte_limit: None,
4510                    terminal: mock_terminal_1.clone(),
4511                },
4512                cx,
4513            );
4514        });
4515
4516        thread.update(cx, |thread, cx| {
4517            thread.on_terminal_provider_event(
4518                TerminalProviderEvent::Output {
4519                    terminal_id: terminal_id_1.clone(),
4520                    data: b"first\n".to_vec(),
4521                },
4522                cx,
4523            );
4524        });
4525
4526        thread.update(cx, |thread, cx| {
4527            thread.on_terminal_provider_event(
4528                TerminalProviderEvent::Exit {
4529                    terminal_id: terminal_id_1.clone(),
4530                    status: acp::TerminalExitStatus::new().exit_code(0),
4531                },
4532                cx,
4533            );
4534        });
4535
4536        let terminal_id_2 = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
4537        let mock_terminal_2 = cx.new(|cx| {
4538            let builder = ::terminal::TerminalBuilder::new_display_only(
4539                ::terminal::terminal_settings::CursorShape::default(),
4540                ::terminal::terminal_settings::AlternateScroll::On,
4541                None,
4542                0,
4543                cx.background_executor(),
4544                PathStyle::local(),
4545            )
4546            .unwrap();
4547            builder.subscribe(cx)
4548        });
4549
4550        thread.update(cx, |thread, cx| {
4551            thread.on_terminal_provider_event(
4552                TerminalProviderEvent::Created {
4553                    terminal_id: terminal_id_2.clone(),
4554                    label: "echo 'second'".to_string(),
4555                    cwd: Some(PathBuf::from("/test")),
4556                    output_byte_limit: None,
4557                    terminal: mock_terminal_2.clone(),
4558                },
4559                cx,
4560            );
4561        });
4562
4563        thread.update(cx, |thread, cx| {
4564            thread.on_terminal_provider_event(
4565                TerminalProviderEvent::Output {
4566                    terminal_id: terminal_id_2.clone(),
4567                    data: b"second\n".to_vec(),
4568                },
4569                cx,
4570            );
4571        });
4572
4573        thread.update(cx, |thread, cx| {
4574            thread.on_terminal_provider_event(
4575                TerminalProviderEvent::Exit {
4576                    terminal_id: terminal_id_2.clone(),
4577                    status: acp::TerminalExitStatus::new().exit_code(0),
4578                },
4579                cx,
4580            );
4581        });
4582
4583        // Get the second message ID to restore to
4584        let second_message_id = thread.read_with(cx, |thread, _| {
4585            // At this point we have:
4586            // - Index 0: First user message (with checkpoint)
4587            // - Index 1: Second user message (with checkpoint)
4588            // No assistant responses because FakeAgentConnection just returns EndTurn
4589            let AgentThreadEntry::UserMessage(message) = &thread.entries[1] else {
4590                panic!("expected user message at index 1");
4591            };
4592            message.id.clone().unwrap()
4593        });
4594
4595        // Create a terminal AFTER the checkpoint we'll restore to.
4596        // This simulates the AI agent starting a long-running terminal command.
4597        let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
4598        let mock_terminal = cx.new(|cx| {
4599            let builder = ::terminal::TerminalBuilder::new_display_only(
4600                ::terminal::terminal_settings::CursorShape::default(),
4601                ::terminal::terminal_settings::AlternateScroll::On,
4602                None,
4603                0,
4604                cx.background_executor(),
4605                PathStyle::local(),
4606            )
4607            .unwrap();
4608            builder.subscribe(cx)
4609        });
4610
4611        // Register the terminal as created
4612        thread.update(cx, |thread, cx| {
4613            thread.on_terminal_provider_event(
4614                TerminalProviderEvent::Created {
4615                    terminal_id: terminal_id.clone(),
4616                    label: "sleep 1000".to_string(),
4617                    cwd: Some(PathBuf::from("/test")),
4618                    output_byte_limit: None,
4619                    terminal: mock_terminal.clone(),
4620                },
4621                cx,
4622            );
4623        });
4624
4625        // Simulate the terminal producing output (still running)
4626        thread.update(cx, |thread, cx| {
4627            thread.on_terminal_provider_event(
4628                TerminalProviderEvent::Output {
4629                    terminal_id: terminal_id.clone(),
4630                    data: b"terminal is running...\n".to_vec(),
4631                },
4632                cx,
4633            );
4634        });
4635
4636        // Create a tool call entry that references this terminal
4637        // This represents the agent requesting a terminal command
4638        thread.update(cx, |thread, cx| {
4639            thread
4640                .handle_session_update(
4641                    acp::SessionUpdate::ToolCall(
4642                        acp::ToolCall::new("terminal-tool-1", "Running command")
4643                            .kind(acp::ToolKind::Execute)
4644                            .status(acp::ToolCallStatus::InProgress)
4645                            .content(vec![acp::ToolCallContent::Terminal(acp::Terminal::new(
4646                                terminal_id.clone(),
4647                            ))])
4648                            .raw_input(serde_json::json!({"command": "sleep 1000", "cd": "/test"})),
4649                    ),
4650                    cx,
4651                )
4652                .unwrap();
4653        });
4654
4655        // Verify terminal exists and is in the thread
4656        let terminal_exists_before =
4657            thread.read_with(cx, |thread, _| thread.terminals.contains_key(&terminal_id));
4658        assert!(
4659            terminal_exists_before,
4660            "Terminal should exist before checkpoint restore"
4661        );
4662
4663        // Verify the terminal's underlying task is still running (not completed)
4664        let terminal_running_before = thread.read_with(cx, |thread, _cx| {
4665            let terminal_entity = thread.terminals.get(&terminal_id).unwrap();
4666            terminal_entity.read_with(cx, |term, _cx| {
4667                term.output().is_none() // output is None means it's still running
4668            })
4669        });
4670        assert!(
4671            terminal_running_before,
4672            "Terminal should be running before checkpoint restore"
4673        );
4674
4675        // Verify we have the expected entries before restore
4676        let entry_count_before = thread.read_with(cx, |thread, _| thread.entries.len());
4677        assert!(
4678            entry_count_before > 1,
4679            "Should have multiple entries before restore"
4680        );
4681
4682        // Restore the checkpoint to the second message.
4683        // This should:
4684        // 1. Cancel any in-progress generation (via the cancel() call)
4685        // 2. Remove the terminal that was created after that point
4686        thread
4687            .update(cx, |thread, cx| {
4688                thread.restore_checkpoint(second_message_id, cx)
4689            })
4690            .await
4691            .unwrap();
4692
4693        // Verify that no send_task is in progress after restore
4694        // (cancel() clears the send_task)
4695        let has_send_task_after = thread.read_with(cx, |thread, _| thread.running_turn.is_some());
4696        assert!(
4697            !has_send_task_after,
4698            "Should not have a send_task after restore (cancel should have cleared it)"
4699        );
4700
4701        // Verify the entries were truncated (restoring to index 1 truncates at 1, keeping only index 0)
4702        let entry_count = thread.read_with(cx, |thread, _| thread.entries.len());
4703        assert_eq!(
4704            entry_count, 1,
4705            "Should have 1 entry after restore (only the first user message)"
4706        );
4707
4708        // Verify the 2 completed terminals from before the checkpoint still exist
4709        let terminal_1_exists = thread.read_with(cx, |thread, _| {
4710            thread.terminals.contains_key(&terminal_id_1)
4711        });
4712        assert!(
4713            terminal_1_exists,
4714            "Terminal 1 (from before checkpoint) should still exist"
4715        );
4716
4717        let terminal_2_exists = thread.read_with(cx, |thread, _| {
4718            thread.terminals.contains_key(&terminal_id_2)
4719        });
4720        assert!(
4721            terminal_2_exists,
4722            "Terminal 2 (from before checkpoint) should still exist"
4723        );
4724
4725        // Verify they're still in completed state
4726        let terminal_1_completed = thread.read_with(cx, |thread, _cx| {
4727            let terminal_entity = thread.terminals.get(&terminal_id_1).unwrap();
4728            terminal_entity.read_with(cx, |term, _cx| term.output().is_some())
4729        });
4730        assert!(terminal_1_completed, "Terminal 1 should still be completed");
4731
4732        let terminal_2_completed = thread.read_with(cx, |thread, _cx| {
4733            let terminal_entity = thread.terminals.get(&terminal_id_2).unwrap();
4734            terminal_entity.read_with(cx, |term, _cx| term.output().is_some())
4735        });
4736        assert!(terminal_2_completed, "Terminal 2 should still be completed");
4737
4738        // Verify the running terminal (created after checkpoint) was removed
4739        let terminal_3_exists =
4740            thread.read_with(cx, |thread, _| thread.terminals.contains_key(&terminal_id));
4741        assert!(
4742            !terminal_3_exists,
4743            "Terminal 3 (created after checkpoint) should have been removed"
4744        );
4745
4746        // Verify total count is 2 (the two from before the checkpoint)
4747        let terminal_count = thread.read_with(cx, |thread, _| thread.terminals.len());
4748        assert_eq!(
4749            terminal_count, 2,
4750            "Should have exactly 2 terminals (the completed ones from before checkpoint)"
4751        );
4752    }
4753
4754    /// Tests that update_last_checkpoint correctly updates the original message's checkpoint
4755    /// even when a new user message is added while the async checkpoint comparison is in progress.
4756    ///
4757    /// This is a regression test for a bug where update_last_checkpoint would fail with
4758    /// "no checkpoint" if a new user message (without a checkpoint) was added between when
4759    /// update_last_checkpoint started and when its async closure ran.
4760    #[gpui::test]
4761    async fn test_update_last_checkpoint_with_new_message_added(cx: &mut TestAppContext) {
4762        init_test(cx);
4763
4764        let fs = FakeFs::new(cx.executor());
4765        fs.insert_tree(path!("/test"), json!({".git": {}, "file.txt": "content"}))
4766            .await;
4767        let project = Project::test(fs.clone(), [Path::new(path!("/test"))], cx).await;
4768
4769        let handler_done = Arc::new(AtomicBool::new(false));
4770        let handler_done_clone = handler_done.clone();
4771        let connection = Rc::new(FakeAgentConnection::new().on_user_message(
4772            move |_, _thread, _cx| {
4773                handler_done_clone.store(true, SeqCst);
4774                async move { Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)) }.boxed_local()
4775            },
4776        ));
4777
4778        let thread = cx
4779            .update(|cx| {
4780                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
4781            })
4782            .await
4783            .unwrap();
4784
4785        let send_future = thread.update(cx, |thread, cx| thread.send_raw("First message", cx));
4786        let send_task = cx.background_executor.spawn(send_future);
4787
4788        // Tick until handler completes, then a few more to let update_last_checkpoint start
4789        while !handler_done.load(SeqCst) {
4790            cx.executor().tick();
4791        }
4792        for _ in 0..5 {
4793            cx.executor().tick();
4794        }
4795
4796        thread.update(cx, |thread, cx| {
4797            thread.push_entry(
4798                AgentThreadEntry::UserMessage(UserMessage {
4799                    id: Some(UserMessageId::new()),
4800                    content: ContentBlock::Empty,
4801                    chunks: vec!["Injected message (no checkpoint)".into()],
4802                    checkpoint: None,
4803                    indented: false,
4804                }),
4805                cx,
4806            );
4807        });
4808
4809        cx.run_until_parked();
4810        let result = send_task.await;
4811
4812        assert!(
4813            result.is_ok(),
4814            "send should succeed even when new message added during update_last_checkpoint: {:?}",
4815            result.err()
4816        );
4817    }
4818
4819    /// Tests that when a follow-up message is sent during generation,
4820    /// the first turn completing does NOT clear `running_turn` because
4821    /// it now belongs to the second turn.
4822    #[gpui::test]
4823    async fn test_follow_up_message_during_generation_does_not_clear_turn(cx: &mut TestAppContext) {
4824        init_test(cx);
4825
4826        let fs = FakeFs::new(cx.executor());
4827        let project = Project::test(fs, [], cx).await;
4828
4829        // First handler waits for this signal before completing
4830        let (first_complete_tx, first_complete_rx) = futures::channel::oneshot::channel::<()>();
4831        let first_complete_rx = RefCell::new(Some(first_complete_rx));
4832
4833        let connection = Rc::new(FakeAgentConnection::new().on_user_message({
4834            move |params, _thread, _cx| {
4835                let first_complete_rx = first_complete_rx.borrow_mut().take();
4836                let is_first = params
4837                    .prompt
4838                    .iter()
4839                    .any(|c| matches!(c, acp::ContentBlock::Text(t) if t.text.contains("first")));
4840
4841                async move {
4842                    if is_first {
4843                        // First handler waits until signaled
4844                        if let Some(rx) = first_complete_rx {
4845                            rx.await.ok();
4846                        }
4847                    }
4848                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
4849                }
4850                .boxed_local()
4851            }
4852        }));
4853
4854        let thread = cx
4855            .update(|cx| {
4856                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
4857            })
4858            .await
4859            .unwrap();
4860
4861        // Send first message (turn_id=1) - handler will block
4862        let first_request = thread.update(cx, |thread, cx| thread.send_raw("first", cx));
4863        assert_eq!(thread.read_with(cx, |t, _| t.turn_id), 1);
4864
4865        // Send second message (turn_id=2) while first is still blocked
4866        // This calls cancel() which takes turn 1's running_turn and sets turn 2's
4867        let second_request = thread.update(cx, |thread, cx| thread.send_raw("second", cx));
4868        assert_eq!(thread.read_with(cx, |t, _| t.turn_id), 2);
4869
4870        let running_turn_after_second_send =
4871            thread.read_with(cx, |thread, _| thread.running_turn.as_ref().map(|t| t.id));
4872        assert_eq!(
4873            running_turn_after_second_send,
4874            Some(2),
4875            "running_turn should be set to turn 2 after sending second message"
4876        );
4877
4878        // Now signal first handler to complete
4879        first_complete_tx.send(()).ok();
4880
4881        // First request completes - should NOT clear running_turn
4882        // because running_turn now belongs to turn 2
4883        first_request.await.unwrap();
4884
4885        let running_turn_after_first =
4886            thread.read_with(cx, |thread, _| thread.running_turn.as_ref().map(|t| t.id));
4887        assert_eq!(
4888            running_turn_after_first,
4889            Some(2),
4890            "first turn completing should not clear running_turn (belongs to turn 2)"
4891        );
4892
4893        // Second request completes - SHOULD clear running_turn
4894        second_request.await.unwrap();
4895
4896        let running_turn_after_second =
4897            thread.read_with(cx, |thread, _| thread.running_turn.is_some());
4898        assert!(
4899            !running_turn_after_second,
4900            "second turn completing should clear running_turn"
4901        );
4902    }
4903
4904    #[gpui::test]
4905    async fn test_send_returns_cancelled_response_and_marks_tools_as_cancelled(
4906        cx: &mut TestAppContext,
4907    ) {
4908        init_test(cx);
4909
4910        let fs = FakeFs::new(cx.executor());
4911        let project = Project::test(fs, [], cx).await;
4912
4913        let connection = Rc::new(FakeAgentConnection::new().on_user_message(
4914            move |_params, thread, mut cx| {
4915                async move {
4916                    thread
4917                        .update(&mut cx, |thread, cx| {
4918                            thread.handle_session_update(
4919                                acp::SessionUpdate::ToolCall(
4920                                    acp::ToolCall::new(
4921                                        acp::ToolCallId::new("test-tool"),
4922                                        "Test Tool",
4923                                    )
4924                                    .kind(acp::ToolKind::Fetch)
4925                                    .status(acp::ToolCallStatus::InProgress),
4926                                ),
4927                                cx,
4928                            )
4929                        })
4930                        .unwrap()
4931                        .unwrap();
4932
4933                    Ok(acp::PromptResponse::new(acp::StopReason::Cancelled))
4934                }
4935                .boxed_local()
4936            },
4937        ));
4938
4939        let thread = cx
4940            .update(|cx| {
4941                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
4942            })
4943            .await
4944            .unwrap();
4945
4946        let response = thread
4947            .update(cx, |thread, cx| thread.send_raw("test message", cx))
4948            .await;
4949
4950        let response = response
4951            .expect("send should succeed")
4952            .expect("should have response");
4953        assert_eq!(
4954            response.stop_reason,
4955            acp::StopReason::Cancelled,
4956            "response should have Cancelled stop_reason"
4957        );
4958
4959        thread.read_with(cx, |thread, _| {
4960            let tool_entry = thread
4961                .entries
4962                .iter()
4963                .find_map(|e| {
4964                    if let AgentThreadEntry::ToolCall(call) = e {
4965                        Some(call)
4966                    } else {
4967                        None
4968                    }
4969                })
4970                .expect("should have tool call entry");
4971
4972            assert!(
4973                matches!(tool_entry.status, ToolCallStatus::Canceled),
4974                "tool should be marked as Canceled when response is Cancelled, got {:?}",
4975                tool_entry.status
4976            );
4977        });
4978    }
4979
4980    #[gpui::test]
4981    async fn test_provisional_title_replaced_by_real_title(cx: &mut TestAppContext) {
4982        init_test(cx);
4983
4984        let fs = FakeFs::new(cx.executor());
4985        let project = Project::test(fs, [], cx).await;
4986        let connection = Rc::new(FakeAgentConnection::new());
4987        let set_title_calls = connection.set_title_calls.clone();
4988
4989        let thread = cx
4990            .update(|cx| {
4991                connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
4992            })
4993            .await
4994            .unwrap();
4995
4996        // Initial title is the default.
4997        thread.read_with(cx, |thread, _| {
4998            assert_eq!(thread.title(), None);
4999        });
5000
5001        // Setting a provisional title updates the display title.
5002        thread.update(cx, |thread, cx| {
5003            thread.set_provisional_title("Hello, can you help…".into(), cx);
5004        });
5005        thread.read_with(cx, |thread, _| {
5006            assert_eq!(
5007                thread.title().as_ref().map(|s| s.as_str()),
5008                Some("Hello, can you help…")
5009            );
5010        });
5011
5012        // The provisional title should NOT have propagated to the connection.
5013        assert_eq!(
5014            set_title_calls.borrow().len(),
5015            0,
5016            "provisional title should not propagate to the connection"
5017        );
5018
5019        // When the real title arrives via set_title, it replaces the
5020        // provisional title and propagates to the connection.
5021        let task = thread.update(cx, |thread, cx| {
5022            thread.set_title("Helping with Rust question".into(), cx)
5023        });
5024        task.await.expect("set_title should succeed");
5025        thread.read_with(cx, |thread, _| {
5026            assert_eq!(
5027                thread.title().as_ref().map(|s| s.as_str()),
5028                Some("Helping with Rust question")
5029            );
5030        });
5031        assert_eq!(
5032            set_title_calls.borrow().as_slice(),
5033            &[SharedString::from("Helping with Rust question")],
5034            "real title should propagate to the connection"
5035        );
5036    }
5037
5038    #[gpui::test]
5039    async fn test_session_info_update_replaces_provisional_title_and_emits_event(
5040        cx: &mut TestAppContext,
5041    ) {
5042        init_test(cx);
5043
5044        let fs = FakeFs::new(cx.executor());
5045        let project = Project::test(fs, [], cx).await;
5046        let connection = Rc::new(FakeAgentConnection::new());
5047
5048        let thread = cx
5049            .update(|cx| {
5050                connection.clone().new_session(
5051                    project,
5052                    PathList::new(&[Path::new(path!("/test"))]),
5053                    cx,
5054                )
5055            })
5056            .await
5057            .unwrap();
5058
5059        let title_updated_events = Rc::new(RefCell::new(0usize));
5060        let title_updated_events_for_subscription = title_updated_events.clone();
5061        thread.update(cx, |_thread, cx| {
5062            cx.subscribe(
5063                &thread,
5064                move |_thread, _event_thread, event: &AcpThreadEvent, _cx| {
5065                    if matches!(event, AcpThreadEvent::TitleUpdated) {
5066                        *title_updated_events_for_subscription.borrow_mut() += 1;
5067                    }
5068                },
5069            )
5070            .detach();
5071        });
5072
5073        thread.update(cx, |thread, cx| {
5074            thread.set_provisional_title("Hello, can you help…".into(), cx);
5075        });
5076        assert_eq!(
5077            *title_updated_events.borrow(),
5078            1,
5079            "setting a provisional title should emit TitleUpdated"
5080        );
5081
5082        let result = thread.update(cx, |thread, cx| {
5083            thread.handle_session_update(
5084                acp::SessionUpdate::SessionInfoUpdate(
5085                    acp::SessionInfoUpdate::new().title("Helping with Rust question"),
5086                ),
5087                cx,
5088            )
5089        });
5090        result.expect("session info update should succeed");
5091
5092        thread.read_with(cx, |thread, _| {
5093            assert_eq!(
5094                thread.title().as_ref().map(|s| s.as_str()),
5095                Some("Helping with Rust question")
5096            );
5097            assert!(
5098                !thread.has_provisional_title(),
5099                "session info title update should clear provisional title"
5100            );
5101        });
5102
5103        assert_eq!(
5104            *title_updated_events.borrow(),
5105            2,
5106            "session info title update should emit TitleUpdated"
5107        );
5108        assert!(
5109            connection.set_title_calls.borrow().is_empty(),
5110            "session info title update should not propagate back to the connection"
5111        );
5112    }
5113}