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    /// True if this thread was imported from a shared thread and can be synced.
 897    imported: bool,
 898    /// If this is a subagent thread, contains context about the parent
 899    subagent_context: Option<SubagentContext>,
 900    /// The user's unsent prompt text, persisted so it can be restored when reloading the thread.
 901    draft_prompt: Option<Vec<acp::ContentBlock>>,
 902    ui_scroll_position: Option<gpui::ListOffset>,
 903    /// Weak references to running subagent threads for cancellation propagation
 904    running_subagents: Vec<WeakEntity<Thread>>,
 905}
 906
 907impl Thread {
 908    fn prompt_capabilities(model: Option<&dyn LanguageModel>) -> acp::PromptCapabilities {
 909        let image = model.map_or(true, |model| model.supports_images());
 910        acp::PromptCapabilities::new()
 911            .image(image)
 912            .embedded_context(true)
 913    }
 914
 915    pub fn new_subagent(parent_thread: &Entity<Thread>, cx: &mut Context<Self>) -> Self {
 916        let project = parent_thread.read(cx).project.clone();
 917        let project_context = parent_thread.read(cx).project_context.clone();
 918        let context_server_registry = parent_thread.read(cx).context_server_registry.clone();
 919        let templates = parent_thread.read(cx).templates.clone();
 920        let model = parent_thread.read(cx).model().cloned();
 921        let parent_action_log = parent_thread.read(cx).action_log().clone();
 922        let action_log =
 923            cx.new(|_cx| ActionLog::new(project.clone()).with_linked_action_log(parent_action_log));
 924        let mut thread = Self::new_internal(
 925            project,
 926            project_context,
 927            context_server_registry,
 928            templates,
 929            model,
 930            action_log,
 931            cx,
 932        );
 933        thread.subagent_context = Some(SubagentContext {
 934            parent_thread_id: parent_thread.read(cx).id().clone(),
 935            depth: parent_thread.read(cx).depth() + 1,
 936        });
 937        thread
 938    }
 939
 940    pub fn new(
 941        project: Entity<Project>,
 942        project_context: Entity<ProjectContext>,
 943        context_server_registry: Entity<ContextServerRegistry>,
 944        templates: Arc<Templates>,
 945        model: Option<Arc<dyn LanguageModel>>,
 946        cx: &mut Context<Self>,
 947    ) -> Self {
 948        Self::new_internal(
 949            project.clone(),
 950            project_context,
 951            context_server_registry,
 952            templates,
 953            model,
 954            cx.new(|_cx| ActionLog::new(project)),
 955            cx,
 956        )
 957    }
 958
 959    fn new_internal(
 960        project: Entity<Project>,
 961        project_context: Entity<ProjectContext>,
 962        context_server_registry: Entity<ContextServerRegistry>,
 963        templates: Arc<Templates>,
 964        model: Option<Arc<dyn LanguageModel>>,
 965        action_log: Entity<ActionLog>,
 966        cx: &mut Context<Self>,
 967    ) -> Self {
 968        let settings = AgentSettings::get_global(cx);
 969        let profile_id = settings.default_profile.clone();
 970        let enable_thinking = settings
 971            .default_model
 972            .as_ref()
 973            .is_some_and(|model| model.enable_thinking);
 974        let thinking_effort = settings
 975            .default_model
 976            .as_ref()
 977            .and_then(|model| model.effort.clone());
 978        let (prompt_capabilities_tx, prompt_capabilities_rx) =
 979            watch::channel(Self::prompt_capabilities(model.as_deref()));
 980        Self {
 981            id: acp::SessionId::new(uuid::Uuid::new_v4().to_string()),
 982            prompt_id: PromptId::new(),
 983            updated_at: Utc::now(),
 984            title: None,
 985            pending_title_generation: None,
 986            pending_summary_generation: None,
 987            summary: None,
 988            messages: Vec::new(),
 989            user_store: project.read(cx).user_store(),
 990            running_turn: None,
 991            has_queued_message: false,
 992            pending_message: None,
 993            tools: BTreeMap::default(),
 994            request_token_usage: HashMap::default(),
 995            cumulative_token_usage: TokenUsage::default(),
 996            initial_project_snapshot: {
 997                let project_snapshot = Self::project_snapshot(project.clone(), cx);
 998                cx.foreground_executor()
 999                    .spawn(async move { Some(project_snapshot.await) })
1000                    .shared()
1001            },
1002            context_server_registry,
1003            profile_id,
1004            project_context,
1005            templates,
1006            model,
1007            summarization_model: None,
1008            thinking_enabled: enable_thinking,
1009            speed: None,
1010            thinking_effort,
1011            prompt_capabilities_tx,
1012            prompt_capabilities_rx,
1013            project,
1014            action_log,
1015            imported: false,
1016            subagent_context: None,
1017            draft_prompt: None,
1018            ui_scroll_position: None,
1019            running_subagents: Vec::new(),
1020        }
1021    }
1022
1023    pub fn id(&self) -> &acp::SessionId {
1024        &self.id
1025    }
1026
1027    /// Returns true if this thread was imported from a shared thread.
1028    pub fn is_imported(&self) -> bool {
1029        self.imported
1030    }
1031
1032    pub fn replay(
1033        &mut self,
1034        cx: &mut Context<Self>,
1035    ) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {
1036        let (tx, rx) = mpsc::unbounded();
1037        let stream = ThreadEventStream(tx);
1038        for message in &self.messages {
1039            match message {
1040                Message::User(user_message) => stream.send_user_message(user_message),
1041                Message::Agent(assistant_message) => {
1042                    for content in &assistant_message.content {
1043                        match content {
1044                            AgentMessageContent::Text(text) => stream.send_text(text),
1045                            AgentMessageContent::Thinking { text, .. } => {
1046                                stream.send_thinking(text)
1047                            }
1048                            AgentMessageContent::RedactedThinking(_) => {}
1049                            AgentMessageContent::ToolUse(tool_use) => {
1050                                self.replay_tool_call(
1051                                    tool_use,
1052                                    assistant_message.tool_results.get(&tool_use.id),
1053                                    &stream,
1054                                    cx,
1055                                );
1056                            }
1057                        }
1058                    }
1059                }
1060                Message::Resume => {}
1061            }
1062        }
1063        rx
1064    }
1065
1066    fn replay_tool_call(
1067        &self,
1068        tool_use: &LanguageModelToolUse,
1069        tool_result: Option<&LanguageModelToolResult>,
1070        stream: &ThreadEventStream,
1071        cx: &mut Context<Self>,
1072    ) {
1073        // Extract saved output and status first, so they're available even if tool is not found
1074        let output = tool_result
1075            .as_ref()
1076            .and_then(|result| result.output.clone());
1077        let status = tool_result
1078            .as_ref()
1079            .map_or(acp::ToolCallStatus::Failed, |result| {
1080                if result.is_error {
1081                    acp::ToolCallStatus::Failed
1082                } else {
1083                    acp::ToolCallStatus::Completed
1084                }
1085            });
1086
1087        let tool = self.tools.get(tool_use.name.as_ref()).cloned().or_else(|| {
1088            self.context_server_registry
1089                .read(cx)
1090                .servers()
1091                .find_map(|(_, tools)| {
1092                    if let Some(tool) = tools.get(tool_use.name.as_ref()) {
1093                        Some(tool.clone())
1094                    } else {
1095                        None
1096                    }
1097                })
1098        });
1099
1100        let Some(tool) = tool else {
1101            // Tool not found (e.g., MCP server not connected after restart),
1102            // but still display the saved result if available.
1103            // We need to send both ToolCall and ToolCallUpdate events because the UI
1104            // only converts raw_output to displayable content in update_fields, not from_acp.
1105            stream
1106                .0
1107                .unbounded_send(Ok(ThreadEvent::ToolCall(
1108                    acp::ToolCall::new(tool_use.id.to_string(), tool_use.name.to_string())
1109                        .status(status)
1110                        .raw_input(tool_use.input.clone()),
1111                )))
1112                .ok();
1113            stream.update_tool_call_fields(
1114                &tool_use.id,
1115                acp::ToolCallUpdateFields::new()
1116                    .status(status)
1117                    .raw_output(output),
1118                None,
1119            );
1120            return;
1121        };
1122
1123        let title = tool.initial_title(tool_use.input.clone(), cx);
1124        let kind = tool.kind();
1125        stream.send_tool_call(
1126            &tool_use.id,
1127            &tool_use.name,
1128            title,
1129            kind,
1130            tool_use.input.clone(),
1131        );
1132
1133        if let Some(output) = output.clone() {
1134            // For replay, we use a dummy cancellation receiver since the tool already completed
1135            let (_cancellation_tx, cancellation_rx) = watch::channel(false);
1136            let tool_event_stream = ToolCallEventStream::new(
1137                tool_use.id.clone(),
1138                stream.clone(),
1139                Some(self.project.read(cx).fs().clone()),
1140                cancellation_rx,
1141            );
1142            tool.replay(tool_use.input.clone(), output, tool_event_stream, cx)
1143                .log_err();
1144        }
1145
1146        stream.update_tool_call_fields(
1147            &tool_use.id,
1148            acp::ToolCallUpdateFields::new()
1149                .status(status)
1150                .raw_output(output),
1151            None,
1152        );
1153    }
1154
1155    pub fn from_db(
1156        id: acp::SessionId,
1157        db_thread: DbThread,
1158        project: Entity<Project>,
1159        project_context: Entity<ProjectContext>,
1160        context_server_registry: Entity<ContextServerRegistry>,
1161        templates: Arc<Templates>,
1162        cx: &mut Context<Self>,
1163    ) -> Self {
1164        let settings = AgentSettings::get_global(cx);
1165        let profile_id = db_thread
1166            .profile
1167            .unwrap_or_else(|| settings.default_profile.clone());
1168
1169        let mut model = LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1170            db_thread
1171                .model
1172                .and_then(|model| {
1173                    let model = SelectedModel {
1174                        provider: model.provider.clone().into(),
1175                        model: model.model.into(),
1176                    };
1177                    registry.select_model(&model, cx)
1178                })
1179                .or_else(|| registry.default_model())
1180                .map(|model| model.model)
1181        });
1182
1183        if model.is_none() {
1184            model = Self::resolve_profile_model(&profile_id, cx);
1185        }
1186        if model.is_none() {
1187            model = LanguageModelRegistry::global(cx).update(cx, |registry, _cx| {
1188                registry.default_model().map(|model| model.model)
1189            });
1190        }
1191
1192        let (prompt_capabilities_tx, prompt_capabilities_rx) =
1193            watch::channel(Self::prompt_capabilities(model.as_deref()));
1194
1195        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1196
1197        Self {
1198            id,
1199            prompt_id: PromptId::new(),
1200            title: if db_thread.title.is_empty() {
1201                None
1202            } else {
1203                Some(db_thread.title.clone())
1204            },
1205            pending_title_generation: None,
1206            pending_summary_generation: None,
1207            summary: db_thread.detailed_summary,
1208            messages: db_thread.messages,
1209            user_store: project.read(cx).user_store(),
1210            running_turn: None,
1211            has_queued_message: false,
1212            pending_message: None,
1213            tools: BTreeMap::default(),
1214            request_token_usage: db_thread.request_token_usage.clone(),
1215            cumulative_token_usage: db_thread.cumulative_token_usage,
1216            initial_project_snapshot: Task::ready(db_thread.initial_project_snapshot).shared(),
1217            context_server_registry,
1218            profile_id,
1219            project_context,
1220            templates,
1221            model,
1222            summarization_model: None,
1223            thinking_enabled: db_thread.thinking_enabled,
1224            thinking_effort: db_thread.thinking_effort,
1225            speed: db_thread.speed,
1226            project,
1227            action_log,
1228            updated_at: db_thread.updated_at,
1229            prompt_capabilities_tx,
1230            prompt_capabilities_rx,
1231            imported: db_thread.imported,
1232            subagent_context: db_thread.subagent_context,
1233            draft_prompt: db_thread.draft_prompt,
1234            ui_scroll_position: db_thread.ui_scroll_position.map(|sp| gpui::ListOffset {
1235                item_ix: sp.item_ix,
1236                offset_in_item: gpui::px(sp.offset_in_item),
1237            }),
1238            running_subagents: Vec::new(),
1239        }
1240    }
1241
1242    pub fn to_db(&self, cx: &App) -> Task<DbThread> {
1243        let initial_project_snapshot = self.initial_project_snapshot.clone();
1244        let mut thread = DbThread {
1245            title: self.title(),
1246            messages: self.messages.clone(),
1247            updated_at: self.updated_at,
1248            detailed_summary: self.summary.clone(),
1249            initial_project_snapshot: None,
1250            cumulative_token_usage: self.cumulative_token_usage,
1251            request_token_usage: self.request_token_usage.clone(),
1252            model: self.model.as_ref().map(|model| DbLanguageModel {
1253                provider: model.provider_id().to_string(),
1254                model: model.id().0.to_string(),
1255            }),
1256            profile: Some(self.profile_id.clone()),
1257            imported: self.imported,
1258            subagent_context: self.subagent_context.clone(),
1259            speed: self.speed,
1260            thinking_enabled: self.thinking_enabled,
1261            thinking_effort: self.thinking_effort.clone(),
1262            draft_prompt: self.draft_prompt.clone(),
1263            ui_scroll_position: self.ui_scroll_position.map(|lo| {
1264                crate::db::SerializedScrollPosition {
1265                    item_ix: lo.item_ix,
1266                    offset_in_item: lo.offset_in_item.as_f32(),
1267                }
1268            }),
1269        };
1270
1271        cx.background_spawn(async move {
1272            let initial_project_snapshot = initial_project_snapshot.await;
1273            thread.initial_project_snapshot = initial_project_snapshot;
1274            thread
1275        })
1276    }
1277
1278    /// Create a snapshot of the current project state including git information and unsaved buffers.
1279    fn project_snapshot(
1280        project: Entity<Project>,
1281        cx: &mut Context<Self>,
1282    ) -> Task<Arc<ProjectSnapshot>> {
1283        let task = project::telemetry_snapshot::TelemetrySnapshot::new(&project, cx);
1284        cx.spawn(async move |_, _| {
1285            let snapshot = task.await;
1286
1287            Arc::new(ProjectSnapshot {
1288                worktree_snapshots: snapshot.worktree_snapshots,
1289                timestamp: Utc::now(),
1290            })
1291        })
1292    }
1293
1294    pub fn project_context(&self) -> &Entity<ProjectContext> {
1295        &self.project_context
1296    }
1297
1298    pub fn project(&self) -> &Entity<Project> {
1299        &self.project
1300    }
1301
1302    pub fn action_log(&self) -> &Entity<ActionLog> {
1303        &self.action_log
1304    }
1305
1306    pub fn is_empty(&self) -> bool {
1307        self.messages.is_empty() && self.title.is_none()
1308    }
1309
1310    pub fn draft_prompt(&self) -> Option<&[acp::ContentBlock]> {
1311        self.draft_prompt.as_deref()
1312    }
1313
1314    pub fn set_draft_prompt(&mut self, prompt: Option<Vec<acp::ContentBlock>>) {
1315        self.draft_prompt = prompt;
1316    }
1317
1318    pub fn ui_scroll_position(&self) -> Option<gpui::ListOffset> {
1319        self.ui_scroll_position
1320    }
1321
1322    pub fn set_ui_scroll_position(&mut self, position: Option<gpui::ListOffset>) {
1323        self.ui_scroll_position = position;
1324    }
1325
1326    pub fn model(&self) -> Option<&Arc<dyn LanguageModel>> {
1327        self.model.as_ref()
1328    }
1329
1330    pub fn set_model(&mut self, model: Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
1331        let old_usage = self.latest_token_usage();
1332        self.model = Some(model.clone());
1333        let new_caps = Self::prompt_capabilities(self.model.as_deref());
1334        let new_usage = self.latest_token_usage();
1335        if old_usage != new_usage {
1336            cx.emit(TokenUsageUpdated(new_usage));
1337        }
1338        self.prompt_capabilities_tx.send(new_caps).log_err();
1339
1340        for subagent in &self.running_subagents {
1341            subagent
1342                .update(cx, |thread, cx| thread.set_model(model.clone(), cx))
1343                .ok();
1344        }
1345
1346        cx.notify()
1347    }
1348
1349    pub fn summarization_model(&self) -> Option<&Arc<dyn LanguageModel>> {
1350        self.summarization_model.as_ref()
1351    }
1352
1353    pub fn set_summarization_model(
1354        &mut self,
1355        model: Option<Arc<dyn LanguageModel>>,
1356        cx: &mut Context<Self>,
1357    ) {
1358        self.summarization_model = model.clone();
1359
1360        for subagent in &self.running_subagents {
1361            subagent
1362                .update(cx, |thread, cx| {
1363                    thread.set_summarization_model(model.clone(), cx)
1364                })
1365                .ok();
1366        }
1367        cx.notify()
1368    }
1369
1370    pub fn thinking_enabled(&self) -> bool {
1371        self.thinking_enabled
1372    }
1373
1374    pub fn set_thinking_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
1375        self.thinking_enabled = enabled;
1376
1377        for subagent in &self.running_subagents {
1378            subagent
1379                .update(cx, |thread, cx| thread.set_thinking_enabled(enabled, cx))
1380                .ok();
1381        }
1382        cx.notify();
1383    }
1384
1385    pub fn thinking_effort(&self) -> Option<&String> {
1386        self.thinking_effort.as_ref()
1387    }
1388
1389    pub fn set_thinking_effort(&mut self, effort: Option<String>, cx: &mut Context<Self>) {
1390        self.thinking_effort = effort.clone();
1391
1392        for subagent in &self.running_subagents {
1393            subagent
1394                .update(cx, |thread, cx| {
1395                    thread.set_thinking_effort(effort.clone(), cx)
1396                })
1397                .ok();
1398        }
1399        cx.notify();
1400    }
1401
1402    pub fn speed(&self) -> Option<Speed> {
1403        self.speed
1404    }
1405
1406    pub fn set_speed(&mut self, speed: Speed, cx: &mut Context<Self>) {
1407        self.speed = Some(speed);
1408
1409        for subagent in &self.running_subagents {
1410            subagent
1411                .update(cx, |thread, cx| thread.set_speed(speed, cx))
1412                .ok();
1413        }
1414        cx.notify();
1415    }
1416
1417    pub fn last_message(&self) -> Option<&Message> {
1418        self.messages.last()
1419    }
1420
1421    #[cfg(any(test, feature = "test-support"))]
1422    pub fn last_received_or_pending_message(&self) -> Option<Message> {
1423        if let Some(message) = self.pending_message.clone() {
1424            Some(Message::Agent(message))
1425        } else {
1426            self.messages.last().cloned()
1427        }
1428    }
1429
1430    pub fn add_default_tools(
1431        &mut self,
1432        environment: Rc<dyn ThreadEnvironment>,
1433        cx: &mut Context<Self>,
1434    ) {
1435        // Only update the agent location for the root thread, not for subagents.
1436        let update_agent_location = self.parent_thread_id().is_none();
1437
1438        let language_registry = self.project.read(cx).languages().clone();
1439        self.add_tool(CopyPathTool::new(self.project.clone()));
1440        self.add_tool(CreateDirectoryTool::new(self.project.clone()));
1441        self.add_tool(DeletePathTool::new(
1442            self.project.clone(),
1443            self.action_log.clone(),
1444        ));
1445        self.add_tool(DiagnosticsTool::new(self.project.clone()));
1446        self.add_tool(EditFileTool::new(
1447            self.project.clone(),
1448            cx.weak_entity(),
1449            language_registry.clone(),
1450            Templates::new(),
1451        ));
1452        self.add_tool(StreamingEditFileTool::new(
1453            self.project.clone(),
1454            cx.weak_entity(),
1455            language_registry,
1456        ));
1457        self.add_tool(FetchTool::new(self.project.read(cx).client().http_client()));
1458        self.add_tool(FindPathTool::new(self.project.clone()));
1459        self.add_tool(GrepTool::new(self.project.clone()));
1460        self.add_tool(ListDirectoryTool::new(self.project.clone()));
1461        self.add_tool(MovePathTool::new(self.project.clone()));
1462        self.add_tool(NowTool);
1463        self.add_tool(OpenTool::new(self.project.clone()));
1464        self.add_tool(ReadFileTool::new(
1465            self.project.clone(),
1466            self.action_log.clone(),
1467            update_agent_location,
1468        ));
1469        self.add_tool(SaveFileTool::new(self.project.clone()));
1470        self.add_tool(RestoreFileFromDiskTool::new(self.project.clone()));
1471        self.add_tool(TerminalTool::new(self.project.clone(), environment.clone()));
1472        self.add_tool(WebSearchTool);
1473
1474        if self.depth() < MAX_SUBAGENT_DEPTH {
1475            self.add_tool(SpawnAgentTool::new(environment));
1476        }
1477    }
1478
1479    pub fn add_tool<T: AgentTool>(&mut self, tool: T) {
1480        debug_assert!(
1481            !self.tools.contains_key(T::NAME),
1482            "Duplicate tool name: {}",
1483            T::NAME,
1484        );
1485        self.tools.insert(T::NAME.into(), tool.erase());
1486    }
1487
1488    #[cfg(any(test, feature = "test-support"))]
1489    pub fn remove_tool(&mut self, name: &str) -> bool {
1490        self.tools.remove(name).is_some()
1491    }
1492
1493    pub fn profile(&self) -> &AgentProfileId {
1494        &self.profile_id
1495    }
1496
1497    pub fn set_profile(&mut self, profile_id: AgentProfileId, cx: &mut Context<Self>) {
1498        if self.profile_id == profile_id {
1499            return;
1500        }
1501
1502        self.profile_id = profile_id.clone();
1503
1504        // Swap to the profile's preferred model when available.
1505        if let Some(model) = Self::resolve_profile_model(&self.profile_id, cx) {
1506            self.set_model(model, cx);
1507        }
1508
1509        for subagent in &self.running_subagents {
1510            subagent
1511                .update(cx, |thread, cx| thread.set_profile(profile_id.clone(), cx))
1512                .ok();
1513        }
1514    }
1515
1516    pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
1517        for subagent in self.running_subagents.drain(..) {
1518            if let Some(subagent) = subagent.upgrade() {
1519                subagent.update(cx, |thread, cx| thread.cancel(cx)).detach();
1520            }
1521        }
1522
1523        let Some(running_turn) = self.running_turn.take() else {
1524            self.flush_pending_message(cx);
1525            return Task::ready(());
1526        };
1527
1528        let turn_task = running_turn.cancel();
1529
1530        cx.spawn(async move |this, cx| {
1531            turn_task.await;
1532            this.update(cx, |this, cx| {
1533                this.flush_pending_message(cx);
1534            })
1535            .ok();
1536        })
1537    }
1538
1539    pub fn set_has_queued_message(&mut self, has_queued: bool) {
1540        self.has_queued_message = has_queued;
1541    }
1542
1543    pub fn has_queued_message(&self) -> bool {
1544        self.has_queued_message
1545    }
1546
1547    fn update_token_usage(&mut self, update: language_model::TokenUsage, cx: &mut Context<Self>) {
1548        let Some(last_user_message) = self.last_user_message() else {
1549            return;
1550        };
1551
1552        self.request_token_usage
1553            .insert(last_user_message.id.clone(), update);
1554        cx.emit(TokenUsageUpdated(self.latest_token_usage()));
1555        cx.notify();
1556    }
1557
1558    pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
1559        self.cancel(cx).detach();
1560        // Clear pending message since cancel will try to flush it asynchronously,
1561        // and we don't want that content to be added after we truncate
1562        self.pending_message.take();
1563        let Some(position) = self.messages.iter().position(
1564            |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
1565        ) else {
1566            return Err(anyhow!("Message not found"));
1567        };
1568
1569        for message in self.messages.drain(position..) {
1570            match message {
1571                Message::User(message) => {
1572                    self.request_token_usage.remove(&message.id);
1573                }
1574                Message::Agent(_) | Message::Resume => {}
1575            }
1576        }
1577        self.clear_summary();
1578        cx.notify();
1579        Ok(())
1580    }
1581
1582    pub fn latest_request_token_usage(&self) -> Option<language_model::TokenUsage> {
1583        let last_user_message = self.last_user_message()?;
1584        let tokens = self.request_token_usage.get(&last_user_message.id)?;
1585        Some(*tokens)
1586    }
1587
1588    pub fn latest_token_usage(&self) -> Option<acp_thread::TokenUsage> {
1589        let usage = self.latest_request_token_usage()?;
1590        let model = self.model.clone()?;
1591        Some(acp_thread::TokenUsage {
1592            max_tokens: model.max_token_count(),
1593            max_output_tokens: model.max_output_tokens(),
1594            used_tokens: usage.total_tokens(),
1595            input_tokens: usage.input_tokens,
1596            output_tokens: usage.output_tokens,
1597        })
1598    }
1599
1600    /// Get the total input token count as of the message before the given message.
1601    ///
1602    /// Returns `None` if:
1603    /// - `target_id` is the first message (no previous message)
1604    /// - The previous message hasn't received a response yet (no usage data)
1605    /// - `target_id` is not found in the messages
1606    pub fn tokens_before_message(&self, target_id: &UserMessageId) -> Option<u64> {
1607        let mut previous_user_message_id: Option<&UserMessageId> = None;
1608
1609        for message in &self.messages {
1610            if let Message::User(user_msg) = message {
1611                if &user_msg.id == target_id {
1612                    let prev_id = previous_user_message_id?;
1613                    let usage = self.request_token_usage.get(prev_id)?;
1614                    return Some(usage.input_tokens);
1615                }
1616                previous_user_message_id = Some(&user_msg.id);
1617            }
1618        }
1619        None
1620    }
1621
1622    /// Look up the active profile and resolve its preferred model if one is configured.
1623    fn resolve_profile_model(
1624        profile_id: &AgentProfileId,
1625        cx: &mut Context<Self>,
1626    ) -> Option<Arc<dyn LanguageModel>> {
1627        let selection = AgentSettings::get_global(cx)
1628            .profiles
1629            .get(profile_id)?
1630            .default_model
1631            .clone()?;
1632        Self::resolve_model_from_selection(&selection, cx)
1633    }
1634
1635    /// Translate a stored model selection into the configured model from the registry.
1636    fn resolve_model_from_selection(
1637        selection: &LanguageModelSelection,
1638        cx: &mut Context<Self>,
1639    ) -> Option<Arc<dyn LanguageModel>> {
1640        let selected = SelectedModel {
1641            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
1642            model: LanguageModelId::from(selection.model.clone()),
1643        };
1644        LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1645            registry
1646                .select_model(&selected, cx)
1647                .map(|configured| configured.model)
1648        })
1649    }
1650
1651    pub fn resume(
1652        &mut self,
1653        cx: &mut Context<Self>,
1654    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1655        self.messages.push(Message::Resume);
1656        cx.notify();
1657
1658        log::debug!("Total messages in thread: {}", self.messages.len());
1659        self.run_turn(cx)
1660    }
1661
1662    /// Sending a message results in the model streaming a response, which could include tool calls.
1663    /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
1664    /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
1665    pub fn send<T>(
1666        &mut self,
1667        id: UserMessageId,
1668        content: impl IntoIterator<Item = T>,
1669        cx: &mut Context<Self>,
1670    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
1671    where
1672        T: Into<UserMessageContent>,
1673    {
1674        let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
1675        log::debug!("Thread::send content: {:?}", content);
1676
1677        self.messages
1678            .push(Message::User(UserMessage { id, content }));
1679        cx.notify();
1680
1681        self.send_existing(cx)
1682    }
1683
1684    pub fn send_existing(
1685        &mut self,
1686        cx: &mut Context<Self>,
1687    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1688        let model = self.model().context("No language model configured")?;
1689
1690        log::info!("Thread::send called with model: {}", model.name().0);
1691        self.advance_prompt_id();
1692
1693        log::debug!("Total messages in thread: {}", self.messages.len());
1694        self.run_turn(cx)
1695    }
1696
1697    pub fn push_acp_user_block(
1698        &mut self,
1699        id: UserMessageId,
1700        blocks: impl IntoIterator<Item = acp::ContentBlock>,
1701        path_style: PathStyle,
1702        cx: &mut Context<Self>,
1703    ) {
1704        let content = blocks
1705            .into_iter()
1706            .map(|block| UserMessageContent::from_content_block(block, path_style))
1707            .collect::<Vec<_>>();
1708        self.messages
1709            .push(Message::User(UserMessage { id, content }));
1710        cx.notify();
1711    }
1712
1713    pub fn push_acp_agent_block(&mut self, block: acp::ContentBlock, cx: &mut Context<Self>) {
1714        let text = match block {
1715            acp::ContentBlock::Text(text_content) => text_content.text,
1716            acp::ContentBlock::Image(_) => "[image]".to_string(),
1717            acp::ContentBlock::Audio(_) => "[audio]".to_string(),
1718            acp::ContentBlock::ResourceLink(resource_link) => resource_link.uri,
1719            acp::ContentBlock::Resource(resource) => match resource.resource {
1720                acp::EmbeddedResourceResource::TextResourceContents(resource) => resource.uri,
1721                acp::EmbeddedResourceResource::BlobResourceContents(resource) => resource.uri,
1722                _ => "[resource]".to_string(),
1723            },
1724            _ => "[unknown]".to_string(),
1725        };
1726
1727        self.messages.push(Message::Agent(AgentMessage {
1728            content: vec![AgentMessageContent::Text(text)],
1729            ..Default::default()
1730        }));
1731        cx.notify();
1732    }
1733
1734    #[cfg(feature = "eval")]
1735    pub fn proceed(
1736        &mut self,
1737        cx: &mut Context<Self>,
1738    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1739        self.run_turn(cx)
1740    }
1741
1742    fn run_turn(
1743        &mut self,
1744        cx: &mut Context<Self>,
1745    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1746        // Flush the old pending message synchronously before cancelling,
1747        // to avoid a race where the detached cancel task might flush the NEW
1748        // turn's pending message instead of the old one.
1749        self.flush_pending_message(cx);
1750        self.cancel(cx).detach();
1751
1752        let model = self.model.clone().context("No language model configured")?;
1753        let profile = AgentSettings::get_global(cx)
1754            .profiles
1755            .get(&self.profile_id)
1756            .context("Profile not found")?;
1757        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1758        let event_stream = ThreadEventStream(events_tx);
1759        let message_ix = self.messages.len().saturating_sub(1);
1760        self.clear_summary();
1761        let (cancellation_tx, mut cancellation_rx) = watch::channel(false);
1762        self.running_turn = Some(RunningTurn {
1763            event_stream: event_stream.clone(),
1764            tools: self.enabled_tools(profile, &model, cx),
1765            cancellation_tx,
1766            streaming_tool_inputs: HashMap::default(),
1767            _task: cx.spawn(async move |this, cx| {
1768                log::debug!("Starting agent turn execution");
1769
1770                let turn_result = Self::run_turn_internal(
1771                    &this,
1772                    model,
1773                    &event_stream,
1774                    cancellation_rx.clone(),
1775                    cx,
1776                )
1777                .await;
1778
1779                // Check if we were cancelled - if so, cancel() already took running_turn
1780                // and we shouldn't touch it (it might be a NEW turn now)
1781                let was_cancelled = *cancellation_rx.borrow();
1782                if was_cancelled {
1783                    log::debug!("Turn was cancelled, skipping cleanup");
1784                    return;
1785                }
1786
1787                _ = this.update(cx, |this, cx| this.flush_pending_message(cx));
1788
1789                match turn_result {
1790                    Ok(()) => {
1791                        log::debug!("Turn execution completed");
1792                        event_stream.send_stop(acp::StopReason::EndTurn);
1793                    }
1794                    Err(error) => {
1795                        log::error!("Turn execution failed: {:?}", error);
1796                        match error.downcast::<CompletionError>() {
1797                            Ok(CompletionError::Refusal) => {
1798                                event_stream.send_stop(acp::StopReason::Refusal);
1799                                _ = this.update(cx, |this, _| this.messages.truncate(message_ix));
1800                            }
1801                            Ok(CompletionError::MaxTokens) => {
1802                                event_stream.send_stop(acp::StopReason::MaxTokens);
1803                            }
1804                            Ok(CompletionError::Other(error)) | Err(error) => {
1805                                event_stream.send_error(error);
1806                            }
1807                        }
1808                    }
1809                }
1810
1811                _ = this.update(cx, |this, _| this.running_turn.take());
1812            }),
1813        });
1814        Ok(events_rx)
1815    }
1816
1817    async fn run_turn_internal(
1818        this: &WeakEntity<Self>,
1819        model: Arc<dyn LanguageModel>,
1820        event_stream: &ThreadEventStream,
1821        mut cancellation_rx: watch::Receiver<bool>,
1822        cx: &mut AsyncApp,
1823    ) -> Result<()> {
1824        let mut attempt = 0;
1825        let mut intent = CompletionIntent::UserPrompt;
1826        loop {
1827            let request =
1828                this.update(cx, |this, cx| this.build_completion_request(intent, cx))??;
1829
1830            telemetry::event!(
1831                "Agent Thread Completion",
1832                thread_id = this.read_with(cx, |this, _| this.id.to_string())?,
1833                parent_thread_id = this.read_with(cx, |this, _| this
1834                    .parent_thread_id()
1835                    .map(|id| id.to_string()))?,
1836                prompt_id = this.read_with(cx, |this, _| this.prompt_id.to_string())?,
1837                model = model.telemetry_id(),
1838                model_provider = model.provider_id().to_string(),
1839                attempt
1840            );
1841
1842            log::debug!("Calling model.stream_completion, attempt {}", attempt);
1843
1844            let (mut events, mut error) = match model.stream_completion(request, cx).await {
1845                Ok(events) => (events.fuse(), None),
1846                Err(err) => (stream::empty().boxed().fuse(), Some(err)),
1847            };
1848            let mut tool_results = FuturesUnordered::new();
1849            let mut cancelled = false;
1850            loop {
1851                // Race between getting the first event and cancellation
1852                let first_event = futures::select! {
1853                    event = events.next().fuse() => event,
1854                    _ = cancellation_rx.changed().fuse() => {
1855                        if *cancellation_rx.borrow() {
1856                            cancelled = true;
1857                            break;
1858                        }
1859                        continue;
1860                    }
1861                };
1862                let Some(first_event) = first_event else {
1863                    break;
1864                };
1865
1866                // Collect all immediately available events to process as a batch
1867                let mut batch = vec![first_event];
1868                while let Some(event) = events.next().now_or_never().flatten() {
1869                    batch.push(event);
1870                }
1871
1872                // Process the batch in a single update
1873                let batch_result = this.update(cx, |this, cx| {
1874                    let mut batch_tool_results = Vec::new();
1875                    let mut batch_error = None;
1876
1877                    for event in batch {
1878                        log::trace!("Received completion event: {:?}", event);
1879                        match event {
1880                            Ok(event) => {
1881                                match this.handle_completion_event(
1882                                    event,
1883                                    event_stream,
1884                                    cancellation_rx.clone(),
1885                                    cx,
1886                                ) {
1887                                    Ok(Some(task)) => batch_tool_results.push(task),
1888                                    Ok(None) => {}
1889                                    Err(err) => {
1890                                        batch_error = Some(err);
1891                                        break;
1892                                    }
1893                                }
1894                            }
1895                            Err(err) => {
1896                                batch_error = Some(err.into());
1897                                break;
1898                            }
1899                        }
1900                    }
1901
1902                    cx.notify();
1903                    (batch_tool_results, batch_error)
1904                })?;
1905
1906                tool_results.extend(batch_result.0);
1907                if let Some(err) = batch_result.1 {
1908                    error = Some(err.downcast()?);
1909                    break;
1910                }
1911            }
1912
1913            // Drop the stream to release the rate limit permit before tool execution.
1914            // The stream holds a semaphore guard that limits concurrent requests.
1915            // Without this, the permit would be held during potentially long-running
1916            // tool execution, which could cause deadlocks when tools spawn subagents
1917            // that need their own permits.
1918            drop(events);
1919
1920            let end_turn = tool_results.is_empty();
1921            while let Some(tool_result) = tool_results.next().await {
1922                log::debug!("Tool finished {:?}", tool_result);
1923
1924                event_stream.update_tool_call_fields(
1925                    &tool_result.tool_use_id,
1926                    acp::ToolCallUpdateFields::new()
1927                        .status(if tool_result.is_error {
1928                            acp::ToolCallStatus::Failed
1929                        } else {
1930                            acp::ToolCallStatus::Completed
1931                        })
1932                        .raw_output(tool_result.output.clone()),
1933                    None,
1934                );
1935                this.update(cx, |this, _cx| {
1936                    this.pending_message()
1937                        .tool_results
1938                        .insert(tool_result.tool_use_id.clone(), tool_result);
1939                })?;
1940            }
1941
1942            this.update(cx, |this, cx| {
1943                this.flush_pending_message(cx);
1944                if this.title.is_none() && this.pending_title_generation.is_none() {
1945                    this.generate_title(cx);
1946                }
1947            })?;
1948
1949            if cancelled {
1950                log::debug!("Turn cancelled by user, exiting");
1951                return Ok(());
1952            }
1953
1954            if let Some(error) = error {
1955                attempt += 1;
1956                let retry = this.update(cx, |this, cx| {
1957                    let user_store = this.user_store.read(cx);
1958                    this.handle_completion_error(error, attempt, user_store.plan())
1959                })??;
1960                let timer = cx.background_executor().timer(retry.duration);
1961                event_stream.send_retry(retry);
1962                futures::select! {
1963                    _ = timer.fuse() => {}
1964                    _ = cancellation_rx.changed().fuse() => {
1965                        if *cancellation_rx.borrow() {
1966                            log::debug!("Turn cancelled during retry delay, exiting");
1967                            return Ok(());
1968                        }
1969                    }
1970                }
1971                this.update(cx, |this, _cx| {
1972                    if let Some(Message::Agent(message)) = this.messages.last() {
1973                        if message.tool_results.is_empty() {
1974                            intent = CompletionIntent::UserPrompt;
1975                            this.messages.push(Message::Resume);
1976                        }
1977                    }
1978                })?;
1979            } else if end_turn {
1980                return Ok(());
1981            } else {
1982                let has_queued = this.update(cx, |this, _| this.has_queued_message())?;
1983                if has_queued {
1984                    log::debug!("Queued message found, ending turn at message boundary");
1985                    return Ok(());
1986                }
1987                intent = CompletionIntent::ToolResults;
1988                attempt = 0;
1989            }
1990        }
1991    }
1992
1993    fn handle_completion_error(
1994        &mut self,
1995        error: LanguageModelCompletionError,
1996        attempt: u8,
1997        plan: Option<Plan>,
1998    ) -> Result<acp_thread::RetryStatus> {
1999        let Some(model) = self.model.as_ref() else {
2000            return Err(anyhow!(error));
2001        };
2002
2003        let auto_retry = if model.provider_id() == ZED_CLOUD_PROVIDER_ID {
2004            plan.is_some()
2005        } else {
2006            true
2007        };
2008
2009        if !auto_retry {
2010            return Err(anyhow!(error));
2011        }
2012
2013        let Some(strategy) = Self::retry_strategy_for(&error) else {
2014            return Err(anyhow!(error));
2015        };
2016
2017        let max_attempts = match &strategy {
2018            RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
2019            RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
2020        };
2021
2022        if attempt > max_attempts {
2023            return Err(anyhow!(error));
2024        }
2025
2026        let delay = match &strategy {
2027            RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
2028                let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
2029                Duration::from_secs(delay_secs)
2030            }
2031            RetryStrategy::Fixed { delay, .. } => *delay,
2032        };
2033        log::debug!("Retry attempt {attempt} with delay {delay:?}");
2034
2035        Ok(acp_thread::RetryStatus {
2036            last_error: error.to_string().into(),
2037            attempt: attempt as usize,
2038            max_attempts: max_attempts as usize,
2039            started_at: Instant::now(),
2040            duration: delay,
2041        })
2042    }
2043
2044    /// A helper method that's called on every streamed completion event.
2045    /// Returns an optional tool result task, which the main agentic loop will
2046    /// send back to the model when it resolves.
2047    fn handle_completion_event(
2048        &mut self,
2049        event: LanguageModelCompletionEvent,
2050        event_stream: &ThreadEventStream,
2051        cancellation_rx: watch::Receiver<bool>,
2052        cx: &mut Context<Self>,
2053    ) -> Result<Option<Task<LanguageModelToolResult>>> {
2054        log::trace!("Handling streamed completion event: {:?}", event);
2055        use LanguageModelCompletionEvent::*;
2056
2057        match event {
2058            StartMessage { .. } => {
2059                self.flush_pending_message(cx);
2060                self.pending_message = Some(AgentMessage::default());
2061            }
2062            Text(new_text) => self.handle_text_event(new_text, event_stream),
2063            Thinking { text, signature } => {
2064                self.handle_thinking_event(text, signature, event_stream)
2065            }
2066            RedactedThinking { data } => self.handle_redacted_thinking_event(data),
2067            ReasoningDetails(details) => {
2068                let last_message = self.pending_message();
2069                // Store the last non-empty reasoning_details (overwrites earlier ones)
2070                // This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
2071                if let serde_json::Value::Array(ref arr) = details {
2072                    if !arr.is_empty() {
2073                        last_message.reasoning_details = Some(details);
2074                    }
2075                } else {
2076                    last_message.reasoning_details = Some(details);
2077                }
2078            }
2079            ToolUse(tool_use) => {
2080                return Ok(self.handle_tool_use_event(tool_use, event_stream, cancellation_rx, cx));
2081            }
2082            ToolUseJsonParseError {
2083                id,
2084                tool_name,
2085                raw_input,
2086                json_parse_error,
2087            } => {
2088                return Ok(Some(Task::ready(
2089                    self.handle_tool_use_json_parse_error_event(
2090                        id,
2091                        tool_name,
2092                        raw_input,
2093                        json_parse_error,
2094                        event_stream,
2095                    ),
2096                )));
2097            }
2098            UsageUpdate(usage) => {
2099                telemetry::event!(
2100                    "Agent Thread Completion Usage Updated",
2101                    thread_id = self.id.to_string(),
2102                    parent_thread_id = self.parent_thread_id().map(|id| id.to_string()),
2103                    prompt_id = self.prompt_id.to_string(),
2104                    model = self.model.as_ref().map(|m| m.telemetry_id()),
2105                    model_provider = self.model.as_ref().map(|m| m.provider_id().to_string()),
2106                    input_tokens = usage.input_tokens,
2107                    output_tokens = usage.output_tokens,
2108                    cache_creation_input_tokens = usage.cache_creation_input_tokens,
2109                    cache_read_input_tokens = usage.cache_read_input_tokens,
2110                );
2111                self.update_token_usage(usage, cx);
2112            }
2113            Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
2114            Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
2115            Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
2116            Started | Queued { .. } => {}
2117        }
2118
2119        Ok(None)
2120    }
2121
2122    fn handle_text_event(&mut self, new_text: String, event_stream: &ThreadEventStream) {
2123        event_stream.send_text(&new_text);
2124
2125        let last_message = self.pending_message();
2126        if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
2127            text.push_str(&new_text);
2128        } else {
2129            last_message
2130                .content
2131                .push(AgentMessageContent::Text(new_text));
2132        }
2133    }
2134
2135    fn handle_thinking_event(
2136        &mut self,
2137        new_text: String,
2138        new_signature: Option<String>,
2139        event_stream: &ThreadEventStream,
2140    ) {
2141        event_stream.send_thinking(&new_text);
2142
2143        let last_message = self.pending_message();
2144        if let Some(AgentMessageContent::Thinking { text, signature }) =
2145            last_message.content.last_mut()
2146        {
2147            text.push_str(&new_text);
2148            *signature = new_signature.or(signature.take());
2149        } else {
2150            last_message.content.push(AgentMessageContent::Thinking {
2151                text: new_text,
2152                signature: new_signature,
2153            });
2154        }
2155    }
2156
2157    fn handle_redacted_thinking_event(&mut self, data: String) {
2158        let last_message = self.pending_message();
2159        last_message
2160            .content
2161            .push(AgentMessageContent::RedactedThinking(data));
2162    }
2163
2164    fn handle_tool_use_event(
2165        &mut self,
2166        tool_use: LanguageModelToolUse,
2167        event_stream: &ThreadEventStream,
2168        cancellation_rx: watch::Receiver<bool>,
2169        cx: &mut Context<Self>,
2170    ) -> Option<Task<LanguageModelToolResult>> {
2171        cx.notify();
2172
2173        let tool = self.tool(tool_use.name.as_ref());
2174        let mut title = SharedString::from(&tool_use.name);
2175        let mut kind = acp::ToolKind::Other;
2176        if let Some(tool) = tool.as_ref() {
2177            title = tool.initial_title(tool_use.input.clone(), cx);
2178            kind = tool.kind();
2179        }
2180
2181        self.send_or_update_tool_use(&tool_use, title, kind, event_stream);
2182
2183        let Some(tool) = tool else {
2184            let content = format!("No tool named {} exists", tool_use.name);
2185            return Some(Task::ready(LanguageModelToolResult {
2186                content: LanguageModelToolResultContent::Text(Arc::from(content)),
2187                tool_use_id: tool_use.id,
2188                tool_name: tool_use.name,
2189                is_error: true,
2190                output: None,
2191            }));
2192        };
2193
2194        if !tool_use.is_input_complete {
2195            if tool.supports_input_streaming() {
2196                let running_turn = self.running_turn.as_mut()?;
2197                if let Some(sender) = running_turn.streaming_tool_inputs.get(&tool_use.id) {
2198                    sender.send_partial(tool_use.input);
2199                    return None;
2200                }
2201
2202                let (sender, tool_input) = ToolInputSender::channel();
2203                sender.send_partial(tool_use.input);
2204                running_turn
2205                    .streaming_tool_inputs
2206                    .insert(tool_use.id.clone(), sender);
2207
2208                let tool = tool.clone();
2209                log::debug!("Running streaming tool {}", tool_use.name);
2210                return Some(self.run_tool(
2211                    tool,
2212                    tool_input,
2213                    tool_use.id,
2214                    tool_use.name,
2215                    event_stream,
2216                    cancellation_rx,
2217                    cx,
2218                ));
2219            } else {
2220                return None;
2221            }
2222        }
2223
2224        if let Some(sender) = self
2225            .running_turn
2226            .as_mut()?
2227            .streaming_tool_inputs
2228            .remove(&tool_use.id)
2229        {
2230            sender.send_final(tool_use.input);
2231            return None;
2232        }
2233
2234        log::debug!("Running tool {}", tool_use.name);
2235        let tool_input = ToolInput::ready(tool_use.input);
2236        Some(self.run_tool(
2237            tool,
2238            tool_input,
2239            tool_use.id,
2240            tool_use.name,
2241            event_stream,
2242            cancellation_rx,
2243            cx,
2244        ))
2245    }
2246
2247    fn run_tool(
2248        &self,
2249        tool: Arc<dyn AnyAgentTool>,
2250        tool_input: ToolInput<serde_json::Value>,
2251        tool_use_id: LanguageModelToolUseId,
2252        tool_name: Arc<str>,
2253        event_stream: &ThreadEventStream,
2254        cancellation_rx: watch::Receiver<bool>,
2255        cx: &mut Context<Self>,
2256    ) -> Task<LanguageModelToolResult> {
2257        let fs = self.project.read(cx).fs().clone();
2258        let tool_event_stream = ToolCallEventStream::new(
2259            tool_use_id.clone(),
2260            event_stream.clone(),
2261            Some(fs),
2262            cancellation_rx,
2263        );
2264        tool_event_stream.update_fields(
2265            acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
2266        );
2267        let supports_images = self.model().is_some_and(|model| model.supports_images());
2268        let tool_result = tool.run(tool_input, tool_event_stream, cx);
2269        cx.foreground_executor().spawn(async move {
2270            let (is_error, output) = match tool_result.await {
2271                Ok(mut output) => {
2272                    if let LanguageModelToolResultContent::Image(_) = &output.llm_output
2273                        && !supports_images
2274                    {
2275                        output = AgentToolOutput::from_error(
2276                            "Attempted to read an image, but this model doesn't support it.",
2277                        );
2278                        (true, output)
2279                    } else {
2280                        (false, output)
2281                    }
2282                }
2283                Err(output) => (true, output),
2284            };
2285
2286            LanguageModelToolResult {
2287                tool_use_id,
2288                tool_name,
2289                is_error,
2290                content: output.llm_output,
2291                output: Some(output.raw_output),
2292            }
2293        })
2294    }
2295
2296    fn handle_tool_use_json_parse_error_event(
2297        &mut self,
2298        tool_use_id: LanguageModelToolUseId,
2299        tool_name: Arc<str>,
2300        raw_input: Arc<str>,
2301        json_parse_error: String,
2302        event_stream: &ThreadEventStream,
2303    ) -> LanguageModelToolResult {
2304        let tool_use = LanguageModelToolUse {
2305            id: tool_use_id.clone(),
2306            name: tool_name.clone(),
2307            raw_input: raw_input.to_string(),
2308            input: serde_json::json!({}),
2309            is_input_complete: true,
2310            thought_signature: None,
2311        };
2312        self.send_or_update_tool_use(
2313            &tool_use,
2314            SharedString::from(&tool_use.name),
2315            acp::ToolKind::Other,
2316            event_stream,
2317        );
2318
2319        let tool_output = format!("Error parsing input JSON: {json_parse_error}");
2320        LanguageModelToolResult {
2321            tool_use_id,
2322            tool_name,
2323            is_error: true,
2324            content: LanguageModelToolResultContent::Text(tool_output.into()),
2325            output: Some(serde_json::Value::String(raw_input.to_string())),
2326        }
2327    }
2328
2329    fn send_or_update_tool_use(
2330        &mut self,
2331        tool_use: &LanguageModelToolUse,
2332        title: SharedString,
2333        kind: acp::ToolKind,
2334        event_stream: &ThreadEventStream,
2335    ) {
2336        // Ensure the last message ends in the current tool use
2337        let last_message = self.pending_message();
2338
2339        let has_tool_use = last_message.content.iter_mut().rev().any(|content| {
2340            if let AgentMessageContent::ToolUse(last_tool_use) = content {
2341                if last_tool_use.id == tool_use.id {
2342                    *last_tool_use = tool_use.clone();
2343                    return true;
2344                }
2345            }
2346            false
2347        });
2348
2349        if !has_tool_use {
2350            event_stream.send_tool_call(
2351                &tool_use.id,
2352                &tool_use.name,
2353                title,
2354                kind,
2355                tool_use.input.clone(),
2356            );
2357            last_message
2358                .content
2359                .push(AgentMessageContent::ToolUse(tool_use.clone()));
2360        } else {
2361            event_stream.update_tool_call_fields(
2362                &tool_use.id,
2363                acp::ToolCallUpdateFields::new()
2364                    .title(title.as_str())
2365                    .kind(kind)
2366                    .raw_input(tool_use.input.clone()),
2367                None,
2368            );
2369        }
2370    }
2371
2372    pub fn title(&self) -> SharedString {
2373        self.title.clone().unwrap_or("New Thread".into())
2374    }
2375
2376    pub fn is_generating_summary(&self) -> bool {
2377        self.pending_summary_generation.is_some()
2378    }
2379
2380    pub fn is_generating_title(&self) -> bool {
2381        self.pending_title_generation.is_some()
2382    }
2383
2384    pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
2385        if let Some(summary) = self.summary.as_ref() {
2386            return Task::ready(Some(summary.clone())).shared();
2387        }
2388        if let Some(task) = self.pending_summary_generation.clone() {
2389            return task;
2390        }
2391        let Some(model) = self.summarization_model.clone() else {
2392            log::error!("No summarization model available");
2393            return Task::ready(None).shared();
2394        };
2395        let mut request = LanguageModelRequest {
2396            intent: Some(CompletionIntent::ThreadContextSummarization),
2397            temperature: AgentSettings::temperature_for_model(&model, cx),
2398            ..Default::default()
2399        };
2400
2401        for message in &self.messages {
2402            request.messages.extend(message.to_request());
2403        }
2404
2405        request.messages.push(LanguageModelRequestMessage {
2406            role: Role::User,
2407            content: vec![SUMMARIZE_THREAD_DETAILED_PROMPT.into()],
2408            cache: false,
2409            reasoning_details: None,
2410        });
2411
2412        let task = cx
2413            .spawn(async move |this, cx| {
2414                let mut summary = String::new();
2415                let mut messages = model.stream_completion(request, cx).await.log_err()?;
2416                while let Some(event) = messages.next().await {
2417                    let event = event.log_err()?;
2418                    let text = match event {
2419                        LanguageModelCompletionEvent::Text(text) => text,
2420                        _ => continue,
2421                    };
2422
2423                    let mut lines = text.lines();
2424                    summary.extend(lines.next());
2425                }
2426
2427                log::debug!("Setting summary: {}", summary);
2428                let summary = SharedString::from(summary);
2429
2430                this.update(cx, |this, cx| {
2431                    this.summary = Some(summary.clone());
2432                    this.pending_summary_generation = None;
2433                    cx.notify()
2434                })
2435                .ok()?;
2436
2437                Some(summary)
2438            })
2439            .shared();
2440        self.pending_summary_generation = Some(task.clone());
2441        task
2442    }
2443
2444    pub fn generate_title(&mut self, cx: &mut Context<Self>) {
2445        let Some(model) = self.summarization_model.clone() else {
2446            return;
2447        };
2448
2449        log::debug!(
2450            "Generating title with model: {:?}",
2451            self.summarization_model.as_ref().map(|model| model.name())
2452        );
2453        let mut request = LanguageModelRequest {
2454            intent: Some(CompletionIntent::ThreadSummarization),
2455            temperature: AgentSettings::temperature_for_model(&model, cx),
2456            ..Default::default()
2457        };
2458
2459        for message in &self.messages {
2460            request.messages.extend(message.to_request());
2461        }
2462
2463        request.messages.push(LanguageModelRequestMessage {
2464            role: Role::User,
2465            content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2466            cache: false,
2467            reasoning_details: None,
2468        });
2469        self.pending_title_generation = Some(cx.spawn(async move |this, cx| {
2470            let mut title = String::new();
2471
2472            let generate = async {
2473                let mut messages = model.stream_completion(request, cx).await?;
2474                while let Some(event) = messages.next().await {
2475                    let event = event?;
2476                    let text = match event {
2477                        LanguageModelCompletionEvent::Text(text) => text,
2478                        _ => continue,
2479                    };
2480
2481                    let mut lines = text.lines();
2482                    title.extend(lines.next());
2483
2484                    // Stop if the LLM generated multiple lines.
2485                    if lines.next().is_some() {
2486                        break;
2487                    }
2488                }
2489                anyhow::Ok(())
2490            };
2491
2492            if generate
2493                .await
2494                .context("failed to generate thread title")
2495                .log_err()
2496                .is_some()
2497            {
2498                _ = this.update(cx, |this, cx| this.set_title(title.into(), cx));
2499            }
2500            _ = this.update(cx, |this, _| this.pending_title_generation = None);
2501        }));
2502    }
2503
2504    pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
2505        self.pending_title_generation = None;
2506        if Some(&title) != self.title.as_ref() {
2507            self.title = Some(title);
2508            cx.emit(TitleUpdated);
2509            cx.notify();
2510        }
2511    }
2512
2513    fn clear_summary(&mut self) {
2514        self.summary = None;
2515        self.pending_summary_generation = None;
2516    }
2517
2518    fn last_user_message(&self) -> Option<&UserMessage> {
2519        self.messages
2520            .iter()
2521            .rev()
2522            .find_map(|message| match message {
2523                Message::User(user_message) => Some(user_message),
2524                Message::Agent(_) => None,
2525                Message::Resume => None,
2526            })
2527    }
2528
2529    fn pending_message(&mut self) -> &mut AgentMessage {
2530        self.pending_message.get_or_insert_default()
2531    }
2532
2533    fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
2534        let Some(mut message) = self.pending_message.take() else {
2535            return;
2536        };
2537
2538        if message.content.is_empty() {
2539            return;
2540        }
2541
2542        for content in &message.content {
2543            let AgentMessageContent::ToolUse(tool_use) = content else {
2544                continue;
2545            };
2546
2547            if !message.tool_results.contains_key(&tool_use.id) {
2548                message.tool_results.insert(
2549                    tool_use.id.clone(),
2550                    LanguageModelToolResult {
2551                        tool_use_id: tool_use.id.clone(),
2552                        tool_name: tool_use.name.clone(),
2553                        is_error: true,
2554                        content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
2555                        output: None,
2556                    },
2557                );
2558            }
2559        }
2560
2561        self.messages.push(Message::Agent(message));
2562        self.updated_at = Utc::now();
2563        self.clear_summary();
2564        cx.notify()
2565    }
2566
2567    pub(crate) fn build_completion_request(
2568        &self,
2569        completion_intent: CompletionIntent,
2570        cx: &App,
2571    ) -> Result<LanguageModelRequest> {
2572        let model = self.model().context("No language model configured")?;
2573        let tools = if let Some(turn) = self.running_turn.as_ref() {
2574            turn.tools
2575                .iter()
2576                .filter_map(|(tool_name, tool)| {
2577                    log::trace!("Including tool: {}", tool_name);
2578                    Some(LanguageModelRequestTool {
2579                        name: tool_name.to_string(),
2580                        description: tool.description().to_string(),
2581                        input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
2582                        use_input_streaming: tool.supports_input_streaming(),
2583                    })
2584                })
2585                .collect::<Vec<_>>()
2586        } else {
2587            Vec::new()
2588        };
2589
2590        log::debug!("Building completion request");
2591        log::debug!("Completion intent: {:?}", completion_intent);
2592
2593        let available_tools: Vec<_> = self
2594            .running_turn
2595            .as_ref()
2596            .map(|turn| turn.tools.keys().cloned().collect())
2597            .unwrap_or_default();
2598
2599        log::debug!("Request includes {} tools", available_tools.len());
2600        let messages = self.build_request_messages(available_tools, cx);
2601        log::debug!("Request will include {} messages", messages.len());
2602
2603        let request = LanguageModelRequest {
2604            thread_id: Some(self.id.to_string()),
2605            prompt_id: Some(self.prompt_id.to_string()),
2606            intent: Some(completion_intent),
2607            messages,
2608            tools,
2609            tool_choice: None,
2610            stop: Vec::new(),
2611            temperature: AgentSettings::temperature_for_model(model, cx),
2612            thinking_allowed: self.thinking_enabled,
2613            thinking_effort: self.thinking_effort.clone(),
2614            speed: self.speed(),
2615        };
2616
2617        log::debug!("Completion request built successfully");
2618        Ok(request)
2619    }
2620
2621    fn enabled_tools(
2622        &self,
2623        profile: &AgentProfileSettings,
2624        model: &Arc<dyn LanguageModel>,
2625        cx: &App,
2626    ) -> BTreeMap<SharedString, Arc<dyn AnyAgentTool>> {
2627        fn truncate(tool_name: &SharedString) -> SharedString {
2628            if tool_name.len() > MAX_TOOL_NAME_LENGTH {
2629                let mut truncated = tool_name.to_string();
2630                truncated.truncate(MAX_TOOL_NAME_LENGTH);
2631                truncated.into()
2632            } else {
2633                tool_name.clone()
2634            }
2635        }
2636
2637        let use_streaming_edit_tool =
2638            cx.has_flag::<StreamingEditFileToolFeatureFlag>() && model.supports_streaming_tools();
2639
2640        let mut tools = self
2641            .tools
2642            .iter()
2643            .filter_map(|(tool_name, tool)| {
2644                // For streaming_edit_file, check profile against "edit_file" since that's what users configure
2645                let profile_tool_name = if tool_name == StreamingEditFileTool::NAME {
2646                    EditFileTool::NAME
2647                } else {
2648                    tool_name.as_ref()
2649                };
2650
2651                if tool.supports_provider(&model.provider_id())
2652                    && profile.is_tool_enabled(profile_tool_name)
2653                {
2654                    match (tool_name.as_ref(), use_streaming_edit_tool) {
2655                        (StreamingEditFileTool::NAME, false) | (EditFileTool::NAME, true) => None,
2656                        (StreamingEditFileTool::NAME, true) => {
2657                            // Expose streaming tool as "edit_file"
2658                            Some((SharedString::from(EditFileTool::NAME), tool.clone()))
2659                        }
2660                        _ => Some((truncate(tool_name), tool.clone())),
2661                    }
2662                } else {
2663                    None
2664                }
2665            })
2666            .collect::<BTreeMap<_, _>>();
2667
2668        let mut context_server_tools = Vec::new();
2669        let mut seen_tools = tools.keys().cloned().collect::<HashSet<_>>();
2670        let mut duplicate_tool_names = HashSet::default();
2671        for (server_id, server_tools) in self.context_server_registry.read(cx).servers() {
2672            for (tool_name, tool) in server_tools {
2673                if profile.is_context_server_tool_enabled(&server_id.0, &tool_name) {
2674                    let tool_name = truncate(tool_name);
2675                    if !seen_tools.insert(tool_name.clone()) {
2676                        duplicate_tool_names.insert(tool_name.clone());
2677                    }
2678                    context_server_tools.push((server_id.clone(), tool_name, tool.clone()));
2679                }
2680            }
2681        }
2682
2683        // When there are duplicate tool names, disambiguate by prefixing them
2684        // with the server ID (converted to snake_case for API compatibility).
2685        // In the rare case there isn't enough space for the disambiguated tool
2686        // name, keep only the last tool with this name.
2687        for (server_id, tool_name, tool) in context_server_tools {
2688            if duplicate_tool_names.contains(&tool_name) {
2689                let available = MAX_TOOL_NAME_LENGTH.saturating_sub(tool_name.len());
2690                if available >= 2 {
2691                    let mut disambiguated = server_id.0.to_snake_case();
2692                    disambiguated.truncate(available - 1);
2693                    disambiguated.push('_');
2694                    disambiguated.push_str(&tool_name);
2695                    tools.insert(disambiguated.into(), tool.clone());
2696                } else {
2697                    tools.insert(tool_name, tool.clone());
2698                }
2699            } else {
2700                tools.insert(tool_name, tool.clone());
2701            }
2702        }
2703
2704        tools
2705    }
2706
2707    fn tool(&self, name: &str) -> Option<Arc<dyn AnyAgentTool>> {
2708        self.running_turn.as_ref()?.tools.get(name).cloned()
2709    }
2710
2711    pub fn has_tool(&self, name: &str) -> bool {
2712        self.running_turn
2713            .as_ref()
2714            .is_some_and(|turn| turn.tools.contains_key(name))
2715    }
2716
2717    #[cfg(any(test, feature = "test-support"))]
2718    pub fn has_registered_tool(&self, name: &str) -> bool {
2719        self.tools.contains_key(name)
2720    }
2721
2722    pub fn registered_tool_names(&self) -> Vec<SharedString> {
2723        self.tools.keys().cloned().collect()
2724    }
2725
2726    pub(crate) fn register_running_subagent(&mut self, subagent: WeakEntity<Thread>) {
2727        self.running_subagents.push(subagent);
2728    }
2729
2730    pub(crate) fn unregister_running_subagent(
2731        &mut self,
2732        subagent_session_id: &acp::SessionId,
2733        cx: &App,
2734    ) {
2735        self.running_subagents.retain(|s| {
2736            s.upgrade()
2737                .map_or(false, |s| s.read(cx).id() != subagent_session_id)
2738        });
2739    }
2740
2741    #[cfg(any(test, feature = "test-support"))]
2742    pub fn running_subagent_ids(&self, cx: &App) -> Vec<acp::SessionId> {
2743        self.running_subagents
2744            .iter()
2745            .filter_map(|s| s.upgrade().map(|s| s.read(cx).id().clone()))
2746            .collect()
2747    }
2748
2749    pub fn is_subagent(&self) -> bool {
2750        self.subagent_context.is_some()
2751    }
2752
2753    pub fn parent_thread_id(&self) -> Option<acp::SessionId> {
2754        self.subagent_context
2755            .as_ref()
2756            .map(|c| c.parent_thread_id.clone())
2757    }
2758
2759    pub fn depth(&self) -> u8 {
2760        self.subagent_context.as_ref().map(|c| c.depth).unwrap_or(0)
2761    }
2762
2763    #[cfg(any(test, feature = "test-support"))]
2764    pub fn set_subagent_context(&mut self, context: SubagentContext) {
2765        self.subagent_context = Some(context);
2766    }
2767
2768    pub fn is_turn_complete(&self) -> bool {
2769        self.running_turn.is_none()
2770    }
2771
2772    fn build_request_messages(
2773        &self,
2774        available_tools: Vec<SharedString>,
2775        cx: &App,
2776    ) -> Vec<LanguageModelRequestMessage> {
2777        log::trace!(
2778            "Building request messages from {} thread messages",
2779            self.messages.len()
2780        );
2781
2782        let system_prompt = SystemPromptTemplate {
2783            project: self.project_context.read(cx),
2784            available_tools,
2785            model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
2786        }
2787        .render(&self.templates)
2788        .context("failed to build system prompt")
2789        .expect("Invalid template");
2790        let mut messages = vec![LanguageModelRequestMessage {
2791            role: Role::System,
2792            content: vec![system_prompt.into()],
2793            cache: false,
2794            reasoning_details: None,
2795        }];
2796        for message in &self.messages {
2797            messages.extend(message.to_request());
2798        }
2799
2800        if let Some(last_message) = messages.last_mut() {
2801            last_message.cache = true;
2802        }
2803
2804        if let Some(message) = self.pending_message.as_ref() {
2805            messages.extend(message.to_request());
2806        }
2807
2808        messages
2809    }
2810
2811    pub fn to_markdown(&self) -> String {
2812        let mut markdown = String::new();
2813        for (ix, message) in self.messages.iter().enumerate() {
2814            if ix > 0 {
2815                markdown.push('\n');
2816            }
2817            match message {
2818                Message::User(_) => markdown.push_str("## User\n\n"),
2819                Message::Agent(_) => markdown.push_str("## Assistant\n\n"),
2820                Message::Resume => {}
2821            }
2822            markdown.push_str(&message.to_markdown());
2823        }
2824
2825        if let Some(message) = self.pending_message.as_ref() {
2826            markdown.push_str("\n## Assistant\n\n");
2827            markdown.push_str(&message.to_markdown());
2828        }
2829
2830        markdown
2831    }
2832
2833    fn advance_prompt_id(&mut self) {
2834        self.prompt_id = PromptId::new();
2835    }
2836
2837    fn retry_strategy_for(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
2838        use LanguageModelCompletionError::*;
2839        use http_client::StatusCode;
2840
2841        // General strategy here:
2842        // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
2843        // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), retry up to 4 times with exponential backoff.
2844        // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), retry up to 3 times.
2845        match error {
2846            HttpResponseError {
2847                status_code: StatusCode::TOO_MANY_REQUESTS,
2848                ..
2849            } => Some(RetryStrategy::ExponentialBackoff {
2850                initial_delay: BASE_RETRY_DELAY,
2851                max_attempts: MAX_RETRY_ATTEMPTS,
2852            }),
2853            ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
2854                Some(RetryStrategy::Fixed {
2855                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2856                    max_attempts: MAX_RETRY_ATTEMPTS,
2857                })
2858            }
2859            UpstreamProviderError {
2860                status,
2861                retry_after,
2862                ..
2863            } => match *status {
2864                StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
2865                    Some(RetryStrategy::Fixed {
2866                        delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2867                        max_attempts: MAX_RETRY_ATTEMPTS,
2868                    })
2869                }
2870                StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
2871                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2872                    // Internal Server Error could be anything, retry up to 3 times.
2873                    max_attempts: 3,
2874                }),
2875                status => {
2876                    // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
2877                    // but we frequently get them in practice. See https://http.dev/529
2878                    if status.as_u16() == 529 {
2879                        Some(RetryStrategy::Fixed {
2880                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2881                            max_attempts: MAX_RETRY_ATTEMPTS,
2882                        })
2883                    } else {
2884                        Some(RetryStrategy::Fixed {
2885                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2886                            max_attempts: 2,
2887                        })
2888                    }
2889                }
2890            },
2891            ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
2892                delay: BASE_RETRY_DELAY,
2893                max_attempts: 3,
2894            }),
2895            ApiReadResponseError { .. }
2896            | HttpSend { .. }
2897            | DeserializeResponse { .. }
2898            | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
2899                delay: BASE_RETRY_DELAY,
2900                max_attempts: 3,
2901            }),
2902            // Retrying these errors definitely shouldn't help.
2903            HttpResponseError {
2904                status_code:
2905                    StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
2906                ..
2907            }
2908            | AuthenticationError { .. }
2909            | PermissionError { .. }
2910            | NoApiKey { .. }
2911            | ApiEndpointNotFound { .. }
2912            | PromptTooLarge { .. } => None,
2913            // These errors might be transient, so retry them
2914            SerializeRequest { .. } | BuildRequestBody { .. } | StreamEndedUnexpectedly { .. } => {
2915                Some(RetryStrategy::Fixed {
2916                    delay: BASE_RETRY_DELAY,
2917                    max_attempts: 1,
2918                })
2919            }
2920            // Retry all other 4xx and 5xx errors once.
2921            HttpResponseError { status_code, .. }
2922                if status_code.is_client_error() || status_code.is_server_error() =>
2923            {
2924                Some(RetryStrategy::Fixed {
2925                    delay: BASE_RETRY_DELAY,
2926                    max_attempts: 3,
2927                })
2928            }
2929            Other(err) if err.is::<language_model::PaymentRequiredError>() => {
2930                // Retrying won't help for Payment Required errors.
2931                None
2932            }
2933            // Conservatively assume that any other errors are non-retryable
2934            HttpResponseError { .. } | Other(..) => Some(RetryStrategy::Fixed {
2935                delay: BASE_RETRY_DELAY,
2936                max_attempts: 2,
2937            }),
2938        }
2939    }
2940}
2941
2942struct RunningTurn {
2943    /// Holds the task that handles agent interaction until the end of the turn.
2944    /// Survives across multiple requests as the model performs tool calls and
2945    /// we run tools, report their results.
2946    _task: Task<()>,
2947    /// The current event stream for the running turn. Used to report a final
2948    /// cancellation event if we cancel the turn.
2949    event_stream: ThreadEventStream,
2950    /// The tools that were enabled for this turn.
2951    tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
2952    /// Sender to signal tool cancellation. When cancel is called, this is
2953    /// set to true so all tools can detect user-initiated cancellation.
2954    cancellation_tx: watch::Sender<bool>,
2955    /// Senders for tools that support input streaming and have already been
2956    /// started but are still receiving input from the LLM.
2957    streaming_tool_inputs: HashMap<LanguageModelToolUseId, ToolInputSender>,
2958}
2959
2960impl RunningTurn {
2961    fn cancel(mut self) -> Task<()> {
2962        log::debug!("Cancelling in progress turn");
2963        self.cancellation_tx.send(true).ok();
2964        self.event_stream.send_canceled();
2965        self._task
2966    }
2967}
2968
2969pub struct TokenUsageUpdated(pub Option<acp_thread::TokenUsage>);
2970
2971impl EventEmitter<TokenUsageUpdated> for Thread {}
2972
2973pub struct TitleUpdated;
2974
2975impl EventEmitter<TitleUpdated> for Thread {}
2976
2977/// A channel-based wrapper that delivers tool input to a running tool.
2978///
2979/// For non-streaming tools, created via `ToolInput::ready()` so `.recv()` resolves immediately.
2980/// For streaming tools, partial JSON snapshots arrive via `.recv_partial()` as the LLM streams
2981/// them, followed by the final complete input available through `.recv()`.
2982pub struct ToolInput<T> {
2983    partial_rx: mpsc::UnboundedReceiver<serde_json::Value>,
2984    final_rx: oneshot::Receiver<serde_json::Value>,
2985    _phantom: PhantomData<T>,
2986}
2987
2988impl<T: DeserializeOwned> ToolInput<T> {
2989    #[cfg(any(test, feature = "test-support"))]
2990    pub fn resolved(input: impl Serialize) -> Self {
2991        let value = serde_json::to_value(input).expect("failed to serialize tool input");
2992        Self::ready(value)
2993    }
2994
2995    pub fn ready(value: serde_json::Value) -> Self {
2996        let (partial_tx, partial_rx) = mpsc::unbounded();
2997        drop(partial_tx);
2998        let (final_tx, final_rx) = oneshot::channel();
2999        final_tx.send(value).ok();
3000        Self {
3001            partial_rx,
3002            final_rx,
3003            _phantom: PhantomData,
3004        }
3005    }
3006
3007    #[cfg(any(test, feature = "test-support"))]
3008    pub fn test() -> (ToolInputSender, Self) {
3009        let (sender, input) = ToolInputSender::channel();
3010        (sender, input.cast())
3011    }
3012
3013    /// Wait for the final deserialized input, ignoring all partial updates.
3014    /// Non-streaming tools can use this to wait until the whole input is available.
3015    pub async fn recv(mut self) -> Result<T> {
3016        // Drain any remaining partials
3017        while self.partial_rx.next().await.is_some() {}
3018        let value = self
3019            .final_rx
3020            .await
3021            .map_err(|_| anyhow!("tool input sender was dropped before sending final input"))?;
3022        serde_json::from_value(value).map_err(Into::into)
3023    }
3024
3025    /// Returns the next partial JSON snapshot, or `None` when input is complete.
3026    /// Once this returns `None`, call `recv()` to get the final input.
3027    pub async fn recv_partial(&mut self) -> Option<serde_json::Value> {
3028        self.partial_rx.next().await
3029    }
3030
3031    fn cast<U: DeserializeOwned>(self) -> ToolInput<U> {
3032        ToolInput {
3033            partial_rx: self.partial_rx,
3034            final_rx: self.final_rx,
3035            _phantom: PhantomData,
3036        }
3037    }
3038}
3039
3040pub struct ToolInputSender {
3041    partial_tx: mpsc::UnboundedSender<serde_json::Value>,
3042    final_tx: Option<oneshot::Sender<serde_json::Value>>,
3043}
3044
3045impl ToolInputSender {
3046    pub(crate) fn channel() -> (Self, ToolInput<serde_json::Value>) {
3047        let (partial_tx, partial_rx) = mpsc::unbounded();
3048        let (final_tx, final_rx) = oneshot::channel();
3049        let sender = Self {
3050            partial_tx,
3051            final_tx: Some(final_tx),
3052        };
3053        let input = ToolInput {
3054            partial_rx,
3055            final_rx,
3056            _phantom: PhantomData,
3057        };
3058        (sender, input)
3059    }
3060
3061    pub(crate) fn send_partial(&self, value: serde_json::Value) {
3062        self.partial_tx.unbounded_send(value).ok();
3063    }
3064
3065    pub(crate) fn send_final(mut self, value: serde_json::Value) {
3066        // Close the partial channel so recv_partial() returns None
3067        self.partial_tx.close_channel();
3068        if let Some(final_tx) = self.final_tx.take() {
3069            final_tx.send(value).ok();
3070        }
3071    }
3072}
3073
3074pub trait AgentTool
3075where
3076    Self: 'static + Sized,
3077{
3078    type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
3079    type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
3080
3081    const NAME: &'static str;
3082
3083    fn description() -> SharedString {
3084        let schema = schemars::schema_for!(Self::Input);
3085        SharedString::new(
3086            schema
3087                .get("description")
3088                .and_then(|description| description.as_str())
3089                .unwrap_or_default(),
3090        )
3091    }
3092
3093    fn kind() -> acp::ToolKind;
3094
3095    /// The initial tool title to display. Can be updated during the tool run.
3096    fn initial_title(
3097        &self,
3098        input: Result<Self::Input, serde_json::Value>,
3099        cx: &mut App,
3100    ) -> SharedString;
3101
3102    /// Returns the JSON schema that describes the tool's input.
3103    fn input_schema(format: LanguageModelToolSchemaFormat) -> Schema {
3104        language_model::tool_schema::root_schema_for::<Self::Input>(format)
3105    }
3106
3107    /// Returns whether the tool supports streaming of tool use parameters.
3108    fn supports_input_streaming() -> bool {
3109        false
3110    }
3111
3112    /// Some tools rely on a provider for the underlying billing or other reasons.
3113    /// Allow the tool to check if they are compatible, or should be filtered out.
3114    fn supports_provider(_provider: &LanguageModelProviderId) -> bool {
3115        true
3116    }
3117
3118    /// Runs the tool with the provided input.
3119    ///
3120    /// Returns `Result<Self::Output, Self::Output>` rather than `Result<Self::Output, anyhow::Error>`
3121    /// because tool errors are sent back to the model as tool results. This means error output must
3122    /// be structured and readable by the agent — not an arbitrary `anyhow::Error`. Returning the
3123    /// same `Output` type for both success and failure lets tools provide structured data while
3124    /// still signaling whether the invocation succeeded or failed.
3125    fn run(
3126        self: Arc<Self>,
3127        input: ToolInput<Self::Input>,
3128        event_stream: ToolCallEventStream,
3129        cx: &mut App,
3130    ) -> Task<Result<Self::Output, Self::Output>>;
3131
3132    /// Emits events for a previous execution of the tool.
3133    fn replay(
3134        &self,
3135        _input: Self::Input,
3136        _output: Self::Output,
3137        _event_stream: ToolCallEventStream,
3138        _cx: &mut App,
3139    ) -> Result<()> {
3140        Ok(())
3141    }
3142
3143    fn erase(self) -> Arc<dyn AnyAgentTool> {
3144        Arc::new(Erased(Arc::new(self)))
3145    }
3146}
3147
3148pub struct Erased<T>(T);
3149
3150pub struct AgentToolOutput {
3151    pub llm_output: LanguageModelToolResultContent,
3152    pub raw_output: serde_json::Value,
3153}
3154
3155impl AgentToolOutput {
3156    pub fn from_error(message: impl Into<String>) -> Self {
3157        let message = message.into();
3158        let llm_output = LanguageModelToolResultContent::Text(Arc::from(message.as_str()));
3159        Self {
3160            raw_output: serde_json::Value::String(message),
3161            llm_output,
3162        }
3163    }
3164}
3165
3166pub trait AnyAgentTool {
3167    fn name(&self) -> SharedString;
3168    fn description(&self) -> SharedString;
3169    fn kind(&self) -> acp::ToolKind;
3170    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString;
3171    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
3172    fn supports_input_streaming(&self) -> bool {
3173        false
3174    }
3175    fn supports_provider(&self, _provider: &LanguageModelProviderId) -> bool {
3176        true
3177    }
3178    /// See [`AgentTool::run`] for why this returns `Result<AgentToolOutput, AgentToolOutput>`.
3179    fn run(
3180        self: Arc<Self>,
3181        input: ToolInput<serde_json::Value>,
3182        event_stream: ToolCallEventStream,
3183        cx: &mut App,
3184    ) -> Task<Result<AgentToolOutput, AgentToolOutput>>;
3185    fn replay(
3186        &self,
3187        input: serde_json::Value,
3188        output: serde_json::Value,
3189        event_stream: ToolCallEventStream,
3190        cx: &mut App,
3191    ) -> Result<()>;
3192}
3193
3194impl<T> AnyAgentTool for Erased<Arc<T>>
3195where
3196    T: AgentTool,
3197{
3198    fn name(&self) -> SharedString {
3199        T::NAME.into()
3200    }
3201
3202    fn description(&self) -> SharedString {
3203        T::description()
3204    }
3205
3206    fn kind(&self) -> agent_client_protocol::ToolKind {
3207        T::kind()
3208    }
3209
3210    fn supports_input_streaming(&self) -> bool {
3211        T::supports_input_streaming()
3212    }
3213
3214    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString {
3215        let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
3216        self.0.initial_title(parsed_input, _cx)
3217    }
3218
3219    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
3220        let mut json = serde_json::to_value(T::input_schema(format))?;
3221        language_model::tool_schema::adapt_schema_to_format(&mut json, format)?;
3222        Ok(json)
3223    }
3224
3225    fn supports_provider(&self, provider: &LanguageModelProviderId) -> bool {
3226        T::supports_provider(provider)
3227    }
3228
3229    fn run(
3230        self: Arc<Self>,
3231        input: ToolInput<serde_json::Value>,
3232        event_stream: ToolCallEventStream,
3233        cx: &mut App,
3234    ) -> Task<Result<AgentToolOutput, AgentToolOutput>> {
3235        let tool_input: ToolInput<T::Input> = input.cast();
3236        let task = self.0.clone().run(tool_input, event_stream, cx);
3237        cx.spawn(async move |_cx| match task.await {
3238            Ok(output) => {
3239                let raw_output = serde_json::to_value(&output).map_err(|e| {
3240                    AgentToolOutput::from_error(format!("Failed to serialize tool output: {e}"))
3241                })?;
3242                Ok(AgentToolOutput {
3243                    llm_output: output.into(),
3244                    raw_output,
3245                })
3246            }
3247            Err(error_output) => {
3248                let raw_output = serde_json::to_value(&error_output).unwrap_or_else(|e| {
3249                    log::error!("Failed to serialize tool error output: {e}");
3250                    serde_json::Value::Null
3251                });
3252                Err(AgentToolOutput {
3253                    llm_output: error_output.into(),
3254                    raw_output,
3255                })
3256            }
3257        })
3258    }
3259
3260    fn replay(
3261        &self,
3262        input: serde_json::Value,
3263        output: serde_json::Value,
3264        event_stream: ToolCallEventStream,
3265        cx: &mut App,
3266    ) -> Result<()> {
3267        let input = serde_json::from_value(input)?;
3268        let output = serde_json::from_value(output)?;
3269        self.0.replay(input, output, event_stream, cx)
3270    }
3271}
3272
3273#[derive(Clone)]
3274struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
3275
3276impl ThreadEventStream {
3277    fn send_user_message(&self, message: &UserMessage) {
3278        self.0
3279            .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
3280            .ok();
3281    }
3282
3283    fn send_text(&self, text: &str) {
3284        self.0
3285            .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
3286            .ok();
3287    }
3288
3289    fn send_thinking(&self, text: &str) {
3290        self.0
3291            .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
3292            .ok();
3293    }
3294
3295    fn send_tool_call(
3296        &self,
3297        id: &LanguageModelToolUseId,
3298        tool_name: &str,
3299        title: SharedString,
3300        kind: acp::ToolKind,
3301        input: serde_json::Value,
3302    ) {
3303        self.0
3304            .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
3305                id,
3306                tool_name,
3307                title.to_string(),
3308                kind,
3309                input,
3310            ))))
3311            .ok();
3312    }
3313
3314    fn initial_tool_call(
3315        id: &LanguageModelToolUseId,
3316        tool_name: &str,
3317        title: String,
3318        kind: acp::ToolKind,
3319        input: serde_json::Value,
3320    ) -> acp::ToolCall {
3321        acp::ToolCall::new(id.to_string(), title)
3322            .kind(kind)
3323            .raw_input(input)
3324            .meta(acp_thread::meta_with_tool_name(tool_name))
3325    }
3326
3327    fn update_tool_call_fields(
3328        &self,
3329        tool_use_id: &LanguageModelToolUseId,
3330        fields: acp::ToolCallUpdateFields,
3331        meta: Option<acp::Meta>,
3332    ) {
3333        self.0
3334            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3335                acp::ToolCallUpdate::new(tool_use_id.to_string(), fields)
3336                    .meta(meta)
3337                    .into(),
3338            )))
3339            .ok();
3340    }
3341
3342    fn send_retry(&self, status: acp_thread::RetryStatus) {
3343        self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();
3344    }
3345
3346    fn send_stop(&self, reason: acp::StopReason) {
3347        self.0.unbounded_send(Ok(ThreadEvent::Stop(reason))).ok();
3348    }
3349
3350    fn send_canceled(&self) {
3351        self.0
3352            .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
3353            .ok();
3354    }
3355
3356    fn send_error(&self, error: impl Into<anyhow::Error>) {
3357        self.0.unbounded_send(Err(error.into())).ok();
3358    }
3359}
3360
3361#[derive(Clone)]
3362pub struct ToolCallEventStream {
3363    tool_use_id: LanguageModelToolUseId,
3364    stream: ThreadEventStream,
3365    fs: Option<Arc<dyn Fs>>,
3366    cancellation_rx: watch::Receiver<bool>,
3367}
3368
3369impl ToolCallEventStream {
3370    #[cfg(any(test, feature = "test-support"))]
3371    pub fn test() -> (Self, ToolCallEventStreamReceiver) {
3372        let (stream, receiver, _cancellation_tx) = Self::test_with_cancellation();
3373        (stream, receiver)
3374    }
3375
3376    #[cfg(any(test, feature = "test-support"))]
3377    pub fn test_with_cancellation() -> (Self, ToolCallEventStreamReceiver, watch::Sender<bool>) {
3378        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
3379        let (cancellation_tx, cancellation_rx) = watch::channel(false);
3380
3381        let stream = ToolCallEventStream::new(
3382            "test_id".into(),
3383            ThreadEventStream(events_tx),
3384            None,
3385            cancellation_rx,
3386        );
3387
3388        (
3389            stream,
3390            ToolCallEventStreamReceiver(events_rx),
3391            cancellation_tx,
3392        )
3393    }
3394
3395    /// Signal cancellation for this event stream. Only available in tests.
3396    #[cfg(any(test, feature = "test-support"))]
3397    pub fn signal_cancellation_with_sender(cancellation_tx: &mut watch::Sender<bool>) {
3398        cancellation_tx.send(true).ok();
3399    }
3400
3401    fn new(
3402        tool_use_id: LanguageModelToolUseId,
3403        stream: ThreadEventStream,
3404        fs: Option<Arc<dyn Fs>>,
3405        cancellation_rx: watch::Receiver<bool>,
3406    ) -> Self {
3407        Self {
3408            tool_use_id,
3409            stream,
3410            fs,
3411            cancellation_rx,
3412        }
3413    }
3414
3415    /// Returns a future that resolves when the user cancels the tool call.
3416    /// Tools should select on this alongside their main work to detect user cancellation.
3417    pub fn cancelled_by_user(&self) -> impl std::future::Future<Output = ()> + '_ {
3418        let mut rx = self.cancellation_rx.clone();
3419        async move {
3420            loop {
3421                if *rx.borrow() {
3422                    return;
3423                }
3424                if rx.changed().await.is_err() {
3425                    // Sender dropped, will never be cancelled
3426                    std::future::pending::<()>().await;
3427                }
3428            }
3429        }
3430    }
3431
3432    /// Returns true if the user has cancelled this tool call.
3433    /// This is useful for checking cancellation state after an operation completes,
3434    /// to determine if the completion was due to user cancellation.
3435    pub fn was_cancelled_by_user(&self) -> bool {
3436        *self.cancellation_rx.clone().borrow()
3437    }
3438
3439    pub fn tool_use_id(&self) -> &LanguageModelToolUseId {
3440        &self.tool_use_id
3441    }
3442
3443    pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
3444        self.stream
3445            .update_tool_call_fields(&self.tool_use_id, fields, None);
3446    }
3447
3448    pub fn update_fields_with_meta(
3449        &self,
3450        fields: acp::ToolCallUpdateFields,
3451        meta: Option<acp::Meta>,
3452    ) {
3453        self.stream
3454            .update_tool_call_fields(&self.tool_use_id, fields, meta);
3455    }
3456
3457    pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
3458        self.stream
3459            .0
3460            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3461                acp_thread::ToolCallUpdateDiff {
3462                    id: acp::ToolCallId::new(self.tool_use_id.to_string()),
3463                    diff,
3464                }
3465                .into(),
3466            )))
3467            .ok();
3468    }
3469
3470    pub fn subagent_spawned(&self, id: acp::SessionId) {
3471        self.stream
3472            .0
3473            .unbounded_send(Ok(ThreadEvent::SubagentSpawned(id)))
3474            .ok();
3475    }
3476
3477    /// Authorize a third-party tool (e.g., MCP tool from a context server).
3478    ///
3479    /// Unlike built-in tools, third-party tools don't support pattern-based permissions.
3480    /// They only support `default` (allow/deny/confirm) per tool.
3481    ///
3482    /// Uses the dropdown authorization flow with two granularities:
3483    /// - "Always for <display_name> MCP tool" → sets `tools.<tool_id>.default = "allow"` or "deny"
3484    /// - "Only this time" → allow/deny once
3485    pub fn authorize_third_party_tool(
3486        &self,
3487        title: impl Into<String>,
3488        tool_id: String,
3489        display_name: String,
3490        cx: &mut App,
3491    ) -> Task<Result<()>> {
3492        let settings = agent_settings::AgentSettings::get_global(cx);
3493
3494        let decision = decide_permission_from_settings(&tool_id, &[String::new()], &settings);
3495
3496        match decision {
3497            ToolPermissionDecision::Allow => return Task::ready(Ok(())),
3498            ToolPermissionDecision::Deny(reason) => return Task::ready(Err(anyhow!(reason))),
3499            ToolPermissionDecision::Confirm => {}
3500        }
3501
3502        let (response_tx, response_rx) = oneshot::channel();
3503        if let Err(error) = self
3504            .stream
3505            .0
3506            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3507                ToolCallAuthorization {
3508                    tool_call: acp::ToolCallUpdate::new(
3509                        self.tool_use_id.to_string(),
3510                        acp::ToolCallUpdateFields::new().title(title.into()),
3511                    ),
3512                    options: acp_thread::PermissionOptions::Dropdown(vec![
3513                        acp_thread::PermissionOptionChoice {
3514                            allow: acp::PermissionOption::new(
3515                                acp::PermissionOptionId::new(format!(
3516                                    "always_allow_mcp:{}",
3517                                    tool_id
3518                                )),
3519                                format!("Always for {} MCP tool", display_name),
3520                                acp::PermissionOptionKind::AllowAlways,
3521                            ),
3522                            deny: acp::PermissionOption::new(
3523                                acp::PermissionOptionId::new(format!(
3524                                    "always_deny_mcp:{}",
3525                                    tool_id
3526                                )),
3527                                format!("Always for {} MCP tool", display_name),
3528                                acp::PermissionOptionKind::RejectAlways,
3529                            ),
3530                        },
3531                        acp_thread::PermissionOptionChoice {
3532                            allow: acp::PermissionOption::new(
3533                                acp::PermissionOptionId::new("allow"),
3534                                "Only this time",
3535                                acp::PermissionOptionKind::AllowOnce,
3536                            ),
3537                            deny: acp::PermissionOption::new(
3538                                acp::PermissionOptionId::new("deny"),
3539                                "Only this time",
3540                                acp::PermissionOptionKind::RejectOnce,
3541                            ),
3542                        },
3543                    ]),
3544                    response: response_tx,
3545                    context: None,
3546                },
3547            )))
3548        {
3549            log::error!("Failed to send tool call authorization: {error}");
3550            return Task::ready(Err(anyhow!(
3551                "Failed to send tool call authorization: {error}"
3552            )));
3553        }
3554
3555        let fs = self.fs.clone();
3556        cx.spawn(async move |cx| {
3557            let response_str = response_rx.await?.0.to_string();
3558
3559            if response_str == format!("always_allow_mcp:{}", tool_id) {
3560                if let Some(fs) = fs.clone() {
3561                    cx.update(|cx| {
3562                        update_settings_file(fs, cx, move |settings, _| {
3563                            settings
3564                                .agent
3565                                .get_or_insert_default()
3566                                .set_tool_default_permission(&tool_id, ToolPermissionMode::Allow);
3567                        });
3568                    });
3569                }
3570                return Ok(());
3571            }
3572            if response_str == format!("always_deny_mcp:{}", tool_id) {
3573                if let Some(fs) = fs.clone() {
3574                    cx.update(|cx| {
3575                        update_settings_file(fs, cx, move |settings, _| {
3576                            settings
3577                                .agent
3578                                .get_or_insert_default()
3579                                .set_tool_default_permission(&tool_id, ToolPermissionMode::Deny);
3580                        });
3581                    });
3582                }
3583                return Err(anyhow!("Permission to run tool denied by user"));
3584            }
3585
3586            if response_str == "allow" {
3587                return Ok(());
3588            }
3589
3590            Err(anyhow!("Permission to run tool denied by user"))
3591        })
3592    }
3593
3594    pub fn authorize(
3595        &self,
3596        title: impl Into<String>,
3597        context: ToolPermissionContext,
3598        cx: &mut App,
3599    ) -> Task<Result<()>> {
3600        use settings::ToolPermissionMode;
3601
3602        let options = context.build_permission_options();
3603
3604        let (response_tx, response_rx) = oneshot::channel();
3605        if let Err(error) = self
3606            .stream
3607            .0
3608            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3609                ToolCallAuthorization {
3610                    tool_call: acp::ToolCallUpdate::new(
3611                        self.tool_use_id.to_string(),
3612                        acp::ToolCallUpdateFields::new().title(title.into()),
3613                    ),
3614                    options,
3615                    response: response_tx,
3616                    context: Some(context),
3617                },
3618            )))
3619        {
3620            log::error!("Failed to send tool call authorization: {error}");
3621            return Task::ready(Err(anyhow!(
3622                "Failed to send tool call authorization: {error}"
3623            )));
3624        }
3625
3626        let fs = self.fs.clone();
3627        cx.spawn(async move |cx| {
3628            let response_str = response_rx.await?.0.to_string();
3629
3630            // Handle "always allow tool" - e.g., "always_allow:terminal"
3631            if let Some(tool) = response_str.strip_prefix("always_allow:") {
3632                if let Some(fs) = fs.clone() {
3633                    let tool = tool.to_string();
3634                    cx.update(|cx| {
3635                        update_settings_file(fs, cx, move |settings, _| {
3636                            settings
3637                                .agent
3638                                .get_or_insert_default()
3639                                .set_tool_default_permission(&tool, ToolPermissionMode::Allow);
3640                        });
3641                    });
3642                }
3643                return Ok(());
3644            }
3645
3646            // Handle "always deny tool" - e.g., "always_deny:terminal"
3647            if let Some(tool) = response_str.strip_prefix("always_deny:") {
3648                if let Some(fs) = fs.clone() {
3649                    let tool = tool.to_string();
3650                    cx.update(|cx| {
3651                        update_settings_file(fs, cx, move |settings, _| {
3652                            settings
3653                                .agent
3654                                .get_or_insert_default()
3655                                .set_tool_default_permission(&tool, ToolPermissionMode::Deny);
3656                        });
3657                    });
3658                }
3659                return Err(anyhow!("Permission to run tool denied by user"));
3660            }
3661
3662            // Handle "always allow pattern" - e.g., "always_allow_pattern:mcp:server:tool\n^cargo\s"
3663            if let Some(rest) = response_str.strip_prefix("always_allow_pattern:") {
3664                if let Some((pattern_tool_name, pattern)) = rest.split_once('\n') {
3665                    let pattern_tool_name = pattern_tool_name.to_string();
3666                    let pattern = pattern.to_string();
3667                    if let Some(fs) = fs.clone() {
3668                        cx.update(|cx| {
3669                            update_settings_file(fs, cx, move |settings, _| {
3670                                settings
3671                                    .agent
3672                                    .get_or_insert_default()
3673                                    .add_tool_allow_pattern(&pattern_tool_name, pattern);
3674                            });
3675                        });
3676                    }
3677                } else {
3678                    log::error!("Failed to parse always allow pattern: missing newline separator in '{rest}'");
3679                }
3680                return Ok(());
3681            }
3682
3683            // Handle "always deny pattern" - e.g., "always_deny_pattern:mcp:server:tool\n^cargo\s"
3684            if let Some(rest) = response_str.strip_prefix("always_deny_pattern:") {
3685                if let Some((pattern_tool_name, pattern)) = rest.split_once('\n') {
3686                    let pattern_tool_name = pattern_tool_name.to_string();
3687                    let pattern = pattern.to_string();
3688                    if let Some(fs) = fs.clone() {
3689                        cx.update(|cx| {
3690                            update_settings_file(fs, cx, move |settings, _| {
3691                                settings
3692                                    .agent
3693                                    .get_or_insert_default()
3694                                    .add_tool_deny_pattern(&pattern_tool_name, pattern);
3695                            });
3696                        });
3697                    }
3698                } else {
3699                    log::error!("Failed to parse always deny pattern: missing newline separator in '{rest}'");
3700                }
3701                return Err(anyhow!("Permission to run tool denied by user"));
3702            }
3703
3704            // Handle simple "allow" (allow once)
3705            if response_str == "allow" {
3706                return Ok(());
3707            }
3708
3709            // Handle simple "deny" (deny once)
3710            Err(anyhow!("Permission to run tool denied by user"))
3711        })
3712    }
3713}
3714
3715#[cfg(any(test, feature = "test-support"))]
3716pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
3717
3718#[cfg(any(test, feature = "test-support"))]
3719impl ToolCallEventStreamReceiver {
3720    pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
3721        let event = self.0.next().await;
3722        if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
3723            auth
3724        } else {
3725            panic!("Expected ToolCallAuthorization but got: {:?}", event);
3726        }
3727    }
3728
3729    pub async fn expect_update_fields(&mut self) -> acp::ToolCallUpdateFields {
3730        let event = self.0.next().await;
3731        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
3732            update,
3733        )))) = event
3734        {
3735            update.fields
3736        } else {
3737            panic!("Expected update fields but got: {:?}", event);
3738        }
3739    }
3740
3741    pub async fn expect_diff(&mut self) -> Entity<acp_thread::Diff> {
3742        let event = self.0.next().await;
3743        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateDiff(
3744            update,
3745        )))) = event
3746        {
3747            update.diff
3748        } else {
3749            panic!("Expected diff but got: {:?}", event);
3750        }
3751    }
3752
3753    pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
3754        let event = self.0.next().await;
3755        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
3756            update,
3757        )))) = event
3758        {
3759            update.terminal
3760        } else {
3761            panic!("Expected terminal but got: {:?}", event);
3762        }
3763    }
3764}
3765
3766#[cfg(any(test, feature = "test-support"))]
3767impl std::ops::Deref for ToolCallEventStreamReceiver {
3768    type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
3769
3770    fn deref(&self) -> &Self::Target {
3771        &self.0
3772    }
3773}
3774
3775#[cfg(any(test, feature = "test-support"))]
3776impl std::ops::DerefMut for ToolCallEventStreamReceiver {
3777    fn deref_mut(&mut self) -> &mut Self::Target {
3778        &mut self.0
3779    }
3780}
3781
3782impl From<&str> for UserMessageContent {
3783    fn from(text: &str) -> Self {
3784        Self::Text(text.into())
3785    }
3786}
3787
3788impl From<String> for UserMessageContent {
3789    fn from(text: String) -> Self {
3790        Self::Text(text)
3791    }
3792}
3793
3794impl UserMessageContent {
3795    pub fn from_content_block(value: acp::ContentBlock, path_style: PathStyle) -> Self {
3796        match value {
3797            acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
3798            acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
3799            acp::ContentBlock::Audio(_) => {
3800                // TODO
3801                Self::Text("[audio]".to_string())
3802            }
3803            acp::ContentBlock::ResourceLink(resource_link) => {
3804                match MentionUri::parse(&resource_link.uri, path_style) {
3805                    Ok(uri) => Self::Mention {
3806                        uri,
3807                        content: String::new(),
3808                    },
3809                    Err(err) => {
3810                        log::error!("Failed to parse mention link: {}", err);
3811                        Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
3812                    }
3813                }
3814            }
3815            acp::ContentBlock::Resource(resource) => match resource.resource {
3816                acp::EmbeddedResourceResource::TextResourceContents(resource) => {
3817                    match MentionUri::parse(&resource.uri, path_style) {
3818                        Ok(uri) => Self::Mention {
3819                            uri,
3820                            content: resource.text,
3821                        },
3822                        Err(err) => {
3823                            log::error!("Failed to parse mention link: {}", err);
3824                            Self::Text(
3825                                MarkdownCodeBlock {
3826                                    tag: &resource.uri,
3827                                    text: &resource.text,
3828                                }
3829                                .to_string(),
3830                            )
3831                        }
3832                    }
3833                }
3834                acp::EmbeddedResourceResource::BlobResourceContents(_) => {
3835                    // TODO
3836                    Self::Text("[blob]".to_string())
3837                }
3838                other => {
3839                    log::warn!("Unexpected content type: {:?}", other);
3840                    Self::Text("[unknown]".to_string())
3841                }
3842            },
3843            other => {
3844                log::warn!("Unexpected content type: {:?}", other);
3845                Self::Text("[unknown]".to_string())
3846            }
3847        }
3848    }
3849}
3850
3851impl From<UserMessageContent> for acp::ContentBlock {
3852    fn from(content: UserMessageContent) -> Self {
3853        match content {
3854            UserMessageContent::Text(text) => text.into(),
3855            UserMessageContent::Image(image) => {
3856                acp::ContentBlock::Image(acp::ImageContent::new(image.source, "image/png"))
3857            }
3858            UserMessageContent::Mention { uri, content } => acp::ContentBlock::Resource(
3859                acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(
3860                    acp::TextResourceContents::new(content, uri.to_uri().to_string()),
3861                )),
3862            ),
3863        }
3864    }
3865}
3866
3867fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
3868    LanguageModelImage {
3869        source: image_content.data.into(),
3870        size: None,
3871    }
3872}
3873
3874#[cfg(test)]
3875mod tests {
3876    use super::*;
3877    use gpui::TestAppContext;
3878    use language_model::LanguageModelToolUseId;
3879    use language_model::fake_provider::FakeLanguageModel;
3880    use serde_json::json;
3881    use std::sync::Arc;
3882
3883    async fn setup_thread_for_test(cx: &mut TestAppContext) -> (Entity<Thread>, ThreadEventStream) {
3884        cx.update(|cx| {
3885            let settings_store = settings::SettingsStore::test(cx);
3886            cx.set_global(settings_store);
3887        });
3888
3889        let fs = fs::FakeFs::new(cx.background_executor.clone());
3890        let templates = Templates::new();
3891        let project = Project::test(fs.clone(), [], cx).await;
3892
3893        cx.update(|cx| {
3894            let project_context = cx.new(|_cx| prompt_store::ProjectContext::default());
3895            let context_server_store = project.read(cx).context_server_store();
3896            let context_server_registry =
3897                cx.new(|cx| ContextServerRegistry::new(context_server_store, cx));
3898
3899            let thread = cx.new(|cx| {
3900                Thread::new(
3901                    project,
3902                    project_context,
3903                    context_server_registry,
3904                    templates,
3905                    None,
3906                    cx,
3907                )
3908            });
3909
3910            let (event_tx, _event_rx) = mpsc::unbounded();
3911            let event_stream = ThreadEventStream(event_tx);
3912
3913            (thread, event_stream)
3914        })
3915    }
3916
3917    fn setup_parent_with_subagents(
3918        cx: &mut TestAppContext,
3919        parent: &Entity<Thread>,
3920        count: usize,
3921    ) -> Vec<Entity<Thread>> {
3922        cx.update(|cx| {
3923            let mut subagents = Vec::new();
3924            for _ in 0..count {
3925                let subagent = cx.new(|cx| Thread::new_subagent(parent, cx));
3926                parent.update(cx, |thread, _cx| {
3927                    thread.register_running_subagent(subagent.downgrade());
3928                });
3929                subagents.push(subagent);
3930            }
3931            subagents
3932        })
3933    }
3934
3935    #[gpui::test]
3936    async fn test_set_model_propagates_to_subagents(cx: &mut TestAppContext) {
3937        let (parent, _event_stream) = setup_thread_for_test(cx).await;
3938        let subagents = setup_parent_with_subagents(cx, &parent, 2);
3939
3940        let new_model: Arc<dyn LanguageModel> = Arc::new(FakeLanguageModel::with_id_and_thinking(
3941            "test-provider",
3942            "new-model",
3943            "New Model",
3944            false,
3945        ));
3946
3947        cx.update(|cx| {
3948            parent.update(cx, |thread, cx| {
3949                thread.set_model(new_model, cx);
3950            });
3951
3952            for subagent in &subagents {
3953                let subagent_model_id = subagent.read(cx).model().unwrap().id();
3954                assert_eq!(
3955                    subagent_model_id.0.as_ref(),
3956                    "new-model",
3957                    "Subagent model should match parent model after set_model"
3958                );
3959            }
3960        });
3961    }
3962
3963    #[gpui::test]
3964    async fn test_set_summarization_model_propagates_to_subagents(cx: &mut TestAppContext) {
3965        let (parent, _event_stream) = setup_thread_for_test(cx).await;
3966        let subagents = setup_parent_with_subagents(cx, &parent, 2);
3967
3968        let summary_model: Arc<dyn LanguageModel> =
3969            Arc::new(FakeLanguageModel::with_id_and_thinking(
3970                "test-provider",
3971                "summary-model",
3972                "Summary Model",
3973                false,
3974            ));
3975
3976        cx.update(|cx| {
3977            parent.update(cx, |thread, cx| {
3978                thread.set_summarization_model(Some(summary_model), cx);
3979            });
3980
3981            for subagent in &subagents {
3982                let subagent_summary_id = subagent.read(cx).summarization_model().unwrap().id();
3983                assert_eq!(
3984                    subagent_summary_id.0.as_ref(),
3985                    "summary-model",
3986                    "Subagent summarization model should match parent after set_summarization_model"
3987                );
3988            }
3989        });
3990    }
3991
3992    #[gpui::test]
3993    async fn test_set_thinking_enabled_propagates_to_subagents(cx: &mut TestAppContext) {
3994        let (parent, _event_stream) = setup_thread_for_test(cx).await;
3995        let subagents = setup_parent_with_subagents(cx, &parent, 2);
3996
3997        cx.update(|cx| {
3998            parent.update(cx, |thread, cx| {
3999                thread.set_thinking_enabled(true, cx);
4000            });
4001
4002            for subagent in &subagents {
4003                assert!(
4004                    subagent.read(cx).thinking_enabled(),
4005                    "Subagent thinking should be enabled after parent enables it"
4006                );
4007            }
4008
4009            parent.update(cx, |thread, cx| {
4010                thread.set_thinking_enabled(false, cx);
4011            });
4012
4013            for subagent in &subagents {
4014                assert!(
4015                    !subagent.read(cx).thinking_enabled(),
4016                    "Subagent thinking should be disabled after parent disables it"
4017                );
4018            }
4019        });
4020    }
4021
4022    #[gpui::test]
4023    async fn test_set_thinking_effort_propagates_to_subagents(cx: &mut TestAppContext) {
4024        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4025        let subagents = setup_parent_with_subagents(cx, &parent, 2);
4026
4027        cx.update(|cx| {
4028            parent.update(cx, |thread, cx| {
4029                thread.set_thinking_effort(Some("high".to_string()), cx);
4030            });
4031
4032            for subagent in &subagents {
4033                assert_eq!(
4034                    subagent.read(cx).thinking_effort().map(|s| s.as_str()),
4035                    Some("high"),
4036                    "Subagent thinking effort should match parent"
4037                );
4038            }
4039
4040            parent.update(cx, |thread, cx| {
4041                thread.set_thinking_effort(None, cx);
4042            });
4043
4044            for subagent in &subagents {
4045                assert_eq!(
4046                    subagent.read(cx).thinking_effort(),
4047                    None,
4048                    "Subagent thinking effort should be None after parent clears it"
4049                );
4050            }
4051        });
4052    }
4053
4054    #[gpui::test]
4055    async fn test_set_speed_propagates_to_subagents(cx: &mut TestAppContext) {
4056        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4057        let subagents = setup_parent_with_subagents(cx, &parent, 2);
4058
4059        cx.update(|cx| {
4060            parent.update(cx, |thread, cx| {
4061                thread.set_speed(Speed::Fast, cx);
4062            });
4063
4064            for subagent in &subagents {
4065                assert_eq!(
4066                    subagent.read(cx).speed(),
4067                    Some(Speed::Fast),
4068                    "Subagent speed should match parent after set_speed"
4069                );
4070            }
4071        });
4072    }
4073
4074    #[gpui::test]
4075    async fn test_dropped_subagent_does_not_panic(cx: &mut TestAppContext) {
4076        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4077        let subagents = setup_parent_with_subagents(cx, &parent, 1);
4078
4079        // Drop the subagent so the WeakEntity can no longer be upgraded
4080        drop(subagents);
4081
4082        // Should not panic even though the subagent was dropped
4083        cx.update(|cx| {
4084            parent.update(cx, |thread, cx| {
4085                thread.set_thinking_enabled(true, cx);
4086                thread.set_speed(Speed::Fast, cx);
4087                thread.set_thinking_effort(Some("high".to_string()), cx);
4088            });
4089        });
4090    }
4091
4092    #[gpui::test]
4093    async fn test_handle_tool_use_json_parse_error_adds_tool_use_to_content(
4094        cx: &mut TestAppContext,
4095    ) {
4096        let (thread, event_stream) = setup_thread_for_test(cx).await;
4097
4098        cx.update(|cx| {
4099            thread.update(cx, |thread, _cx| {
4100                let tool_use_id = LanguageModelToolUseId::from("test_tool_id");
4101                let tool_name: Arc<str> = Arc::from("test_tool");
4102                let raw_input: Arc<str> = Arc::from("{invalid json");
4103                let json_parse_error = "expected value at line 1 column 1".to_string();
4104
4105                // Call the function under test
4106                let result = thread.handle_tool_use_json_parse_error_event(
4107                    tool_use_id.clone(),
4108                    tool_name.clone(),
4109                    raw_input.clone(),
4110                    json_parse_error,
4111                    &event_stream,
4112                );
4113
4114                // Verify the result is an error
4115                assert!(result.is_error);
4116                assert_eq!(result.tool_use_id, tool_use_id);
4117                assert_eq!(result.tool_name, tool_name);
4118                assert!(matches!(
4119                    result.content,
4120                    LanguageModelToolResultContent::Text(_)
4121                ));
4122
4123                // Verify the tool use was added to the message content
4124                {
4125                    let last_message = thread.pending_message();
4126                    assert_eq!(
4127                        last_message.content.len(),
4128                        1,
4129                        "Should have one tool_use in content"
4130                    );
4131
4132                    match &last_message.content[0] {
4133                        AgentMessageContent::ToolUse(tool_use) => {
4134                            assert_eq!(tool_use.id, tool_use_id);
4135                            assert_eq!(tool_use.name, tool_name);
4136                            assert_eq!(tool_use.raw_input, raw_input.to_string());
4137                            assert!(tool_use.is_input_complete);
4138                            // Should fall back to empty object for invalid JSON
4139                            assert_eq!(tool_use.input, json!({}));
4140                        }
4141                        _ => panic!("Expected ToolUse content"),
4142                    }
4143                }
4144
4145                // Insert the tool result (simulating what the caller does)
4146                thread
4147                    .pending_message()
4148                    .tool_results
4149                    .insert(result.tool_use_id.clone(), result);
4150
4151                // Verify the tool result was added
4152                let last_message = thread.pending_message();
4153                assert_eq!(
4154                    last_message.tool_results.len(),
4155                    1,
4156                    "Should have one tool_result"
4157                );
4158                assert!(last_message.tool_results.contains_key(&tool_use_id));
4159            });
4160        });
4161    }
4162}