acp_thread.rs

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