acp_thread.rs

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