acp_thread.rs

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