acp_thread.rs

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