thread.rs

   1use crate::{
   2    ContextServerRegistry, CopyPathTool, CreateDirectoryTool, DbLanguageModel, DbThread,
   3    DeletePathTool, DiagnosticsTool, EditFileTool, FetchTool, FindPathTool, GrepTool,
   4    ListDirectoryTool, MovePathTool, NowTool, OpenTool, ProjectSnapshot, ReadFileTool,
   5    RestoreFileFromDiskTool, SaveFileTool, SpawnAgentTool, StreamingEditFileTool,
   6    SystemPromptTemplate, Template, Templates, TerminalTool, ToolPermissionDecision, WebSearchTool,
   7    decide_permission_from_settings,
   8};
   9use acp_thread::{MentionUri, UserMessageId};
  10use action_log::ActionLog;
  11use feature_flags::{FeatureFlagAppExt as _, StreamingEditFileToolFeatureFlag};
  12
  13use agent_client_protocol as acp;
  14use agent_settings::{
  15    AgentProfileId, AgentProfileSettings, AgentSettings, SUMMARIZE_THREAD_DETAILED_PROMPT,
  16    SUMMARIZE_THREAD_PROMPT,
  17};
  18use anyhow::{Context as _, Result, anyhow};
  19use chrono::{DateTime, Utc};
  20use client::UserStore;
  21use cloud_api_types::Plan;
  22use cloud_llm_client::CompletionIntent;
  23use collections::{HashMap, HashSet, IndexMap};
  24use fs::Fs;
  25use futures::stream;
  26use futures::{
  27    FutureExt,
  28    channel::{mpsc, oneshot},
  29    future::Shared,
  30    stream::FuturesUnordered,
  31};
  32use gpui::{
  33    App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task, WeakEntity,
  34};
  35use heck::ToSnakeCase as _;
  36use language_model::{
  37    LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId,
  38    LanguageModelImage, LanguageModelProviderId, LanguageModelRegistry, LanguageModelRequest,
  39    LanguageModelRequestMessage, LanguageModelRequestTool, LanguageModelToolResult,
  40    LanguageModelToolResultContent, LanguageModelToolSchemaFormat, LanguageModelToolUse,
  41    LanguageModelToolUseId, Role, SelectedModel, Speed, StopReason, TokenUsage,
  42    ZED_CLOUD_PROVIDER_ID,
  43};
  44use project::Project;
  45use prompt_store::ProjectContext;
  46use schemars::{JsonSchema, Schema};
  47use serde::de::DeserializeOwned;
  48use serde::{Deserialize, Serialize};
  49use settings::{LanguageModelSelection, Settings, ToolPermissionMode, update_settings_file};
  50use smol::stream::StreamExt;
  51use std::{
  52    collections::BTreeMap,
  53    marker::PhantomData,
  54    ops::RangeInclusive,
  55    path::Path,
  56    rc::Rc,
  57    sync::Arc,
  58    time::{Duration, Instant},
  59};
  60use std::{fmt::Write, path::PathBuf};
  61use util::{ResultExt, debug_panic, markdown::MarkdownCodeBlock, paths::PathStyle};
  62use uuid::Uuid;
  63
  64const TOOL_CANCELED_MESSAGE: &str = "Tool canceled by user";
  65pub const MAX_TOOL_NAME_LENGTH: usize = 64;
  66pub const MAX_SUBAGENT_DEPTH: u8 = 1;
  67
  68/// Context passed to a subagent thread for lifecycle management
  69#[derive(Clone, Debug, Serialize, Deserialize)]
  70pub struct SubagentContext {
  71    /// ID of the parent thread
  72    pub parent_thread_id: acp::SessionId,
  73
  74    /// Current depth level (0 = root agent, 1 = first-level subagent, etc.)
  75    pub depth: u8,
  76}
  77
  78/// The ID of the user prompt that initiated a request.
  79///
  80/// This equates to the user physically submitting a message to the model (e.g., by pressing the Enter key).
  81#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
  82pub struct PromptId(Arc<str>);
  83
  84impl PromptId {
  85    pub fn new() -> Self {
  86        Self(Uuid::new_v4().to_string().into())
  87    }
  88}
  89
  90impl std::fmt::Display for PromptId {
  91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  92        write!(f, "{}", self.0)
  93    }
  94}
  95
  96pub(crate) const MAX_RETRY_ATTEMPTS: u8 = 4;
  97pub(crate) const BASE_RETRY_DELAY: Duration = Duration::from_secs(5);
  98
  99#[derive(Debug, Clone)]
 100enum RetryStrategy {
 101    ExponentialBackoff {
 102        initial_delay: Duration,
 103        max_attempts: u8,
 104    },
 105    Fixed {
 106        delay: Duration,
 107        max_attempts: u8,
 108    },
 109}
 110
 111#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 112pub enum Message {
 113    User(UserMessage),
 114    Agent(AgentMessage),
 115    Resume,
 116}
 117
 118impl Message {
 119    pub fn as_agent_message(&self) -> Option<&AgentMessage> {
 120        match self {
 121            Message::Agent(agent_message) => Some(agent_message),
 122            _ => None,
 123        }
 124    }
 125
 126    pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
 127        match self {
 128            Message::User(message) => {
 129                if message.content.is_empty() {
 130                    vec![]
 131                } else {
 132                    vec![message.to_request()]
 133                }
 134            }
 135            Message::Agent(message) => message.to_request(),
 136            Message::Resume => vec![LanguageModelRequestMessage {
 137                role: Role::User,
 138                content: vec!["Continue where you left off".into()],
 139                cache: false,
 140                reasoning_details: None,
 141            }],
 142        }
 143    }
 144
 145    pub fn to_markdown(&self) -> String {
 146        match self {
 147            Message::User(message) => message.to_markdown(),
 148            Message::Agent(message) => message.to_markdown(),
 149            Message::Resume => "[resume]\n".into(),
 150        }
 151    }
 152
 153    pub fn role(&self) -> Role {
 154        match self {
 155            Message::User(_) | Message::Resume => Role::User,
 156            Message::Agent(_) => Role::Assistant,
 157        }
 158    }
 159}
 160
 161#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 162pub struct UserMessage {
 163    pub id: UserMessageId,
 164    pub content: Vec<UserMessageContent>,
 165}
 166
 167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 168pub enum UserMessageContent {
 169    Text(String),
 170    Mention { uri: MentionUri, content: String },
 171    Image(LanguageModelImage),
 172}
 173
 174impl UserMessage {
 175    pub fn to_markdown(&self) -> String {
 176        let mut markdown = String::new();
 177
 178        for content in &self.content {
 179            match content {
 180                UserMessageContent::Text(text) => {
 181                    markdown.push_str(text);
 182                    markdown.push('\n');
 183                }
 184                UserMessageContent::Image(_) => {
 185                    markdown.push_str("<image />\n");
 186                }
 187                UserMessageContent::Mention { uri, content } => {
 188                    if !content.is_empty() {
 189                        let _ = writeln!(&mut markdown, "{}\n\n{}", uri.as_link(), content);
 190                    } else {
 191                        let _ = writeln!(&mut markdown, "{}", uri.as_link());
 192                    }
 193                }
 194            }
 195        }
 196
 197        markdown
 198    }
 199
 200    fn to_request(&self) -> LanguageModelRequestMessage {
 201        let mut message = LanguageModelRequestMessage {
 202            role: Role::User,
 203            content: Vec::with_capacity(self.content.len()),
 204            cache: false,
 205            reasoning_details: None,
 206        };
 207
 208        const OPEN_CONTEXT: &str = "<context>\n\
 209            The following items were attached by the user. \
 210            They are up-to-date and don't need to be re-read.\n\n";
 211
 212        const OPEN_FILES_TAG: &str = "<files>";
 213        const OPEN_DIRECTORIES_TAG: &str = "<directories>";
 214        const OPEN_SYMBOLS_TAG: &str = "<symbols>";
 215        const OPEN_SELECTIONS_TAG: &str = "<selections>";
 216        const OPEN_THREADS_TAG: &str = "<threads>";
 217        const OPEN_FETCH_TAG: &str = "<fetched_urls>";
 218        const OPEN_RULES_TAG: &str =
 219            "<rules>\nThe user has specified the following rules that should be applied:\n";
 220        const OPEN_DIAGNOSTICS_TAG: &str = "<diagnostics>";
 221        const OPEN_DIFFS_TAG: &str = "<diffs>";
 222
 223        let mut file_context = OPEN_FILES_TAG.to_string();
 224        let mut directory_context = OPEN_DIRECTORIES_TAG.to_string();
 225        let mut symbol_context = OPEN_SYMBOLS_TAG.to_string();
 226        let mut selection_context = OPEN_SELECTIONS_TAG.to_string();
 227        let mut thread_context = OPEN_THREADS_TAG.to_string();
 228        let mut fetch_context = OPEN_FETCH_TAG.to_string();
 229        let mut rules_context = OPEN_RULES_TAG.to_string();
 230        let mut diagnostics_context = OPEN_DIAGNOSTICS_TAG.to_string();
 231        let mut diffs_context = OPEN_DIFFS_TAG.to_string();
 232
 233        for chunk in &self.content {
 234            let chunk = match chunk {
 235                UserMessageContent::Text(text) => {
 236                    language_model::MessageContent::Text(text.clone())
 237                }
 238                UserMessageContent::Image(value) => {
 239                    language_model::MessageContent::Image(value.clone())
 240                }
 241                UserMessageContent::Mention { uri, content } => {
 242                    match uri {
 243                        MentionUri::File { abs_path } => {
 244                            write!(
 245                                &mut file_context,
 246                                "\n{}",
 247                                MarkdownCodeBlock {
 248                                    tag: &codeblock_tag(abs_path, None),
 249                                    text: &content.to_string(),
 250                                }
 251                            )
 252                            .ok();
 253                        }
 254                        MentionUri::PastedImage => {
 255                            debug_panic!("pasted image URI should not be used in mention content")
 256                        }
 257                        MentionUri::Directory { .. } => {
 258                            write!(&mut directory_context, "\n{}\n", content).ok();
 259                        }
 260                        MentionUri::Symbol {
 261                            abs_path: path,
 262                            line_range,
 263                            ..
 264                        } => {
 265                            write!(
 266                                &mut symbol_context,
 267                                "\n{}",
 268                                MarkdownCodeBlock {
 269                                    tag: &codeblock_tag(path, Some(line_range)),
 270                                    text: content
 271                                }
 272                            )
 273                            .ok();
 274                        }
 275                        MentionUri::Selection {
 276                            abs_path: path,
 277                            line_range,
 278                            ..
 279                        } => {
 280                            write!(
 281                                &mut selection_context,
 282                                "\n{}",
 283                                MarkdownCodeBlock {
 284                                    tag: &codeblock_tag(
 285                                        path.as_deref().unwrap_or("Untitled".as_ref()),
 286                                        Some(line_range)
 287                                    ),
 288                                    text: content
 289                                }
 290                            )
 291                            .ok();
 292                        }
 293                        MentionUri::Thread { .. } => {
 294                            write!(&mut thread_context, "\n{}\n", content).ok();
 295                        }
 296                        MentionUri::TextThread { .. } => {
 297                            write!(&mut thread_context, "\n{}\n", content).ok();
 298                        }
 299                        MentionUri::Rule { .. } => {
 300                            write!(
 301                                &mut rules_context,
 302                                "\n{}",
 303                                MarkdownCodeBlock {
 304                                    tag: "",
 305                                    text: content
 306                                }
 307                            )
 308                            .ok();
 309                        }
 310                        MentionUri::Fetch { url } => {
 311                            write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();
 312                        }
 313                        MentionUri::Diagnostics { .. } => {
 314                            write!(&mut diagnostics_context, "\n{}\n", content).ok();
 315                        }
 316                        MentionUri::TerminalSelection { .. } => {
 317                            write!(
 318                                &mut selection_context,
 319                                "\n{}",
 320                                MarkdownCodeBlock {
 321                                    tag: "console",
 322                                    text: content
 323                                }
 324                            )
 325                            .ok();
 326                        }
 327                        MentionUri::GitDiff { base_ref } => {
 328                            write!(
 329                                &mut diffs_context,
 330                                "\nBranch diff against {}:\n{}",
 331                                base_ref,
 332                                MarkdownCodeBlock {
 333                                    tag: "diff",
 334                                    text: content
 335                                }
 336                            )
 337                            .ok();
 338                        }
 339                    }
 340
 341                    language_model::MessageContent::Text(uri.as_link().to_string())
 342                }
 343            };
 344
 345            message.content.push(chunk);
 346        }
 347
 348        let len_before_context = message.content.len();
 349
 350        if file_context.len() > OPEN_FILES_TAG.len() {
 351            file_context.push_str("</files>\n");
 352            message
 353                .content
 354                .push(language_model::MessageContent::Text(file_context));
 355        }
 356
 357        if directory_context.len() > OPEN_DIRECTORIES_TAG.len() {
 358            directory_context.push_str("</directories>\n");
 359            message
 360                .content
 361                .push(language_model::MessageContent::Text(directory_context));
 362        }
 363
 364        if symbol_context.len() > OPEN_SYMBOLS_TAG.len() {
 365            symbol_context.push_str("</symbols>\n");
 366            message
 367                .content
 368                .push(language_model::MessageContent::Text(symbol_context));
 369        }
 370
 371        if selection_context.len() > OPEN_SELECTIONS_TAG.len() {
 372            selection_context.push_str("</selections>\n");
 373            message
 374                .content
 375                .push(language_model::MessageContent::Text(selection_context));
 376        }
 377
 378        if diffs_context.len() > OPEN_DIFFS_TAG.len() {
 379            diffs_context.push_str("</diffs>\n");
 380            message
 381                .content
 382                .push(language_model::MessageContent::Text(diffs_context));
 383        }
 384
 385        if thread_context.len() > OPEN_THREADS_TAG.len() {
 386            thread_context.push_str("</threads>\n");
 387            message
 388                .content
 389                .push(language_model::MessageContent::Text(thread_context));
 390        }
 391
 392        if fetch_context.len() > OPEN_FETCH_TAG.len() {
 393            fetch_context.push_str("</fetched_urls>\n");
 394            message
 395                .content
 396                .push(language_model::MessageContent::Text(fetch_context));
 397        }
 398
 399        if rules_context.len() > OPEN_RULES_TAG.len() {
 400            rules_context.push_str("</user_rules>\n");
 401            message
 402                .content
 403                .push(language_model::MessageContent::Text(rules_context));
 404        }
 405
 406        if diagnostics_context.len() > OPEN_DIAGNOSTICS_TAG.len() {
 407            diagnostics_context.push_str("</diagnostics>\n");
 408            message
 409                .content
 410                .push(language_model::MessageContent::Text(diagnostics_context));
 411        }
 412
 413        if message.content.len() > len_before_context {
 414            message.content.insert(
 415                len_before_context,
 416                language_model::MessageContent::Text(OPEN_CONTEXT.into()),
 417            );
 418            message
 419                .content
 420                .push(language_model::MessageContent::Text("</context>".into()));
 421        }
 422
 423        message
 424    }
 425}
 426
 427fn codeblock_tag(full_path: &Path, line_range: Option<&RangeInclusive<u32>>) -> String {
 428    let mut result = String::new();
 429
 430    if let Some(extension) = full_path.extension().and_then(|ext| ext.to_str()) {
 431        let _ = write!(result, "{} ", extension);
 432    }
 433
 434    let _ = write!(result, "{}", full_path.display());
 435
 436    if let Some(range) = line_range {
 437        if range.start() == range.end() {
 438            let _ = write!(result, ":{}", range.start() + 1);
 439        } else {
 440            let _ = write!(result, ":{}-{}", range.start() + 1, range.end() + 1);
 441        }
 442    }
 443
 444    result
 445}
 446
 447impl AgentMessage {
 448    pub fn to_markdown(&self) -> String {
 449        let mut markdown = String::new();
 450
 451        for content in &self.content {
 452            match content {
 453                AgentMessageContent::Text(text) => {
 454                    markdown.push_str(text);
 455                    markdown.push('\n');
 456                }
 457                AgentMessageContent::Thinking { text, .. } => {
 458                    markdown.push_str("<think>");
 459                    markdown.push_str(text);
 460                    markdown.push_str("</think>\n");
 461                }
 462                AgentMessageContent::RedactedThinking(_) => {
 463                    markdown.push_str("<redacted_thinking />\n")
 464                }
 465                AgentMessageContent::ToolUse(tool_use) => {
 466                    markdown.push_str(&format!(
 467                        "**Tool Use**: {} (ID: {})\n",
 468                        tool_use.name, tool_use.id
 469                    ));
 470                    markdown.push_str(&format!(
 471                        "{}\n",
 472                        MarkdownCodeBlock {
 473                            tag: "json",
 474                            text: &format!("{:#}", tool_use.input)
 475                        }
 476                    ));
 477                }
 478            }
 479        }
 480
 481        for tool_result in self.tool_results.values() {
 482            markdown.push_str(&format!(
 483                "**Tool Result**: {} (ID: {})\n\n",
 484                tool_result.tool_name, tool_result.tool_use_id
 485            ));
 486            if tool_result.is_error {
 487                markdown.push_str("**ERROR:**\n");
 488            }
 489
 490            match &tool_result.content {
 491                LanguageModelToolResultContent::Text(text) => {
 492                    writeln!(markdown, "{text}\n").ok();
 493                }
 494                LanguageModelToolResultContent::Image(_) => {
 495                    writeln!(markdown, "<image />\n").ok();
 496                }
 497            }
 498
 499            if let Some(output) = tool_result.output.as_ref() {
 500                writeln!(
 501                    markdown,
 502                    "**Debug Output**:\n\n```json\n{}\n```\n",
 503                    serde_json::to_string_pretty(output).unwrap()
 504                )
 505                .unwrap();
 506            }
 507        }
 508
 509        markdown
 510    }
 511
 512    pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
 513        let mut assistant_message = LanguageModelRequestMessage {
 514            role: Role::Assistant,
 515            content: Vec::with_capacity(self.content.len()),
 516            cache: false,
 517            reasoning_details: self.reasoning_details.clone(),
 518        };
 519        for chunk in &self.content {
 520            match chunk {
 521                AgentMessageContent::Text(text) => {
 522                    assistant_message
 523                        .content
 524                        .push(language_model::MessageContent::Text(text.clone()));
 525                }
 526                AgentMessageContent::Thinking { text, signature } => {
 527                    assistant_message
 528                        .content
 529                        .push(language_model::MessageContent::Thinking {
 530                            text: text.clone(),
 531                            signature: signature.clone(),
 532                        });
 533                }
 534                AgentMessageContent::RedactedThinking(value) => {
 535                    assistant_message.content.push(
 536                        language_model::MessageContent::RedactedThinking(value.clone()),
 537                    );
 538                }
 539                AgentMessageContent::ToolUse(tool_use) => {
 540                    if self.tool_results.contains_key(&tool_use.id) {
 541                        assistant_message
 542                            .content
 543                            .push(language_model::MessageContent::ToolUse(tool_use.clone()));
 544                    }
 545                }
 546            };
 547        }
 548
 549        let mut user_message = LanguageModelRequestMessage {
 550            role: Role::User,
 551            content: Vec::new(),
 552            cache: false,
 553            reasoning_details: None,
 554        };
 555
 556        for tool_result in self.tool_results.values() {
 557            let mut tool_result = tool_result.clone();
 558            // Surprisingly, the API fails if we return an empty string here.
 559            // It thinks we are sending a tool use without a tool result.
 560            if tool_result.content.is_empty() {
 561                tool_result.content = "<Tool returned an empty string>".into();
 562            }
 563            user_message
 564                .content
 565                .push(language_model::MessageContent::ToolResult(tool_result));
 566        }
 567
 568        let mut messages = Vec::new();
 569        if !assistant_message.content.is_empty() {
 570            messages.push(assistant_message);
 571        }
 572        if !user_message.content.is_empty() {
 573            messages.push(user_message);
 574        }
 575        messages
 576    }
 577}
 578
 579#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 580pub struct AgentMessage {
 581    pub content: Vec<AgentMessageContent>,
 582    pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
 583    pub reasoning_details: Option<serde_json::Value>,
 584}
 585
 586#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 587pub enum AgentMessageContent {
 588    Text(String),
 589    Thinking {
 590        text: String,
 591        signature: Option<String>,
 592    },
 593    RedactedThinking(String),
 594    ToolUse(LanguageModelToolUse),
 595}
 596
 597pub trait TerminalHandle {
 598    fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId>;
 599    fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse>;
 600    fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>>;
 601    fn kill(&self, cx: &AsyncApp) -> Result<()>;
 602    fn was_stopped_by_user(&self, cx: &AsyncApp) -> Result<bool>;
 603}
 604
 605pub trait SubagentHandle {
 606    /// The session ID of this subagent thread
 607    fn id(&self) -> acp::SessionId;
 608    /// The current number of entries in the thread.
 609    /// Useful for knowing where the next turn will begin
 610    fn num_entries(&self, cx: &App) -> usize;
 611    /// Runs a turn for a given message and returns both the response and the index of that output message.
 612    fn send(&self, message: String, cx: &AsyncApp) -> Task<Result<String>>;
 613}
 614
 615pub trait ThreadEnvironment {
 616    fn create_terminal(
 617        &self,
 618        command: String,
 619        cwd: Option<PathBuf>,
 620        output_byte_limit: Option<u64>,
 621        cx: &mut AsyncApp,
 622    ) -> Task<Result<Rc<dyn TerminalHandle>>>;
 623
 624    fn create_subagent(&self, label: String, cx: &mut App) -> Result<Rc<dyn SubagentHandle>>;
 625
 626    fn resume_subagent(
 627        &self,
 628        _session_id: acp::SessionId,
 629        _cx: &mut App,
 630    ) -> Result<Rc<dyn SubagentHandle>> {
 631        Err(anyhow::anyhow!(
 632            "Resuming subagent sessions is not supported"
 633        ))
 634    }
 635}
 636
 637#[derive(Debug)]
 638pub enum ThreadEvent {
 639    UserMessage(UserMessage),
 640    AgentText(String),
 641    AgentThinking(String),
 642    ToolCall(acp::ToolCall),
 643    ToolCallUpdate(acp_thread::ToolCallUpdate),
 644    ToolCallAuthorization(ToolCallAuthorization),
 645    SubagentSpawned(acp::SessionId),
 646    Retry(acp_thread::RetryStatus),
 647    Stop(acp::StopReason),
 648}
 649
 650#[derive(Debug)]
 651pub struct NewTerminal {
 652    pub command: String,
 653    pub output_byte_limit: Option<u64>,
 654    pub cwd: Option<PathBuf>,
 655    pub response: oneshot::Sender<Result<Entity<acp_thread::Terminal>>>,
 656}
 657
 658#[derive(Debug, Clone)]
 659pub struct ToolPermissionContext {
 660    pub tool_name: String,
 661    pub input_values: Vec<String>,
 662    pub scope: ToolPermissionScope,
 663}
 664
 665#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 666pub enum ToolPermissionScope {
 667    ToolInput,
 668    SymlinkTarget,
 669}
 670
 671impl ToolPermissionContext {
 672    pub fn new(tool_name: impl Into<String>, input_values: Vec<String>) -> Self {
 673        Self {
 674            tool_name: tool_name.into(),
 675            input_values,
 676            scope: ToolPermissionScope::ToolInput,
 677        }
 678    }
 679
 680    pub fn symlink_target(tool_name: impl Into<String>, target_paths: Vec<String>) -> Self {
 681        Self {
 682            tool_name: tool_name.into(),
 683            input_values: target_paths,
 684            scope: ToolPermissionScope::SymlinkTarget,
 685        }
 686    }
 687
 688    /// Builds the permission options for this tool context.
 689    ///
 690    /// This is the canonical source for permission option generation.
 691    /// Tests should use this function rather than manually constructing options.
 692    ///
 693    /// # Shell Compatibility for Terminal Tool
 694    ///
 695    /// For the terminal tool, "Always allow" options are only shown when the user's
 696    /// shell supports POSIX-like command chaining syntax (`&&`, `||`, `;`, `|`).
 697    ///
 698    /// **Why this matters:** When a user sets up an "always allow" pattern like `^cargo`,
 699    /// we need to parse the command to extract all sub-commands and verify that EVERY
 700    /// sub-command matches the pattern. Otherwise, an attacker could craft a command like
 701    /// `cargo build && rm -rf /` that would bypass the security check.
 702    ///
 703    /// **Supported shells:** Posix (sh, bash, dash, zsh), Fish 3.0+, PowerShell 7+/Pwsh,
 704    /// Cmd, Xonsh, Csh, Tcsh
 705    ///
 706    /// **Unsupported shells:** Nushell (uses `and`/`or` keywords), Elvish (uses `and`/`or`
 707    /// keywords), Rc (Plan 9 shell - no `&&`/`||` operators)
 708    ///
 709    /// For unsupported shells, we hide the "Always allow" UI options entirely, and if
 710    /// the user has `always_allow` rules configured in settings, `ToolPermissionDecision::from_input`
 711    /// will return a `Deny` with an explanatory error message.
 712    pub fn build_permission_options(&self) -> acp_thread::PermissionOptions {
 713        use crate::pattern_extraction::*;
 714        use util::shell::ShellKind;
 715
 716        let tool_name = &self.tool_name;
 717        let input_values = &self.input_values;
 718        if self.scope == ToolPermissionScope::SymlinkTarget {
 719            return acp_thread::PermissionOptions::Flat(vec![
 720                acp::PermissionOption::new(
 721                    acp::PermissionOptionId::new("allow"),
 722                    "Yes",
 723                    acp::PermissionOptionKind::AllowOnce,
 724                ),
 725                acp::PermissionOption::new(
 726                    acp::PermissionOptionId::new("deny"),
 727                    "No",
 728                    acp::PermissionOptionKind::RejectOnce,
 729                ),
 730            ]);
 731        }
 732
 733        // Check if the user's shell supports POSIX-like command chaining.
 734        // See the doc comment above for the full explanation of why this is needed.
 735        let shell_supports_always_allow = if tool_name == TerminalTool::NAME {
 736            ShellKind::system().supports_posix_chaining()
 737        } else {
 738            true
 739        };
 740
 741        let extract_for_value = |value: &str| -> (Option<String>, Option<String>) {
 742            if tool_name == TerminalTool::NAME {
 743                (
 744                    extract_terminal_pattern(value),
 745                    extract_terminal_pattern_display(value),
 746                )
 747            } else if tool_name == CopyPathTool::NAME
 748                || tool_name == MovePathTool::NAME
 749                || tool_name == EditFileTool::NAME
 750                || tool_name == DeletePathTool::NAME
 751                || tool_name == CreateDirectoryTool::NAME
 752                || tool_name == SaveFileTool::NAME
 753            {
 754                (
 755                    extract_path_pattern(value),
 756                    extract_path_pattern_display(value),
 757                )
 758            } else if tool_name == FetchTool::NAME {
 759                (
 760                    extract_url_pattern(value),
 761                    extract_url_pattern_display(value),
 762                )
 763            } else {
 764                (None, None)
 765            }
 766        };
 767
 768        // Extract patterns from all input values. Only offer a pattern-specific
 769        // "always allow/deny" button when every value produces the same pattern.
 770        let (pattern, pattern_display) = match input_values.as_slice() {
 771            [single] => extract_for_value(single),
 772            _ => {
 773                let mut iter = input_values.iter().map(|v| extract_for_value(v));
 774                match iter.next() {
 775                    Some(first) => {
 776                        if iter.all(|pair| pair.0 == first.0) {
 777                            first
 778                        } else {
 779                            (None, None)
 780                        }
 781                    }
 782                    None => (None, None),
 783                }
 784            }
 785        };
 786
 787        let mut choices = Vec::new();
 788
 789        let mut push_choice = |label: String, allow_id, deny_id, allow_kind, deny_kind| {
 790            choices.push(acp_thread::PermissionOptionChoice {
 791                allow: acp::PermissionOption::new(
 792                    acp::PermissionOptionId::new(allow_id),
 793                    label.clone(),
 794                    allow_kind,
 795                ),
 796                deny: acp::PermissionOption::new(
 797                    acp::PermissionOptionId::new(deny_id),
 798                    label,
 799                    deny_kind,
 800                ),
 801            });
 802        };
 803
 804        if shell_supports_always_allow {
 805            push_choice(
 806                format!("Always for {}", tool_name.replace('_', " ")),
 807                format!("always_allow:{}", tool_name),
 808                format!("always_deny:{}", tool_name),
 809                acp::PermissionOptionKind::AllowAlways,
 810                acp::PermissionOptionKind::RejectAlways,
 811            );
 812
 813            if let (Some(pattern), Some(display)) = (pattern, pattern_display) {
 814                let button_text = if tool_name == TerminalTool::NAME {
 815                    format!("Always for `{}` commands", display)
 816                } else {
 817                    format!("Always for `{}`", display)
 818                };
 819                push_choice(
 820                    button_text,
 821                    format!("always_allow_pattern:{}\n{}", tool_name, pattern),
 822                    format!("always_deny_pattern:{}\n{}", tool_name, pattern),
 823                    acp::PermissionOptionKind::AllowAlways,
 824                    acp::PermissionOptionKind::RejectAlways,
 825                );
 826            }
 827        }
 828
 829        push_choice(
 830            "Only this time".to_string(),
 831            "allow".to_string(),
 832            "deny".to_string(),
 833            acp::PermissionOptionKind::AllowOnce,
 834            acp::PermissionOptionKind::RejectOnce,
 835        );
 836
 837        acp_thread::PermissionOptions::Dropdown(choices)
 838    }
 839}
 840
 841#[derive(Debug)]
 842pub struct ToolCallAuthorization {
 843    pub tool_call: acp::ToolCallUpdate,
 844    pub options: acp_thread::PermissionOptions,
 845    pub response: oneshot::Sender<acp::PermissionOptionId>,
 846    pub context: Option<ToolPermissionContext>,
 847}
 848
 849#[derive(Debug, thiserror::Error)]
 850enum CompletionError {
 851    #[error("max tokens")]
 852    MaxTokens,
 853    #[error("refusal")]
 854    Refusal,
 855    #[error(transparent)]
 856    Other(#[from] anyhow::Error),
 857}
 858
 859pub struct Thread {
 860    id: acp::SessionId,
 861    prompt_id: PromptId,
 862    updated_at: DateTime<Utc>,
 863    title: Option<SharedString>,
 864    pending_title_generation: Option<Task<()>>,
 865    pending_summary_generation: Option<Shared<Task<Option<SharedString>>>>,
 866    summary: Option<SharedString>,
 867    messages: Vec<Message>,
 868    user_store: Entity<UserStore>,
 869    /// Holds the task that handles agent interaction until the end of the turn.
 870    /// Survives across multiple requests as the model performs tool calls and
 871    /// we run tools, report their results.
 872    running_turn: Option<RunningTurn>,
 873    /// Flag indicating the UI has a queued message waiting to be sent.
 874    /// Used to signal that the turn should end at the next message boundary.
 875    has_queued_message: bool,
 876    pending_message: Option<AgentMessage>,
 877    pub(crate) tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
 878    request_token_usage: HashMap<UserMessageId, language_model::TokenUsage>,
 879    #[allow(unused)]
 880    cumulative_token_usage: TokenUsage,
 881    #[allow(unused)]
 882    initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
 883    pub(crate) context_server_registry: Entity<ContextServerRegistry>,
 884    profile_id: AgentProfileId,
 885    project_context: Entity<ProjectContext>,
 886    pub(crate) templates: Arc<Templates>,
 887    model: Option<Arc<dyn LanguageModel>>,
 888    summarization_model: Option<Arc<dyn LanguageModel>>,
 889    thinking_enabled: bool,
 890    thinking_effort: Option<String>,
 891    speed: Option<Speed>,
 892    prompt_capabilities_tx: watch::Sender<acp::PromptCapabilities>,
 893    pub(crate) prompt_capabilities_rx: watch::Receiver<acp::PromptCapabilities>,
 894    pub(crate) project: Entity<Project>,
 895    pub(crate) action_log: Entity<ActionLog>,
 896    /// Tracks the last time files were read by the agent, to detect external modifications
 897    pub(crate) file_read_times: HashMap<PathBuf, fs::MTime>,
 898    /// True if this thread was imported from a shared thread and can be synced.
 899    imported: bool,
 900    /// If this is a subagent thread, contains context about the parent
 901    subagent_context: Option<SubagentContext>,
 902    /// The user's unsent prompt text, persisted so it can be restored when reloading the thread.
 903    draft_prompt: Option<Vec<acp::ContentBlock>>,
 904    /// Weak references to running subagent threads for cancellation propagation
 905    running_subagents: Vec<WeakEntity<Thread>>,
 906}
 907
 908impl Thread {
 909    fn prompt_capabilities(model: Option<&dyn LanguageModel>) -> acp::PromptCapabilities {
 910        let image = model.map_or(true, |model| model.supports_images());
 911        acp::PromptCapabilities::new()
 912            .image(image)
 913            .embedded_context(true)
 914    }
 915
 916    pub fn new_subagent(parent_thread: &Entity<Thread>, cx: &mut Context<Self>) -> Self {
 917        let project = parent_thread.read(cx).project.clone();
 918        let project_context = parent_thread.read(cx).project_context.clone();
 919        let context_server_registry = parent_thread.read(cx).context_server_registry.clone();
 920        let templates = parent_thread.read(cx).templates.clone();
 921        let model = parent_thread.read(cx).model().cloned();
 922        let parent_action_log = parent_thread.read(cx).action_log().clone();
 923        let action_log =
 924            cx.new(|_cx| ActionLog::new(project.clone()).with_linked_action_log(parent_action_log));
 925        let mut thread = Self::new_internal(
 926            project,
 927            project_context,
 928            context_server_registry,
 929            templates,
 930            model,
 931            action_log,
 932            cx,
 933        );
 934        thread.subagent_context = Some(SubagentContext {
 935            parent_thread_id: parent_thread.read(cx).id().clone(),
 936            depth: parent_thread.read(cx).depth() + 1,
 937        });
 938        thread
 939    }
 940
 941    pub fn new(
 942        project: Entity<Project>,
 943        project_context: Entity<ProjectContext>,
 944        context_server_registry: Entity<ContextServerRegistry>,
 945        templates: Arc<Templates>,
 946        model: Option<Arc<dyn LanguageModel>>,
 947        cx: &mut Context<Self>,
 948    ) -> Self {
 949        Self::new_internal(
 950            project.clone(),
 951            project_context,
 952            context_server_registry,
 953            templates,
 954            model,
 955            cx.new(|_cx| ActionLog::new(project)),
 956            cx,
 957        )
 958    }
 959
 960    fn new_internal(
 961        project: Entity<Project>,
 962        project_context: Entity<ProjectContext>,
 963        context_server_registry: Entity<ContextServerRegistry>,
 964        templates: Arc<Templates>,
 965        model: Option<Arc<dyn LanguageModel>>,
 966        action_log: Entity<ActionLog>,
 967        cx: &mut Context<Self>,
 968    ) -> Self {
 969        let settings = AgentSettings::get_global(cx);
 970        let profile_id = settings.default_profile.clone();
 971        let enable_thinking = settings
 972            .default_model
 973            .as_ref()
 974            .is_some_and(|model| model.enable_thinking);
 975        let thinking_effort = settings
 976            .default_model
 977            .as_ref()
 978            .and_then(|model| model.effort.clone());
 979        let (prompt_capabilities_tx, prompt_capabilities_rx) =
 980            watch::channel(Self::prompt_capabilities(model.as_deref()));
 981        Self {
 982            id: acp::SessionId::new(uuid::Uuid::new_v4().to_string()),
 983            prompt_id: PromptId::new(),
 984            updated_at: Utc::now(),
 985            title: None,
 986            pending_title_generation: None,
 987            pending_summary_generation: None,
 988            summary: None,
 989            messages: Vec::new(),
 990            user_store: project.read(cx).user_store(),
 991            running_turn: None,
 992            has_queued_message: false,
 993            pending_message: None,
 994            tools: BTreeMap::default(),
 995            request_token_usage: HashMap::default(),
 996            cumulative_token_usage: TokenUsage::default(),
 997            initial_project_snapshot: {
 998                let project_snapshot = Self::project_snapshot(project.clone(), cx);
 999                cx.foreground_executor()
1000                    .spawn(async move { Some(project_snapshot.await) })
1001                    .shared()
1002            },
1003            context_server_registry,
1004            profile_id,
1005            project_context,
1006            templates,
1007            model,
1008            summarization_model: None,
1009            thinking_enabled: enable_thinking,
1010            speed: None,
1011            thinking_effort,
1012            prompt_capabilities_tx,
1013            prompt_capabilities_rx,
1014            project,
1015            action_log,
1016            file_read_times: HashMap::default(),
1017            imported: false,
1018            subagent_context: None,
1019            draft_prompt: None,
1020            running_subagents: Vec::new(),
1021        }
1022    }
1023
1024    pub fn id(&self) -> &acp::SessionId {
1025        &self.id
1026    }
1027
1028    /// Returns true if this thread was imported from a shared thread.
1029    pub fn is_imported(&self) -> bool {
1030        self.imported
1031    }
1032
1033    pub fn replay(
1034        &mut self,
1035        cx: &mut Context<Self>,
1036    ) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {
1037        let (tx, rx) = mpsc::unbounded();
1038        let stream = ThreadEventStream(tx);
1039        for message in &self.messages {
1040            match message {
1041                Message::User(user_message) => stream.send_user_message(user_message),
1042                Message::Agent(assistant_message) => {
1043                    for content in &assistant_message.content {
1044                        match content {
1045                            AgentMessageContent::Text(text) => stream.send_text(text),
1046                            AgentMessageContent::Thinking { text, .. } => {
1047                                stream.send_thinking(text)
1048                            }
1049                            AgentMessageContent::RedactedThinking(_) => {}
1050                            AgentMessageContent::ToolUse(tool_use) => {
1051                                self.replay_tool_call(
1052                                    tool_use,
1053                                    assistant_message.tool_results.get(&tool_use.id),
1054                                    &stream,
1055                                    cx,
1056                                );
1057                            }
1058                        }
1059                    }
1060                }
1061                Message::Resume => {}
1062            }
1063        }
1064        rx
1065    }
1066
1067    fn replay_tool_call(
1068        &self,
1069        tool_use: &LanguageModelToolUse,
1070        tool_result: Option<&LanguageModelToolResult>,
1071        stream: &ThreadEventStream,
1072        cx: &mut Context<Self>,
1073    ) {
1074        // Extract saved output and status first, so they're available even if tool is not found
1075        let output = tool_result
1076            .as_ref()
1077            .and_then(|result| result.output.clone());
1078        let status = tool_result
1079            .as_ref()
1080            .map_or(acp::ToolCallStatus::Failed, |result| {
1081                if result.is_error {
1082                    acp::ToolCallStatus::Failed
1083                } else {
1084                    acp::ToolCallStatus::Completed
1085                }
1086            });
1087
1088        let tool = self.tools.get(tool_use.name.as_ref()).cloned().or_else(|| {
1089            self.context_server_registry
1090                .read(cx)
1091                .servers()
1092                .find_map(|(_, tools)| {
1093                    if let Some(tool) = tools.get(tool_use.name.as_ref()) {
1094                        Some(tool.clone())
1095                    } else {
1096                        None
1097                    }
1098                })
1099        });
1100
1101        let Some(tool) = tool else {
1102            // Tool not found (e.g., MCP server not connected after restart),
1103            // but still display the saved result if available.
1104            // We need to send both ToolCall and ToolCallUpdate events because the UI
1105            // only converts raw_output to displayable content in update_fields, not from_acp.
1106            stream
1107                .0
1108                .unbounded_send(Ok(ThreadEvent::ToolCall(
1109                    acp::ToolCall::new(tool_use.id.to_string(), tool_use.name.to_string())
1110                        .status(status)
1111                        .raw_input(tool_use.input.clone()),
1112                )))
1113                .ok();
1114            stream.update_tool_call_fields(
1115                &tool_use.id,
1116                acp::ToolCallUpdateFields::new()
1117                    .status(status)
1118                    .raw_output(output),
1119                None,
1120            );
1121            return;
1122        };
1123
1124        let title = tool.initial_title(tool_use.input.clone(), cx);
1125        let kind = tool.kind();
1126        stream.send_tool_call(
1127            &tool_use.id,
1128            &tool_use.name,
1129            title,
1130            kind,
1131            tool_use.input.clone(),
1132        );
1133
1134        if let Some(output) = output.clone() {
1135            // For replay, we use a dummy cancellation receiver since the tool already completed
1136            let (_cancellation_tx, cancellation_rx) = watch::channel(false);
1137            let tool_event_stream = ToolCallEventStream::new(
1138                tool_use.id.clone(),
1139                stream.clone(),
1140                Some(self.project.read(cx).fs().clone()),
1141                cancellation_rx,
1142            );
1143            tool.replay(tool_use.input.clone(), output, tool_event_stream, cx)
1144                .log_err();
1145        }
1146
1147        stream.update_tool_call_fields(
1148            &tool_use.id,
1149            acp::ToolCallUpdateFields::new()
1150                .status(status)
1151                .raw_output(output),
1152            None,
1153        );
1154    }
1155
1156    pub fn from_db(
1157        id: acp::SessionId,
1158        db_thread: DbThread,
1159        project: Entity<Project>,
1160        project_context: Entity<ProjectContext>,
1161        context_server_registry: Entity<ContextServerRegistry>,
1162        templates: Arc<Templates>,
1163        cx: &mut Context<Self>,
1164    ) -> Self {
1165        let settings = AgentSettings::get_global(cx);
1166        let profile_id = db_thread
1167            .profile
1168            .unwrap_or_else(|| settings.default_profile.clone());
1169
1170        let mut model = LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1171            db_thread
1172                .model
1173                .and_then(|model| {
1174                    let model = SelectedModel {
1175                        provider: model.provider.clone().into(),
1176                        model: model.model.into(),
1177                    };
1178                    registry.select_model(&model, cx)
1179                })
1180                .or_else(|| registry.default_model())
1181                .map(|model| model.model)
1182        });
1183
1184        if model.is_none() {
1185            model = Self::resolve_profile_model(&profile_id, cx);
1186        }
1187        if model.is_none() {
1188            model = LanguageModelRegistry::global(cx).update(cx, |registry, _cx| {
1189                registry.default_model().map(|model| model.model)
1190            });
1191        }
1192
1193        let (prompt_capabilities_tx, prompt_capabilities_rx) =
1194            watch::channel(Self::prompt_capabilities(model.as_deref()));
1195
1196        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1197
1198        Self {
1199            id,
1200            prompt_id: PromptId::new(),
1201            title: if db_thread.title.is_empty() {
1202                None
1203            } else {
1204                Some(db_thread.title.clone())
1205            },
1206            pending_title_generation: None,
1207            pending_summary_generation: None,
1208            summary: db_thread.detailed_summary,
1209            messages: db_thread.messages,
1210            user_store: project.read(cx).user_store(),
1211            running_turn: None,
1212            has_queued_message: false,
1213            pending_message: None,
1214            tools: BTreeMap::default(),
1215            request_token_usage: db_thread.request_token_usage.clone(),
1216            cumulative_token_usage: db_thread.cumulative_token_usage,
1217            initial_project_snapshot: Task::ready(db_thread.initial_project_snapshot).shared(),
1218            context_server_registry,
1219            profile_id,
1220            project_context,
1221            templates,
1222            model,
1223            summarization_model: None,
1224            thinking_enabled: db_thread.thinking_enabled,
1225            thinking_effort: db_thread.thinking_effort,
1226            speed: db_thread.speed,
1227            project,
1228            action_log,
1229            updated_at: db_thread.updated_at,
1230            prompt_capabilities_tx,
1231            prompt_capabilities_rx,
1232            file_read_times: HashMap::default(),
1233            imported: db_thread.imported,
1234            subagent_context: db_thread.subagent_context,
1235            draft_prompt: db_thread.draft_prompt,
1236            running_subagents: Vec::new(),
1237        }
1238    }
1239
1240    pub fn to_db(&self, cx: &App) -> Task<DbThread> {
1241        let initial_project_snapshot = self.initial_project_snapshot.clone();
1242        let mut thread = DbThread {
1243            title: self.title(),
1244            messages: self.messages.clone(),
1245            updated_at: self.updated_at,
1246            detailed_summary: self.summary.clone(),
1247            initial_project_snapshot: None,
1248            cumulative_token_usage: self.cumulative_token_usage,
1249            request_token_usage: self.request_token_usage.clone(),
1250            model: self.model.as_ref().map(|model| DbLanguageModel {
1251                provider: model.provider_id().to_string(),
1252                model: model.id().0.to_string(),
1253            }),
1254            profile: Some(self.profile_id.clone()),
1255            imported: self.imported,
1256            subagent_context: self.subagent_context.clone(),
1257            speed: self.speed,
1258            thinking_enabled: self.thinking_enabled,
1259            thinking_effort: self.thinking_effort.clone(),
1260            draft_prompt: self.draft_prompt.clone(),
1261        };
1262
1263        cx.background_spawn(async move {
1264            let initial_project_snapshot = initial_project_snapshot.await;
1265            thread.initial_project_snapshot = initial_project_snapshot;
1266            thread
1267        })
1268    }
1269
1270    /// Create a snapshot of the current project state including git information and unsaved buffers.
1271    fn project_snapshot(
1272        project: Entity<Project>,
1273        cx: &mut Context<Self>,
1274    ) -> Task<Arc<ProjectSnapshot>> {
1275        let task = project::telemetry_snapshot::TelemetrySnapshot::new(&project, cx);
1276        cx.spawn(async move |_, _| {
1277            let snapshot = task.await;
1278
1279            Arc::new(ProjectSnapshot {
1280                worktree_snapshots: snapshot.worktree_snapshots,
1281                timestamp: Utc::now(),
1282            })
1283        })
1284    }
1285
1286    pub fn project_context(&self) -> &Entity<ProjectContext> {
1287        &self.project_context
1288    }
1289
1290    pub fn project(&self) -> &Entity<Project> {
1291        &self.project
1292    }
1293
1294    pub fn action_log(&self) -> &Entity<ActionLog> {
1295        &self.action_log
1296    }
1297
1298    pub fn is_empty(&self) -> bool {
1299        self.messages.is_empty() && self.title.is_none()
1300    }
1301
1302    pub fn draft_prompt(&self) -> Option<&[acp::ContentBlock]> {
1303        self.draft_prompt.as_deref()
1304    }
1305
1306    pub fn set_draft_prompt(&mut self, prompt: Option<Vec<acp::ContentBlock>>) {
1307        self.draft_prompt = prompt;
1308    }
1309
1310    pub fn model(&self) -> Option<&Arc<dyn LanguageModel>> {
1311        self.model.as_ref()
1312    }
1313
1314    pub fn set_model(&mut self, model: Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
1315        let old_usage = self.latest_token_usage();
1316        self.model = Some(model.clone());
1317        let new_caps = Self::prompt_capabilities(self.model.as_deref());
1318        let new_usage = self.latest_token_usage();
1319        if old_usage != new_usage {
1320            cx.emit(TokenUsageUpdated(new_usage));
1321        }
1322        self.prompt_capabilities_tx.send(new_caps).log_err();
1323
1324        for subagent in &self.running_subagents {
1325            subagent
1326                .update(cx, |thread, cx| thread.set_model(model.clone(), cx))
1327                .ok();
1328        }
1329
1330        cx.notify()
1331    }
1332
1333    pub fn summarization_model(&self) -> Option<&Arc<dyn LanguageModel>> {
1334        self.summarization_model.as_ref()
1335    }
1336
1337    pub fn set_summarization_model(
1338        &mut self,
1339        model: Option<Arc<dyn LanguageModel>>,
1340        cx: &mut Context<Self>,
1341    ) {
1342        self.summarization_model = model.clone();
1343
1344        for subagent in &self.running_subagents {
1345            subagent
1346                .update(cx, |thread, cx| {
1347                    thread.set_summarization_model(model.clone(), cx)
1348                })
1349                .ok();
1350        }
1351        cx.notify()
1352    }
1353
1354    pub fn thinking_enabled(&self) -> bool {
1355        self.thinking_enabled
1356    }
1357
1358    pub fn set_thinking_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
1359        self.thinking_enabled = enabled;
1360
1361        for subagent in &self.running_subagents {
1362            subagent
1363                .update(cx, |thread, cx| thread.set_thinking_enabled(enabled, cx))
1364                .ok();
1365        }
1366        cx.notify();
1367    }
1368
1369    pub fn thinking_effort(&self) -> Option<&String> {
1370        self.thinking_effort.as_ref()
1371    }
1372
1373    pub fn set_thinking_effort(&mut self, effort: Option<String>, cx: &mut Context<Self>) {
1374        self.thinking_effort = effort.clone();
1375
1376        for subagent in &self.running_subagents {
1377            subagent
1378                .update(cx, |thread, cx| {
1379                    thread.set_thinking_effort(effort.clone(), cx)
1380                })
1381                .ok();
1382        }
1383        cx.notify();
1384    }
1385
1386    pub fn speed(&self) -> Option<Speed> {
1387        self.speed
1388    }
1389
1390    pub fn set_speed(&mut self, speed: Speed, cx: &mut Context<Self>) {
1391        self.speed = Some(speed);
1392
1393        for subagent in &self.running_subagents {
1394            subagent
1395                .update(cx, |thread, cx| thread.set_speed(speed, cx))
1396                .ok();
1397        }
1398        cx.notify();
1399    }
1400
1401    pub fn last_message(&self) -> Option<&Message> {
1402        self.messages.last()
1403    }
1404
1405    #[cfg(any(test, feature = "test-support"))]
1406    pub fn last_received_or_pending_message(&self) -> Option<Message> {
1407        if let Some(message) = self.pending_message.clone() {
1408            Some(Message::Agent(message))
1409        } else {
1410            self.messages.last().cloned()
1411        }
1412    }
1413
1414    pub fn add_default_tools(
1415        &mut self,
1416        environment: Rc<dyn ThreadEnvironment>,
1417        cx: &mut Context<Self>,
1418    ) {
1419        let language_registry = self.project.read(cx).languages().clone();
1420        self.add_tool(CopyPathTool::new(self.project.clone()));
1421        self.add_tool(CreateDirectoryTool::new(self.project.clone()));
1422        self.add_tool(DeletePathTool::new(
1423            self.project.clone(),
1424            self.action_log.clone(),
1425        ));
1426        self.add_tool(DiagnosticsTool::new(self.project.clone()));
1427        self.add_tool(EditFileTool::new(
1428            self.project.clone(),
1429            cx.weak_entity(),
1430            language_registry.clone(),
1431            Templates::new(),
1432        ));
1433        self.add_tool(StreamingEditFileTool::new(
1434            self.project.clone(),
1435            cx.weak_entity(),
1436            language_registry,
1437        ));
1438        self.add_tool(FetchTool::new(self.project.read(cx).client().http_client()));
1439        self.add_tool(FindPathTool::new(self.project.clone()));
1440        self.add_tool(GrepTool::new(self.project.clone()));
1441        self.add_tool(ListDirectoryTool::new(self.project.clone()));
1442        self.add_tool(MovePathTool::new(self.project.clone()));
1443        self.add_tool(NowTool);
1444        self.add_tool(OpenTool::new(self.project.clone()));
1445        self.add_tool(ReadFileTool::new(
1446            cx.weak_entity(),
1447            self.project.clone(),
1448            self.action_log.clone(),
1449        ));
1450        self.add_tool(SaveFileTool::new(self.project.clone()));
1451        self.add_tool(RestoreFileFromDiskTool::new(self.project.clone()));
1452        self.add_tool(TerminalTool::new(self.project.clone(), environment.clone()));
1453        self.add_tool(WebSearchTool);
1454
1455        if self.depth() < MAX_SUBAGENT_DEPTH {
1456            self.add_tool(SpawnAgentTool::new(environment));
1457        }
1458    }
1459
1460    pub fn add_tool<T: AgentTool>(&mut self, tool: T) {
1461        debug_assert!(
1462            !self.tools.contains_key(T::NAME),
1463            "Duplicate tool name: {}",
1464            T::NAME,
1465        );
1466        self.tools.insert(T::NAME.into(), tool.erase());
1467    }
1468
1469    #[cfg(any(test, feature = "test-support"))]
1470    pub fn remove_tool(&mut self, name: &str) -> bool {
1471        self.tools.remove(name).is_some()
1472    }
1473
1474    pub fn profile(&self) -> &AgentProfileId {
1475        &self.profile_id
1476    }
1477
1478    pub fn set_profile(&mut self, profile_id: AgentProfileId, cx: &mut Context<Self>) {
1479        if self.profile_id == profile_id {
1480            return;
1481        }
1482
1483        self.profile_id = profile_id.clone();
1484
1485        // Swap to the profile's preferred model when available.
1486        if let Some(model) = Self::resolve_profile_model(&self.profile_id, cx) {
1487            self.set_model(model, cx);
1488        }
1489
1490        for subagent in &self.running_subagents {
1491            subagent
1492                .update(cx, |thread, cx| thread.set_profile(profile_id.clone(), cx))
1493                .ok();
1494        }
1495    }
1496
1497    pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
1498        for subagent in self.running_subagents.drain(..) {
1499            if let Some(subagent) = subagent.upgrade() {
1500                subagent.update(cx, |thread, cx| thread.cancel(cx)).detach();
1501            }
1502        }
1503
1504        let Some(running_turn) = self.running_turn.take() else {
1505            self.flush_pending_message(cx);
1506            return Task::ready(());
1507        };
1508
1509        let turn_task = running_turn.cancel();
1510
1511        cx.spawn(async move |this, cx| {
1512            turn_task.await;
1513            this.update(cx, |this, cx| {
1514                this.flush_pending_message(cx);
1515            })
1516            .ok();
1517        })
1518    }
1519
1520    pub fn set_has_queued_message(&mut self, has_queued: bool) {
1521        self.has_queued_message = has_queued;
1522    }
1523
1524    pub fn has_queued_message(&self) -> bool {
1525        self.has_queued_message
1526    }
1527
1528    fn update_token_usage(&mut self, update: language_model::TokenUsage, cx: &mut Context<Self>) {
1529        let Some(last_user_message) = self.last_user_message() else {
1530            return;
1531        };
1532
1533        self.request_token_usage
1534            .insert(last_user_message.id.clone(), update);
1535        cx.emit(TokenUsageUpdated(self.latest_token_usage()));
1536        cx.notify();
1537    }
1538
1539    pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
1540        self.cancel(cx).detach();
1541        // Clear pending message since cancel will try to flush it asynchronously,
1542        // and we don't want that content to be added after we truncate
1543        self.pending_message.take();
1544        let Some(position) = self.messages.iter().position(
1545            |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
1546        ) else {
1547            return Err(anyhow!("Message not found"));
1548        };
1549
1550        for message in self.messages.drain(position..) {
1551            match message {
1552                Message::User(message) => {
1553                    self.request_token_usage.remove(&message.id);
1554                }
1555                Message::Agent(_) | Message::Resume => {}
1556            }
1557        }
1558        self.clear_summary();
1559        cx.notify();
1560        Ok(())
1561    }
1562
1563    pub fn latest_request_token_usage(&self) -> Option<language_model::TokenUsage> {
1564        let last_user_message = self.last_user_message()?;
1565        let tokens = self.request_token_usage.get(&last_user_message.id)?;
1566        Some(*tokens)
1567    }
1568
1569    pub fn latest_token_usage(&self) -> Option<acp_thread::TokenUsage> {
1570        let usage = self.latest_request_token_usage()?;
1571        let model = self.model.clone()?;
1572        Some(acp_thread::TokenUsage {
1573            max_tokens: model.max_token_count(),
1574            max_output_tokens: model.max_output_tokens(),
1575            used_tokens: usage.total_tokens(),
1576            input_tokens: usage.input_tokens,
1577            output_tokens: usage.output_tokens,
1578        })
1579    }
1580
1581    /// Get the total input token count as of the message before the given message.
1582    ///
1583    /// Returns `None` if:
1584    /// - `target_id` is the first message (no previous message)
1585    /// - The previous message hasn't received a response yet (no usage data)
1586    /// - `target_id` is not found in the messages
1587    pub fn tokens_before_message(&self, target_id: &UserMessageId) -> Option<u64> {
1588        let mut previous_user_message_id: Option<&UserMessageId> = None;
1589
1590        for message in &self.messages {
1591            if let Message::User(user_msg) = message {
1592                if &user_msg.id == target_id {
1593                    let prev_id = previous_user_message_id?;
1594                    let usage = self.request_token_usage.get(prev_id)?;
1595                    return Some(usage.input_tokens);
1596                }
1597                previous_user_message_id = Some(&user_msg.id);
1598            }
1599        }
1600        None
1601    }
1602
1603    /// Look up the active profile and resolve its preferred model if one is configured.
1604    fn resolve_profile_model(
1605        profile_id: &AgentProfileId,
1606        cx: &mut Context<Self>,
1607    ) -> Option<Arc<dyn LanguageModel>> {
1608        let selection = AgentSettings::get_global(cx)
1609            .profiles
1610            .get(profile_id)?
1611            .default_model
1612            .clone()?;
1613        Self::resolve_model_from_selection(&selection, cx)
1614    }
1615
1616    /// Translate a stored model selection into the configured model from the registry.
1617    fn resolve_model_from_selection(
1618        selection: &LanguageModelSelection,
1619        cx: &mut Context<Self>,
1620    ) -> Option<Arc<dyn LanguageModel>> {
1621        let selected = SelectedModel {
1622            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
1623            model: LanguageModelId::from(selection.model.clone()),
1624        };
1625        LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1626            registry
1627                .select_model(&selected, cx)
1628                .map(|configured| configured.model)
1629        })
1630    }
1631
1632    pub fn resume(
1633        &mut self,
1634        cx: &mut Context<Self>,
1635    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1636        self.messages.push(Message::Resume);
1637        cx.notify();
1638
1639        log::debug!("Total messages in thread: {}", self.messages.len());
1640        self.run_turn(cx)
1641    }
1642
1643    /// Sending a message results in the model streaming a response, which could include tool calls.
1644    /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
1645    /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
1646    pub fn send<T>(
1647        &mut self,
1648        id: UserMessageId,
1649        content: impl IntoIterator<Item = T>,
1650        cx: &mut Context<Self>,
1651    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
1652    where
1653        T: Into<UserMessageContent>,
1654    {
1655        let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
1656        log::debug!("Thread::send content: {:?}", content);
1657
1658        self.messages
1659            .push(Message::User(UserMessage { id, content }));
1660        cx.notify();
1661
1662        self.send_existing(cx)
1663    }
1664
1665    pub fn send_existing(
1666        &mut self,
1667        cx: &mut Context<Self>,
1668    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1669        let model = self.model().context("No language model configured")?;
1670
1671        log::info!("Thread::send called with model: {}", model.name().0);
1672        self.advance_prompt_id();
1673
1674        log::debug!("Total messages in thread: {}", self.messages.len());
1675        self.run_turn(cx)
1676    }
1677
1678    pub fn push_acp_user_block(
1679        &mut self,
1680        id: UserMessageId,
1681        blocks: impl IntoIterator<Item = acp::ContentBlock>,
1682        path_style: PathStyle,
1683        cx: &mut Context<Self>,
1684    ) {
1685        let content = blocks
1686            .into_iter()
1687            .map(|block| UserMessageContent::from_content_block(block, path_style))
1688            .collect::<Vec<_>>();
1689        self.messages
1690            .push(Message::User(UserMessage { id, content }));
1691        cx.notify();
1692    }
1693
1694    pub fn push_acp_agent_block(&mut self, block: acp::ContentBlock, cx: &mut Context<Self>) {
1695        let text = match block {
1696            acp::ContentBlock::Text(text_content) => text_content.text,
1697            acp::ContentBlock::Image(_) => "[image]".to_string(),
1698            acp::ContentBlock::Audio(_) => "[audio]".to_string(),
1699            acp::ContentBlock::ResourceLink(resource_link) => resource_link.uri,
1700            acp::ContentBlock::Resource(resource) => match resource.resource {
1701                acp::EmbeddedResourceResource::TextResourceContents(resource) => resource.uri,
1702                acp::EmbeddedResourceResource::BlobResourceContents(resource) => resource.uri,
1703                _ => "[resource]".to_string(),
1704            },
1705            _ => "[unknown]".to_string(),
1706        };
1707
1708        self.messages.push(Message::Agent(AgentMessage {
1709            content: vec![AgentMessageContent::Text(text)],
1710            ..Default::default()
1711        }));
1712        cx.notify();
1713    }
1714
1715    #[cfg(feature = "eval")]
1716    pub fn proceed(
1717        &mut self,
1718        cx: &mut Context<Self>,
1719    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1720        self.run_turn(cx)
1721    }
1722
1723    fn run_turn(
1724        &mut self,
1725        cx: &mut Context<Self>,
1726    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1727        // Flush the old pending message synchronously before cancelling,
1728        // to avoid a race where the detached cancel task might flush the NEW
1729        // turn's pending message instead of the old one.
1730        self.flush_pending_message(cx);
1731        self.cancel(cx).detach();
1732
1733        let model = self.model.clone().context("No language model configured")?;
1734        let profile = AgentSettings::get_global(cx)
1735            .profiles
1736            .get(&self.profile_id)
1737            .context("Profile not found")?;
1738        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1739        let event_stream = ThreadEventStream(events_tx);
1740        let message_ix = self.messages.len().saturating_sub(1);
1741        self.clear_summary();
1742        let (cancellation_tx, mut cancellation_rx) = watch::channel(false);
1743        self.running_turn = Some(RunningTurn {
1744            event_stream: event_stream.clone(),
1745            tools: self.enabled_tools(profile, &model, cx),
1746            cancellation_tx,
1747            streaming_tool_inputs: HashMap::default(),
1748            _task: cx.spawn(async move |this, cx| {
1749                log::debug!("Starting agent turn execution");
1750
1751                let turn_result = Self::run_turn_internal(
1752                    &this,
1753                    model,
1754                    &event_stream,
1755                    cancellation_rx.clone(),
1756                    cx,
1757                )
1758                .await;
1759
1760                // Check if we were cancelled - if so, cancel() already took running_turn
1761                // and we shouldn't touch it (it might be a NEW turn now)
1762                let was_cancelled = *cancellation_rx.borrow();
1763                if was_cancelled {
1764                    log::debug!("Turn was cancelled, skipping cleanup");
1765                    return;
1766                }
1767
1768                _ = this.update(cx, |this, cx| this.flush_pending_message(cx));
1769
1770                match turn_result {
1771                    Ok(()) => {
1772                        log::debug!("Turn execution completed");
1773                        event_stream.send_stop(acp::StopReason::EndTurn);
1774                    }
1775                    Err(error) => {
1776                        log::error!("Turn execution failed: {:?}", error);
1777                        match error.downcast::<CompletionError>() {
1778                            Ok(CompletionError::Refusal) => {
1779                                event_stream.send_stop(acp::StopReason::Refusal);
1780                                _ = this.update(cx, |this, _| this.messages.truncate(message_ix));
1781                            }
1782                            Ok(CompletionError::MaxTokens) => {
1783                                event_stream.send_stop(acp::StopReason::MaxTokens);
1784                            }
1785                            Ok(CompletionError::Other(error)) | Err(error) => {
1786                                event_stream.send_error(error);
1787                            }
1788                        }
1789                    }
1790                }
1791
1792                _ = this.update(cx, |this, _| this.running_turn.take());
1793            }),
1794        });
1795        Ok(events_rx)
1796    }
1797
1798    async fn run_turn_internal(
1799        this: &WeakEntity<Self>,
1800        model: Arc<dyn LanguageModel>,
1801        event_stream: &ThreadEventStream,
1802        mut cancellation_rx: watch::Receiver<bool>,
1803        cx: &mut AsyncApp,
1804    ) -> Result<()> {
1805        let mut attempt = 0;
1806        let mut intent = CompletionIntent::UserPrompt;
1807        loop {
1808            let request =
1809                this.update(cx, |this, cx| this.build_completion_request(intent, cx))??;
1810
1811            telemetry::event!(
1812                "Agent Thread Completion",
1813                thread_id = this.read_with(cx, |this, _| this.id.to_string())?,
1814                parent_thread_id = this.read_with(cx, |this, _| this
1815                    .parent_thread_id()
1816                    .map(|id| id.to_string()))?,
1817                prompt_id = this.read_with(cx, |this, _| this.prompt_id.to_string())?,
1818                model = model.telemetry_id(),
1819                model_provider = model.provider_id().to_string(),
1820                attempt
1821            );
1822
1823            log::debug!("Calling model.stream_completion, attempt {}", attempt);
1824
1825            let (mut events, mut error) = match model.stream_completion(request, cx).await {
1826                Ok(events) => (events.fuse(), None),
1827                Err(err) => (stream::empty().boxed().fuse(), Some(err)),
1828            };
1829            let mut tool_results = FuturesUnordered::new();
1830            let mut cancelled = false;
1831            loop {
1832                // Race between getting the first event and cancellation
1833                let first_event = futures::select! {
1834                    event = events.next().fuse() => event,
1835                    _ = cancellation_rx.changed().fuse() => {
1836                        if *cancellation_rx.borrow() {
1837                            cancelled = true;
1838                            break;
1839                        }
1840                        continue;
1841                    }
1842                };
1843                let Some(first_event) = first_event else {
1844                    break;
1845                };
1846
1847                // Collect all immediately available events to process as a batch
1848                let mut batch = vec![first_event];
1849                while let Some(event) = events.next().now_or_never().flatten() {
1850                    batch.push(event);
1851                }
1852
1853                // Process the batch in a single update
1854                let batch_result = this.update(cx, |this, cx| {
1855                    let mut batch_tool_results = Vec::new();
1856                    let mut batch_error = None;
1857
1858                    for event in batch {
1859                        log::trace!("Received completion event: {:?}", event);
1860                        match event {
1861                            Ok(event) => {
1862                                match this.handle_completion_event(
1863                                    event,
1864                                    event_stream,
1865                                    cancellation_rx.clone(),
1866                                    cx,
1867                                ) {
1868                                    Ok(Some(task)) => batch_tool_results.push(task),
1869                                    Ok(None) => {}
1870                                    Err(err) => {
1871                                        batch_error = Some(err);
1872                                        break;
1873                                    }
1874                                }
1875                            }
1876                            Err(err) => {
1877                                batch_error = Some(err.into());
1878                                break;
1879                            }
1880                        }
1881                    }
1882
1883                    cx.notify();
1884                    (batch_tool_results, batch_error)
1885                })?;
1886
1887                tool_results.extend(batch_result.0);
1888                if let Some(err) = batch_result.1 {
1889                    error = Some(err.downcast()?);
1890                    break;
1891                }
1892            }
1893
1894            // Drop the stream to release the rate limit permit before tool execution.
1895            // The stream holds a semaphore guard that limits concurrent requests.
1896            // Without this, the permit would be held during potentially long-running
1897            // tool execution, which could cause deadlocks when tools spawn subagents
1898            // that need their own permits.
1899            drop(events);
1900
1901            let end_turn = tool_results.is_empty();
1902            while let Some(tool_result) = tool_results.next().await {
1903                log::debug!("Tool finished {:?}", tool_result);
1904
1905                event_stream.update_tool_call_fields(
1906                    &tool_result.tool_use_id,
1907                    acp::ToolCallUpdateFields::new()
1908                        .status(if tool_result.is_error {
1909                            acp::ToolCallStatus::Failed
1910                        } else {
1911                            acp::ToolCallStatus::Completed
1912                        })
1913                        .raw_output(tool_result.output.clone()),
1914                    None,
1915                );
1916                this.update(cx, |this, _cx| {
1917                    this.pending_message()
1918                        .tool_results
1919                        .insert(tool_result.tool_use_id.clone(), tool_result);
1920                })?;
1921            }
1922
1923            this.update(cx, |this, cx| {
1924                this.flush_pending_message(cx);
1925                if this.title.is_none() && this.pending_title_generation.is_none() {
1926                    this.generate_title(cx);
1927                }
1928            })?;
1929
1930            if cancelled {
1931                log::debug!("Turn cancelled by user, exiting");
1932                return Ok(());
1933            }
1934
1935            if let Some(error) = error {
1936                attempt += 1;
1937                let retry = this.update(cx, |this, cx| {
1938                    let user_store = this.user_store.read(cx);
1939                    this.handle_completion_error(error, attempt, user_store.plan())
1940                })??;
1941                let timer = cx.background_executor().timer(retry.duration);
1942                event_stream.send_retry(retry);
1943                futures::select! {
1944                    _ = timer.fuse() => {}
1945                    _ = cancellation_rx.changed().fuse() => {
1946                        if *cancellation_rx.borrow() {
1947                            log::debug!("Turn cancelled during retry delay, exiting");
1948                            return Ok(());
1949                        }
1950                    }
1951                }
1952                this.update(cx, |this, _cx| {
1953                    if let Some(Message::Agent(message)) = this.messages.last() {
1954                        if message.tool_results.is_empty() {
1955                            intent = CompletionIntent::UserPrompt;
1956                            this.messages.push(Message::Resume);
1957                        }
1958                    }
1959                })?;
1960            } else if end_turn {
1961                return Ok(());
1962            } else {
1963                let has_queued = this.update(cx, |this, _| this.has_queued_message())?;
1964                if has_queued {
1965                    log::debug!("Queued message found, ending turn at message boundary");
1966                    return Ok(());
1967                }
1968                intent = CompletionIntent::ToolResults;
1969                attempt = 0;
1970            }
1971        }
1972    }
1973
1974    fn handle_completion_error(
1975        &mut self,
1976        error: LanguageModelCompletionError,
1977        attempt: u8,
1978        plan: Option<Plan>,
1979    ) -> Result<acp_thread::RetryStatus> {
1980        let Some(model) = self.model.as_ref() else {
1981            return Err(anyhow!(error));
1982        };
1983
1984        let auto_retry = if model.provider_id() == ZED_CLOUD_PROVIDER_ID {
1985            plan.is_some()
1986        } else {
1987            true
1988        };
1989
1990        if !auto_retry {
1991            return Err(anyhow!(error));
1992        }
1993
1994        let Some(strategy) = Self::retry_strategy_for(&error) else {
1995            return Err(anyhow!(error));
1996        };
1997
1998        let max_attempts = match &strategy {
1999            RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
2000            RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
2001        };
2002
2003        if attempt > max_attempts {
2004            return Err(anyhow!(error));
2005        }
2006
2007        let delay = match &strategy {
2008            RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
2009                let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
2010                Duration::from_secs(delay_secs)
2011            }
2012            RetryStrategy::Fixed { delay, .. } => *delay,
2013        };
2014        log::debug!("Retry attempt {attempt} with delay {delay:?}");
2015
2016        Ok(acp_thread::RetryStatus {
2017            last_error: error.to_string().into(),
2018            attempt: attempt as usize,
2019            max_attempts: max_attempts as usize,
2020            started_at: Instant::now(),
2021            duration: delay,
2022        })
2023    }
2024
2025    /// A helper method that's called on every streamed completion event.
2026    /// Returns an optional tool result task, which the main agentic loop will
2027    /// send back to the model when it resolves.
2028    fn handle_completion_event(
2029        &mut self,
2030        event: LanguageModelCompletionEvent,
2031        event_stream: &ThreadEventStream,
2032        cancellation_rx: watch::Receiver<bool>,
2033        cx: &mut Context<Self>,
2034    ) -> Result<Option<Task<LanguageModelToolResult>>> {
2035        log::trace!("Handling streamed completion event: {:?}", event);
2036        use LanguageModelCompletionEvent::*;
2037
2038        match event {
2039            StartMessage { .. } => {
2040                self.flush_pending_message(cx);
2041                self.pending_message = Some(AgentMessage::default());
2042            }
2043            Text(new_text) => self.handle_text_event(new_text, event_stream),
2044            Thinking { text, signature } => {
2045                self.handle_thinking_event(text, signature, event_stream)
2046            }
2047            RedactedThinking { data } => self.handle_redacted_thinking_event(data),
2048            ReasoningDetails(details) => {
2049                let last_message = self.pending_message();
2050                // Store the last non-empty reasoning_details (overwrites earlier ones)
2051                // This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
2052                if let serde_json::Value::Array(ref arr) = details {
2053                    if !arr.is_empty() {
2054                        last_message.reasoning_details = Some(details);
2055                    }
2056                } else {
2057                    last_message.reasoning_details = Some(details);
2058                }
2059            }
2060            ToolUse(tool_use) => {
2061                return Ok(self.handle_tool_use_event(tool_use, event_stream, cancellation_rx, cx));
2062            }
2063            ToolUseJsonParseError {
2064                id,
2065                tool_name,
2066                raw_input,
2067                json_parse_error,
2068            } => {
2069                return Ok(Some(Task::ready(
2070                    self.handle_tool_use_json_parse_error_event(
2071                        id,
2072                        tool_name,
2073                        raw_input,
2074                        json_parse_error,
2075                        event_stream,
2076                    ),
2077                )));
2078            }
2079            UsageUpdate(usage) => {
2080                telemetry::event!(
2081                    "Agent Thread Completion Usage Updated",
2082                    thread_id = self.id.to_string(),
2083                    parent_thread_id = self.parent_thread_id().map(|id| id.to_string()),
2084                    prompt_id = self.prompt_id.to_string(),
2085                    model = self.model.as_ref().map(|m| m.telemetry_id()),
2086                    model_provider = self.model.as_ref().map(|m| m.provider_id().to_string()),
2087                    input_tokens = usage.input_tokens,
2088                    output_tokens = usage.output_tokens,
2089                    cache_creation_input_tokens = usage.cache_creation_input_tokens,
2090                    cache_read_input_tokens = usage.cache_read_input_tokens,
2091                );
2092                self.update_token_usage(usage, cx);
2093            }
2094            Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
2095            Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
2096            Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
2097            Started | Queued { .. } => {}
2098        }
2099
2100        Ok(None)
2101    }
2102
2103    fn handle_text_event(&mut self, new_text: String, event_stream: &ThreadEventStream) {
2104        event_stream.send_text(&new_text);
2105
2106        let last_message = self.pending_message();
2107        if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
2108            text.push_str(&new_text);
2109        } else {
2110            last_message
2111                .content
2112                .push(AgentMessageContent::Text(new_text));
2113        }
2114    }
2115
2116    fn handle_thinking_event(
2117        &mut self,
2118        new_text: String,
2119        new_signature: Option<String>,
2120        event_stream: &ThreadEventStream,
2121    ) {
2122        event_stream.send_thinking(&new_text);
2123
2124        let last_message = self.pending_message();
2125        if let Some(AgentMessageContent::Thinking { text, signature }) =
2126            last_message.content.last_mut()
2127        {
2128            text.push_str(&new_text);
2129            *signature = new_signature.or(signature.take());
2130        } else {
2131            last_message.content.push(AgentMessageContent::Thinking {
2132                text: new_text,
2133                signature: new_signature,
2134            });
2135        }
2136    }
2137
2138    fn handle_redacted_thinking_event(&mut self, data: String) {
2139        let last_message = self.pending_message();
2140        last_message
2141            .content
2142            .push(AgentMessageContent::RedactedThinking(data));
2143    }
2144
2145    fn handle_tool_use_event(
2146        &mut self,
2147        tool_use: LanguageModelToolUse,
2148        event_stream: &ThreadEventStream,
2149        cancellation_rx: watch::Receiver<bool>,
2150        cx: &mut Context<Self>,
2151    ) -> Option<Task<LanguageModelToolResult>> {
2152        cx.notify();
2153
2154        let tool = self.tool(tool_use.name.as_ref());
2155        let mut title = SharedString::from(&tool_use.name);
2156        let mut kind = acp::ToolKind::Other;
2157        if let Some(tool) = tool.as_ref() {
2158            title = tool.initial_title(tool_use.input.clone(), cx);
2159            kind = tool.kind();
2160        }
2161
2162        self.send_or_update_tool_use(&tool_use, title, kind, event_stream);
2163
2164        let Some(tool) = tool else {
2165            let content = format!("No tool named {} exists", tool_use.name);
2166            return Some(Task::ready(LanguageModelToolResult {
2167                content: LanguageModelToolResultContent::Text(Arc::from(content)),
2168                tool_use_id: tool_use.id,
2169                tool_name: tool_use.name,
2170                is_error: true,
2171                output: None,
2172            }));
2173        };
2174
2175        if !tool_use.is_input_complete {
2176            if tool.supports_input_streaming() {
2177                let running_turn = self.running_turn.as_mut()?;
2178                if let Some(sender) = running_turn.streaming_tool_inputs.get(&tool_use.id) {
2179                    sender.send_partial(tool_use.input);
2180                    return None;
2181                }
2182
2183                let (sender, tool_input) = ToolInputSender::channel();
2184                sender.send_partial(tool_use.input);
2185                running_turn
2186                    .streaming_tool_inputs
2187                    .insert(tool_use.id.clone(), sender);
2188
2189                let tool = tool.clone();
2190                log::debug!("Running streaming tool {}", tool_use.name);
2191                return Some(self.run_tool(
2192                    tool,
2193                    tool_input,
2194                    tool_use.id,
2195                    tool_use.name,
2196                    event_stream,
2197                    cancellation_rx,
2198                    cx,
2199                ));
2200            } else {
2201                return None;
2202            }
2203        }
2204
2205        if let Some(sender) = self
2206            .running_turn
2207            .as_mut()?
2208            .streaming_tool_inputs
2209            .remove(&tool_use.id)
2210        {
2211            sender.send_final(tool_use.input);
2212            return None;
2213        }
2214
2215        log::debug!("Running tool {}", tool_use.name);
2216        let tool_input = ToolInput::ready(tool_use.input);
2217        Some(self.run_tool(
2218            tool,
2219            tool_input,
2220            tool_use.id,
2221            tool_use.name,
2222            event_stream,
2223            cancellation_rx,
2224            cx,
2225        ))
2226    }
2227
2228    fn run_tool(
2229        &self,
2230        tool: Arc<dyn AnyAgentTool>,
2231        tool_input: ToolInput<serde_json::Value>,
2232        tool_use_id: LanguageModelToolUseId,
2233        tool_name: Arc<str>,
2234        event_stream: &ThreadEventStream,
2235        cancellation_rx: watch::Receiver<bool>,
2236        cx: &mut Context<Self>,
2237    ) -> Task<LanguageModelToolResult> {
2238        let fs = self.project.read(cx).fs().clone();
2239        let tool_event_stream = ToolCallEventStream::new(
2240            tool_use_id.clone(),
2241            event_stream.clone(),
2242            Some(fs),
2243            cancellation_rx,
2244        );
2245        tool_event_stream.update_fields(
2246            acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
2247        );
2248        let supports_images = self.model().is_some_and(|model| model.supports_images());
2249        let tool_result = tool.run(tool_input, tool_event_stream, cx);
2250        cx.foreground_executor().spawn(async move {
2251            let (is_error, output) = match tool_result.await {
2252                Ok(mut output) => {
2253                    if let LanguageModelToolResultContent::Image(_) = &output.llm_output
2254                        && !supports_images
2255                    {
2256                        output = AgentToolOutput::from_error(
2257                            "Attempted to read an image, but this model doesn't support it.",
2258                        );
2259                        (true, output)
2260                    } else {
2261                        (false, output)
2262                    }
2263                }
2264                Err(output) => (true, output),
2265            };
2266
2267            LanguageModelToolResult {
2268                tool_use_id,
2269                tool_name,
2270                is_error,
2271                content: output.llm_output,
2272                output: Some(output.raw_output),
2273            }
2274        })
2275    }
2276
2277    fn handle_tool_use_json_parse_error_event(
2278        &mut self,
2279        tool_use_id: LanguageModelToolUseId,
2280        tool_name: Arc<str>,
2281        raw_input: Arc<str>,
2282        json_parse_error: String,
2283        event_stream: &ThreadEventStream,
2284    ) -> LanguageModelToolResult {
2285        let tool_use = LanguageModelToolUse {
2286            id: tool_use_id.clone(),
2287            name: tool_name.clone(),
2288            raw_input: raw_input.to_string(),
2289            input: serde_json::json!({}),
2290            is_input_complete: true,
2291            thought_signature: None,
2292        };
2293        self.send_or_update_tool_use(
2294            &tool_use,
2295            SharedString::from(&tool_use.name),
2296            acp::ToolKind::Other,
2297            event_stream,
2298        );
2299
2300        let tool_output = format!("Error parsing input JSON: {json_parse_error}");
2301        LanguageModelToolResult {
2302            tool_use_id,
2303            tool_name,
2304            is_error: true,
2305            content: LanguageModelToolResultContent::Text(tool_output.into()),
2306            output: Some(serde_json::Value::String(raw_input.to_string())),
2307        }
2308    }
2309
2310    fn send_or_update_tool_use(
2311        &mut self,
2312        tool_use: &LanguageModelToolUse,
2313        title: SharedString,
2314        kind: acp::ToolKind,
2315        event_stream: &ThreadEventStream,
2316    ) {
2317        // Ensure the last message ends in the current tool use
2318        let last_message = self.pending_message();
2319        let push_new_tool_use = last_message.content.last_mut().is_none_or(|content| {
2320            if let AgentMessageContent::ToolUse(last_tool_use) = content {
2321                if last_tool_use.id == tool_use.id {
2322                    *last_tool_use = tool_use.clone();
2323                    false
2324                } else {
2325                    true
2326                }
2327            } else {
2328                true
2329            }
2330        });
2331
2332        if push_new_tool_use {
2333            event_stream.send_tool_call(
2334                &tool_use.id,
2335                &tool_use.name,
2336                title,
2337                kind,
2338                tool_use.input.clone(),
2339            );
2340            last_message
2341                .content
2342                .push(AgentMessageContent::ToolUse(tool_use.clone()));
2343        } else {
2344            event_stream.update_tool_call_fields(
2345                &tool_use.id,
2346                acp::ToolCallUpdateFields::new()
2347                    .title(title.as_str())
2348                    .kind(kind)
2349                    .raw_input(tool_use.input.clone()),
2350                None,
2351            );
2352        }
2353    }
2354
2355    pub fn title(&self) -> SharedString {
2356        self.title.clone().unwrap_or("New Thread".into())
2357    }
2358
2359    pub fn is_generating_summary(&self) -> bool {
2360        self.pending_summary_generation.is_some()
2361    }
2362
2363    pub fn is_generating_title(&self) -> bool {
2364        self.pending_title_generation.is_some()
2365    }
2366
2367    pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
2368        if let Some(summary) = self.summary.as_ref() {
2369            return Task::ready(Some(summary.clone())).shared();
2370        }
2371        if let Some(task) = self.pending_summary_generation.clone() {
2372            return task;
2373        }
2374        let Some(model) = self.summarization_model.clone() else {
2375            log::error!("No summarization model available");
2376            return Task::ready(None).shared();
2377        };
2378        let mut request = LanguageModelRequest {
2379            intent: Some(CompletionIntent::ThreadContextSummarization),
2380            temperature: AgentSettings::temperature_for_model(&model, cx),
2381            ..Default::default()
2382        };
2383
2384        for message in &self.messages {
2385            request.messages.extend(message.to_request());
2386        }
2387
2388        request.messages.push(LanguageModelRequestMessage {
2389            role: Role::User,
2390            content: vec![SUMMARIZE_THREAD_DETAILED_PROMPT.into()],
2391            cache: false,
2392            reasoning_details: None,
2393        });
2394
2395        let task = cx
2396            .spawn(async move |this, cx| {
2397                let mut summary = String::new();
2398                let mut messages = model.stream_completion(request, cx).await.log_err()?;
2399                while let Some(event) = messages.next().await {
2400                    let event = event.log_err()?;
2401                    let text = match event {
2402                        LanguageModelCompletionEvent::Text(text) => text,
2403                        _ => continue,
2404                    };
2405
2406                    let mut lines = text.lines();
2407                    summary.extend(lines.next());
2408                }
2409
2410                log::debug!("Setting summary: {}", summary);
2411                let summary = SharedString::from(summary);
2412
2413                this.update(cx, |this, cx| {
2414                    this.summary = Some(summary.clone());
2415                    this.pending_summary_generation = None;
2416                    cx.notify()
2417                })
2418                .ok()?;
2419
2420                Some(summary)
2421            })
2422            .shared();
2423        self.pending_summary_generation = Some(task.clone());
2424        task
2425    }
2426
2427    pub fn generate_title(&mut self, cx: &mut Context<Self>) {
2428        let Some(model) = self.summarization_model.clone() else {
2429            return;
2430        };
2431
2432        log::debug!(
2433            "Generating title with model: {:?}",
2434            self.summarization_model.as_ref().map(|model| model.name())
2435        );
2436        let mut request = LanguageModelRequest {
2437            intent: Some(CompletionIntent::ThreadSummarization),
2438            temperature: AgentSettings::temperature_for_model(&model, cx),
2439            ..Default::default()
2440        };
2441
2442        for message in &self.messages {
2443            request.messages.extend(message.to_request());
2444        }
2445
2446        request.messages.push(LanguageModelRequestMessage {
2447            role: Role::User,
2448            content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2449            cache: false,
2450            reasoning_details: None,
2451        });
2452        self.pending_title_generation = Some(cx.spawn(async move |this, cx| {
2453            let mut title = String::new();
2454
2455            let generate = async {
2456                let mut messages = model.stream_completion(request, cx).await?;
2457                while let Some(event) = messages.next().await {
2458                    let event = event?;
2459                    let text = match event {
2460                        LanguageModelCompletionEvent::Text(text) => text,
2461                        _ => continue,
2462                    };
2463
2464                    let mut lines = text.lines();
2465                    title.extend(lines.next());
2466
2467                    // Stop if the LLM generated multiple lines.
2468                    if lines.next().is_some() {
2469                        break;
2470                    }
2471                }
2472                anyhow::Ok(())
2473            };
2474
2475            if generate
2476                .await
2477                .context("failed to generate thread title")
2478                .log_err()
2479                .is_some()
2480            {
2481                _ = this.update(cx, |this, cx| this.set_title(title.into(), cx));
2482            }
2483            _ = this.update(cx, |this, _| this.pending_title_generation = None);
2484        }));
2485    }
2486
2487    pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
2488        self.pending_title_generation = None;
2489        if Some(&title) != self.title.as_ref() {
2490            self.title = Some(title);
2491            cx.emit(TitleUpdated);
2492            cx.notify();
2493        }
2494    }
2495
2496    fn clear_summary(&mut self) {
2497        self.summary = None;
2498        self.pending_summary_generation = None;
2499    }
2500
2501    fn last_user_message(&self) -> Option<&UserMessage> {
2502        self.messages
2503            .iter()
2504            .rev()
2505            .find_map(|message| match message {
2506                Message::User(user_message) => Some(user_message),
2507                Message::Agent(_) => None,
2508                Message::Resume => None,
2509            })
2510    }
2511
2512    fn pending_message(&mut self) -> &mut AgentMessage {
2513        self.pending_message.get_or_insert_default()
2514    }
2515
2516    fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
2517        let Some(mut message) = self.pending_message.take() else {
2518            return;
2519        };
2520
2521        if message.content.is_empty() {
2522            return;
2523        }
2524
2525        for content in &message.content {
2526            let AgentMessageContent::ToolUse(tool_use) = content else {
2527                continue;
2528            };
2529
2530            if !message.tool_results.contains_key(&tool_use.id) {
2531                message.tool_results.insert(
2532                    tool_use.id.clone(),
2533                    LanguageModelToolResult {
2534                        tool_use_id: tool_use.id.clone(),
2535                        tool_name: tool_use.name.clone(),
2536                        is_error: true,
2537                        content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
2538                        output: None,
2539                    },
2540                );
2541            }
2542        }
2543
2544        self.messages.push(Message::Agent(message));
2545        self.updated_at = Utc::now();
2546        self.clear_summary();
2547        cx.notify()
2548    }
2549
2550    pub(crate) fn build_completion_request(
2551        &self,
2552        completion_intent: CompletionIntent,
2553        cx: &App,
2554    ) -> Result<LanguageModelRequest> {
2555        let model = self.model().context("No language model configured")?;
2556        let tools = if let Some(turn) = self.running_turn.as_ref() {
2557            turn.tools
2558                .iter()
2559                .filter_map(|(tool_name, tool)| {
2560                    log::trace!("Including tool: {}", tool_name);
2561                    Some(LanguageModelRequestTool {
2562                        name: tool_name.to_string(),
2563                        description: tool.description().to_string(),
2564                        input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
2565                        use_input_streaming: tool.supports_input_streaming(),
2566                    })
2567                })
2568                .collect::<Vec<_>>()
2569        } else {
2570            Vec::new()
2571        };
2572
2573        log::debug!("Building completion request");
2574        log::debug!("Completion intent: {:?}", completion_intent);
2575
2576        let available_tools: Vec<_> = self
2577            .running_turn
2578            .as_ref()
2579            .map(|turn| turn.tools.keys().cloned().collect())
2580            .unwrap_or_default();
2581
2582        log::debug!("Request includes {} tools", available_tools.len());
2583        let messages = self.build_request_messages(available_tools, cx);
2584        log::debug!("Request will include {} messages", messages.len());
2585
2586        let request = LanguageModelRequest {
2587            thread_id: Some(self.id.to_string()),
2588            prompt_id: Some(self.prompt_id.to_string()),
2589            intent: Some(completion_intent),
2590            messages,
2591            tools,
2592            tool_choice: None,
2593            stop: Vec::new(),
2594            temperature: AgentSettings::temperature_for_model(model, cx),
2595            thinking_allowed: self.thinking_enabled,
2596            thinking_effort: self.thinking_effort.clone(),
2597            speed: self.speed(),
2598        };
2599
2600        log::debug!("Completion request built successfully");
2601        Ok(request)
2602    }
2603
2604    fn enabled_tools(
2605        &self,
2606        profile: &AgentProfileSettings,
2607        model: &Arc<dyn LanguageModel>,
2608        cx: &App,
2609    ) -> BTreeMap<SharedString, Arc<dyn AnyAgentTool>> {
2610        fn truncate(tool_name: &SharedString) -> SharedString {
2611            if tool_name.len() > MAX_TOOL_NAME_LENGTH {
2612                let mut truncated = tool_name.to_string();
2613                truncated.truncate(MAX_TOOL_NAME_LENGTH);
2614                truncated.into()
2615            } else {
2616                tool_name.clone()
2617            }
2618        }
2619
2620        let use_streaming_edit_tool =
2621            cx.has_flag::<StreamingEditFileToolFeatureFlag>() && model.supports_streaming_tools();
2622
2623        let mut tools = self
2624            .tools
2625            .iter()
2626            .filter_map(|(tool_name, tool)| {
2627                // For streaming_edit_file, check profile against "edit_file" since that's what users configure
2628                let profile_tool_name = if tool_name == StreamingEditFileTool::NAME {
2629                    EditFileTool::NAME
2630                } else {
2631                    tool_name.as_ref()
2632                };
2633
2634                if tool.supports_provider(&model.provider_id())
2635                    && profile.is_tool_enabled(profile_tool_name)
2636                {
2637                    match (tool_name.as_ref(), use_streaming_edit_tool) {
2638                        (StreamingEditFileTool::NAME, false) | (EditFileTool::NAME, true) => None,
2639                        (StreamingEditFileTool::NAME, true) => {
2640                            // Expose streaming tool as "edit_file"
2641                            Some((SharedString::from(EditFileTool::NAME), tool.clone()))
2642                        }
2643                        _ => Some((truncate(tool_name), tool.clone())),
2644                    }
2645                } else {
2646                    None
2647                }
2648            })
2649            .collect::<BTreeMap<_, _>>();
2650
2651        let mut context_server_tools = Vec::new();
2652        let mut seen_tools = tools.keys().cloned().collect::<HashSet<_>>();
2653        let mut duplicate_tool_names = HashSet::default();
2654        for (server_id, server_tools) in self.context_server_registry.read(cx).servers() {
2655            for (tool_name, tool) in server_tools {
2656                if profile.is_context_server_tool_enabled(&server_id.0, &tool_name) {
2657                    let tool_name = truncate(tool_name);
2658                    if !seen_tools.insert(tool_name.clone()) {
2659                        duplicate_tool_names.insert(tool_name.clone());
2660                    }
2661                    context_server_tools.push((server_id.clone(), tool_name, tool.clone()));
2662                }
2663            }
2664        }
2665
2666        // When there are duplicate tool names, disambiguate by prefixing them
2667        // with the server ID (converted to snake_case for API compatibility).
2668        // In the rare case there isn't enough space for the disambiguated tool
2669        // name, keep only the last tool with this name.
2670        for (server_id, tool_name, tool) in context_server_tools {
2671            if duplicate_tool_names.contains(&tool_name) {
2672                let available = MAX_TOOL_NAME_LENGTH.saturating_sub(tool_name.len());
2673                if available >= 2 {
2674                    let mut disambiguated = server_id.0.to_snake_case();
2675                    disambiguated.truncate(available - 1);
2676                    disambiguated.push('_');
2677                    disambiguated.push_str(&tool_name);
2678                    tools.insert(disambiguated.into(), tool.clone());
2679                } else {
2680                    tools.insert(tool_name, tool.clone());
2681                }
2682            } else {
2683                tools.insert(tool_name, tool.clone());
2684            }
2685        }
2686
2687        tools
2688    }
2689
2690    fn tool(&self, name: &str) -> Option<Arc<dyn AnyAgentTool>> {
2691        self.running_turn.as_ref()?.tools.get(name).cloned()
2692    }
2693
2694    pub fn has_tool(&self, name: &str) -> bool {
2695        self.running_turn
2696            .as_ref()
2697            .is_some_and(|turn| turn.tools.contains_key(name))
2698    }
2699
2700    #[cfg(any(test, feature = "test-support"))]
2701    pub fn has_registered_tool(&self, name: &str) -> bool {
2702        self.tools.contains_key(name)
2703    }
2704
2705    pub fn registered_tool_names(&self) -> Vec<SharedString> {
2706        self.tools.keys().cloned().collect()
2707    }
2708
2709    pub(crate) fn register_running_subagent(&mut self, subagent: WeakEntity<Thread>) {
2710        self.running_subagents.push(subagent);
2711    }
2712
2713    pub(crate) fn unregister_running_subagent(
2714        &mut self,
2715        subagent_session_id: &acp::SessionId,
2716        cx: &App,
2717    ) {
2718        self.running_subagents.retain(|s| {
2719            s.upgrade()
2720                .map_or(false, |s| s.read(cx).id() != subagent_session_id)
2721        });
2722    }
2723
2724    #[cfg(any(test, feature = "test-support"))]
2725    pub fn running_subagent_ids(&self, cx: &App) -> Vec<acp::SessionId> {
2726        self.running_subagents
2727            .iter()
2728            .filter_map(|s| s.upgrade().map(|s| s.read(cx).id().clone()))
2729            .collect()
2730    }
2731
2732    pub fn is_subagent(&self) -> bool {
2733        self.subagent_context.is_some()
2734    }
2735
2736    pub fn parent_thread_id(&self) -> Option<acp::SessionId> {
2737        self.subagent_context
2738            .as_ref()
2739            .map(|c| c.parent_thread_id.clone())
2740    }
2741
2742    pub fn depth(&self) -> u8 {
2743        self.subagent_context.as_ref().map(|c| c.depth).unwrap_or(0)
2744    }
2745
2746    #[cfg(any(test, feature = "test-support"))]
2747    pub fn set_subagent_context(&mut self, context: SubagentContext) {
2748        self.subagent_context = Some(context);
2749    }
2750
2751    pub fn is_turn_complete(&self) -> bool {
2752        self.running_turn.is_none()
2753    }
2754
2755    fn build_request_messages(
2756        &self,
2757        available_tools: Vec<SharedString>,
2758        cx: &App,
2759    ) -> Vec<LanguageModelRequestMessage> {
2760        log::trace!(
2761            "Building request messages from {} thread messages",
2762            self.messages.len()
2763        );
2764
2765        let system_prompt = SystemPromptTemplate {
2766            project: self.project_context.read(cx),
2767            available_tools,
2768            model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
2769        }
2770        .render(&self.templates)
2771        .context("failed to build system prompt")
2772        .expect("Invalid template");
2773        let mut messages = vec![LanguageModelRequestMessage {
2774            role: Role::System,
2775            content: vec![system_prompt.into()],
2776            cache: false,
2777            reasoning_details: None,
2778        }];
2779        for message in &self.messages {
2780            messages.extend(message.to_request());
2781        }
2782
2783        if let Some(last_message) = messages.last_mut() {
2784            last_message.cache = true;
2785        }
2786
2787        if let Some(message) = self.pending_message.as_ref() {
2788            messages.extend(message.to_request());
2789        }
2790
2791        messages
2792    }
2793
2794    pub fn to_markdown(&self) -> String {
2795        let mut markdown = String::new();
2796        for (ix, message) in self.messages.iter().enumerate() {
2797            if ix > 0 {
2798                markdown.push('\n');
2799            }
2800            match message {
2801                Message::User(_) => markdown.push_str("## User\n\n"),
2802                Message::Agent(_) => markdown.push_str("## Assistant\n\n"),
2803                Message::Resume => {}
2804            }
2805            markdown.push_str(&message.to_markdown());
2806        }
2807
2808        if let Some(message) = self.pending_message.as_ref() {
2809            markdown.push_str("\n## Assistant\n\n");
2810            markdown.push_str(&message.to_markdown());
2811        }
2812
2813        markdown
2814    }
2815
2816    fn advance_prompt_id(&mut self) {
2817        self.prompt_id = PromptId::new();
2818    }
2819
2820    fn retry_strategy_for(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
2821        use LanguageModelCompletionError::*;
2822        use http_client::StatusCode;
2823
2824        // General strategy here:
2825        // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
2826        // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), retry up to 4 times with exponential backoff.
2827        // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), retry up to 3 times.
2828        match error {
2829            HttpResponseError {
2830                status_code: StatusCode::TOO_MANY_REQUESTS,
2831                ..
2832            } => Some(RetryStrategy::ExponentialBackoff {
2833                initial_delay: BASE_RETRY_DELAY,
2834                max_attempts: MAX_RETRY_ATTEMPTS,
2835            }),
2836            ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
2837                Some(RetryStrategy::Fixed {
2838                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2839                    max_attempts: MAX_RETRY_ATTEMPTS,
2840                })
2841            }
2842            UpstreamProviderError {
2843                status,
2844                retry_after,
2845                ..
2846            } => match *status {
2847                StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
2848                    Some(RetryStrategy::Fixed {
2849                        delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2850                        max_attempts: MAX_RETRY_ATTEMPTS,
2851                    })
2852                }
2853                StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
2854                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2855                    // Internal Server Error could be anything, retry up to 3 times.
2856                    max_attempts: 3,
2857                }),
2858                status => {
2859                    // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
2860                    // but we frequently get them in practice. See https://http.dev/529
2861                    if status.as_u16() == 529 {
2862                        Some(RetryStrategy::Fixed {
2863                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2864                            max_attempts: MAX_RETRY_ATTEMPTS,
2865                        })
2866                    } else {
2867                        Some(RetryStrategy::Fixed {
2868                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2869                            max_attempts: 2,
2870                        })
2871                    }
2872                }
2873            },
2874            ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
2875                delay: BASE_RETRY_DELAY,
2876                max_attempts: 3,
2877            }),
2878            ApiReadResponseError { .. }
2879            | HttpSend { .. }
2880            | DeserializeResponse { .. }
2881            | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
2882                delay: BASE_RETRY_DELAY,
2883                max_attempts: 3,
2884            }),
2885            // Retrying these errors definitely shouldn't help.
2886            HttpResponseError {
2887                status_code:
2888                    StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
2889                ..
2890            }
2891            | AuthenticationError { .. }
2892            | PermissionError { .. }
2893            | NoApiKey { .. }
2894            | ApiEndpointNotFound { .. }
2895            | PromptTooLarge { .. } => None,
2896            // These errors might be transient, so retry them
2897            SerializeRequest { .. } | BuildRequestBody { .. } | StreamEndedUnexpectedly { .. } => {
2898                Some(RetryStrategy::Fixed {
2899                    delay: BASE_RETRY_DELAY,
2900                    max_attempts: 1,
2901                })
2902            }
2903            // Retry all other 4xx and 5xx errors once.
2904            HttpResponseError { status_code, .. }
2905                if status_code.is_client_error() || status_code.is_server_error() =>
2906            {
2907                Some(RetryStrategy::Fixed {
2908                    delay: BASE_RETRY_DELAY,
2909                    max_attempts: 3,
2910                })
2911            }
2912            Other(err) if err.is::<language_model::PaymentRequiredError>() => {
2913                // Retrying won't help for Payment Required errors.
2914                None
2915            }
2916            // Conservatively assume that any other errors are non-retryable
2917            HttpResponseError { .. } | Other(..) => Some(RetryStrategy::Fixed {
2918                delay: BASE_RETRY_DELAY,
2919                max_attempts: 2,
2920            }),
2921        }
2922    }
2923}
2924
2925struct RunningTurn {
2926    /// Holds the task that handles agent interaction until the end of the turn.
2927    /// Survives across multiple requests as the model performs tool calls and
2928    /// we run tools, report their results.
2929    _task: Task<()>,
2930    /// The current event stream for the running turn. Used to report a final
2931    /// cancellation event if we cancel the turn.
2932    event_stream: ThreadEventStream,
2933    /// The tools that were enabled for this turn.
2934    tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
2935    /// Sender to signal tool cancellation. When cancel is called, this is
2936    /// set to true so all tools can detect user-initiated cancellation.
2937    cancellation_tx: watch::Sender<bool>,
2938    /// Senders for tools that support input streaming and have already been
2939    /// started but are still receiving input from the LLM.
2940    streaming_tool_inputs: HashMap<LanguageModelToolUseId, ToolInputSender>,
2941}
2942
2943impl RunningTurn {
2944    fn cancel(mut self) -> Task<()> {
2945        log::debug!("Cancelling in progress turn");
2946        self.cancellation_tx.send(true).ok();
2947        self.event_stream.send_canceled();
2948        self._task
2949    }
2950}
2951
2952pub struct TokenUsageUpdated(pub Option<acp_thread::TokenUsage>);
2953
2954impl EventEmitter<TokenUsageUpdated> for Thread {}
2955
2956pub struct TitleUpdated;
2957
2958impl EventEmitter<TitleUpdated> for Thread {}
2959
2960/// A channel-based wrapper that delivers tool input to a running tool.
2961///
2962/// For non-streaming tools, created via `ToolInput::ready()` so `.recv()` resolves immediately.
2963/// For streaming tools, partial JSON snapshots arrive via `.recv_partial()` as the LLM streams
2964/// them, followed by the final complete input available through `.recv()`.
2965pub struct ToolInput<T> {
2966    partial_rx: mpsc::UnboundedReceiver<serde_json::Value>,
2967    final_rx: oneshot::Receiver<serde_json::Value>,
2968    _phantom: PhantomData<T>,
2969}
2970
2971impl<T: DeserializeOwned> ToolInput<T> {
2972    #[cfg(any(test, feature = "test-support"))]
2973    pub fn resolved(input: impl Serialize) -> Self {
2974        let value = serde_json::to_value(input).expect("failed to serialize tool input");
2975        Self::ready(value)
2976    }
2977
2978    pub fn ready(value: serde_json::Value) -> Self {
2979        let (partial_tx, partial_rx) = mpsc::unbounded();
2980        drop(partial_tx);
2981        let (final_tx, final_rx) = oneshot::channel();
2982        final_tx.send(value).ok();
2983        Self {
2984            partial_rx,
2985            final_rx,
2986            _phantom: PhantomData,
2987        }
2988    }
2989
2990    #[cfg(any(test, feature = "test-support"))]
2991    pub fn test() -> (ToolInputSender, Self) {
2992        let (sender, input) = ToolInputSender::channel();
2993        (sender, input.cast())
2994    }
2995
2996    /// Wait for the final deserialized input, ignoring all partial updates.
2997    /// Non-streaming tools can use this to wait until the whole input is available.
2998    pub async fn recv(mut self) -> Result<T> {
2999        // Drain any remaining partials
3000        while self.partial_rx.next().await.is_some() {}
3001        let value = self
3002            .final_rx
3003            .await
3004            .map_err(|_| anyhow!("tool input sender was dropped before sending final input"))?;
3005        serde_json::from_value(value).map_err(Into::into)
3006    }
3007
3008    /// Returns the next partial JSON snapshot, or `None` when input is complete.
3009    /// Once this returns `None`, call `recv()` to get the final input.
3010    pub async fn recv_partial(&mut self) -> Option<serde_json::Value> {
3011        self.partial_rx.next().await
3012    }
3013
3014    fn cast<U: DeserializeOwned>(self) -> ToolInput<U> {
3015        ToolInput {
3016            partial_rx: self.partial_rx,
3017            final_rx: self.final_rx,
3018            _phantom: PhantomData,
3019        }
3020    }
3021}
3022
3023pub struct ToolInputSender {
3024    partial_tx: mpsc::UnboundedSender<serde_json::Value>,
3025    final_tx: Option<oneshot::Sender<serde_json::Value>>,
3026}
3027
3028impl ToolInputSender {
3029    pub(crate) fn channel() -> (Self, ToolInput<serde_json::Value>) {
3030        let (partial_tx, partial_rx) = mpsc::unbounded();
3031        let (final_tx, final_rx) = oneshot::channel();
3032        let sender = Self {
3033            partial_tx,
3034            final_tx: Some(final_tx),
3035        };
3036        let input = ToolInput {
3037            partial_rx,
3038            final_rx,
3039            _phantom: PhantomData,
3040        };
3041        (sender, input)
3042    }
3043
3044    pub(crate) fn send_partial(&self, value: serde_json::Value) {
3045        self.partial_tx.unbounded_send(value).ok();
3046    }
3047
3048    pub(crate) fn send_final(mut self, value: serde_json::Value) {
3049        // Close the partial channel so recv_partial() returns None
3050        self.partial_tx.close_channel();
3051        if let Some(final_tx) = self.final_tx.take() {
3052            final_tx.send(value).ok();
3053        }
3054    }
3055}
3056
3057pub trait AgentTool
3058where
3059    Self: 'static + Sized,
3060{
3061    type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
3062    type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
3063
3064    const NAME: &'static str;
3065
3066    fn description() -> SharedString {
3067        let schema = schemars::schema_for!(Self::Input);
3068        SharedString::new(
3069            schema
3070                .get("description")
3071                .and_then(|description| description.as_str())
3072                .unwrap_or_default(),
3073        )
3074    }
3075
3076    fn kind() -> acp::ToolKind;
3077
3078    /// The initial tool title to display. Can be updated during the tool run.
3079    fn initial_title(
3080        &self,
3081        input: Result<Self::Input, serde_json::Value>,
3082        cx: &mut App,
3083    ) -> SharedString;
3084
3085    /// Returns the JSON schema that describes the tool's input.
3086    fn input_schema(format: LanguageModelToolSchemaFormat) -> Schema {
3087        language_model::tool_schema::root_schema_for::<Self::Input>(format)
3088    }
3089
3090    /// Returns whether the tool supports streaming of tool use parameters.
3091    fn supports_input_streaming() -> bool {
3092        false
3093    }
3094
3095    /// Some tools rely on a provider for the underlying billing or other reasons.
3096    /// Allow the tool to check if they are compatible, or should be filtered out.
3097    fn supports_provider(_provider: &LanguageModelProviderId) -> bool {
3098        true
3099    }
3100
3101    /// Runs the tool with the provided input.
3102    ///
3103    /// Returns `Result<Self::Output, Self::Output>` rather than `Result<Self::Output, anyhow::Error>`
3104    /// because tool errors are sent back to the model as tool results. This means error output must
3105    /// be structured and readable by the agent — not an arbitrary `anyhow::Error`. Returning the
3106    /// same `Output` type for both success and failure lets tools provide structured data while
3107    /// still signaling whether the invocation succeeded or failed.
3108    fn run(
3109        self: Arc<Self>,
3110        input: ToolInput<Self::Input>,
3111        event_stream: ToolCallEventStream,
3112        cx: &mut App,
3113    ) -> Task<Result<Self::Output, Self::Output>>;
3114
3115    /// Emits events for a previous execution of the tool.
3116    fn replay(
3117        &self,
3118        _input: Self::Input,
3119        _output: Self::Output,
3120        _event_stream: ToolCallEventStream,
3121        _cx: &mut App,
3122    ) -> Result<()> {
3123        Ok(())
3124    }
3125
3126    fn erase(self) -> Arc<dyn AnyAgentTool> {
3127        Arc::new(Erased(Arc::new(self)))
3128    }
3129}
3130
3131pub struct Erased<T>(T);
3132
3133pub struct AgentToolOutput {
3134    pub llm_output: LanguageModelToolResultContent,
3135    pub raw_output: serde_json::Value,
3136}
3137
3138impl AgentToolOutput {
3139    pub fn from_error(message: impl Into<String>) -> Self {
3140        let message = message.into();
3141        let llm_output = LanguageModelToolResultContent::Text(Arc::from(message.as_str()));
3142        Self {
3143            raw_output: serde_json::Value::String(message),
3144            llm_output,
3145        }
3146    }
3147}
3148
3149pub trait AnyAgentTool {
3150    fn name(&self) -> SharedString;
3151    fn description(&self) -> SharedString;
3152    fn kind(&self) -> acp::ToolKind;
3153    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString;
3154    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
3155    fn supports_input_streaming(&self) -> bool {
3156        false
3157    }
3158    fn supports_provider(&self, _provider: &LanguageModelProviderId) -> bool {
3159        true
3160    }
3161    /// See [`AgentTool::run`] for why this returns `Result<AgentToolOutput, AgentToolOutput>`.
3162    fn run(
3163        self: Arc<Self>,
3164        input: ToolInput<serde_json::Value>,
3165        event_stream: ToolCallEventStream,
3166        cx: &mut App,
3167    ) -> Task<Result<AgentToolOutput, AgentToolOutput>>;
3168    fn replay(
3169        &self,
3170        input: serde_json::Value,
3171        output: serde_json::Value,
3172        event_stream: ToolCallEventStream,
3173        cx: &mut App,
3174    ) -> Result<()>;
3175}
3176
3177impl<T> AnyAgentTool for Erased<Arc<T>>
3178where
3179    T: AgentTool,
3180{
3181    fn name(&self) -> SharedString {
3182        T::NAME.into()
3183    }
3184
3185    fn description(&self) -> SharedString {
3186        T::description()
3187    }
3188
3189    fn kind(&self) -> agent_client_protocol::ToolKind {
3190        T::kind()
3191    }
3192
3193    fn supports_input_streaming(&self) -> bool {
3194        T::supports_input_streaming()
3195    }
3196
3197    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString {
3198        let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
3199        self.0.initial_title(parsed_input, _cx)
3200    }
3201
3202    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
3203        let mut json = serde_json::to_value(T::input_schema(format))?;
3204        language_model::tool_schema::adapt_schema_to_format(&mut json, format)?;
3205        Ok(json)
3206    }
3207
3208    fn supports_provider(&self, provider: &LanguageModelProviderId) -> bool {
3209        T::supports_provider(provider)
3210    }
3211
3212    fn run(
3213        self: Arc<Self>,
3214        input: ToolInput<serde_json::Value>,
3215        event_stream: ToolCallEventStream,
3216        cx: &mut App,
3217    ) -> Task<Result<AgentToolOutput, AgentToolOutput>> {
3218        let tool_input: ToolInput<T::Input> = input.cast();
3219        let task = self.0.clone().run(tool_input, event_stream, cx);
3220        cx.spawn(async move |_cx| match task.await {
3221            Ok(output) => {
3222                let raw_output = serde_json::to_value(&output).map_err(|e| {
3223                    AgentToolOutput::from_error(format!("Failed to serialize tool output: {e}"))
3224                })?;
3225                Ok(AgentToolOutput {
3226                    llm_output: output.into(),
3227                    raw_output,
3228                })
3229            }
3230            Err(error_output) => {
3231                let raw_output = serde_json::to_value(&error_output).unwrap_or_else(|e| {
3232                    log::error!("Failed to serialize tool error output: {e}");
3233                    serde_json::Value::Null
3234                });
3235                Err(AgentToolOutput {
3236                    llm_output: error_output.into(),
3237                    raw_output,
3238                })
3239            }
3240        })
3241    }
3242
3243    fn replay(
3244        &self,
3245        input: serde_json::Value,
3246        output: serde_json::Value,
3247        event_stream: ToolCallEventStream,
3248        cx: &mut App,
3249    ) -> Result<()> {
3250        let input = serde_json::from_value(input)?;
3251        let output = serde_json::from_value(output)?;
3252        self.0.replay(input, output, event_stream, cx)
3253    }
3254}
3255
3256#[derive(Clone)]
3257struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
3258
3259impl ThreadEventStream {
3260    fn send_user_message(&self, message: &UserMessage) {
3261        self.0
3262            .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
3263            .ok();
3264    }
3265
3266    fn send_text(&self, text: &str) {
3267        self.0
3268            .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
3269            .ok();
3270    }
3271
3272    fn send_thinking(&self, text: &str) {
3273        self.0
3274            .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
3275            .ok();
3276    }
3277
3278    fn send_tool_call(
3279        &self,
3280        id: &LanguageModelToolUseId,
3281        tool_name: &str,
3282        title: SharedString,
3283        kind: acp::ToolKind,
3284        input: serde_json::Value,
3285    ) {
3286        self.0
3287            .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
3288                id,
3289                tool_name,
3290                title.to_string(),
3291                kind,
3292                input,
3293            ))))
3294            .ok();
3295    }
3296
3297    fn initial_tool_call(
3298        id: &LanguageModelToolUseId,
3299        tool_name: &str,
3300        title: String,
3301        kind: acp::ToolKind,
3302        input: serde_json::Value,
3303    ) -> acp::ToolCall {
3304        acp::ToolCall::new(id.to_string(), title)
3305            .kind(kind)
3306            .raw_input(input)
3307            .meta(acp_thread::meta_with_tool_name(tool_name))
3308    }
3309
3310    fn update_tool_call_fields(
3311        &self,
3312        tool_use_id: &LanguageModelToolUseId,
3313        fields: acp::ToolCallUpdateFields,
3314        meta: Option<acp::Meta>,
3315    ) {
3316        self.0
3317            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3318                acp::ToolCallUpdate::new(tool_use_id.to_string(), fields)
3319                    .meta(meta)
3320                    .into(),
3321            )))
3322            .ok();
3323    }
3324
3325    fn send_retry(&self, status: acp_thread::RetryStatus) {
3326        self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();
3327    }
3328
3329    fn send_stop(&self, reason: acp::StopReason) {
3330        self.0.unbounded_send(Ok(ThreadEvent::Stop(reason))).ok();
3331    }
3332
3333    fn send_canceled(&self) {
3334        self.0
3335            .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
3336            .ok();
3337    }
3338
3339    fn send_error(&self, error: impl Into<anyhow::Error>) {
3340        self.0.unbounded_send(Err(error.into())).ok();
3341    }
3342}
3343
3344#[derive(Clone)]
3345pub struct ToolCallEventStream {
3346    tool_use_id: LanguageModelToolUseId,
3347    stream: ThreadEventStream,
3348    fs: Option<Arc<dyn Fs>>,
3349    cancellation_rx: watch::Receiver<bool>,
3350}
3351
3352impl ToolCallEventStream {
3353    #[cfg(any(test, feature = "test-support"))]
3354    pub fn test() -> (Self, ToolCallEventStreamReceiver) {
3355        let (stream, receiver, _cancellation_tx) = Self::test_with_cancellation();
3356        (stream, receiver)
3357    }
3358
3359    #[cfg(any(test, feature = "test-support"))]
3360    pub fn test_with_cancellation() -> (Self, ToolCallEventStreamReceiver, watch::Sender<bool>) {
3361        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
3362        let (cancellation_tx, cancellation_rx) = watch::channel(false);
3363
3364        let stream = ToolCallEventStream::new(
3365            "test_id".into(),
3366            ThreadEventStream(events_tx),
3367            None,
3368            cancellation_rx,
3369        );
3370
3371        (
3372            stream,
3373            ToolCallEventStreamReceiver(events_rx),
3374            cancellation_tx,
3375        )
3376    }
3377
3378    /// Signal cancellation for this event stream. Only available in tests.
3379    #[cfg(any(test, feature = "test-support"))]
3380    pub fn signal_cancellation_with_sender(cancellation_tx: &mut watch::Sender<bool>) {
3381        cancellation_tx.send(true).ok();
3382    }
3383
3384    fn new(
3385        tool_use_id: LanguageModelToolUseId,
3386        stream: ThreadEventStream,
3387        fs: Option<Arc<dyn Fs>>,
3388        cancellation_rx: watch::Receiver<bool>,
3389    ) -> Self {
3390        Self {
3391            tool_use_id,
3392            stream,
3393            fs,
3394            cancellation_rx,
3395        }
3396    }
3397
3398    /// Returns a future that resolves when the user cancels the tool call.
3399    /// Tools should select on this alongside their main work to detect user cancellation.
3400    pub fn cancelled_by_user(&self) -> impl std::future::Future<Output = ()> + '_ {
3401        let mut rx = self.cancellation_rx.clone();
3402        async move {
3403            loop {
3404                if *rx.borrow() {
3405                    return;
3406                }
3407                if rx.changed().await.is_err() {
3408                    // Sender dropped, will never be cancelled
3409                    std::future::pending::<()>().await;
3410                }
3411            }
3412        }
3413    }
3414
3415    /// Returns true if the user has cancelled this tool call.
3416    /// This is useful for checking cancellation state after an operation completes,
3417    /// to determine if the completion was due to user cancellation.
3418    pub fn was_cancelled_by_user(&self) -> bool {
3419        *self.cancellation_rx.clone().borrow()
3420    }
3421
3422    pub fn tool_use_id(&self) -> &LanguageModelToolUseId {
3423        &self.tool_use_id
3424    }
3425
3426    pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
3427        self.stream
3428            .update_tool_call_fields(&self.tool_use_id, fields, None);
3429    }
3430
3431    pub fn update_fields_with_meta(
3432        &self,
3433        fields: acp::ToolCallUpdateFields,
3434        meta: Option<acp::Meta>,
3435    ) {
3436        self.stream
3437            .update_tool_call_fields(&self.tool_use_id, fields, meta);
3438    }
3439
3440    pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
3441        self.stream
3442            .0
3443            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3444                acp_thread::ToolCallUpdateDiff {
3445                    id: acp::ToolCallId::new(self.tool_use_id.to_string()),
3446                    diff,
3447                }
3448                .into(),
3449            )))
3450            .ok();
3451    }
3452
3453    pub fn subagent_spawned(&self, id: acp::SessionId) {
3454        self.stream
3455            .0
3456            .unbounded_send(Ok(ThreadEvent::SubagentSpawned(id)))
3457            .ok();
3458    }
3459
3460    /// Authorize a third-party tool (e.g., MCP tool from a context server).
3461    ///
3462    /// Unlike built-in tools, third-party tools don't support pattern-based permissions.
3463    /// They only support `default` (allow/deny/confirm) per tool.
3464    ///
3465    /// Uses the dropdown authorization flow with two granularities:
3466    /// - "Always for <display_name> MCP tool" → sets `tools.<tool_id>.default = "allow"` or "deny"
3467    /// - "Only this time" → allow/deny once
3468    pub fn authorize_third_party_tool(
3469        &self,
3470        title: impl Into<String>,
3471        tool_id: String,
3472        display_name: String,
3473        cx: &mut App,
3474    ) -> Task<Result<()>> {
3475        let settings = agent_settings::AgentSettings::get_global(cx);
3476
3477        let decision = decide_permission_from_settings(&tool_id, &[String::new()], &settings);
3478
3479        match decision {
3480            ToolPermissionDecision::Allow => return Task::ready(Ok(())),
3481            ToolPermissionDecision::Deny(reason) => return Task::ready(Err(anyhow!(reason))),
3482            ToolPermissionDecision::Confirm => {}
3483        }
3484
3485        let (response_tx, response_rx) = oneshot::channel();
3486        if let Err(error) = self
3487            .stream
3488            .0
3489            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3490                ToolCallAuthorization {
3491                    tool_call: acp::ToolCallUpdate::new(
3492                        self.tool_use_id.to_string(),
3493                        acp::ToolCallUpdateFields::new().title(title.into()),
3494                    ),
3495                    options: acp_thread::PermissionOptions::Dropdown(vec![
3496                        acp_thread::PermissionOptionChoice {
3497                            allow: acp::PermissionOption::new(
3498                                acp::PermissionOptionId::new(format!(
3499                                    "always_allow_mcp:{}",
3500                                    tool_id
3501                                )),
3502                                format!("Always for {} MCP tool", display_name),
3503                                acp::PermissionOptionKind::AllowAlways,
3504                            ),
3505                            deny: acp::PermissionOption::new(
3506                                acp::PermissionOptionId::new(format!(
3507                                    "always_deny_mcp:{}",
3508                                    tool_id
3509                                )),
3510                                format!("Always for {} MCP tool", display_name),
3511                                acp::PermissionOptionKind::RejectAlways,
3512                            ),
3513                        },
3514                        acp_thread::PermissionOptionChoice {
3515                            allow: acp::PermissionOption::new(
3516                                acp::PermissionOptionId::new("allow"),
3517                                "Only this time",
3518                                acp::PermissionOptionKind::AllowOnce,
3519                            ),
3520                            deny: acp::PermissionOption::new(
3521                                acp::PermissionOptionId::new("deny"),
3522                                "Only this time",
3523                                acp::PermissionOptionKind::RejectOnce,
3524                            ),
3525                        },
3526                    ]),
3527                    response: response_tx,
3528                    context: None,
3529                },
3530            )))
3531        {
3532            log::error!("Failed to send tool call authorization: {error}");
3533            return Task::ready(Err(anyhow!(
3534                "Failed to send tool call authorization: {error}"
3535            )));
3536        }
3537
3538        let fs = self.fs.clone();
3539        cx.spawn(async move |cx| {
3540            let response_str = response_rx.await?.0.to_string();
3541
3542            if response_str == format!("always_allow_mcp:{}", tool_id) {
3543                if let Some(fs) = fs.clone() {
3544                    cx.update(|cx| {
3545                        update_settings_file(fs, cx, move |settings, _| {
3546                            settings
3547                                .agent
3548                                .get_or_insert_default()
3549                                .set_tool_default_permission(&tool_id, ToolPermissionMode::Allow);
3550                        });
3551                    });
3552                }
3553                return Ok(());
3554            }
3555            if response_str == format!("always_deny_mcp:{}", tool_id) {
3556                if let Some(fs) = fs.clone() {
3557                    cx.update(|cx| {
3558                        update_settings_file(fs, cx, move |settings, _| {
3559                            settings
3560                                .agent
3561                                .get_or_insert_default()
3562                                .set_tool_default_permission(&tool_id, ToolPermissionMode::Deny);
3563                        });
3564                    });
3565                }
3566                return Err(anyhow!("Permission to run tool denied by user"));
3567            }
3568
3569            if response_str == "allow" {
3570                return Ok(());
3571            }
3572
3573            Err(anyhow!("Permission to run tool denied by user"))
3574        })
3575    }
3576
3577    pub fn authorize(
3578        &self,
3579        title: impl Into<String>,
3580        context: ToolPermissionContext,
3581        cx: &mut App,
3582    ) -> Task<Result<()>> {
3583        use settings::ToolPermissionMode;
3584
3585        let options = context.build_permission_options();
3586
3587        let (response_tx, response_rx) = oneshot::channel();
3588        if let Err(error) = self
3589            .stream
3590            .0
3591            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3592                ToolCallAuthorization {
3593                    tool_call: acp::ToolCallUpdate::new(
3594                        self.tool_use_id.to_string(),
3595                        acp::ToolCallUpdateFields::new().title(title.into()),
3596                    ),
3597                    options,
3598                    response: response_tx,
3599                    context: Some(context),
3600                },
3601            )))
3602        {
3603            log::error!("Failed to send tool call authorization: {error}");
3604            return Task::ready(Err(anyhow!(
3605                "Failed to send tool call authorization: {error}"
3606            )));
3607        }
3608
3609        let fs = self.fs.clone();
3610        cx.spawn(async move |cx| {
3611            let response_str = response_rx.await?.0.to_string();
3612
3613            // Handle "always allow tool" - e.g., "always_allow:terminal"
3614            if let Some(tool) = response_str.strip_prefix("always_allow:") {
3615                if let Some(fs) = fs.clone() {
3616                    let tool = tool.to_string();
3617                    cx.update(|cx| {
3618                        update_settings_file(fs, cx, move |settings, _| {
3619                            settings
3620                                .agent
3621                                .get_or_insert_default()
3622                                .set_tool_default_permission(&tool, ToolPermissionMode::Allow);
3623                        });
3624                    });
3625                }
3626                return Ok(());
3627            }
3628
3629            // Handle "always deny tool" - e.g., "always_deny:terminal"
3630            if let Some(tool) = response_str.strip_prefix("always_deny:") {
3631                if let Some(fs) = fs.clone() {
3632                    let tool = tool.to_string();
3633                    cx.update(|cx| {
3634                        update_settings_file(fs, cx, move |settings, _| {
3635                            settings
3636                                .agent
3637                                .get_or_insert_default()
3638                                .set_tool_default_permission(&tool, ToolPermissionMode::Deny);
3639                        });
3640                    });
3641                }
3642                return Err(anyhow!("Permission to run tool denied by user"));
3643            }
3644
3645            // Handle "always allow pattern" - e.g., "always_allow_pattern:mcp:server:tool\n^cargo\s"
3646            if let Some(rest) = response_str.strip_prefix("always_allow_pattern:") {
3647                if let Some((pattern_tool_name, pattern)) = rest.split_once('\n') {
3648                    let pattern_tool_name = pattern_tool_name.to_string();
3649                    let pattern = pattern.to_string();
3650                    if let Some(fs) = fs.clone() {
3651                        cx.update(|cx| {
3652                            update_settings_file(fs, cx, move |settings, _| {
3653                                settings
3654                                    .agent
3655                                    .get_or_insert_default()
3656                                    .add_tool_allow_pattern(&pattern_tool_name, pattern);
3657                            });
3658                        });
3659                    }
3660                } else {
3661                    log::error!("Failed to parse always allow pattern: missing newline separator in '{rest}'");
3662                }
3663                return Ok(());
3664            }
3665
3666            // Handle "always deny pattern" - e.g., "always_deny_pattern:mcp:server:tool\n^cargo\s"
3667            if let Some(rest) = response_str.strip_prefix("always_deny_pattern:") {
3668                if let Some((pattern_tool_name, pattern)) = rest.split_once('\n') {
3669                    let pattern_tool_name = pattern_tool_name.to_string();
3670                    let pattern = pattern.to_string();
3671                    if let Some(fs) = fs.clone() {
3672                        cx.update(|cx| {
3673                            update_settings_file(fs, cx, move |settings, _| {
3674                                settings
3675                                    .agent
3676                                    .get_or_insert_default()
3677                                    .add_tool_deny_pattern(&pattern_tool_name, pattern);
3678                            });
3679                        });
3680                    }
3681                } else {
3682                    log::error!("Failed to parse always deny pattern: missing newline separator in '{rest}'");
3683                }
3684                return Err(anyhow!("Permission to run tool denied by user"));
3685            }
3686
3687            // Handle simple "allow" (allow once)
3688            if response_str == "allow" {
3689                return Ok(());
3690            }
3691
3692            // Handle simple "deny" (deny once)
3693            Err(anyhow!("Permission to run tool denied by user"))
3694        })
3695    }
3696}
3697
3698#[cfg(any(test, feature = "test-support"))]
3699pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
3700
3701#[cfg(any(test, feature = "test-support"))]
3702impl ToolCallEventStreamReceiver {
3703    pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
3704        let event = self.0.next().await;
3705        if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
3706            auth
3707        } else {
3708            panic!("Expected ToolCallAuthorization but got: {:?}", event);
3709        }
3710    }
3711
3712    pub async fn expect_update_fields(&mut self) -> acp::ToolCallUpdateFields {
3713        let event = self.0.next().await;
3714        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
3715            update,
3716        )))) = event
3717        {
3718            update.fields
3719        } else {
3720            panic!("Expected update fields but got: {:?}", event);
3721        }
3722    }
3723
3724    pub async fn expect_diff(&mut self) -> Entity<acp_thread::Diff> {
3725        let event = self.0.next().await;
3726        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateDiff(
3727            update,
3728        )))) = event
3729        {
3730            update.diff
3731        } else {
3732            panic!("Expected diff but got: {:?}", event);
3733        }
3734    }
3735
3736    pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
3737        let event = self.0.next().await;
3738        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
3739            update,
3740        )))) = event
3741        {
3742            update.terminal
3743        } else {
3744            panic!("Expected terminal but got: {:?}", event);
3745        }
3746    }
3747}
3748
3749#[cfg(any(test, feature = "test-support"))]
3750impl std::ops::Deref for ToolCallEventStreamReceiver {
3751    type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
3752
3753    fn deref(&self) -> &Self::Target {
3754        &self.0
3755    }
3756}
3757
3758#[cfg(any(test, feature = "test-support"))]
3759impl std::ops::DerefMut for ToolCallEventStreamReceiver {
3760    fn deref_mut(&mut self) -> &mut Self::Target {
3761        &mut self.0
3762    }
3763}
3764
3765impl From<&str> for UserMessageContent {
3766    fn from(text: &str) -> Self {
3767        Self::Text(text.into())
3768    }
3769}
3770
3771impl From<String> for UserMessageContent {
3772    fn from(text: String) -> Self {
3773        Self::Text(text)
3774    }
3775}
3776
3777impl UserMessageContent {
3778    pub fn from_content_block(value: acp::ContentBlock, path_style: PathStyle) -> Self {
3779        match value {
3780            acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
3781            acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
3782            acp::ContentBlock::Audio(_) => {
3783                // TODO
3784                Self::Text("[audio]".to_string())
3785            }
3786            acp::ContentBlock::ResourceLink(resource_link) => {
3787                match MentionUri::parse(&resource_link.uri, path_style) {
3788                    Ok(uri) => Self::Mention {
3789                        uri,
3790                        content: String::new(),
3791                    },
3792                    Err(err) => {
3793                        log::error!("Failed to parse mention link: {}", err);
3794                        Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
3795                    }
3796                }
3797            }
3798            acp::ContentBlock::Resource(resource) => match resource.resource {
3799                acp::EmbeddedResourceResource::TextResourceContents(resource) => {
3800                    match MentionUri::parse(&resource.uri, path_style) {
3801                        Ok(uri) => Self::Mention {
3802                            uri,
3803                            content: resource.text,
3804                        },
3805                        Err(err) => {
3806                            log::error!("Failed to parse mention link: {}", err);
3807                            Self::Text(
3808                                MarkdownCodeBlock {
3809                                    tag: &resource.uri,
3810                                    text: &resource.text,
3811                                }
3812                                .to_string(),
3813                            )
3814                        }
3815                    }
3816                }
3817                acp::EmbeddedResourceResource::BlobResourceContents(_) => {
3818                    // TODO
3819                    Self::Text("[blob]".to_string())
3820                }
3821                other => {
3822                    log::warn!("Unexpected content type: {:?}", other);
3823                    Self::Text("[unknown]".to_string())
3824                }
3825            },
3826            other => {
3827                log::warn!("Unexpected content type: {:?}", other);
3828                Self::Text("[unknown]".to_string())
3829            }
3830        }
3831    }
3832}
3833
3834impl From<UserMessageContent> for acp::ContentBlock {
3835    fn from(content: UserMessageContent) -> Self {
3836        match content {
3837            UserMessageContent::Text(text) => text.into(),
3838            UserMessageContent::Image(image) => {
3839                acp::ContentBlock::Image(acp::ImageContent::new(image.source, "image/png"))
3840            }
3841            UserMessageContent::Mention { uri, content } => acp::ContentBlock::Resource(
3842                acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(
3843                    acp::TextResourceContents::new(content, uri.to_uri().to_string()),
3844                )),
3845            ),
3846        }
3847    }
3848}
3849
3850fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
3851    LanguageModelImage {
3852        source: image_content.data.into(),
3853        size: None,
3854    }
3855}
3856
3857#[cfg(test)]
3858mod tests {
3859    use super::*;
3860    use gpui::TestAppContext;
3861    use language_model::LanguageModelToolUseId;
3862    use language_model::fake_provider::FakeLanguageModel;
3863    use serde_json::json;
3864    use std::sync::Arc;
3865
3866    async fn setup_thread_for_test(cx: &mut TestAppContext) -> (Entity<Thread>, ThreadEventStream) {
3867        cx.update(|cx| {
3868            let settings_store = settings::SettingsStore::test(cx);
3869            cx.set_global(settings_store);
3870        });
3871
3872        let fs = fs::FakeFs::new(cx.background_executor.clone());
3873        let templates = Templates::new();
3874        let project = Project::test(fs.clone(), [], cx).await;
3875
3876        cx.update(|cx| {
3877            let project_context = cx.new(|_cx| prompt_store::ProjectContext::default());
3878            let context_server_store = project.read(cx).context_server_store();
3879            let context_server_registry =
3880                cx.new(|cx| ContextServerRegistry::new(context_server_store, cx));
3881
3882            let thread = cx.new(|cx| {
3883                Thread::new(
3884                    project,
3885                    project_context,
3886                    context_server_registry,
3887                    templates,
3888                    None,
3889                    cx,
3890                )
3891            });
3892
3893            let (event_tx, _event_rx) = mpsc::unbounded();
3894            let event_stream = ThreadEventStream(event_tx);
3895
3896            (thread, event_stream)
3897        })
3898    }
3899
3900    fn setup_parent_with_subagents(
3901        cx: &mut TestAppContext,
3902        parent: &Entity<Thread>,
3903        count: usize,
3904    ) -> Vec<Entity<Thread>> {
3905        cx.update(|cx| {
3906            let mut subagents = Vec::new();
3907            for _ in 0..count {
3908                let subagent = cx.new(|cx| Thread::new_subagent(parent, cx));
3909                parent.update(cx, |thread, _cx| {
3910                    thread.register_running_subagent(subagent.downgrade());
3911                });
3912                subagents.push(subagent);
3913            }
3914            subagents
3915        })
3916    }
3917
3918    #[gpui::test]
3919    async fn test_set_model_propagates_to_subagents(cx: &mut TestAppContext) {
3920        let (parent, _event_stream) = setup_thread_for_test(cx).await;
3921        let subagents = setup_parent_with_subagents(cx, &parent, 2);
3922
3923        let new_model: Arc<dyn LanguageModel> = Arc::new(FakeLanguageModel::with_id_and_thinking(
3924            "test-provider",
3925            "new-model",
3926            "New Model",
3927            false,
3928        ));
3929
3930        cx.update(|cx| {
3931            parent.update(cx, |thread, cx| {
3932                thread.set_model(new_model, cx);
3933            });
3934
3935            for subagent in &subagents {
3936                let subagent_model_id = subagent.read(cx).model().unwrap().id();
3937                assert_eq!(
3938                    subagent_model_id.0.as_ref(),
3939                    "new-model",
3940                    "Subagent model should match parent model after set_model"
3941                );
3942            }
3943        });
3944    }
3945
3946    #[gpui::test]
3947    async fn test_set_summarization_model_propagates_to_subagents(cx: &mut TestAppContext) {
3948        let (parent, _event_stream) = setup_thread_for_test(cx).await;
3949        let subagents = setup_parent_with_subagents(cx, &parent, 2);
3950
3951        let summary_model: Arc<dyn LanguageModel> =
3952            Arc::new(FakeLanguageModel::with_id_and_thinking(
3953                "test-provider",
3954                "summary-model",
3955                "Summary Model",
3956                false,
3957            ));
3958
3959        cx.update(|cx| {
3960            parent.update(cx, |thread, cx| {
3961                thread.set_summarization_model(Some(summary_model), cx);
3962            });
3963
3964            for subagent in &subagents {
3965                let subagent_summary_id = subagent.read(cx).summarization_model().unwrap().id();
3966                assert_eq!(
3967                    subagent_summary_id.0.as_ref(),
3968                    "summary-model",
3969                    "Subagent summarization model should match parent after set_summarization_model"
3970                );
3971            }
3972        });
3973    }
3974
3975    #[gpui::test]
3976    async fn test_set_thinking_enabled_propagates_to_subagents(cx: &mut TestAppContext) {
3977        let (parent, _event_stream) = setup_thread_for_test(cx).await;
3978        let subagents = setup_parent_with_subagents(cx, &parent, 2);
3979
3980        cx.update(|cx| {
3981            parent.update(cx, |thread, cx| {
3982                thread.set_thinking_enabled(true, cx);
3983            });
3984
3985            for subagent in &subagents {
3986                assert!(
3987                    subagent.read(cx).thinking_enabled(),
3988                    "Subagent thinking should be enabled after parent enables it"
3989                );
3990            }
3991
3992            parent.update(cx, |thread, cx| {
3993                thread.set_thinking_enabled(false, cx);
3994            });
3995
3996            for subagent in &subagents {
3997                assert!(
3998                    !subagent.read(cx).thinking_enabled(),
3999                    "Subagent thinking should be disabled after parent disables it"
4000                );
4001            }
4002        });
4003    }
4004
4005    #[gpui::test]
4006    async fn test_set_thinking_effort_propagates_to_subagents(cx: &mut TestAppContext) {
4007        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4008        let subagents = setup_parent_with_subagents(cx, &parent, 2);
4009
4010        cx.update(|cx| {
4011            parent.update(cx, |thread, cx| {
4012                thread.set_thinking_effort(Some("high".to_string()), cx);
4013            });
4014
4015            for subagent in &subagents {
4016                assert_eq!(
4017                    subagent.read(cx).thinking_effort().map(|s| s.as_str()),
4018                    Some("high"),
4019                    "Subagent thinking effort should match parent"
4020                );
4021            }
4022
4023            parent.update(cx, |thread, cx| {
4024                thread.set_thinking_effort(None, cx);
4025            });
4026
4027            for subagent in &subagents {
4028                assert_eq!(
4029                    subagent.read(cx).thinking_effort(),
4030                    None,
4031                    "Subagent thinking effort should be None after parent clears it"
4032                );
4033            }
4034        });
4035    }
4036
4037    #[gpui::test]
4038    async fn test_set_speed_propagates_to_subagents(cx: &mut TestAppContext) {
4039        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4040        let subagents = setup_parent_with_subagents(cx, &parent, 2);
4041
4042        cx.update(|cx| {
4043            parent.update(cx, |thread, cx| {
4044                thread.set_speed(Speed::Fast, cx);
4045            });
4046
4047            for subagent in &subagents {
4048                assert_eq!(
4049                    subagent.read(cx).speed(),
4050                    Some(Speed::Fast),
4051                    "Subagent speed should match parent after set_speed"
4052                );
4053            }
4054        });
4055    }
4056
4057    #[gpui::test]
4058    async fn test_dropped_subagent_does_not_panic(cx: &mut TestAppContext) {
4059        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4060        let subagents = setup_parent_with_subagents(cx, &parent, 1);
4061
4062        // Drop the subagent so the WeakEntity can no longer be upgraded
4063        drop(subagents);
4064
4065        // Should not panic even though the subagent was dropped
4066        cx.update(|cx| {
4067            parent.update(cx, |thread, cx| {
4068                thread.set_thinking_enabled(true, cx);
4069                thread.set_speed(Speed::Fast, cx);
4070                thread.set_thinking_effort(Some("high".to_string()), cx);
4071            });
4072        });
4073    }
4074
4075    #[gpui::test]
4076    async fn test_handle_tool_use_json_parse_error_adds_tool_use_to_content(
4077        cx: &mut TestAppContext,
4078    ) {
4079        let (thread, event_stream) = setup_thread_for_test(cx).await;
4080
4081        cx.update(|cx| {
4082            thread.update(cx, |thread, _cx| {
4083                let tool_use_id = LanguageModelToolUseId::from("test_tool_id");
4084                let tool_name: Arc<str> = Arc::from("test_tool");
4085                let raw_input: Arc<str> = Arc::from("{invalid json");
4086                let json_parse_error = "expected value at line 1 column 1".to_string();
4087
4088                // Call the function under test
4089                let result = thread.handle_tool_use_json_parse_error_event(
4090                    tool_use_id.clone(),
4091                    tool_name.clone(),
4092                    raw_input.clone(),
4093                    json_parse_error,
4094                    &event_stream,
4095                );
4096
4097                // Verify the result is an error
4098                assert!(result.is_error);
4099                assert_eq!(result.tool_use_id, tool_use_id);
4100                assert_eq!(result.tool_name, tool_name);
4101                assert!(matches!(
4102                    result.content,
4103                    LanguageModelToolResultContent::Text(_)
4104                ));
4105
4106                // Verify the tool use was added to the message content
4107                {
4108                    let last_message = thread.pending_message();
4109                    assert_eq!(
4110                        last_message.content.len(),
4111                        1,
4112                        "Should have one tool_use in content"
4113                    );
4114
4115                    match &last_message.content[0] {
4116                        AgentMessageContent::ToolUse(tool_use) => {
4117                            assert_eq!(tool_use.id, tool_use_id);
4118                            assert_eq!(tool_use.name, tool_name);
4119                            assert_eq!(tool_use.raw_input, raw_input.to_string());
4120                            assert!(tool_use.is_input_complete);
4121                            // Should fall back to empty object for invalid JSON
4122                            assert_eq!(tool_use.input, json!({}));
4123                        }
4124                        _ => panic!("Expected ToolUse content"),
4125                    }
4126                }
4127
4128                // Insert the tool result (simulating what the caller does)
4129                thread
4130                    .pending_message()
4131                    .tool_results
4132                    .insert(result.tool_use_id.clone(), result);
4133
4134                // Verify the tool result was added
4135                let last_message = thread.pending_message();
4136                assert_eq!(
4137                    last_message.tool_results.len(),
4138                    1,
4139                    "Should have one tool_result"
4140                );
4141                assert!(last_message.tool_results.contains_key(&tool_use_id));
4142            });
4143        });
4144    }
4145}