thread.rs

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