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