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