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