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