thread.rs

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