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