thread.rs

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