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