thread.rs

   1use crate::{
   2    agent_profile::AgentProfile,
   3    context::{AgentContext, AgentContextHandle, ContextLoadResult, LoadedContext},
   4    thread_store::{
   5        SerializedCrease, SerializedLanguageModel, SerializedMessage, SerializedMessageSegment,
   6        SerializedThread, SerializedToolResult, SerializedToolUse, SharedProjectContext,
   7        ThreadStore,
   8    },
   9    tool_use::{PendingToolUse, ToolUse, ToolUseMetadata, ToolUseState},
  10};
  11use agent_settings::{AgentProfileId, AgentSettings, CompletionMode};
  12use anyhow::{Result, anyhow};
  13use assistant_tool::{ActionLog, AnyToolCard, Tool, ToolWorkingSet};
  14use chrono::{DateTime, Utc};
  15use client::{ModelRequestUsage, RequestUsage};
  16use collections::HashMap;
  17use feature_flags::{self, FeatureFlagAppExt};
  18use futures::{FutureExt, StreamExt as _, future::Shared};
  19use git::repository::DiffType;
  20use gpui::{
  21    AnyWindowHandle, App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task,
  22    WeakEntity, Window,
  23};
  24use http_client::StatusCode;
  25use language_model::{
  26    ConfiguredModel, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
  27    LanguageModelExt as _, LanguageModelId, LanguageModelRegistry, LanguageModelRequest,
  28    LanguageModelRequestMessage, LanguageModelRequestTool, LanguageModelToolResult,
  29    LanguageModelToolResultContent, LanguageModelToolUse, LanguageModelToolUseId, MessageContent,
  30    ModelRequestLimitReachedError, PaymentRequiredError, Role, SelectedModel, StopReason,
  31    TokenUsage,
  32};
  33use postage::stream::Stream as _;
  34use project::{
  35    Project,
  36    git_store::{GitStore, GitStoreCheckpoint, RepositoryState},
  37};
  38use prompt_store::{ModelContext, PromptBuilder};
  39use proto::Plan;
  40use schemars::JsonSchema;
  41use serde::{Deserialize, Serialize};
  42use settings::Settings;
  43use std::{
  44    io::Write,
  45    ops::Range,
  46    sync::Arc,
  47    time::{Duration, Instant},
  48};
  49use thiserror::Error;
  50use util::{ResultExt as _, post_inc};
  51use uuid::Uuid;
  52use zed_llm_client::{CompletionIntent, CompletionRequestStatus, UsageLimit};
  53
  54const MAX_RETRY_ATTEMPTS: u8 = 4;
  55const BASE_RETRY_DELAY: Duration = Duration::from_secs(5);
  56
  57#[derive(Debug, Clone)]
  58enum RetryStrategy {
  59    ExponentialBackoff {
  60        initial_delay: Duration,
  61        max_attempts: u8,
  62    },
  63    Fixed {
  64        delay: Duration,
  65        max_attempts: u8,
  66    },
  67}
  68
  69#[derive(
  70    Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize, JsonSchema,
  71)]
  72pub struct ThreadId(Arc<str>);
  73
  74impl ThreadId {
  75    pub fn new() -> Self {
  76        Self(Uuid::new_v4().to_string().into())
  77    }
  78}
  79
  80impl std::fmt::Display for ThreadId {
  81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  82        write!(f, "{}", self.0)
  83    }
  84}
  85
  86impl From<&str> for ThreadId {
  87    fn from(value: &str) -> Self {
  88        Self(value.into())
  89    }
  90}
  91
  92/// The ID of the user prompt that initiated a request.
  93///
  94/// This equates to the user physically submitting a message to the model (e.g., by pressing the Enter key).
  95#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
  96pub struct PromptId(Arc<str>);
  97
  98impl PromptId {
  99    pub fn new() -> Self {
 100        Self(Uuid::new_v4().to_string().into())
 101    }
 102}
 103
 104impl std::fmt::Display for PromptId {
 105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 106        write!(f, "{}", self.0)
 107    }
 108}
 109
 110#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
 111pub struct MessageId(pub(crate) usize);
 112
 113impl MessageId {
 114    fn post_inc(&mut self) -> Self {
 115        Self(post_inc(&mut self.0))
 116    }
 117
 118    pub fn as_usize(&self) -> usize {
 119        self.0
 120    }
 121}
 122
 123/// Stored information that can be used to resurrect a context crease when creating an editor for a past message.
 124#[derive(Clone, Debug)]
 125pub struct MessageCrease {
 126    pub range: Range<usize>,
 127    pub icon_path: SharedString,
 128    pub label: SharedString,
 129    /// None for a deserialized message, Some otherwise.
 130    pub context: Option<AgentContextHandle>,
 131}
 132
 133/// A message in a [`Thread`].
 134#[derive(Debug, Clone)]
 135pub struct Message {
 136    pub id: MessageId,
 137    pub role: Role,
 138    pub segments: Vec<MessageSegment>,
 139    pub loaded_context: LoadedContext,
 140    pub creases: Vec<MessageCrease>,
 141    pub is_hidden: bool,
 142    pub ui_only: bool,
 143}
 144
 145impl Message {
 146    /// Returns whether the message contains any meaningful text that should be displayed
 147    /// The model sometimes runs tool without producing any text or just a marker ([`USING_TOOL_MARKER`])
 148    pub fn should_display_content(&self) -> bool {
 149        self.segments.iter().all(|segment| segment.should_display())
 150    }
 151
 152    pub fn push_thinking(&mut self, text: &str, signature: Option<String>) {
 153        if let Some(MessageSegment::Thinking {
 154            text: segment,
 155            signature: current_signature,
 156        }) = self.segments.last_mut()
 157        {
 158            if let Some(signature) = signature {
 159                *current_signature = Some(signature);
 160            }
 161            segment.push_str(text);
 162        } else {
 163            self.segments.push(MessageSegment::Thinking {
 164                text: text.to_string(),
 165                signature,
 166            });
 167        }
 168    }
 169
 170    pub fn push_redacted_thinking(&mut self, data: String) {
 171        self.segments.push(MessageSegment::RedactedThinking(data));
 172    }
 173
 174    pub fn push_text(&mut self, text: &str) {
 175        if let Some(MessageSegment::Text(segment)) = self.segments.last_mut() {
 176            segment.push_str(text);
 177        } else {
 178            self.segments.push(MessageSegment::Text(text.to_string()));
 179        }
 180    }
 181
 182    pub fn to_string(&self) -> String {
 183        let mut result = String::new();
 184
 185        if !self.loaded_context.text.is_empty() {
 186            result.push_str(&self.loaded_context.text);
 187        }
 188
 189        for segment in &self.segments {
 190            match segment {
 191                MessageSegment::Text(text) => result.push_str(text),
 192                MessageSegment::Thinking { text, .. } => {
 193                    result.push_str("<think>\n");
 194                    result.push_str(text);
 195                    result.push_str("\n</think>");
 196                }
 197                MessageSegment::RedactedThinking(_) => {}
 198            }
 199        }
 200
 201        result
 202    }
 203}
 204
 205#[derive(Debug, Clone, PartialEq, Eq)]
 206pub enum MessageSegment {
 207    Text(String),
 208    Thinking {
 209        text: String,
 210        signature: Option<String>,
 211    },
 212    RedactedThinking(String),
 213}
 214
 215impl MessageSegment {
 216    pub fn should_display(&self) -> bool {
 217        match self {
 218            Self::Text(text) => text.is_empty(),
 219            Self::Thinking { text, .. } => text.is_empty(),
 220            Self::RedactedThinking(_) => false,
 221        }
 222    }
 223
 224    pub fn text(&self) -> Option<&str> {
 225        match self {
 226            MessageSegment::Text(text) => Some(text),
 227            _ => None,
 228        }
 229    }
 230}
 231
 232#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
 233pub struct ProjectSnapshot {
 234    pub worktree_snapshots: Vec<WorktreeSnapshot>,
 235    pub unsaved_buffer_paths: Vec<String>,
 236    pub timestamp: DateTime<Utc>,
 237}
 238
 239#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
 240pub struct WorktreeSnapshot {
 241    pub worktree_path: String,
 242    pub git_state: Option<GitState>,
 243}
 244
 245#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
 246pub struct GitState {
 247    pub remote_url: Option<String>,
 248    pub head_sha: Option<String>,
 249    pub current_branch: Option<String>,
 250    pub diff: Option<String>,
 251}
 252
 253#[derive(Clone, Debug)]
 254pub struct ThreadCheckpoint {
 255    message_id: MessageId,
 256    git_checkpoint: GitStoreCheckpoint,
 257}
 258
 259#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 260pub enum ThreadFeedback {
 261    Positive,
 262    Negative,
 263}
 264
 265pub enum LastRestoreCheckpoint {
 266    Pending {
 267        message_id: MessageId,
 268    },
 269    Error {
 270        message_id: MessageId,
 271        error: String,
 272    },
 273}
 274
 275impl LastRestoreCheckpoint {
 276    pub fn message_id(&self) -> MessageId {
 277        match self {
 278            LastRestoreCheckpoint::Pending { message_id } => *message_id,
 279            LastRestoreCheckpoint::Error { message_id, .. } => *message_id,
 280        }
 281    }
 282}
 283
 284#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
 285pub enum DetailedSummaryState {
 286    #[default]
 287    NotGenerated,
 288    Generating {
 289        message_id: MessageId,
 290    },
 291    Generated {
 292        text: SharedString,
 293        message_id: MessageId,
 294    },
 295}
 296
 297impl DetailedSummaryState {
 298    fn text(&self) -> Option<SharedString> {
 299        if let Self::Generated { text, .. } = self {
 300            Some(text.clone())
 301        } else {
 302            None
 303        }
 304    }
 305}
 306
 307#[derive(Default, Debug)]
 308pub struct TotalTokenUsage {
 309    pub total: u64,
 310    pub max: u64,
 311}
 312
 313impl TotalTokenUsage {
 314    pub fn ratio(&self) -> TokenUsageRatio {
 315        #[cfg(debug_assertions)]
 316        let warning_threshold: f32 = std::env::var("ZED_THREAD_WARNING_THRESHOLD")
 317            .unwrap_or("0.8".to_string())
 318            .parse()
 319            .unwrap();
 320        #[cfg(not(debug_assertions))]
 321        let warning_threshold: f32 = 0.8;
 322
 323        // When the maximum is unknown because there is no selected model,
 324        // avoid showing the token limit warning.
 325        if self.max == 0 {
 326            TokenUsageRatio::Normal
 327        } else if self.total >= self.max {
 328            TokenUsageRatio::Exceeded
 329        } else if self.total as f32 / self.max as f32 >= warning_threshold {
 330            TokenUsageRatio::Warning
 331        } else {
 332            TokenUsageRatio::Normal
 333        }
 334    }
 335
 336    pub fn add(&self, tokens: u64) -> TotalTokenUsage {
 337        TotalTokenUsage {
 338            total: self.total + tokens,
 339            max: self.max,
 340        }
 341    }
 342}
 343
 344#[derive(Debug, Default, PartialEq, Eq)]
 345pub enum TokenUsageRatio {
 346    #[default]
 347    Normal,
 348    Warning,
 349    Exceeded,
 350}
 351
 352#[derive(Debug, Clone, Copy)]
 353pub enum QueueState {
 354    Sending,
 355    Queued { position: usize },
 356    Started,
 357}
 358
 359/// A thread of conversation with the LLM.
 360pub struct Thread {
 361    id: ThreadId,
 362    updated_at: DateTime<Utc>,
 363    summary: ThreadSummary,
 364    pending_summary: Task<Option<()>>,
 365    detailed_summary_task: Task<Option<()>>,
 366    detailed_summary_tx: postage::watch::Sender<DetailedSummaryState>,
 367    detailed_summary_rx: postage::watch::Receiver<DetailedSummaryState>,
 368    completion_mode: agent_settings::CompletionMode,
 369    messages: Vec<Message>,
 370    next_message_id: MessageId,
 371    last_prompt_id: PromptId,
 372    project_context: SharedProjectContext,
 373    checkpoints_by_message: HashMap<MessageId, ThreadCheckpoint>,
 374    completion_count: usize,
 375    pending_completions: Vec<PendingCompletion>,
 376    project: Entity<Project>,
 377    prompt_builder: Arc<PromptBuilder>,
 378    tools: Entity<ToolWorkingSet>,
 379    tool_use: ToolUseState,
 380    action_log: Entity<ActionLog>,
 381    last_restore_checkpoint: Option<LastRestoreCheckpoint>,
 382    pending_checkpoint: Option<ThreadCheckpoint>,
 383    initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
 384    request_token_usage: Vec<TokenUsage>,
 385    cumulative_token_usage: TokenUsage,
 386    exceeded_window_error: Option<ExceededWindowError>,
 387    tool_use_limit_reached: bool,
 388    feedback: Option<ThreadFeedback>,
 389    retry_state: Option<RetryState>,
 390    message_feedback: HashMap<MessageId, ThreadFeedback>,
 391    last_auto_capture_at: Option<Instant>,
 392    last_received_chunk_at: Option<Instant>,
 393    request_callback: Option<
 394        Box<dyn FnMut(&LanguageModelRequest, &[Result<LanguageModelCompletionEvent, String>])>,
 395    >,
 396    remaining_turns: u32,
 397    configured_model: Option<ConfiguredModel>,
 398    profile: AgentProfile,
 399    last_error_context: Option<(Arc<dyn LanguageModel>, CompletionIntent)>,
 400}
 401
 402#[derive(Clone, Debug)]
 403struct RetryState {
 404    attempt: u8,
 405    max_attempts: u8,
 406    intent: CompletionIntent,
 407}
 408
 409#[derive(Clone, Debug, PartialEq, Eq)]
 410pub enum ThreadSummary {
 411    Pending,
 412    Generating,
 413    Ready(SharedString),
 414    Error,
 415}
 416
 417impl ThreadSummary {
 418    pub const DEFAULT: SharedString = SharedString::new_static("New Thread");
 419
 420    pub fn or_default(&self) -> SharedString {
 421        self.unwrap_or(Self::DEFAULT)
 422    }
 423
 424    pub fn unwrap_or(&self, message: impl Into<SharedString>) -> SharedString {
 425        self.ready().unwrap_or_else(|| message.into())
 426    }
 427
 428    pub fn ready(&self) -> Option<SharedString> {
 429        match self {
 430            ThreadSummary::Ready(summary) => Some(summary.clone()),
 431            ThreadSummary::Pending | ThreadSummary::Generating | ThreadSummary::Error => None,
 432        }
 433    }
 434}
 435
 436#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
 437pub struct ExceededWindowError {
 438    /// Model used when last message exceeded context window
 439    model_id: LanguageModelId,
 440    /// Token count including last message
 441    token_count: u64,
 442}
 443
 444impl Thread {
 445    pub fn new(
 446        project: Entity<Project>,
 447        tools: Entity<ToolWorkingSet>,
 448        prompt_builder: Arc<PromptBuilder>,
 449        system_prompt: SharedProjectContext,
 450        cx: &mut Context<Self>,
 451    ) -> Self {
 452        let (detailed_summary_tx, detailed_summary_rx) = postage::watch::channel();
 453        let configured_model = LanguageModelRegistry::read_global(cx).default_model();
 454        let profile_id = AgentSettings::get_global(cx).default_profile.clone();
 455
 456        Self {
 457            id: ThreadId::new(),
 458            updated_at: Utc::now(),
 459            summary: ThreadSummary::Pending,
 460            pending_summary: Task::ready(None),
 461            detailed_summary_task: Task::ready(None),
 462            detailed_summary_tx,
 463            detailed_summary_rx,
 464            completion_mode: AgentSettings::get_global(cx).preferred_completion_mode,
 465            messages: Vec::new(),
 466            next_message_id: MessageId(0),
 467            last_prompt_id: PromptId::new(),
 468            project_context: system_prompt,
 469            checkpoints_by_message: HashMap::default(),
 470            completion_count: 0,
 471            pending_completions: Vec::new(),
 472            project: project.clone(),
 473            prompt_builder,
 474            tools: tools.clone(),
 475            last_restore_checkpoint: None,
 476            pending_checkpoint: None,
 477            tool_use: ToolUseState::new(tools.clone()),
 478            action_log: cx.new(|_| ActionLog::new(project.clone())),
 479            initial_project_snapshot: {
 480                let project_snapshot = Self::project_snapshot(project, cx);
 481                cx.foreground_executor()
 482                    .spawn(async move { Some(project_snapshot.await) })
 483                    .shared()
 484            },
 485            request_token_usage: Vec::new(),
 486            cumulative_token_usage: TokenUsage::default(),
 487            exceeded_window_error: None,
 488            tool_use_limit_reached: false,
 489            feedback: None,
 490            retry_state: None,
 491            message_feedback: HashMap::default(),
 492            last_auto_capture_at: None,
 493            last_error_context: None,
 494            last_received_chunk_at: None,
 495            request_callback: None,
 496            remaining_turns: u32::MAX,
 497            configured_model: configured_model.clone(),
 498            profile: AgentProfile::new(profile_id, tools),
 499        }
 500    }
 501
 502    pub fn deserialize(
 503        id: ThreadId,
 504        serialized: SerializedThread,
 505        project: Entity<Project>,
 506        tools: Entity<ToolWorkingSet>,
 507        prompt_builder: Arc<PromptBuilder>,
 508        project_context: SharedProjectContext,
 509        window: Option<&mut Window>, // None in headless mode
 510        cx: &mut Context<Self>,
 511    ) -> Self {
 512        let next_message_id = MessageId(
 513            serialized
 514                .messages
 515                .last()
 516                .map(|message| message.id.0 + 1)
 517                .unwrap_or(0),
 518        );
 519        let tool_use = ToolUseState::from_serialized_messages(
 520            tools.clone(),
 521            &serialized.messages,
 522            project.clone(),
 523            window,
 524            cx,
 525        );
 526        let (detailed_summary_tx, detailed_summary_rx) =
 527            postage::watch::channel_with(serialized.detailed_summary_state);
 528
 529        let configured_model = LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
 530            serialized
 531                .model
 532                .and_then(|model| {
 533                    let model = SelectedModel {
 534                        provider: model.provider.clone().into(),
 535                        model: model.model.clone().into(),
 536                    };
 537                    registry.select_model(&model, cx)
 538                })
 539                .or_else(|| registry.default_model())
 540        });
 541
 542        let completion_mode = serialized
 543            .completion_mode
 544            .unwrap_or_else(|| AgentSettings::get_global(cx).preferred_completion_mode);
 545        let profile_id = serialized
 546            .profile
 547            .unwrap_or_else(|| AgentSettings::get_global(cx).default_profile.clone());
 548
 549        Self {
 550            id,
 551            updated_at: serialized.updated_at,
 552            summary: ThreadSummary::Ready(serialized.summary),
 553            pending_summary: Task::ready(None),
 554            detailed_summary_task: Task::ready(None),
 555            detailed_summary_tx,
 556            detailed_summary_rx,
 557            completion_mode,
 558            retry_state: None,
 559            messages: serialized
 560                .messages
 561                .into_iter()
 562                .map(|message| Message {
 563                    id: message.id,
 564                    role: message.role,
 565                    segments: message
 566                        .segments
 567                        .into_iter()
 568                        .map(|segment| match segment {
 569                            SerializedMessageSegment::Text { text } => MessageSegment::Text(text),
 570                            SerializedMessageSegment::Thinking { text, signature } => {
 571                                MessageSegment::Thinking { text, signature }
 572                            }
 573                            SerializedMessageSegment::RedactedThinking { data } => {
 574                                MessageSegment::RedactedThinking(data)
 575                            }
 576                        })
 577                        .collect(),
 578                    loaded_context: LoadedContext {
 579                        contexts: Vec::new(),
 580                        text: message.context,
 581                        images: Vec::new(),
 582                    },
 583                    creases: message
 584                        .creases
 585                        .into_iter()
 586                        .map(|crease| MessageCrease {
 587                            range: crease.start..crease.end,
 588                            icon_path: crease.icon_path,
 589                            label: crease.label,
 590                            context: None,
 591                        })
 592                        .collect(),
 593                    is_hidden: message.is_hidden,
 594                    ui_only: false, // UI-only messages are not persisted
 595                })
 596                .collect(),
 597            next_message_id,
 598            last_prompt_id: PromptId::new(),
 599            project_context,
 600            checkpoints_by_message: HashMap::default(),
 601            completion_count: 0,
 602            pending_completions: Vec::new(),
 603            last_restore_checkpoint: None,
 604            pending_checkpoint: None,
 605            project: project.clone(),
 606            prompt_builder,
 607            tools: tools.clone(),
 608            tool_use,
 609            action_log: cx.new(|_| ActionLog::new(project)),
 610            initial_project_snapshot: Task::ready(serialized.initial_project_snapshot).shared(),
 611            request_token_usage: serialized.request_token_usage,
 612            cumulative_token_usage: serialized.cumulative_token_usage,
 613            exceeded_window_error: None,
 614            tool_use_limit_reached: serialized.tool_use_limit_reached,
 615            feedback: None,
 616            message_feedback: HashMap::default(),
 617            last_auto_capture_at: None,
 618            last_error_context: None,
 619            last_received_chunk_at: None,
 620            request_callback: None,
 621            remaining_turns: u32::MAX,
 622            configured_model,
 623            profile: AgentProfile::new(profile_id, tools),
 624        }
 625    }
 626
 627    pub fn set_request_callback(
 628        &mut self,
 629        callback: impl 'static
 630        + FnMut(&LanguageModelRequest, &[Result<LanguageModelCompletionEvent, String>]),
 631    ) {
 632        self.request_callback = Some(Box::new(callback));
 633    }
 634
 635    pub fn id(&self) -> &ThreadId {
 636        &self.id
 637    }
 638
 639    pub fn profile(&self) -> &AgentProfile {
 640        &self.profile
 641    }
 642
 643    pub fn set_profile(&mut self, id: AgentProfileId, cx: &mut Context<Self>) {
 644        if &id != self.profile.id() {
 645            self.profile = AgentProfile::new(id, self.tools.clone());
 646            cx.emit(ThreadEvent::ProfileChanged);
 647        }
 648    }
 649
 650    pub fn is_empty(&self) -> bool {
 651        self.messages.is_empty()
 652    }
 653
 654    pub fn updated_at(&self) -> DateTime<Utc> {
 655        self.updated_at
 656    }
 657
 658    pub fn touch_updated_at(&mut self) {
 659        self.updated_at = Utc::now();
 660    }
 661
 662    pub fn advance_prompt_id(&mut self) {
 663        self.last_prompt_id = PromptId::new();
 664    }
 665
 666    pub fn project_context(&self) -> SharedProjectContext {
 667        self.project_context.clone()
 668    }
 669
 670    pub fn get_or_init_configured_model(&mut self, cx: &App) -> Option<ConfiguredModel> {
 671        if self.configured_model.is_none() {
 672            self.configured_model = LanguageModelRegistry::read_global(cx).default_model();
 673        }
 674        self.configured_model.clone()
 675    }
 676
 677    pub fn configured_model(&self) -> Option<ConfiguredModel> {
 678        self.configured_model.clone()
 679    }
 680
 681    pub fn set_configured_model(&mut self, model: Option<ConfiguredModel>, cx: &mut Context<Self>) {
 682        self.configured_model = model;
 683        cx.notify();
 684    }
 685
 686    pub fn summary(&self) -> &ThreadSummary {
 687        &self.summary
 688    }
 689
 690    pub fn set_summary(&mut self, new_summary: impl Into<SharedString>, cx: &mut Context<Self>) {
 691        let current_summary = match &self.summary {
 692            ThreadSummary::Pending | ThreadSummary::Generating => return,
 693            ThreadSummary::Ready(summary) => summary,
 694            ThreadSummary::Error => &ThreadSummary::DEFAULT,
 695        };
 696
 697        let mut new_summary = new_summary.into();
 698
 699        if new_summary.is_empty() {
 700            new_summary = ThreadSummary::DEFAULT;
 701        }
 702
 703        if current_summary != &new_summary {
 704            self.summary = ThreadSummary::Ready(new_summary);
 705            cx.emit(ThreadEvent::SummaryChanged);
 706        }
 707    }
 708
 709    pub fn completion_mode(&self) -> CompletionMode {
 710        self.completion_mode
 711    }
 712
 713    pub fn set_completion_mode(&mut self, mode: CompletionMode) {
 714        self.completion_mode = mode;
 715    }
 716
 717    pub fn message(&self, id: MessageId) -> Option<&Message> {
 718        let index = self
 719            .messages
 720            .binary_search_by(|message| message.id.cmp(&id))
 721            .ok()?;
 722
 723        self.messages.get(index)
 724    }
 725
 726    pub fn messages(&self) -> impl ExactSizeIterator<Item = &Message> {
 727        self.messages.iter()
 728    }
 729
 730    pub fn is_generating(&self) -> bool {
 731        !self.pending_completions.is_empty() || !self.all_tools_finished()
 732    }
 733
 734    /// Indicates whether streaming of language model events is stale.
 735    /// When `is_generating()` is false, this method returns `None`.
 736    pub fn is_generation_stale(&self) -> Option<bool> {
 737        const STALE_THRESHOLD: u128 = 250;
 738
 739        self.last_received_chunk_at
 740            .map(|instant| instant.elapsed().as_millis() > STALE_THRESHOLD)
 741    }
 742
 743    fn received_chunk(&mut self) {
 744        self.last_received_chunk_at = Some(Instant::now());
 745    }
 746
 747    pub fn queue_state(&self) -> Option<QueueState> {
 748        self.pending_completions
 749            .first()
 750            .map(|pending_completion| pending_completion.queue_state)
 751    }
 752
 753    pub fn tools(&self) -> &Entity<ToolWorkingSet> {
 754        &self.tools
 755    }
 756
 757    pub fn pending_tool(&self, id: &LanguageModelToolUseId) -> Option<&PendingToolUse> {
 758        self.tool_use
 759            .pending_tool_uses()
 760            .into_iter()
 761            .find(|tool_use| &tool_use.id == id)
 762    }
 763
 764    pub fn tools_needing_confirmation(&self) -> impl Iterator<Item = &PendingToolUse> {
 765        self.tool_use
 766            .pending_tool_uses()
 767            .into_iter()
 768            .filter(|tool_use| tool_use.status.needs_confirmation())
 769    }
 770
 771    pub fn has_pending_tool_uses(&self) -> bool {
 772        !self.tool_use.pending_tool_uses().is_empty()
 773    }
 774
 775    pub fn checkpoint_for_message(&self, id: MessageId) -> Option<ThreadCheckpoint> {
 776        self.checkpoints_by_message.get(&id).cloned()
 777    }
 778
 779    pub fn restore_checkpoint(
 780        &mut self,
 781        checkpoint: ThreadCheckpoint,
 782        cx: &mut Context<Self>,
 783    ) -> Task<Result<()>> {
 784        self.last_restore_checkpoint = Some(LastRestoreCheckpoint::Pending {
 785            message_id: checkpoint.message_id,
 786        });
 787        cx.emit(ThreadEvent::CheckpointChanged);
 788        cx.notify();
 789
 790        let git_store = self.project().read(cx).git_store().clone();
 791        let restore = git_store.update(cx, |git_store, cx| {
 792            git_store.restore_checkpoint(checkpoint.git_checkpoint.clone(), cx)
 793        });
 794
 795        cx.spawn(async move |this, cx| {
 796            let result = restore.await;
 797            this.update(cx, |this, cx| {
 798                if let Err(err) = result.as_ref() {
 799                    this.last_restore_checkpoint = Some(LastRestoreCheckpoint::Error {
 800                        message_id: checkpoint.message_id,
 801                        error: err.to_string(),
 802                    });
 803                } else {
 804                    this.truncate(checkpoint.message_id, cx);
 805                    this.last_restore_checkpoint = None;
 806                }
 807                this.pending_checkpoint = None;
 808                cx.emit(ThreadEvent::CheckpointChanged);
 809                cx.notify();
 810            })?;
 811            result
 812        })
 813    }
 814
 815    fn finalize_pending_checkpoint(&mut self, cx: &mut Context<Self>) {
 816        let pending_checkpoint = if self.is_generating() {
 817            return;
 818        } else if let Some(checkpoint) = self.pending_checkpoint.take() {
 819            checkpoint
 820        } else {
 821            return;
 822        };
 823
 824        self.finalize_checkpoint(pending_checkpoint, cx);
 825    }
 826
 827    fn finalize_checkpoint(
 828        &mut self,
 829        pending_checkpoint: ThreadCheckpoint,
 830        cx: &mut Context<Self>,
 831    ) {
 832        let git_store = self.project.read(cx).git_store().clone();
 833        let final_checkpoint = git_store.update(cx, |git_store, cx| git_store.checkpoint(cx));
 834        cx.spawn(async move |this, cx| match final_checkpoint.await {
 835            Ok(final_checkpoint) => {
 836                let equal = git_store
 837                    .update(cx, |store, cx| {
 838                        store.compare_checkpoints(
 839                            pending_checkpoint.git_checkpoint.clone(),
 840                            final_checkpoint.clone(),
 841                            cx,
 842                        )
 843                    })?
 844                    .await
 845                    .unwrap_or(false);
 846
 847                if !equal {
 848                    this.update(cx, |this, cx| {
 849                        this.insert_checkpoint(pending_checkpoint, cx)
 850                    })?;
 851                }
 852
 853                Ok(())
 854            }
 855            Err(_) => this.update(cx, |this, cx| {
 856                this.insert_checkpoint(pending_checkpoint, cx)
 857            }),
 858        })
 859        .detach();
 860    }
 861
 862    fn insert_checkpoint(&mut self, checkpoint: ThreadCheckpoint, cx: &mut Context<Self>) {
 863        self.checkpoints_by_message
 864            .insert(checkpoint.message_id, checkpoint);
 865        cx.emit(ThreadEvent::CheckpointChanged);
 866        cx.notify();
 867    }
 868
 869    pub fn last_restore_checkpoint(&self) -> Option<&LastRestoreCheckpoint> {
 870        self.last_restore_checkpoint.as_ref()
 871    }
 872
 873    pub fn truncate(&mut self, message_id: MessageId, cx: &mut Context<Self>) {
 874        let Some(message_ix) = self
 875            .messages
 876            .iter()
 877            .rposition(|message| message.id == message_id)
 878        else {
 879            return;
 880        };
 881        for deleted_message in self.messages.drain(message_ix..) {
 882            self.checkpoints_by_message.remove(&deleted_message.id);
 883        }
 884        cx.notify();
 885    }
 886
 887    pub fn context_for_message(&self, id: MessageId) -> impl Iterator<Item = &AgentContext> {
 888        self.messages
 889            .iter()
 890            .find(|message| message.id == id)
 891            .into_iter()
 892            .flat_map(|message| message.loaded_context.contexts.iter())
 893    }
 894
 895    pub fn is_turn_end(&self, ix: usize) -> bool {
 896        if self.messages.is_empty() {
 897            return false;
 898        }
 899
 900        if !self.is_generating() && ix == self.messages.len() - 1 {
 901            return true;
 902        }
 903
 904        let Some(message) = self.messages.get(ix) else {
 905            return false;
 906        };
 907
 908        if message.role != Role::Assistant {
 909            return false;
 910        }
 911
 912        self.messages
 913            .get(ix + 1)
 914            .and_then(|message| {
 915                self.message(message.id)
 916                    .map(|next_message| next_message.role == Role::User && !next_message.is_hidden)
 917            })
 918            .unwrap_or(false)
 919    }
 920
 921    pub fn tool_use_limit_reached(&self) -> bool {
 922        self.tool_use_limit_reached
 923    }
 924
 925    /// Returns whether all of the tool uses have finished running.
 926    pub fn all_tools_finished(&self) -> bool {
 927        // If the only pending tool uses left are the ones with errors, then
 928        // that means that we've finished running all of the pending tools.
 929        self.tool_use
 930            .pending_tool_uses()
 931            .iter()
 932            .all(|pending_tool_use| pending_tool_use.status.is_error())
 933    }
 934
 935    /// Returns whether any pending tool uses may perform edits
 936    pub fn has_pending_edit_tool_uses(&self) -> bool {
 937        self.tool_use
 938            .pending_tool_uses()
 939            .iter()
 940            .filter(|pending_tool_use| !pending_tool_use.status.is_error())
 941            .any(|pending_tool_use| pending_tool_use.may_perform_edits)
 942    }
 943
 944    pub fn tool_uses_for_message(&self, id: MessageId, cx: &App) -> Vec<ToolUse> {
 945        self.tool_use.tool_uses_for_message(id, cx)
 946    }
 947
 948    pub fn tool_results_for_message(
 949        &self,
 950        assistant_message_id: MessageId,
 951    ) -> Vec<&LanguageModelToolResult> {
 952        self.tool_use.tool_results_for_message(assistant_message_id)
 953    }
 954
 955    pub fn tool_result(&self, id: &LanguageModelToolUseId) -> Option<&LanguageModelToolResult> {
 956        self.tool_use.tool_result(id)
 957    }
 958
 959    pub fn output_for_tool(&self, id: &LanguageModelToolUseId) -> Option<&Arc<str>> {
 960        match &self.tool_use.tool_result(id)?.content {
 961            LanguageModelToolResultContent::Text(text) => Some(text),
 962            LanguageModelToolResultContent::Image(_) => {
 963                // TODO: We should display image
 964                None
 965            }
 966        }
 967    }
 968
 969    pub fn card_for_tool(&self, id: &LanguageModelToolUseId) -> Option<AnyToolCard> {
 970        self.tool_use.tool_result_card(id).cloned()
 971    }
 972
 973    /// Return tools that are both enabled and supported by the model
 974    pub fn available_tools(
 975        &self,
 976        cx: &App,
 977        model: Arc<dyn LanguageModel>,
 978    ) -> Vec<LanguageModelRequestTool> {
 979        if model.supports_tools() {
 980            self.profile
 981                .enabled_tools(cx)
 982                .into_iter()
 983                .filter_map(|(name, tool)| {
 984                    // Skip tools that cannot be supported
 985                    let input_schema = tool.input_schema(model.tool_input_format()).ok()?;
 986                    Some(LanguageModelRequestTool {
 987                        name: name.into(),
 988                        description: tool.description(),
 989                        input_schema,
 990                    })
 991                })
 992                .collect()
 993        } else {
 994            Vec::default()
 995        }
 996    }
 997
 998    pub fn insert_user_message(
 999        &mut self,
1000        text: impl Into<String>,
1001        loaded_context: ContextLoadResult,
1002        git_checkpoint: Option<GitStoreCheckpoint>,
1003        creases: Vec<MessageCrease>,
1004        cx: &mut Context<Self>,
1005    ) -> MessageId {
1006        if !loaded_context.referenced_buffers.is_empty() {
1007            self.action_log.update(cx, |log, cx| {
1008                for buffer in loaded_context.referenced_buffers {
1009                    log.buffer_read(buffer, cx);
1010                }
1011            });
1012        }
1013
1014        let message_id = self.insert_message(
1015            Role::User,
1016            vec![MessageSegment::Text(text.into())],
1017            loaded_context.loaded_context,
1018            creases,
1019            false,
1020            cx,
1021        );
1022
1023        if let Some(git_checkpoint) = git_checkpoint {
1024            self.pending_checkpoint = Some(ThreadCheckpoint {
1025                message_id,
1026                git_checkpoint,
1027            });
1028        }
1029
1030        self.auto_capture_telemetry(cx);
1031
1032        message_id
1033    }
1034
1035    pub fn insert_invisible_continue_message(&mut self, cx: &mut Context<Self>) -> MessageId {
1036        let id = self.insert_message(
1037            Role::User,
1038            vec![MessageSegment::Text("Continue where you left off".into())],
1039            LoadedContext::default(),
1040            vec![],
1041            true,
1042            cx,
1043        );
1044        self.pending_checkpoint = None;
1045
1046        id
1047    }
1048
1049    pub fn insert_assistant_message(
1050        &mut self,
1051        segments: Vec<MessageSegment>,
1052        cx: &mut Context<Self>,
1053    ) -> MessageId {
1054        self.insert_message(
1055            Role::Assistant,
1056            segments,
1057            LoadedContext::default(),
1058            Vec::new(),
1059            false,
1060            cx,
1061        )
1062    }
1063
1064    pub fn insert_message(
1065        &mut self,
1066        role: Role,
1067        segments: Vec<MessageSegment>,
1068        loaded_context: LoadedContext,
1069        creases: Vec<MessageCrease>,
1070        is_hidden: bool,
1071        cx: &mut Context<Self>,
1072    ) -> MessageId {
1073        let id = self.next_message_id.post_inc();
1074        self.messages.push(Message {
1075            id,
1076            role,
1077            segments,
1078            loaded_context,
1079            creases,
1080            is_hidden,
1081            ui_only: false,
1082        });
1083        self.touch_updated_at();
1084        cx.emit(ThreadEvent::MessageAdded(id));
1085        id
1086    }
1087
1088    pub fn edit_message(
1089        &mut self,
1090        id: MessageId,
1091        new_role: Role,
1092        new_segments: Vec<MessageSegment>,
1093        creases: Vec<MessageCrease>,
1094        loaded_context: Option<LoadedContext>,
1095        checkpoint: Option<GitStoreCheckpoint>,
1096        cx: &mut Context<Self>,
1097    ) -> bool {
1098        let Some(message) = self.messages.iter_mut().find(|message| message.id == id) else {
1099            return false;
1100        };
1101        message.role = new_role;
1102        message.segments = new_segments;
1103        message.creases = creases;
1104        if let Some(context) = loaded_context {
1105            message.loaded_context = context;
1106        }
1107        if let Some(git_checkpoint) = checkpoint {
1108            self.checkpoints_by_message.insert(
1109                id,
1110                ThreadCheckpoint {
1111                    message_id: id,
1112                    git_checkpoint,
1113                },
1114            );
1115        }
1116        self.touch_updated_at();
1117        cx.emit(ThreadEvent::MessageEdited(id));
1118        true
1119    }
1120
1121    pub fn delete_message(&mut self, id: MessageId, cx: &mut Context<Self>) -> bool {
1122        let Some(index) = self.messages.iter().position(|message| message.id == id) else {
1123            return false;
1124        };
1125        self.messages.remove(index);
1126        self.touch_updated_at();
1127        cx.emit(ThreadEvent::MessageDeleted(id));
1128        true
1129    }
1130
1131    /// Returns the representation of this [`Thread`] in a textual form.
1132    ///
1133    /// This is the representation we use when attaching a thread as context to another thread.
1134    pub fn text(&self) -> String {
1135        let mut text = String::new();
1136
1137        for message in &self.messages {
1138            text.push_str(match message.role {
1139                language_model::Role::User => "User:",
1140                language_model::Role::Assistant => "Agent:",
1141                language_model::Role::System => "System:",
1142            });
1143            text.push('\n');
1144
1145            for segment in &message.segments {
1146                match segment {
1147                    MessageSegment::Text(content) => text.push_str(content),
1148                    MessageSegment::Thinking { text: content, .. } => {
1149                        text.push_str(&format!("<think>{}</think>", content))
1150                    }
1151                    MessageSegment::RedactedThinking(_) => {}
1152                }
1153            }
1154            text.push('\n');
1155        }
1156
1157        text
1158    }
1159
1160    /// Serializes this thread into a format for storage or telemetry.
1161    pub fn serialize(&self, cx: &mut Context<Self>) -> Task<Result<SerializedThread>> {
1162        let initial_project_snapshot = self.initial_project_snapshot.clone();
1163        cx.spawn(async move |this, cx| {
1164            let initial_project_snapshot = initial_project_snapshot.await;
1165            this.read_with(cx, |this, cx| SerializedThread {
1166                version: SerializedThread::VERSION.to_string(),
1167                summary: this.summary().or_default(),
1168                updated_at: this.updated_at(),
1169                messages: this
1170                    .messages()
1171                    .filter(|message| !message.ui_only)
1172                    .map(|message| SerializedMessage {
1173                        id: message.id,
1174                        role: message.role,
1175                        segments: message
1176                            .segments
1177                            .iter()
1178                            .map(|segment| match segment {
1179                                MessageSegment::Text(text) => {
1180                                    SerializedMessageSegment::Text { text: text.clone() }
1181                                }
1182                                MessageSegment::Thinking { text, signature } => {
1183                                    SerializedMessageSegment::Thinking {
1184                                        text: text.clone(),
1185                                        signature: signature.clone(),
1186                                    }
1187                                }
1188                                MessageSegment::RedactedThinking(data) => {
1189                                    SerializedMessageSegment::RedactedThinking {
1190                                        data: data.clone(),
1191                                    }
1192                                }
1193                            })
1194                            .collect(),
1195                        tool_uses: this
1196                            .tool_uses_for_message(message.id, cx)
1197                            .into_iter()
1198                            .map(|tool_use| SerializedToolUse {
1199                                id: tool_use.id,
1200                                name: tool_use.name,
1201                                input: tool_use.input,
1202                            })
1203                            .collect(),
1204                        tool_results: this
1205                            .tool_results_for_message(message.id)
1206                            .into_iter()
1207                            .map(|tool_result| SerializedToolResult {
1208                                tool_use_id: tool_result.tool_use_id.clone(),
1209                                is_error: tool_result.is_error,
1210                                content: tool_result.content.clone(),
1211                                output: tool_result.output.clone(),
1212                            })
1213                            .collect(),
1214                        context: message.loaded_context.text.clone(),
1215                        creases: message
1216                            .creases
1217                            .iter()
1218                            .map(|crease| SerializedCrease {
1219                                start: crease.range.start,
1220                                end: crease.range.end,
1221                                icon_path: crease.icon_path.clone(),
1222                                label: crease.label.clone(),
1223                            })
1224                            .collect(),
1225                        is_hidden: message.is_hidden,
1226                    })
1227                    .collect(),
1228                initial_project_snapshot,
1229                cumulative_token_usage: this.cumulative_token_usage,
1230                request_token_usage: this.request_token_usage.clone(),
1231                detailed_summary_state: this.detailed_summary_rx.borrow().clone(),
1232                exceeded_window_error: this.exceeded_window_error.clone(),
1233                model: this
1234                    .configured_model
1235                    .as_ref()
1236                    .map(|model| SerializedLanguageModel {
1237                        provider: model.provider.id().0.to_string(),
1238                        model: model.model.id().0.to_string(),
1239                    }),
1240                completion_mode: Some(this.completion_mode),
1241                tool_use_limit_reached: this.tool_use_limit_reached,
1242                profile: Some(this.profile.id().clone()),
1243            })
1244        })
1245    }
1246
1247    pub fn remaining_turns(&self) -> u32 {
1248        self.remaining_turns
1249    }
1250
1251    pub fn set_remaining_turns(&mut self, remaining_turns: u32) {
1252        self.remaining_turns = remaining_turns;
1253    }
1254
1255    pub fn send_to_model(
1256        &mut self,
1257        model: Arc<dyn LanguageModel>,
1258        intent: CompletionIntent,
1259        window: Option<AnyWindowHandle>,
1260        cx: &mut Context<Self>,
1261    ) {
1262        if self.remaining_turns == 0 {
1263            return;
1264        }
1265
1266        self.remaining_turns -= 1;
1267
1268        self.flush_notifications(model.clone(), intent, cx);
1269
1270        let _checkpoint = self.finalize_pending_checkpoint(cx);
1271        self.stream_completion(
1272            self.to_completion_request(model.clone(), intent, cx),
1273            model,
1274            intent,
1275            window,
1276            cx,
1277        );
1278    }
1279
1280    pub fn retry_last_completion(
1281        &mut self,
1282        window: Option<AnyWindowHandle>,
1283        cx: &mut Context<Self>,
1284    ) {
1285        // Clear any existing error state
1286        self.retry_state = None;
1287
1288        // Use the last error context if available, otherwise fall back to configured model
1289        let (model, intent) = if let Some((model, intent)) = self.last_error_context.take() {
1290            (model, intent)
1291        } else if let Some(configured_model) = self.configured_model.as_ref() {
1292            let model = configured_model.model.clone();
1293            let intent = if self.has_pending_tool_uses() {
1294                CompletionIntent::ToolResults
1295            } else {
1296                CompletionIntent::UserPrompt
1297            };
1298            (model, intent)
1299        } else if let Some(configured_model) = self.get_or_init_configured_model(cx) {
1300            let model = configured_model.model.clone();
1301            let intent = if self.has_pending_tool_uses() {
1302                CompletionIntent::ToolResults
1303            } else {
1304                CompletionIntent::UserPrompt
1305            };
1306            (model, intent)
1307        } else {
1308            return;
1309        };
1310
1311        self.send_to_model(model, intent, window, cx);
1312    }
1313
1314    pub fn enable_burn_mode_and_retry(
1315        &mut self,
1316        window: Option<AnyWindowHandle>,
1317        cx: &mut Context<Self>,
1318    ) {
1319        self.completion_mode = CompletionMode::Burn;
1320        cx.emit(ThreadEvent::ProfileChanged);
1321        self.retry_last_completion(window, cx);
1322    }
1323
1324    pub fn used_tools_since_last_user_message(&self) -> bool {
1325        for message in self.messages.iter().rev() {
1326            if self.tool_use.message_has_tool_results(message.id) {
1327                return true;
1328            } else if message.role == Role::User {
1329                return false;
1330            }
1331        }
1332
1333        false
1334    }
1335
1336    pub fn to_completion_request(
1337        &self,
1338        model: Arc<dyn LanguageModel>,
1339        intent: CompletionIntent,
1340        cx: &mut Context<Self>,
1341    ) -> LanguageModelRequest {
1342        let mut request = LanguageModelRequest {
1343            thread_id: Some(self.id.to_string()),
1344            prompt_id: Some(self.last_prompt_id.to_string()),
1345            intent: Some(intent),
1346            mode: None,
1347            messages: vec![],
1348            tools: Vec::new(),
1349            tool_choice: None,
1350            stop: Vec::new(),
1351            temperature: AgentSettings::temperature_for_model(&model, cx),
1352            thinking_allowed: true,
1353        };
1354
1355        let available_tools = self.available_tools(cx, model.clone());
1356        let available_tool_names = available_tools
1357            .iter()
1358            .map(|tool| tool.name.clone())
1359            .collect();
1360
1361        let model_context = &ModelContext {
1362            available_tools: available_tool_names,
1363        };
1364
1365        if let Some(project_context) = self.project_context.borrow().as_ref() {
1366            match self
1367                .prompt_builder
1368                .generate_assistant_system_prompt(project_context, model_context)
1369            {
1370                Err(err) => {
1371                    let message = format!("{err:?}").into();
1372                    log::error!("{message}");
1373                    cx.emit(ThreadEvent::ShowError(ThreadError::Message {
1374                        header: "Error generating system prompt".into(),
1375                        message,
1376                    }));
1377                }
1378                Ok(system_prompt) => {
1379                    request.messages.push(LanguageModelRequestMessage {
1380                        role: Role::System,
1381                        content: vec![MessageContent::Text(system_prompt)],
1382                        cache: true,
1383                    });
1384                }
1385            }
1386        } else {
1387            let message = "Context for system prompt unexpectedly not ready.".into();
1388            log::error!("{message}");
1389            cx.emit(ThreadEvent::ShowError(ThreadError::Message {
1390                header: "Error generating system prompt".into(),
1391                message,
1392            }));
1393        }
1394
1395        let mut message_ix_to_cache = None;
1396        for message in &self.messages {
1397            // ui_only messages are for the UI only, not for the model
1398            if message.ui_only {
1399                continue;
1400            }
1401
1402            let mut request_message = LanguageModelRequestMessage {
1403                role: message.role,
1404                content: Vec::new(),
1405                cache: false,
1406            };
1407
1408            message
1409                .loaded_context
1410                .add_to_request_message(&mut request_message);
1411
1412            for segment in &message.segments {
1413                match segment {
1414                    MessageSegment::Text(text) => {
1415                        let text = text.trim_end();
1416                        if !text.is_empty() {
1417                            request_message
1418                                .content
1419                                .push(MessageContent::Text(text.into()));
1420                        }
1421                    }
1422                    MessageSegment::Thinking { text, signature } => {
1423                        if !text.is_empty() {
1424                            request_message.content.push(MessageContent::Thinking {
1425                                text: text.into(),
1426                                signature: signature.clone(),
1427                            });
1428                        }
1429                    }
1430                    MessageSegment::RedactedThinking(data) => {
1431                        request_message
1432                            .content
1433                            .push(MessageContent::RedactedThinking(data.clone()));
1434                    }
1435                };
1436            }
1437
1438            let mut cache_message = true;
1439            let mut tool_results_message = LanguageModelRequestMessage {
1440                role: Role::User,
1441                content: Vec::new(),
1442                cache: false,
1443            };
1444            for (tool_use, tool_result) in self.tool_use.tool_results(message.id) {
1445                if let Some(tool_result) = tool_result {
1446                    request_message
1447                        .content
1448                        .push(MessageContent::ToolUse(tool_use.clone()));
1449                    tool_results_message
1450                        .content
1451                        .push(MessageContent::ToolResult(LanguageModelToolResult {
1452                            tool_use_id: tool_use.id.clone(),
1453                            tool_name: tool_result.tool_name.clone(),
1454                            is_error: tool_result.is_error,
1455                            content: if tool_result.content.is_empty() {
1456                                // Surprisingly, the API fails if we return an empty string here.
1457                                // It thinks we are sending a tool use without a tool result.
1458                                "<Tool returned an empty string>".into()
1459                            } else {
1460                                tool_result.content.clone()
1461                            },
1462                            output: None,
1463                        }));
1464                } else {
1465                    cache_message = false;
1466                    log::debug!(
1467                        "skipped tool use {:?} because it is still pending",
1468                        tool_use
1469                    );
1470                }
1471            }
1472
1473            if cache_message {
1474                message_ix_to_cache = Some(request.messages.len());
1475            }
1476            request.messages.push(request_message);
1477
1478            if !tool_results_message.content.is_empty() {
1479                if cache_message {
1480                    message_ix_to_cache = Some(request.messages.len());
1481                }
1482                request.messages.push(tool_results_message);
1483            }
1484        }
1485
1486        // https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
1487        if let Some(message_ix_to_cache) = message_ix_to_cache {
1488            request.messages[message_ix_to_cache].cache = true;
1489        }
1490
1491        request.tools = available_tools;
1492        request.mode = if model.supports_burn_mode() {
1493            Some(self.completion_mode.into())
1494        } else {
1495            Some(CompletionMode::Normal.into())
1496        };
1497
1498        request
1499    }
1500
1501    fn to_summarize_request(
1502        &self,
1503        model: &Arc<dyn LanguageModel>,
1504        intent: CompletionIntent,
1505        added_user_message: String,
1506        cx: &App,
1507    ) -> LanguageModelRequest {
1508        let mut request = LanguageModelRequest {
1509            thread_id: None,
1510            prompt_id: None,
1511            intent: Some(intent),
1512            mode: None,
1513            messages: vec![],
1514            tools: Vec::new(),
1515            tool_choice: None,
1516            stop: Vec::new(),
1517            temperature: AgentSettings::temperature_for_model(model, cx),
1518            thinking_allowed: false,
1519        };
1520
1521        for message in &self.messages {
1522            let mut request_message = LanguageModelRequestMessage {
1523                role: message.role,
1524                content: Vec::new(),
1525                cache: false,
1526            };
1527
1528            for segment in &message.segments {
1529                match segment {
1530                    MessageSegment::Text(text) => request_message
1531                        .content
1532                        .push(MessageContent::Text(text.clone())),
1533                    MessageSegment::Thinking { .. } => {}
1534                    MessageSegment::RedactedThinking(_) => {}
1535                }
1536            }
1537
1538            if request_message.content.is_empty() {
1539                continue;
1540            }
1541
1542            request.messages.push(request_message);
1543        }
1544
1545        request.messages.push(LanguageModelRequestMessage {
1546            role: Role::User,
1547            content: vec![MessageContent::Text(added_user_message)],
1548            cache: false,
1549        });
1550
1551        request
1552    }
1553
1554    /// Insert auto-generated notifications (if any) to the thread
1555    fn flush_notifications(
1556        &mut self,
1557        model: Arc<dyn LanguageModel>,
1558        intent: CompletionIntent,
1559        cx: &mut Context<Self>,
1560    ) {
1561        match intent {
1562            CompletionIntent::UserPrompt | CompletionIntent::ToolResults => {
1563                if let Some(pending_tool_use) = self.attach_tracked_files_state(model, cx) {
1564                    cx.emit(ThreadEvent::ToolFinished {
1565                        tool_use_id: pending_tool_use.id.clone(),
1566                        pending_tool_use: Some(pending_tool_use),
1567                    });
1568                }
1569            }
1570            CompletionIntent::ThreadSummarization
1571            | CompletionIntent::ThreadContextSummarization
1572            | CompletionIntent::CreateFile
1573            | CompletionIntent::EditFile
1574            | CompletionIntent::InlineAssist
1575            | CompletionIntent::TerminalInlineAssist
1576            | CompletionIntent::GenerateGitCommitMessage => {}
1577        };
1578    }
1579
1580    fn attach_tracked_files_state(
1581        &mut self,
1582        model: Arc<dyn LanguageModel>,
1583        cx: &mut App,
1584    ) -> Option<PendingToolUse> {
1585        // Represent notification as a simulated `project_notifications` tool call
1586        let tool_name = Arc::from("project_notifications");
1587        let tool = self.tools.read(cx).tool(&tool_name, cx)?;
1588
1589        if !self.profile.is_tool_enabled(tool.source(), tool.name(), cx) {
1590            return None;
1591        }
1592
1593        if self
1594            .action_log
1595            .update(cx, |log, cx| log.unnotified_user_edits(cx).is_none())
1596        {
1597            return None;
1598        }
1599
1600        let input = serde_json::json!({});
1601        let request = Arc::new(LanguageModelRequest::default()); // unused
1602        let window = None;
1603        let tool_result = tool.run(
1604            input,
1605            request,
1606            self.project.clone(),
1607            self.action_log.clone(),
1608            model.clone(),
1609            window,
1610            cx,
1611        );
1612
1613        let tool_use_id =
1614            LanguageModelToolUseId::from(format!("project_notifications_{}", self.messages.len()));
1615
1616        let tool_use = LanguageModelToolUse {
1617            id: tool_use_id.clone(),
1618            name: tool_name.clone(),
1619            raw_input: "{}".to_string(),
1620            input: serde_json::json!({}),
1621            is_input_complete: true,
1622        };
1623
1624        let tool_output = cx.background_executor().block(tool_result.output);
1625
1626        // Attach a project_notification tool call to the latest existing
1627        // Assistant message. We cannot create a new Assistant message
1628        // because thinking models require a `thinking` block that we
1629        // cannot mock. We cannot send a notification as a normal
1630        // (non-tool-use) User message because this distracts Agent
1631        // too much.
1632        let tool_message_id = self
1633            .messages
1634            .iter()
1635            .enumerate()
1636            .rfind(|(_, message)| message.role == Role::Assistant)
1637            .map(|(_, message)| message.id)?;
1638
1639        let tool_use_metadata = ToolUseMetadata {
1640            model: model.clone(),
1641            thread_id: self.id.clone(),
1642            prompt_id: self.last_prompt_id.clone(),
1643        };
1644
1645        self.tool_use
1646            .request_tool_use(tool_message_id, tool_use, tool_use_metadata.clone(), cx);
1647
1648        let pending_tool_use = self.tool_use.insert_tool_output(
1649            tool_use_id.clone(),
1650            tool_name,
1651            tool_output,
1652            self.configured_model.as_ref(),
1653            self.completion_mode,
1654        );
1655
1656        pending_tool_use
1657    }
1658
1659    pub fn stream_completion(
1660        &mut self,
1661        request: LanguageModelRequest,
1662        model: Arc<dyn LanguageModel>,
1663        intent: CompletionIntent,
1664        window: Option<AnyWindowHandle>,
1665        cx: &mut Context<Self>,
1666    ) {
1667        self.tool_use_limit_reached = false;
1668
1669        let pending_completion_id = post_inc(&mut self.completion_count);
1670        let mut request_callback_parameters = if self.request_callback.is_some() {
1671            Some((request.clone(), Vec::new()))
1672        } else {
1673            None
1674        };
1675        let prompt_id = self.last_prompt_id.clone();
1676        let tool_use_metadata = ToolUseMetadata {
1677            model: model.clone(),
1678            thread_id: self.id.clone(),
1679            prompt_id: prompt_id.clone(),
1680        };
1681
1682        let completion_mode = request
1683            .mode
1684            .unwrap_or(zed_llm_client::CompletionMode::Normal);
1685
1686        self.last_received_chunk_at = Some(Instant::now());
1687
1688        let task = cx.spawn(async move |thread, cx| {
1689            let stream_completion_future = model.stream_completion(request, &cx);
1690            let initial_token_usage =
1691                thread.read_with(cx, |thread, _cx| thread.cumulative_token_usage);
1692            let stream_completion = async {
1693                let mut events = stream_completion_future.await?;
1694
1695                let mut stop_reason = StopReason::EndTurn;
1696                let mut current_token_usage = TokenUsage::default();
1697
1698                thread
1699                    .update(cx, |_thread, cx| {
1700                        cx.emit(ThreadEvent::NewRequest);
1701                    })
1702                    .ok();
1703
1704                let mut request_assistant_message_id = None;
1705
1706                while let Some(event) = events.next().await {
1707                    if let Some((_, response_events)) = request_callback_parameters.as_mut() {
1708                        response_events
1709                            .push(event.as_ref().map_err(|error| error.to_string()).cloned());
1710                    }
1711
1712                    thread.update(cx, |thread, cx| {
1713                        match event? {
1714                            LanguageModelCompletionEvent::StartMessage { .. } => {
1715                                request_assistant_message_id =
1716                                    Some(thread.insert_assistant_message(
1717                                        vec![MessageSegment::Text(String::new())],
1718                                        cx,
1719                                    ));
1720                            }
1721                            LanguageModelCompletionEvent::Stop(reason) => {
1722                                stop_reason = reason;
1723                            }
1724                            LanguageModelCompletionEvent::UsageUpdate(token_usage) => {
1725                                thread.update_token_usage_at_last_message(token_usage);
1726                                thread.cumulative_token_usage = thread.cumulative_token_usage
1727                                    + token_usage
1728                                    - current_token_usage;
1729                                current_token_usage = token_usage;
1730                            }
1731                            LanguageModelCompletionEvent::Text(chunk) => {
1732                                thread.received_chunk();
1733
1734                                cx.emit(ThreadEvent::ReceivedTextChunk);
1735                                if let Some(last_message) = thread.messages.last_mut() {
1736                                    if last_message.role == Role::Assistant
1737                                        && !thread.tool_use.has_tool_results(last_message.id)
1738                                    {
1739                                        last_message.push_text(&chunk);
1740                                        cx.emit(ThreadEvent::StreamedAssistantText(
1741                                            last_message.id,
1742                                            chunk,
1743                                        ));
1744                                    } else {
1745                                        // If we won't have an Assistant message yet, assume this chunk marks the beginning
1746                                        // of a new Assistant response.
1747                                        //
1748                                        // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
1749                                        // will result in duplicating the text of the chunk in the rendered Markdown.
1750                                        request_assistant_message_id =
1751                                            Some(thread.insert_assistant_message(
1752                                                vec![MessageSegment::Text(chunk.to_string())],
1753                                                cx,
1754                                            ));
1755                                    };
1756                                }
1757                            }
1758                            LanguageModelCompletionEvent::Thinking {
1759                                text: chunk,
1760                                signature,
1761                            } => {
1762                                thread.received_chunk();
1763
1764                                if let Some(last_message) = thread.messages.last_mut() {
1765                                    if last_message.role == Role::Assistant
1766                                        && !thread.tool_use.has_tool_results(last_message.id)
1767                                    {
1768                                        last_message.push_thinking(&chunk, signature);
1769                                        cx.emit(ThreadEvent::StreamedAssistantThinking(
1770                                            last_message.id,
1771                                            chunk,
1772                                        ));
1773                                    } else {
1774                                        // If we won't have an Assistant message yet, assume this chunk marks the beginning
1775                                        // of a new Assistant response.
1776                                        //
1777                                        // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
1778                                        // will result in duplicating the text of the chunk in the rendered Markdown.
1779                                        request_assistant_message_id =
1780                                            Some(thread.insert_assistant_message(
1781                                                vec![MessageSegment::Thinking {
1782                                                    text: chunk.to_string(),
1783                                                    signature,
1784                                                }],
1785                                                cx,
1786                                            ));
1787                                    };
1788                                }
1789                            }
1790                            LanguageModelCompletionEvent::RedactedThinking { data } => {
1791                                thread.received_chunk();
1792
1793                                if let Some(last_message) = thread.messages.last_mut() {
1794                                    if last_message.role == Role::Assistant
1795                                        && !thread.tool_use.has_tool_results(last_message.id)
1796                                    {
1797                                        last_message.push_redacted_thinking(data);
1798                                    } else {
1799                                        request_assistant_message_id =
1800                                            Some(thread.insert_assistant_message(
1801                                                vec![MessageSegment::RedactedThinking(data)],
1802                                                cx,
1803                                            ));
1804                                    };
1805                                }
1806                            }
1807                            LanguageModelCompletionEvent::ToolUse(tool_use) => {
1808                                let last_assistant_message_id = request_assistant_message_id
1809                                    .unwrap_or_else(|| {
1810                                        let new_assistant_message_id =
1811                                            thread.insert_assistant_message(vec![], cx);
1812                                        request_assistant_message_id =
1813                                            Some(new_assistant_message_id);
1814                                        new_assistant_message_id
1815                                    });
1816
1817                                let tool_use_id = tool_use.id.clone();
1818                                let streamed_input = if tool_use.is_input_complete {
1819                                    None
1820                                } else {
1821                                    Some((&tool_use.input).clone())
1822                                };
1823
1824                                let ui_text = thread.tool_use.request_tool_use(
1825                                    last_assistant_message_id,
1826                                    tool_use,
1827                                    tool_use_metadata.clone(),
1828                                    cx,
1829                                );
1830
1831                                if let Some(input) = streamed_input {
1832                                    cx.emit(ThreadEvent::StreamedToolUse {
1833                                        tool_use_id,
1834                                        ui_text,
1835                                        input,
1836                                    });
1837                                }
1838                            }
1839                            LanguageModelCompletionEvent::ToolUseJsonParseError {
1840                                id,
1841                                tool_name,
1842                                raw_input: invalid_input_json,
1843                                json_parse_error,
1844                            } => {
1845                                thread.receive_invalid_tool_json(
1846                                    id,
1847                                    tool_name,
1848                                    invalid_input_json,
1849                                    json_parse_error,
1850                                    window,
1851                                    cx,
1852                                );
1853                            }
1854                            LanguageModelCompletionEvent::StatusUpdate(status_update) => {
1855                                if let Some(completion) = thread
1856                                    .pending_completions
1857                                    .iter_mut()
1858                                    .find(|completion| completion.id == pending_completion_id)
1859                                {
1860                                    match status_update {
1861                                        CompletionRequestStatus::Queued { position } => {
1862                                            completion.queue_state =
1863                                                QueueState::Queued { position };
1864                                        }
1865                                        CompletionRequestStatus::Started => {
1866                                            completion.queue_state = QueueState::Started;
1867                                        }
1868                                        CompletionRequestStatus::Failed {
1869                                            code,
1870                                            message,
1871                                            request_id: _,
1872                                            retry_after,
1873                                        } => {
1874                                            return Err(
1875                                                LanguageModelCompletionError::from_cloud_failure(
1876                                                    model.upstream_provider_name(),
1877                                                    code,
1878                                                    message,
1879                                                    retry_after.map(Duration::from_secs_f64),
1880                                                ),
1881                                            );
1882                                        }
1883                                        CompletionRequestStatus::UsageUpdated { amount, limit } => {
1884                                            thread.update_model_request_usage(
1885                                                amount as u32,
1886                                                limit,
1887                                                cx,
1888                                            );
1889                                        }
1890                                        CompletionRequestStatus::ToolUseLimitReached => {
1891                                            thread.tool_use_limit_reached = true;
1892                                            cx.emit(ThreadEvent::ToolUseLimitReached);
1893                                        }
1894                                    }
1895                                }
1896                            }
1897                        }
1898
1899                        thread.touch_updated_at();
1900                        cx.emit(ThreadEvent::StreamedCompletion);
1901                        cx.notify();
1902
1903                        thread.auto_capture_telemetry(cx);
1904                        Ok(())
1905                    })??;
1906
1907                    smol::future::yield_now().await;
1908                }
1909
1910                thread.update(cx, |thread, cx| {
1911                    thread.last_received_chunk_at = None;
1912                    thread
1913                        .pending_completions
1914                        .retain(|completion| completion.id != pending_completion_id);
1915
1916                    // If there is a response without tool use, summarize the message. Otherwise,
1917                    // allow two tool uses before summarizing.
1918                    if matches!(thread.summary, ThreadSummary::Pending)
1919                        && thread.messages.len() >= 2
1920                        && (!thread.has_pending_tool_uses() || thread.messages.len() >= 6)
1921                    {
1922                        thread.summarize(cx);
1923                    }
1924                })?;
1925
1926                anyhow::Ok(stop_reason)
1927            };
1928
1929            let result = stream_completion.await;
1930            let mut retry_scheduled = false;
1931
1932            thread
1933                .update(cx, |thread, cx| {
1934                    thread.finalize_pending_checkpoint(cx);
1935                    match result.as_ref() {
1936                        Ok(stop_reason) => {
1937                            match stop_reason {
1938                                StopReason::ToolUse => {
1939                                    let tool_uses =
1940                                        thread.use_pending_tools(window, model.clone(), cx);
1941                                    cx.emit(ThreadEvent::UsePendingTools { tool_uses });
1942                                }
1943                                StopReason::EndTurn | StopReason::MaxTokens => {
1944                                    thread.project.update(cx, |project, cx| {
1945                                        project.set_agent_location(None, cx);
1946                                    });
1947                                }
1948                                StopReason::Refusal => {
1949                                    thread.project.update(cx, |project, cx| {
1950                                        project.set_agent_location(None, cx);
1951                                    });
1952
1953                                    // Remove the turn that was refused.
1954                                    //
1955                                    // https://docs.anthropic.com/en/docs/test-and-evaluate/strengthen-guardrails/handle-streaming-refusals#reset-context-after-refusal
1956                                    {
1957                                        let mut messages_to_remove = Vec::new();
1958
1959                                        for (ix, message) in
1960                                            thread.messages.iter().enumerate().rev()
1961                                        {
1962                                            messages_to_remove.push(message.id);
1963
1964                                            if message.role == Role::User {
1965                                                if ix == 0 {
1966                                                    break;
1967                                                }
1968
1969                                                if let Some(prev_message) =
1970                                                    thread.messages.get(ix - 1)
1971                                                {
1972                                                    if prev_message.role == Role::Assistant {
1973                                                        break;
1974                                                    }
1975                                                }
1976                                            }
1977                                        }
1978
1979                                        for message_id in messages_to_remove {
1980                                            thread.delete_message(message_id, cx);
1981                                        }
1982                                    }
1983
1984                                    cx.emit(ThreadEvent::ShowError(ThreadError::Message {
1985                                        header: "Language model refusal".into(),
1986                                        message:
1987                                            "Model refused to generate content for safety reasons."
1988                                                .into(),
1989                                    }));
1990                                }
1991                            }
1992
1993                            // We successfully completed, so cancel any remaining retries.
1994                            thread.retry_state = None;
1995                        }
1996                        Err(error) => {
1997                            thread.project.update(cx, |project, cx| {
1998                                project.set_agent_location(None, cx);
1999                            });
2000
2001                            if error.is::<PaymentRequiredError>() {
2002                                cx.emit(ThreadEvent::ShowError(ThreadError::PaymentRequired));
2003                            } else if let Some(error) =
2004                                error.downcast_ref::<ModelRequestLimitReachedError>()
2005                            {
2006                                cx.emit(ThreadEvent::ShowError(
2007                                    ThreadError::ModelRequestLimitReached { plan: error.plan },
2008                                ));
2009                            } else if let Some(completion_error) =
2010                                error.downcast_ref::<LanguageModelCompletionError>()
2011                            {
2012                                match &completion_error {
2013                                    LanguageModelCompletionError::PromptTooLarge {
2014                                        tokens, ..
2015                                    } => {
2016                                        let tokens = tokens.unwrap_or_else(|| {
2017                                            // We didn't get an exact token count from the API, so fall back on our estimate.
2018                                            thread
2019                                                .total_token_usage()
2020                                                .map(|usage| usage.total)
2021                                                .unwrap_or(0)
2022                                                // We know the context window was exceeded in practice, so if our estimate was
2023                                                // lower than max tokens, the estimate was wrong; return that we exceeded by 1.
2024                                                .max(
2025                                                    model
2026                                                        .max_token_count_for_mode(completion_mode)
2027                                                        .saturating_add(1),
2028                                                )
2029                                        });
2030                                        thread.exceeded_window_error = Some(ExceededWindowError {
2031                                            model_id: model.id(),
2032                                            token_count: tokens,
2033                                        });
2034                                        cx.notify();
2035                                    }
2036                                    _ => {
2037                                        if let Some(retry_strategy) =
2038                                            Thread::get_retry_strategy(completion_error)
2039                                        {
2040                                            retry_scheduled = thread
2041                                                .handle_retryable_error_with_delay(
2042                                                    &completion_error,
2043                                                    Some(retry_strategy),
2044                                                    model.clone(),
2045                                                    intent,
2046                                                    window,
2047                                                    cx,
2048                                                );
2049                                        }
2050                                    }
2051                                }
2052                            }
2053
2054                            if !retry_scheduled {
2055                                thread.cancel_last_completion(window, cx);
2056                            }
2057                        }
2058                    }
2059
2060                    if !retry_scheduled {
2061                        cx.emit(ThreadEvent::Stopped(result.map_err(Arc::new)));
2062                    }
2063
2064                    if let Some((request_callback, (request, response_events))) = thread
2065                        .request_callback
2066                        .as_mut()
2067                        .zip(request_callback_parameters.as_ref())
2068                    {
2069                        request_callback(request, response_events);
2070                    }
2071
2072                    thread.auto_capture_telemetry(cx);
2073
2074                    if let Ok(initial_usage) = initial_token_usage {
2075                        let usage = thread.cumulative_token_usage - initial_usage;
2076
2077                        telemetry::event!(
2078                            "Assistant Thread Completion",
2079                            thread_id = thread.id().to_string(),
2080                            prompt_id = prompt_id,
2081                            model = model.telemetry_id(),
2082                            model_provider = model.provider_id().to_string(),
2083                            input_tokens = usage.input_tokens,
2084                            output_tokens = usage.output_tokens,
2085                            cache_creation_input_tokens = usage.cache_creation_input_tokens,
2086                            cache_read_input_tokens = usage.cache_read_input_tokens,
2087                        );
2088                    }
2089                })
2090                .ok();
2091        });
2092
2093        self.pending_completions.push(PendingCompletion {
2094            id: pending_completion_id,
2095            queue_state: QueueState::Sending,
2096            _task: task,
2097        });
2098    }
2099
2100    pub fn summarize(&mut self, cx: &mut Context<Self>) {
2101        let Some(model) = LanguageModelRegistry::read_global(cx).thread_summary_model() else {
2102            println!("No thread summary model");
2103            return;
2104        };
2105
2106        if !model.provider.is_authenticated(cx) {
2107            return;
2108        }
2109
2110        let added_user_message = include_str!("./prompts/summarize_thread_prompt.txt");
2111
2112        let request = self.to_summarize_request(
2113            &model.model,
2114            CompletionIntent::ThreadSummarization,
2115            added_user_message.into(),
2116            cx,
2117        );
2118
2119        self.summary = ThreadSummary::Generating;
2120
2121        self.pending_summary = cx.spawn(async move |this, cx| {
2122            let result = async {
2123                let mut messages = model.model.stream_completion(request, &cx).await?;
2124
2125                let mut new_summary = String::new();
2126                while let Some(event) = messages.next().await {
2127                    let Ok(event) = event else {
2128                        continue;
2129                    };
2130                    let text = match event {
2131                        LanguageModelCompletionEvent::Text(text) => text,
2132                        LanguageModelCompletionEvent::StatusUpdate(
2133                            CompletionRequestStatus::UsageUpdated { amount, limit },
2134                        ) => {
2135                            this.update(cx, |thread, cx| {
2136                                thread.update_model_request_usage(amount as u32, limit, cx);
2137                            })?;
2138                            continue;
2139                        }
2140                        _ => continue,
2141                    };
2142
2143                    let mut lines = text.lines();
2144                    new_summary.extend(lines.next());
2145
2146                    // Stop if the LLM generated multiple lines.
2147                    if lines.next().is_some() {
2148                        break;
2149                    }
2150                }
2151
2152                anyhow::Ok(new_summary)
2153            }
2154            .await;
2155
2156            this.update(cx, |this, cx| {
2157                match result {
2158                    Ok(new_summary) => {
2159                        if new_summary.is_empty() {
2160                            this.summary = ThreadSummary::Error;
2161                        } else {
2162                            this.summary = ThreadSummary::Ready(new_summary.into());
2163                        }
2164                    }
2165                    Err(err) => {
2166                        this.summary = ThreadSummary::Error;
2167                        log::error!("Failed to generate thread summary: {}", err);
2168                    }
2169                }
2170                cx.emit(ThreadEvent::SummaryGenerated);
2171            })
2172            .log_err()?;
2173
2174            Some(())
2175        });
2176    }
2177
2178    fn get_retry_strategy(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
2179        use LanguageModelCompletionError::*;
2180
2181        // General strategy here:
2182        // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
2183        // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), retry up to 4 times with exponential backoff.
2184        // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), retry up to 3 times.
2185        match error {
2186            HttpResponseError {
2187                status_code: StatusCode::TOO_MANY_REQUESTS,
2188                ..
2189            } => Some(RetryStrategy::ExponentialBackoff {
2190                initial_delay: BASE_RETRY_DELAY,
2191                max_attempts: MAX_RETRY_ATTEMPTS,
2192            }),
2193            ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
2194                Some(RetryStrategy::Fixed {
2195                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2196                    max_attempts: MAX_RETRY_ATTEMPTS,
2197                })
2198            }
2199            UpstreamProviderError {
2200                status,
2201                retry_after,
2202                ..
2203            } => match *status {
2204                StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
2205                    Some(RetryStrategy::Fixed {
2206                        delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2207                        max_attempts: MAX_RETRY_ATTEMPTS,
2208                    })
2209                }
2210                StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
2211                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2212                    // Internal Server Error could be anything, retry up to 3 times.
2213                    max_attempts: 3,
2214                }),
2215                status => {
2216                    // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
2217                    // but we frequently get them in practice. See https://http.dev/529
2218                    if status.as_u16() == 529 {
2219                        Some(RetryStrategy::Fixed {
2220                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2221                            max_attempts: MAX_RETRY_ATTEMPTS,
2222                        })
2223                    } else {
2224                        Some(RetryStrategy::Fixed {
2225                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2226                            max_attempts: 2,
2227                        })
2228                    }
2229                }
2230            },
2231            ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
2232                delay: BASE_RETRY_DELAY,
2233                max_attempts: 3,
2234            }),
2235            ApiReadResponseError { .. }
2236            | HttpSend { .. }
2237            | DeserializeResponse { .. }
2238            | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
2239                delay: BASE_RETRY_DELAY,
2240                max_attempts: 3,
2241            }),
2242            // Retrying these errors definitely shouldn't help.
2243            HttpResponseError {
2244                status_code:
2245                    StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
2246                ..
2247            }
2248            | AuthenticationError { .. }
2249            | PermissionError { .. } => None,
2250            // These errors might be transient, so retry them
2251            SerializeRequest { .. }
2252            | BuildRequestBody { .. }
2253            | PromptTooLarge { .. }
2254            | ApiEndpointNotFound { .. }
2255            | NoApiKey { .. } => Some(RetryStrategy::Fixed {
2256                delay: BASE_RETRY_DELAY,
2257                max_attempts: 2,
2258            }),
2259            // Retry all other 4xx and 5xx errors once.
2260            HttpResponseError { status_code, .. }
2261                if status_code.is_client_error() || status_code.is_server_error() =>
2262            {
2263                Some(RetryStrategy::Fixed {
2264                    delay: BASE_RETRY_DELAY,
2265                    max_attempts: 3,
2266                })
2267            }
2268            // Conservatively assume that any other errors are non-retryable
2269            HttpResponseError { .. } | Other(..) => Some(RetryStrategy::Fixed {
2270                delay: BASE_RETRY_DELAY,
2271                max_attempts: 2,
2272            }),
2273        }
2274    }
2275
2276    fn handle_retryable_error_with_delay(
2277        &mut self,
2278        error: &LanguageModelCompletionError,
2279        strategy: Option<RetryStrategy>,
2280        model: Arc<dyn LanguageModel>,
2281        intent: CompletionIntent,
2282        window: Option<AnyWindowHandle>,
2283        cx: &mut Context<Self>,
2284    ) -> bool {
2285        // Store context for the Retry button
2286        self.last_error_context = Some((model.clone(), intent));
2287
2288        // Only auto-retry if Burn Mode is enabled
2289        if self.completion_mode != CompletionMode::Burn {
2290            // Show error with retry options
2291            cx.emit(ThreadEvent::ShowError(ThreadError::RetryableError {
2292                message: format!(
2293                    "{}\n\nTo automatically retry when similar errors happen, enable Burn Mode.",
2294                    error
2295                )
2296                .into(),
2297                can_enable_burn_mode: true,
2298            }));
2299            return false;
2300        }
2301
2302        let Some(strategy) = strategy.or_else(|| Self::get_retry_strategy(error)) else {
2303            return false;
2304        };
2305
2306        let max_attempts = match &strategy {
2307            RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
2308            RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
2309        };
2310
2311        let retry_state = self.retry_state.get_or_insert(RetryState {
2312            attempt: 0,
2313            max_attempts,
2314            intent,
2315        });
2316
2317        retry_state.attempt += 1;
2318        let attempt = retry_state.attempt;
2319        let max_attempts = retry_state.max_attempts;
2320        let intent = retry_state.intent;
2321
2322        if attempt <= max_attempts {
2323            let delay = match &strategy {
2324                RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
2325                    let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
2326                    Duration::from_secs(delay_secs)
2327                }
2328                RetryStrategy::Fixed { delay, .. } => *delay,
2329            };
2330
2331            // Add a transient message to inform the user
2332            let delay_secs = delay.as_secs();
2333            let retry_message = if max_attempts == 1 {
2334                format!("{error}. Retrying in {delay_secs} seconds...")
2335            } else {
2336                format!(
2337                    "{error}. Retrying (attempt {attempt} of {max_attempts}) \
2338                    in {delay_secs} seconds..."
2339                )
2340            };
2341            log::warn!(
2342                "Retrying completion request (attempt {attempt} of {max_attempts}) \
2343                in {delay_secs} seconds: {error:?}",
2344            );
2345
2346            // Add a UI-only message instead of a regular message
2347            let id = self.next_message_id.post_inc();
2348            self.messages.push(Message {
2349                id,
2350                role: Role::System,
2351                segments: vec![MessageSegment::Text(retry_message)],
2352                loaded_context: LoadedContext::default(),
2353                creases: Vec::new(),
2354                is_hidden: false,
2355                ui_only: true,
2356            });
2357            cx.emit(ThreadEvent::MessageAdded(id));
2358
2359            // Schedule the retry
2360            let thread_handle = cx.entity().downgrade();
2361
2362            cx.spawn(async move |_thread, cx| {
2363                cx.background_executor().timer(delay).await;
2364
2365                thread_handle
2366                    .update(cx, |thread, cx| {
2367                        // Retry the completion
2368                        thread.send_to_model(model, intent, window, cx);
2369                    })
2370                    .log_err();
2371            })
2372            .detach();
2373
2374            true
2375        } else {
2376            // Max retries exceeded
2377            self.retry_state = None;
2378
2379            // Stop generating since we're giving up on retrying.
2380            self.pending_completions.clear();
2381
2382            // Show error alongside a Retry button, but no
2383            // Enable Burn Mode button (since it's already enabled)
2384            cx.emit(ThreadEvent::ShowError(ThreadError::RetryableError {
2385                message: format!("Failed after retrying: {}", error).into(),
2386                can_enable_burn_mode: false,
2387            }));
2388
2389            false
2390        }
2391    }
2392
2393    pub fn start_generating_detailed_summary_if_needed(
2394        &mut self,
2395        thread_store: WeakEntity<ThreadStore>,
2396        cx: &mut Context<Self>,
2397    ) {
2398        let Some(last_message_id) = self.messages.last().map(|message| message.id) else {
2399            return;
2400        };
2401
2402        match &*self.detailed_summary_rx.borrow() {
2403            DetailedSummaryState::Generating { message_id, .. }
2404            | DetailedSummaryState::Generated { message_id, .. }
2405                if *message_id == last_message_id =>
2406            {
2407                // Already up-to-date
2408                return;
2409            }
2410            _ => {}
2411        }
2412
2413        let Some(ConfiguredModel { model, provider }) =
2414            LanguageModelRegistry::read_global(cx).thread_summary_model()
2415        else {
2416            return;
2417        };
2418
2419        if !provider.is_authenticated(cx) {
2420            return;
2421        }
2422
2423        let added_user_message = include_str!("./prompts/summarize_thread_detailed_prompt.txt");
2424
2425        let request = self.to_summarize_request(
2426            &model,
2427            CompletionIntent::ThreadContextSummarization,
2428            added_user_message.into(),
2429            cx,
2430        );
2431
2432        *self.detailed_summary_tx.borrow_mut() = DetailedSummaryState::Generating {
2433            message_id: last_message_id,
2434        };
2435
2436        // Replace the detailed summarization task if there is one, cancelling it. It would probably
2437        // be better to allow the old task to complete, but this would require logic for choosing
2438        // which result to prefer (the old task could complete after the new one, resulting in a
2439        // stale summary).
2440        self.detailed_summary_task = cx.spawn(async move |thread, cx| {
2441            let stream = model.stream_completion_text(request, &cx);
2442            let Some(mut messages) = stream.await.log_err() else {
2443                thread
2444                    .update(cx, |thread, _cx| {
2445                        *thread.detailed_summary_tx.borrow_mut() =
2446                            DetailedSummaryState::NotGenerated;
2447                    })
2448                    .ok()?;
2449                return None;
2450            };
2451
2452            let mut new_detailed_summary = String::new();
2453
2454            while let Some(chunk) = messages.stream.next().await {
2455                if let Some(chunk) = chunk.log_err() {
2456                    new_detailed_summary.push_str(&chunk);
2457                }
2458            }
2459
2460            thread
2461                .update(cx, |thread, _cx| {
2462                    *thread.detailed_summary_tx.borrow_mut() = DetailedSummaryState::Generated {
2463                        text: new_detailed_summary.into(),
2464                        message_id: last_message_id,
2465                    };
2466                })
2467                .ok()?;
2468
2469            // Save thread so its summary can be reused later
2470            if let Some(thread) = thread.upgrade() {
2471                if let Ok(Ok(save_task)) = cx.update(|cx| {
2472                    thread_store
2473                        .update(cx, |thread_store, cx| thread_store.save_thread(&thread, cx))
2474                }) {
2475                    save_task.await.log_err();
2476                }
2477            }
2478
2479            Some(())
2480        });
2481    }
2482
2483    pub async fn wait_for_detailed_summary_or_text(
2484        this: &Entity<Self>,
2485        cx: &mut AsyncApp,
2486    ) -> Option<SharedString> {
2487        let mut detailed_summary_rx = this
2488            .read_with(cx, |this, _cx| this.detailed_summary_rx.clone())
2489            .ok()?;
2490        loop {
2491            match detailed_summary_rx.recv().await? {
2492                DetailedSummaryState::Generating { .. } => {}
2493                DetailedSummaryState::NotGenerated => {
2494                    return this.read_with(cx, |this, _cx| this.text().into()).ok();
2495                }
2496                DetailedSummaryState::Generated { text, .. } => return Some(text),
2497            }
2498        }
2499    }
2500
2501    pub fn latest_detailed_summary_or_text(&self) -> SharedString {
2502        self.detailed_summary_rx
2503            .borrow()
2504            .text()
2505            .unwrap_or_else(|| self.text().into())
2506    }
2507
2508    pub fn is_generating_detailed_summary(&self) -> bool {
2509        matches!(
2510            &*self.detailed_summary_rx.borrow(),
2511            DetailedSummaryState::Generating { .. }
2512        )
2513    }
2514
2515    pub fn use_pending_tools(
2516        &mut self,
2517        window: Option<AnyWindowHandle>,
2518        model: Arc<dyn LanguageModel>,
2519        cx: &mut Context<Self>,
2520    ) -> Vec<PendingToolUse> {
2521        self.auto_capture_telemetry(cx);
2522        let request =
2523            Arc::new(self.to_completion_request(model.clone(), CompletionIntent::ToolResults, cx));
2524        let pending_tool_uses = self
2525            .tool_use
2526            .pending_tool_uses()
2527            .into_iter()
2528            .filter(|tool_use| tool_use.status.is_idle())
2529            .cloned()
2530            .collect::<Vec<_>>();
2531
2532        for tool_use in pending_tool_uses.iter() {
2533            self.use_pending_tool(tool_use.clone(), request.clone(), model.clone(), window, cx);
2534        }
2535
2536        pending_tool_uses
2537    }
2538
2539    fn use_pending_tool(
2540        &mut self,
2541        tool_use: PendingToolUse,
2542        request: Arc<LanguageModelRequest>,
2543        model: Arc<dyn LanguageModel>,
2544        window: Option<AnyWindowHandle>,
2545        cx: &mut Context<Self>,
2546    ) {
2547        let Some(tool) = self.tools.read(cx).tool(&tool_use.name, cx) else {
2548            return self.handle_hallucinated_tool_use(tool_use.id, tool_use.name, window, cx);
2549        };
2550
2551        if !self.profile.is_tool_enabled(tool.source(), tool.name(), cx) {
2552            return self.handle_hallucinated_tool_use(tool_use.id, tool_use.name, window, cx);
2553        }
2554
2555        if tool.needs_confirmation(&tool_use.input, cx)
2556            && !AgentSettings::get_global(cx).always_allow_tool_actions
2557        {
2558            self.tool_use.confirm_tool_use(
2559                tool_use.id,
2560                tool_use.ui_text,
2561                tool_use.input,
2562                request,
2563                tool,
2564            );
2565            cx.emit(ThreadEvent::ToolConfirmationNeeded);
2566        } else {
2567            self.run_tool(
2568                tool_use.id,
2569                tool_use.ui_text,
2570                tool_use.input,
2571                request,
2572                tool,
2573                model,
2574                window,
2575                cx,
2576            );
2577        }
2578    }
2579
2580    pub fn handle_hallucinated_tool_use(
2581        &mut self,
2582        tool_use_id: LanguageModelToolUseId,
2583        hallucinated_tool_name: Arc<str>,
2584        window: Option<AnyWindowHandle>,
2585        cx: &mut Context<Thread>,
2586    ) {
2587        let available_tools = self.profile.enabled_tools(cx);
2588
2589        let tool_list = available_tools
2590            .iter()
2591            .map(|(name, tool)| format!("- {}: {}", name, tool.description()))
2592            .collect::<Vec<_>>()
2593            .join("\n");
2594
2595        let error_message = format!(
2596            "The tool '{}' doesn't exist or is not enabled. Available tools:\n{}",
2597            hallucinated_tool_name, tool_list
2598        );
2599
2600        let pending_tool_use = self.tool_use.insert_tool_output(
2601            tool_use_id.clone(),
2602            hallucinated_tool_name,
2603            Err(anyhow!("Missing tool call: {error_message}")),
2604            self.configured_model.as_ref(),
2605            self.completion_mode,
2606        );
2607
2608        cx.emit(ThreadEvent::MissingToolUse {
2609            tool_use_id: tool_use_id.clone(),
2610            ui_text: error_message.into(),
2611        });
2612
2613        self.tool_finished(tool_use_id, pending_tool_use, false, window, cx);
2614    }
2615
2616    pub fn receive_invalid_tool_json(
2617        &mut self,
2618        tool_use_id: LanguageModelToolUseId,
2619        tool_name: Arc<str>,
2620        invalid_json: Arc<str>,
2621        error: String,
2622        window: Option<AnyWindowHandle>,
2623        cx: &mut Context<Thread>,
2624    ) {
2625        log::error!("The model returned invalid input JSON: {invalid_json}");
2626
2627        let pending_tool_use = self.tool_use.insert_tool_output(
2628            tool_use_id.clone(),
2629            tool_name,
2630            Err(anyhow!("Error parsing input JSON: {error}")),
2631            self.configured_model.as_ref(),
2632            self.completion_mode,
2633        );
2634        let ui_text = if let Some(pending_tool_use) = &pending_tool_use {
2635            pending_tool_use.ui_text.clone()
2636        } else {
2637            log::error!(
2638                "There was no pending tool use for tool use {tool_use_id}, even though it finished (with invalid input JSON)."
2639            );
2640            format!("Unknown tool {}", tool_use_id).into()
2641        };
2642
2643        cx.emit(ThreadEvent::InvalidToolInput {
2644            tool_use_id: tool_use_id.clone(),
2645            ui_text,
2646            invalid_input_json: invalid_json,
2647        });
2648
2649        self.tool_finished(tool_use_id, pending_tool_use, false, window, cx);
2650    }
2651
2652    pub fn run_tool(
2653        &mut self,
2654        tool_use_id: LanguageModelToolUseId,
2655        ui_text: impl Into<SharedString>,
2656        input: serde_json::Value,
2657        request: Arc<LanguageModelRequest>,
2658        tool: Arc<dyn Tool>,
2659        model: Arc<dyn LanguageModel>,
2660        window: Option<AnyWindowHandle>,
2661        cx: &mut Context<Thread>,
2662    ) {
2663        let task =
2664            self.spawn_tool_use(tool_use_id.clone(), request, input, tool, model, window, cx);
2665        self.tool_use
2666            .run_pending_tool(tool_use_id, ui_text.into(), task);
2667    }
2668
2669    fn spawn_tool_use(
2670        &mut self,
2671        tool_use_id: LanguageModelToolUseId,
2672        request: Arc<LanguageModelRequest>,
2673        input: serde_json::Value,
2674        tool: Arc<dyn Tool>,
2675        model: Arc<dyn LanguageModel>,
2676        window: Option<AnyWindowHandle>,
2677        cx: &mut Context<Thread>,
2678    ) -> Task<()> {
2679        let tool_name: Arc<str> = tool.name().into();
2680
2681        let tool_result = tool.run(
2682            input,
2683            request,
2684            self.project.clone(),
2685            self.action_log.clone(),
2686            model,
2687            window,
2688            cx,
2689        );
2690
2691        // Store the card separately if it exists
2692        if let Some(card) = tool_result.card.clone() {
2693            self.tool_use
2694                .insert_tool_result_card(tool_use_id.clone(), card);
2695        }
2696
2697        cx.spawn({
2698            async move |thread: WeakEntity<Thread>, cx| {
2699                let output = tool_result.output.await;
2700
2701                thread
2702                    .update(cx, |thread, cx| {
2703                        let pending_tool_use = thread.tool_use.insert_tool_output(
2704                            tool_use_id.clone(),
2705                            tool_name,
2706                            output,
2707                            thread.configured_model.as_ref(),
2708                            thread.completion_mode,
2709                        );
2710                        thread.tool_finished(tool_use_id, pending_tool_use, false, window, cx);
2711                    })
2712                    .ok();
2713            }
2714        })
2715    }
2716
2717    fn tool_finished(
2718        &mut self,
2719        tool_use_id: LanguageModelToolUseId,
2720        pending_tool_use: Option<PendingToolUse>,
2721        canceled: bool,
2722        window: Option<AnyWindowHandle>,
2723        cx: &mut Context<Self>,
2724    ) {
2725        if self.all_tools_finished() {
2726            if let Some(ConfiguredModel { model, .. }) = self.configured_model.as_ref() {
2727                if !canceled {
2728                    self.send_to_model(model.clone(), CompletionIntent::ToolResults, window, cx);
2729                }
2730                self.auto_capture_telemetry(cx);
2731            }
2732        }
2733
2734        cx.emit(ThreadEvent::ToolFinished {
2735            tool_use_id,
2736            pending_tool_use,
2737        });
2738    }
2739
2740    /// Cancels the last pending completion, if there are any pending.
2741    ///
2742    /// Returns whether a completion was canceled.
2743    pub fn cancel_last_completion(
2744        &mut self,
2745        window: Option<AnyWindowHandle>,
2746        cx: &mut Context<Self>,
2747    ) -> bool {
2748        let mut canceled = self.pending_completions.pop().is_some() || self.retry_state.is_some();
2749
2750        self.retry_state = None;
2751
2752        for pending_tool_use in self.tool_use.cancel_pending() {
2753            canceled = true;
2754            self.tool_finished(
2755                pending_tool_use.id.clone(),
2756                Some(pending_tool_use),
2757                true,
2758                window,
2759                cx,
2760            );
2761        }
2762
2763        if canceled {
2764            cx.emit(ThreadEvent::CompletionCanceled);
2765
2766            // When canceled, we always want to insert the checkpoint.
2767            // (We skip over finalize_pending_checkpoint, because it
2768            // would conclude we didn't have anything to insert here.)
2769            if let Some(checkpoint) = self.pending_checkpoint.take() {
2770                self.insert_checkpoint(checkpoint, cx);
2771            }
2772        } else {
2773            self.finalize_pending_checkpoint(cx);
2774        }
2775
2776        canceled
2777    }
2778
2779    /// Signals that any in-progress editing should be canceled.
2780    ///
2781    /// This method is used to notify listeners (like ActiveThread) that
2782    /// they should cancel any editing operations.
2783    pub fn cancel_editing(&mut self, cx: &mut Context<Self>) {
2784        cx.emit(ThreadEvent::CancelEditing);
2785    }
2786
2787    pub fn feedback(&self) -> Option<ThreadFeedback> {
2788        self.feedback
2789    }
2790
2791    pub fn message_feedback(&self, message_id: MessageId) -> Option<ThreadFeedback> {
2792        self.message_feedback.get(&message_id).copied()
2793    }
2794
2795    pub fn report_message_feedback(
2796        &mut self,
2797        message_id: MessageId,
2798        feedback: ThreadFeedback,
2799        cx: &mut Context<Self>,
2800    ) -> Task<Result<()>> {
2801        if self.message_feedback.get(&message_id) == Some(&feedback) {
2802            return Task::ready(Ok(()));
2803        }
2804
2805        let final_project_snapshot = Self::project_snapshot(self.project.clone(), cx);
2806        let serialized_thread = self.serialize(cx);
2807        let thread_id = self.id().clone();
2808        let client = self.project.read(cx).client();
2809
2810        let enabled_tool_names: Vec<String> = self
2811            .profile
2812            .enabled_tools(cx)
2813            .iter()
2814            .map(|(name, _)| name.clone().into())
2815            .collect();
2816
2817        self.message_feedback.insert(message_id, feedback);
2818
2819        cx.notify();
2820
2821        let message_content = self
2822            .message(message_id)
2823            .map(|msg| msg.to_string())
2824            .unwrap_or_default();
2825
2826        cx.background_spawn(async move {
2827            let final_project_snapshot = final_project_snapshot.await;
2828            let serialized_thread = serialized_thread.await?;
2829            let thread_data =
2830                serde_json::to_value(serialized_thread).unwrap_or_else(|_| serde_json::Value::Null);
2831
2832            let rating = match feedback {
2833                ThreadFeedback::Positive => "positive",
2834                ThreadFeedback::Negative => "negative",
2835            };
2836            telemetry::event!(
2837                "Assistant Thread Rated",
2838                rating,
2839                thread_id,
2840                enabled_tool_names,
2841                message_id = message_id.0,
2842                message_content,
2843                thread_data,
2844                final_project_snapshot
2845            );
2846            client.telemetry().flush_events().await;
2847
2848            Ok(())
2849        })
2850    }
2851
2852    pub fn report_feedback(
2853        &mut self,
2854        feedback: ThreadFeedback,
2855        cx: &mut Context<Self>,
2856    ) -> Task<Result<()>> {
2857        let last_assistant_message_id = self
2858            .messages
2859            .iter()
2860            .rev()
2861            .find(|msg| msg.role == Role::Assistant)
2862            .map(|msg| msg.id);
2863
2864        if let Some(message_id) = last_assistant_message_id {
2865            self.report_message_feedback(message_id, feedback, cx)
2866        } else {
2867            let final_project_snapshot = Self::project_snapshot(self.project.clone(), cx);
2868            let serialized_thread = self.serialize(cx);
2869            let thread_id = self.id().clone();
2870            let client = self.project.read(cx).client();
2871            self.feedback = Some(feedback);
2872            cx.notify();
2873
2874            cx.background_spawn(async move {
2875                let final_project_snapshot = final_project_snapshot.await;
2876                let serialized_thread = serialized_thread.await?;
2877                let thread_data = serde_json::to_value(serialized_thread)
2878                    .unwrap_or_else(|_| serde_json::Value::Null);
2879
2880                let rating = match feedback {
2881                    ThreadFeedback::Positive => "positive",
2882                    ThreadFeedback::Negative => "negative",
2883                };
2884                telemetry::event!(
2885                    "Assistant Thread Rated",
2886                    rating,
2887                    thread_id,
2888                    thread_data,
2889                    final_project_snapshot
2890                );
2891                client.telemetry().flush_events().await;
2892
2893                Ok(())
2894            })
2895        }
2896    }
2897
2898    /// Create a snapshot of the current project state including git information and unsaved buffers.
2899    fn project_snapshot(
2900        project: Entity<Project>,
2901        cx: &mut Context<Self>,
2902    ) -> Task<Arc<ProjectSnapshot>> {
2903        let git_store = project.read(cx).git_store().clone();
2904        let worktree_snapshots: Vec<_> = project
2905            .read(cx)
2906            .visible_worktrees(cx)
2907            .map(|worktree| Self::worktree_snapshot(worktree, git_store.clone(), cx))
2908            .collect();
2909
2910        cx.spawn(async move |_, cx| {
2911            let worktree_snapshots = futures::future::join_all(worktree_snapshots).await;
2912
2913            let mut unsaved_buffers = Vec::new();
2914            cx.update(|app_cx| {
2915                let buffer_store = project.read(app_cx).buffer_store();
2916                for buffer_handle in buffer_store.read(app_cx).buffers() {
2917                    let buffer = buffer_handle.read(app_cx);
2918                    if buffer.is_dirty() {
2919                        if let Some(file) = buffer.file() {
2920                            let path = file.path().to_string_lossy().to_string();
2921                            unsaved_buffers.push(path);
2922                        }
2923                    }
2924                }
2925            })
2926            .ok();
2927
2928            Arc::new(ProjectSnapshot {
2929                worktree_snapshots,
2930                unsaved_buffer_paths: unsaved_buffers,
2931                timestamp: Utc::now(),
2932            })
2933        })
2934    }
2935
2936    fn worktree_snapshot(
2937        worktree: Entity<project::Worktree>,
2938        git_store: Entity<GitStore>,
2939        cx: &App,
2940    ) -> Task<WorktreeSnapshot> {
2941        cx.spawn(async move |cx| {
2942            // Get worktree path and snapshot
2943            let worktree_info = cx.update(|app_cx| {
2944                let worktree = worktree.read(app_cx);
2945                let path = worktree.abs_path().to_string_lossy().to_string();
2946                let snapshot = worktree.snapshot();
2947                (path, snapshot)
2948            });
2949
2950            let Ok((worktree_path, _snapshot)) = worktree_info else {
2951                return WorktreeSnapshot {
2952                    worktree_path: String::new(),
2953                    git_state: None,
2954                };
2955            };
2956
2957            let git_state = git_store
2958                .update(cx, |git_store, cx| {
2959                    git_store
2960                        .repositories()
2961                        .values()
2962                        .find(|repo| {
2963                            repo.read(cx)
2964                                .abs_path_to_repo_path(&worktree.read(cx).abs_path())
2965                                .is_some()
2966                        })
2967                        .cloned()
2968                })
2969                .ok()
2970                .flatten()
2971                .map(|repo| {
2972                    repo.update(cx, |repo, _| {
2973                        let current_branch =
2974                            repo.branch.as_ref().map(|branch| branch.name().to_owned());
2975                        repo.send_job(None, |state, _| async move {
2976                            let RepositoryState::Local { backend, .. } = state else {
2977                                return GitState {
2978                                    remote_url: None,
2979                                    head_sha: None,
2980                                    current_branch,
2981                                    diff: None,
2982                                };
2983                            };
2984
2985                            let remote_url = backend.remote_url("origin");
2986                            let head_sha = backend.head_sha().await;
2987                            let diff = backend.diff(DiffType::HeadToWorktree).await.ok();
2988
2989                            GitState {
2990                                remote_url,
2991                                head_sha,
2992                                current_branch,
2993                                diff,
2994                            }
2995                        })
2996                    })
2997                });
2998
2999            let git_state = match git_state {
3000                Some(git_state) => match git_state.ok() {
3001                    Some(git_state) => git_state.await.ok(),
3002                    None => None,
3003                },
3004                None => None,
3005            };
3006
3007            WorktreeSnapshot {
3008                worktree_path,
3009                git_state,
3010            }
3011        })
3012    }
3013
3014    pub fn to_markdown(&self, cx: &App) -> Result<String> {
3015        let mut markdown = Vec::new();
3016
3017        let summary = self.summary().or_default();
3018        writeln!(markdown, "# {summary}\n")?;
3019
3020        for message in self.messages() {
3021            writeln!(
3022                markdown,
3023                "## {role}\n",
3024                role = match message.role {
3025                    Role::User => "User",
3026                    Role::Assistant => "Agent",
3027                    Role::System => "System",
3028                }
3029            )?;
3030
3031            if !message.loaded_context.text.is_empty() {
3032                writeln!(markdown, "{}", message.loaded_context.text)?;
3033            }
3034
3035            if !message.loaded_context.images.is_empty() {
3036                writeln!(
3037                    markdown,
3038                    "\n{} images attached as context.\n",
3039                    message.loaded_context.images.len()
3040                )?;
3041            }
3042
3043            for segment in &message.segments {
3044                match segment {
3045                    MessageSegment::Text(text) => writeln!(markdown, "{}\n", text)?,
3046                    MessageSegment::Thinking { text, .. } => {
3047                        writeln!(markdown, "<think>\n{}\n</think>\n", text)?
3048                    }
3049                    MessageSegment::RedactedThinking(_) => {}
3050                }
3051            }
3052
3053            for tool_use in self.tool_uses_for_message(message.id, cx) {
3054                writeln!(
3055                    markdown,
3056                    "**Use Tool: {} ({})**",
3057                    tool_use.name, tool_use.id
3058                )?;
3059                writeln!(markdown, "```json")?;
3060                writeln!(
3061                    markdown,
3062                    "{}",
3063                    serde_json::to_string_pretty(&tool_use.input)?
3064                )?;
3065                writeln!(markdown, "```")?;
3066            }
3067
3068            for tool_result in self.tool_results_for_message(message.id) {
3069                write!(markdown, "\n**Tool Results: {}", tool_result.tool_use_id)?;
3070                if tool_result.is_error {
3071                    write!(markdown, " (Error)")?;
3072                }
3073
3074                writeln!(markdown, "**\n")?;
3075                match &tool_result.content {
3076                    LanguageModelToolResultContent::Text(text) => {
3077                        writeln!(markdown, "{text}")?;
3078                    }
3079                    LanguageModelToolResultContent::Image(image) => {
3080                        writeln!(markdown, "![Image](data:base64,{})", image.source)?;
3081                    }
3082                }
3083
3084                if let Some(output) = tool_result.output.as_ref() {
3085                    writeln!(
3086                        markdown,
3087                        "\n\nDebug Output:\n\n```json\n{}\n```\n",
3088                        serde_json::to_string_pretty(output)?
3089                    )?;
3090                }
3091            }
3092        }
3093
3094        Ok(String::from_utf8_lossy(&markdown).to_string())
3095    }
3096
3097    pub fn keep_edits_in_range(
3098        &mut self,
3099        buffer: Entity<language::Buffer>,
3100        buffer_range: Range<language::Anchor>,
3101        cx: &mut Context<Self>,
3102    ) {
3103        self.action_log.update(cx, |action_log, cx| {
3104            action_log.keep_edits_in_range(buffer, buffer_range, cx)
3105        });
3106    }
3107
3108    pub fn keep_all_edits(&mut self, cx: &mut Context<Self>) {
3109        self.action_log
3110            .update(cx, |action_log, cx| action_log.keep_all_edits(cx));
3111    }
3112
3113    pub fn reject_edits_in_ranges(
3114        &mut self,
3115        buffer: Entity<language::Buffer>,
3116        buffer_ranges: Vec<Range<language::Anchor>>,
3117        cx: &mut Context<Self>,
3118    ) -> Task<Result<()>> {
3119        self.action_log.update(cx, |action_log, cx| {
3120            action_log.reject_edits_in_ranges(buffer, buffer_ranges, cx)
3121        })
3122    }
3123
3124    pub fn action_log(&self) -> &Entity<ActionLog> {
3125        &self.action_log
3126    }
3127
3128    pub fn project(&self) -> &Entity<Project> {
3129        &self.project
3130    }
3131
3132    pub fn auto_capture_telemetry(&mut self, cx: &mut Context<Self>) {
3133        if !cx.has_flag::<feature_flags::ThreadAutoCaptureFeatureFlag>() {
3134            return;
3135        }
3136
3137        let now = Instant::now();
3138        if let Some(last) = self.last_auto_capture_at {
3139            if now.duration_since(last).as_secs() < 10 {
3140                return;
3141            }
3142        }
3143
3144        self.last_auto_capture_at = Some(now);
3145
3146        let thread_id = self.id().clone();
3147        let github_login = self
3148            .project
3149            .read(cx)
3150            .user_store()
3151            .read(cx)
3152            .current_user()
3153            .map(|user| user.github_login.clone());
3154        let client = self.project.read(cx).client();
3155        let serialize_task = self.serialize(cx);
3156
3157        cx.background_executor()
3158            .spawn(async move {
3159                if let Ok(serialized_thread) = serialize_task.await {
3160                    if let Ok(thread_data) = serde_json::to_value(serialized_thread) {
3161                        telemetry::event!(
3162                            "Agent Thread Auto-Captured",
3163                            thread_id = thread_id.to_string(),
3164                            thread_data = thread_data,
3165                            auto_capture_reason = "tracked_user",
3166                            github_login = github_login
3167                        );
3168
3169                        client.telemetry().flush_events().await;
3170                    }
3171                }
3172            })
3173            .detach();
3174    }
3175
3176    pub fn cumulative_token_usage(&self) -> TokenUsage {
3177        self.cumulative_token_usage
3178    }
3179
3180    pub fn token_usage_up_to_message(&self, message_id: MessageId) -> TotalTokenUsage {
3181        let Some(model) = self.configured_model.as_ref() else {
3182            return TotalTokenUsage::default();
3183        };
3184
3185        let max = model
3186            .model
3187            .max_token_count_for_mode(self.completion_mode().into());
3188
3189        let index = self
3190            .messages
3191            .iter()
3192            .position(|msg| msg.id == message_id)
3193            .unwrap_or(0);
3194
3195        if index == 0 {
3196            return TotalTokenUsage { total: 0, max };
3197        }
3198
3199        let token_usage = &self
3200            .request_token_usage
3201            .get(index - 1)
3202            .cloned()
3203            .unwrap_or_default();
3204
3205        TotalTokenUsage {
3206            total: token_usage.total_tokens(),
3207            max,
3208        }
3209    }
3210
3211    pub fn total_token_usage(&self) -> Option<TotalTokenUsage> {
3212        let model = self.configured_model.as_ref()?;
3213
3214        let max = model
3215            .model
3216            .max_token_count_for_mode(self.completion_mode().into());
3217
3218        if let Some(exceeded_error) = &self.exceeded_window_error {
3219            if model.model.id() == exceeded_error.model_id {
3220                return Some(TotalTokenUsage {
3221                    total: exceeded_error.token_count,
3222                    max,
3223                });
3224            }
3225        }
3226
3227        let total = self
3228            .token_usage_at_last_message()
3229            .unwrap_or_default()
3230            .total_tokens();
3231
3232        Some(TotalTokenUsage { total, max })
3233    }
3234
3235    fn token_usage_at_last_message(&self) -> Option<TokenUsage> {
3236        self.request_token_usage
3237            .get(self.messages.len().saturating_sub(1))
3238            .or_else(|| self.request_token_usage.last())
3239            .cloned()
3240    }
3241
3242    fn update_token_usage_at_last_message(&mut self, token_usage: TokenUsage) {
3243        let placeholder = self.token_usage_at_last_message().unwrap_or_default();
3244        self.request_token_usage
3245            .resize(self.messages.len(), placeholder);
3246
3247        if let Some(last) = self.request_token_usage.last_mut() {
3248            *last = token_usage;
3249        }
3250    }
3251
3252    fn update_model_request_usage(&self, amount: u32, limit: UsageLimit, cx: &mut Context<Self>) {
3253        self.project.update(cx, |project, cx| {
3254            project.user_store().update(cx, |user_store, cx| {
3255                user_store.update_model_request_usage(
3256                    ModelRequestUsage(RequestUsage {
3257                        amount: amount as i32,
3258                        limit,
3259                    }),
3260                    cx,
3261                )
3262            })
3263        });
3264    }
3265
3266    pub fn deny_tool_use(
3267        &mut self,
3268        tool_use_id: LanguageModelToolUseId,
3269        tool_name: Arc<str>,
3270        window: Option<AnyWindowHandle>,
3271        cx: &mut Context<Self>,
3272    ) {
3273        let err = Err(anyhow::anyhow!(
3274            "Permission to run tool action denied by user"
3275        ));
3276
3277        self.tool_use.insert_tool_output(
3278            tool_use_id.clone(),
3279            tool_name,
3280            err,
3281            self.configured_model.as_ref(),
3282            self.completion_mode,
3283        );
3284        self.tool_finished(tool_use_id.clone(), None, true, window, cx);
3285    }
3286}
3287
3288#[derive(Debug, Clone, Error)]
3289pub enum ThreadError {
3290    #[error("Payment required")]
3291    PaymentRequired,
3292    #[error("Model request limit reached")]
3293    ModelRequestLimitReached { plan: Plan },
3294    #[error("Message {header}: {message}")]
3295    Message {
3296        header: SharedString,
3297        message: SharedString,
3298    },
3299    #[error("Retryable error: {message}")]
3300    RetryableError {
3301        message: SharedString,
3302        can_enable_burn_mode: bool,
3303    },
3304}
3305
3306#[derive(Debug, Clone)]
3307pub enum ThreadEvent {
3308    ShowError(ThreadError),
3309    StreamedCompletion,
3310    ReceivedTextChunk,
3311    NewRequest,
3312    StreamedAssistantText(MessageId, String),
3313    StreamedAssistantThinking(MessageId, String),
3314    StreamedToolUse {
3315        tool_use_id: LanguageModelToolUseId,
3316        ui_text: Arc<str>,
3317        input: serde_json::Value,
3318    },
3319    MissingToolUse {
3320        tool_use_id: LanguageModelToolUseId,
3321        ui_text: Arc<str>,
3322    },
3323    InvalidToolInput {
3324        tool_use_id: LanguageModelToolUseId,
3325        ui_text: Arc<str>,
3326        invalid_input_json: Arc<str>,
3327    },
3328    Stopped(Result<StopReason, Arc<anyhow::Error>>),
3329    MessageAdded(MessageId),
3330    MessageEdited(MessageId),
3331    MessageDeleted(MessageId),
3332    SummaryGenerated,
3333    SummaryChanged,
3334    UsePendingTools {
3335        tool_uses: Vec<PendingToolUse>,
3336    },
3337    ToolFinished {
3338        #[allow(unused)]
3339        tool_use_id: LanguageModelToolUseId,
3340        /// The pending tool use that corresponds to this tool.
3341        pending_tool_use: Option<PendingToolUse>,
3342    },
3343    CheckpointChanged,
3344    ToolConfirmationNeeded,
3345    ToolUseLimitReached,
3346    CancelEditing,
3347    CompletionCanceled,
3348    ProfileChanged,
3349}
3350
3351impl EventEmitter<ThreadEvent> for Thread {}
3352
3353struct PendingCompletion {
3354    id: usize,
3355    queue_state: QueueState,
3356    _task: Task<()>,
3357}
3358
3359#[cfg(test)]
3360mod tests {
3361    use super::*;
3362    use crate::{
3363        context::load_context, context_store::ContextStore, thread_store, thread_store::ThreadStore,
3364    };
3365
3366    // Test-specific constants
3367    const TEST_RATE_LIMIT_RETRY_SECS: u64 = 30;
3368    use agent_settings::{AgentProfileId, AgentSettings, LanguageModelParameters};
3369    use assistant_tool::ToolRegistry;
3370    use assistant_tools;
3371    use futures::StreamExt;
3372    use futures::future::BoxFuture;
3373    use futures::stream::BoxStream;
3374    use gpui::TestAppContext;
3375    use http_client;
3376    use language_model::fake_provider::{FakeLanguageModel, FakeLanguageModelProvider};
3377    use language_model::{
3378        LanguageModelCompletionError, LanguageModelName, LanguageModelProviderId,
3379        LanguageModelProviderName, LanguageModelToolChoice,
3380    };
3381    use parking_lot::Mutex;
3382    use project::{FakeFs, Project};
3383    use prompt_store::PromptBuilder;
3384    use serde_json::json;
3385    use settings::{Settings, SettingsStore};
3386    use std::sync::Arc;
3387    use std::time::Duration;
3388    use theme::ThemeSettings;
3389    use util::path;
3390    use workspace::Workspace;
3391
3392    #[gpui::test]
3393    async fn test_message_with_context(cx: &mut TestAppContext) {
3394        init_test_settings(cx);
3395
3396        let project = create_test_project(
3397            cx,
3398            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3399        )
3400        .await;
3401
3402        let (_workspace, _thread_store, thread, context_store, model) =
3403            setup_test_environment(cx, project.clone()).await;
3404
3405        add_file_to_context(&project, &context_store, "test/code.rs", cx)
3406            .await
3407            .unwrap();
3408
3409        let context =
3410            context_store.read_with(cx, |store, _| store.context().next().cloned().unwrap());
3411        let loaded_context = cx
3412            .update(|cx| load_context(vec![context], &project, &None, cx))
3413            .await;
3414
3415        // Insert user message with context
3416        let message_id = thread.update(cx, |thread, cx| {
3417            thread.insert_user_message(
3418                "Please explain this code",
3419                loaded_context,
3420                None,
3421                Vec::new(),
3422                cx,
3423            )
3424        });
3425
3426        // Check content and context in message object
3427        let message = thread.read_with(cx, |thread, _| thread.message(message_id).unwrap().clone());
3428
3429        // Use different path format strings based on platform for the test
3430        #[cfg(windows)]
3431        let path_part = r"test\code.rs";
3432        #[cfg(not(windows))]
3433        let path_part = "test/code.rs";
3434
3435        let expected_context = format!(
3436            r#"
3437<context>
3438The following items were attached by the user. They are up-to-date and don't need to be re-read.
3439
3440<files>
3441```rs {path_part}
3442fn main() {{
3443    println!("Hello, world!");
3444}}
3445```
3446</files>
3447</context>
3448"#
3449        );
3450
3451        assert_eq!(message.role, Role::User);
3452        assert_eq!(message.segments.len(), 1);
3453        assert_eq!(
3454            message.segments[0],
3455            MessageSegment::Text("Please explain this code".to_string())
3456        );
3457        assert_eq!(message.loaded_context.text, expected_context);
3458
3459        // Check message in request
3460        let request = thread.update(cx, |thread, cx| {
3461            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3462        });
3463
3464        assert_eq!(request.messages.len(), 2);
3465        let expected_full_message = format!("{}Please explain this code", expected_context);
3466        assert_eq!(request.messages[1].string_contents(), expected_full_message);
3467    }
3468
3469    #[gpui::test]
3470    async fn test_only_include_new_contexts(cx: &mut TestAppContext) {
3471        init_test_settings(cx);
3472
3473        let project = create_test_project(
3474            cx,
3475            json!({
3476                "file1.rs": "fn function1() {}\n",
3477                "file2.rs": "fn function2() {}\n",
3478                "file3.rs": "fn function3() {}\n",
3479                "file4.rs": "fn function4() {}\n",
3480            }),
3481        )
3482        .await;
3483
3484        let (_, _thread_store, thread, context_store, model) =
3485            setup_test_environment(cx, project.clone()).await;
3486
3487        // First message with context 1
3488        add_file_to_context(&project, &context_store, "test/file1.rs", cx)
3489            .await
3490            .unwrap();
3491        let new_contexts = context_store.update(cx, |store, cx| {
3492            store.new_context_for_thread(thread.read(cx), None)
3493        });
3494        assert_eq!(new_contexts.len(), 1);
3495        let loaded_context = cx
3496            .update(|cx| load_context(new_contexts, &project, &None, cx))
3497            .await;
3498        let message1_id = thread.update(cx, |thread, cx| {
3499            thread.insert_user_message("Message 1", loaded_context, None, Vec::new(), cx)
3500        });
3501
3502        // Second message with contexts 1 and 2 (context 1 should be skipped as it's already included)
3503        add_file_to_context(&project, &context_store, "test/file2.rs", cx)
3504            .await
3505            .unwrap();
3506        let new_contexts = context_store.update(cx, |store, cx| {
3507            store.new_context_for_thread(thread.read(cx), None)
3508        });
3509        assert_eq!(new_contexts.len(), 1);
3510        let loaded_context = cx
3511            .update(|cx| load_context(new_contexts, &project, &None, cx))
3512            .await;
3513        let message2_id = thread.update(cx, |thread, cx| {
3514            thread.insert_user_message("Message 2", loaded_context, None, Vec::new(), cx)
3515        });
3516
3517        // Third message with all three contexts (contexts 1 and 2 should be skipped)
3518        //
3519        add_file_to_context(&project, &context_store, "test/file3.rs", cx)
3520            .await
3521            .unwrap();
3522        let new_contexts = context_store.update(cx, |store, cx| {
3523            store.new_context_for_thread(thread.read(cx), None)
3524        });
3525        assert_eq!(new_contexts.len(), 1);
3526        let loaded_context = cx
3527            .update(|cx| load_context(new_contexts, &project, &None, cx))
3528            .await;
3529        let message3_id = thread.update(cx, |thread, cx| {
3530            thread.insert_user_message("Message 3", loaded_context, None, Vec::new(), cx)
3531        });
3532
3533        // Check what contexts are included in each message
3534        let (message1, message2, message3) = thread.read_with(cx, |thread, _| {
3535            (
3536                thread.message(message1_id).unwrap().clone(),
3537                thread.message(message2_id).unwrap().clone(),
3538                thread.message(message3_id).unwrap().clone(),
3539            )
3540        });
3541
3542        // First message should include context 1
3543        assert!(message1.loaded_context.text.contains("file1.rs"));
3544
3545        // Second message should include only context 2 (not 1)
3546        assert!(!message2.loaded_context.text.contains("file1.rs"));
3547        assert!(message2.loaded_context.text.contains("file2.rs"));
3548
3549        // Third message should include only context 3 (not 1 or 2)
3550        assert!(!message3.loaded_context.text.contains("file1.rs"));
3551        assert!(!message3.loaded_context.text.contains("file2.rs"));
3552        assert!(message3.loaded_context.text.contains("file3.rs"));
3553
3554        // Check entire request to make sure all contexts are properly included
3555        let request = thread.update(cx, |thread, cx| {
3556            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3557        });
3558
3559        // The request should contain all 3 messages
3560        assert_eq!(request.messages.len(), 4);
3561
3562        // Check that the contexts are properly formatted in each message
3563        assert!(request.messages[1].string_contents().contains("file1.rs"));
3564        assert!(!request.messages[1].string_contents().contains("file2.rs"));
3565        assert!(!request.messages[1].string_contents().contains("file3.rs"));
3566
3567        assert!(!request.messages[2].string_contents().contains("file1.rs"));
3568        assert!(request.messages[2].string_contents().contains("file2.rs"));
3569        assert!(!request.messages[2].string_contents().contains("file3.rs"));
3570
3571        assert!(!request.messages[3].string_contents().contains("file1.rs"));
3572        assert!(!request.messages[3].string_contents().contains("file2.rs"));
3573        assert!(request.messages[3].string_contents().contains("file3.rs"));
3574
3575        add_file_to_context(&project, &context_store, "test/file4.rs", cx)
3576            .await
3577            .unwrap();
3578        let new_contexts = context_store.update(cx, |store, cx| {
3579            store.new_context_for_thread(thread.read(cx), Some(message2_id))
3580        });
3581        assert_eq!(new_contexts.len(), 3);
3582        let loaded_context = cx
3583            .update(|cx| load_context(new_contexts, &project, &None, cx))
3584            .await
3585            .loaded_context;
3586
3587        assert!(!loaded_context.text.contains("file1.rs"));
3588        assert!(loaded_context.text.contains("file2.rs"));
3589        assert!(loaded_context.text.contains("file3.rs"));
3590        assert!(loaded_context.text.contains("file4.rs"));
3591
3592        let new_contexts = context_store.update(cx, |store, cx| {
3593            // Remove file4.rs
3594            store.remove_context(&loaded_context.contexts[2].handle(), cx);
3595            store.new_context_for_thread(thread.read(cx), Some(message2_id))
3596        });
3597        assert_eq!(new_contexts.len(), 2);
3598        let loaded_context = cx
3599            .update(|cx| load_context(new_contexts, &project, &None, cx))
3600            .await
3601            .loaded_context;
3602
3603        assert!(!loaded_context.text.contains("file1.rs"));
3604        assert!(loaded_context.text.contains("file2.rs"));
3605        assert!(loaded_context.text.contains("file3.rs"));
3606        assert!(!loaded_context.text.contains("file4.rs"));
3607
3608        let new_contexts = context_store.update(cx, |store, cx| {
3609            // Remove file3.rs
3610            store.remove_context(&loaded_context.contexts[1].handle(), cx);
3611            store.new_context_for_thread(thread.read(cx), Some(message2_id))
3612        });
3613        assert_eq!(new_contexts.len(), 1);
3614        let loaded_context = cx
3615            .update(|cx| load_context(new_contexts, &project, &None, cx))
3616            .await
3617            .loaded_context;
3618
3619        assert!(!loaded_context.text.contains("file1.rs"));
3620        assert!(loaded_context.text.contains("file2.rs"));
3621        assert!(!loaded_context.text.contains("file3.rs"));
3622        assert!(!loaded_context.text.contains("file4.rs"));
3623    }
3624
3625    #[gpui::test]
3626    async fn test_message_without_files(cx: &mut TestAppContext) {
3627        init_test_settings(cx);
3628
3629        let project = create_test_project(
3630            cx,
3631            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3632        )
3633        .await;
3634
3635        let (_, _thread_store, thread, _context_store, model) =
3636            setup_test_environment(cx, project.clone()).await;
3637
3638        // Insert user message without any context (empty context vector)
3639        let message_id = thread.update(cx, |thread, cx| {
3640            thread.insert_user_message(
3641                "What is the best way to learn Rust?",
3642                ContextLoadResult::default(),
3643                None,
3644                Vec::new(),
3645                cx,
3646            )
3647        });
3648
3649        // Check content and context in message object
3650        let message = thread.read_with(cx, |thread, _| thread.message(message_id).unwrap().clone());
3651
3652        // Context should be empty when no files are included
3653        assert_eq!(message.role, Role::User);
3654        assert_eq!(message.segments.len(), 1);
3655        assert_eq!(
3656            message.segments[0],
3657            MessageSegment::Text("What is the best way to learn Rust?".to_string())
3658        );
3659        assert_eq!(message.loaded_context.text, "");
3660
3661        // Check message in request
3662        let request = thread.update(cx, |thread, cx| {
3663            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3664        });
3665
3666        assert_eq!(request.messages.len(), 2);
3667        assert_eq!(
3668            request.messages[1].string_contents(),
3669            "What is the best way to learn Rust?"
3670        );
3671
3672        // Add second message, also without context
3673        let message2_id = thread.update(cx, |thread, cx| {
3674            thread.insert_user_message(
3675                "Are there any good books?",
3676                ContextLoadResult::default(),
3677                None,
3678                Vec::new(),
3679                cx,
3680            )
3681        });
3682
3683        let message2 =
3684            thread.read_with(cx, |thread, _| thread.message(message2_id).unwrap().clone());
3685        assert_eq!(message2.loaded_context.text, "");
3686
3687        // Check that both messages appear in the request
3688        let request = thread.update(cx, |thread, cx| {
3689            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3690        });
3691
3692        assert_eq!(request.messages.len(), 3);
3693        assert_eq!(
3694            request.messages[1].string_contents(),
3695            "What is the best way to learn Rust?"
3696        );
3697        assert_eq!(
3698            request.messages[2].string_contents(),
3699            "Are there any good books?"
3700        );
3701    }
3702
3703    #[gpui::test]
3704    #[ignore] // turn this test on when project_notifications tool is re-enabled
3705    async fn test_stale_buffer_notification(cx: &mut TestAppContext) {
3706        init_test_settings(cx);
3707
3708        let project = create_test_project(
3709            cx,
3710            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3711        )
3712        .await;
3713
3714        let (_workspace, _thread_store, thread, context_store, model) =
3715            setup_test_environment(cx, project.clone()).await;
3716
3717        // Add a buffer to the context. This will be a tracked buffer
3718        let buffer = add_file_to_context(&project, &context_store, "test/code.rs", cx)
3719            .await
3720            .unwrap();
3721
3722        let context = context_store
3723            .read_with(cx, |store, _| store.context().next().cloned())
3724            .unwrap();
3725        let loaded_context = cx
3726            .update(|cx| load_context(vec![context], &project, &None, cx))
3727            .await;
3728
3729        // Insert user message and assistant response
3730        thread.update(cx, |thread, cx| {
3731            thread.insert_user_message("Explain this code", loaded_context, None, Vec::new(), cx);
3732            thread.insert_assistant_message(
3733                vec![MessageSegment::Text("This code prints 42.".into())],
3734                cx,
3735            );
3736        });
3737        cx.run_until_parked();
3738
3739        // We shouldn't have a stale buffer notification yet
3740        let notifications = thread.read_with(cx, |thread, _| {
3741            find_tool_uses(thread, "project_notifications")
3742        });
3743        assert!(
3744            notifications.is_empty(),
3745            "Should not have stale buffer notification before buffer is modified"
3746        );
3747
3748        // Modify the buffer
3749        buffer.update(cx, |buffer, cx| {
3750            buffer.edit(
3751                [(1..1, "\n    println!(\"Added a new line\");\n")],
3752                None,
3753                cx,
3754            );
3755        });
3756
3757        // Insert another user message
3758        thread.update(cx, |thread, cx| {
3759            thread.insert_user_message(
3760                "What does the code do now?",
3761                ContextLoadResult::default(),
3762                None,
3763                Vec::new(),
3764                cx,
3765            )
3766        });
3767        cx.run_until_parked();
3768
3769        // Check for the stale buffer warning
3770        thread.update(cx, |thread, cx| {
3771            thread.flush_notifications(model.clone(), CompletionIntent::UserPrompt, cx)
3772        });
3773        cx.run_until_parked();
3774
3775        let notifications = thread.read_with(cx, |thread, _cx| {
3776            find_tool_uses(thread, "project_notifications")
3777        });
3778
3779        let [notification] = notifications.as_slice() else {
3780            panic!("Should have a `project_notifications` tool use");
3781        };
3782
3783        let Some(notification_content) = notification.content.to_str() else {
3784            panic!("`project_notifications` should return text");
3785        };
3786
3787        assert!(notification_content.contains("These files have changed since the last read:"));
3788        assert!(notification_content.contains("code.rs"));
3789
3790        // Insert another user message and flush notifications again
3791        thread.update(cx, |thread, cx| {
3792            thread.insert_user_message(
3793                "Can you tell me more?",
3794                ContextLoadResult::default(),
3795                None,
3796                Vec::new(),
3797                cx,
3798            )
3799        });
3800
3801        thread.update(cx, |thread, cx| {
3802            thread.flush_notifications(model.clone(), CompletionIntent::UserPrompt, cx)
3803        });
3804        cx.run_until_parked();
3805
3806        // There should be no new notifications (we already flushed one)
3807        let notifications = thread.read_with(cx, |thread, _cx| {
3808            find_tool_uses(thread, "project_notifications")
3809        });
3810
3811        assert_eq!(
3812            notifications.len(),
3813            1,
3814            "Should still have only one notification after second flush - no duplicates"
3815        );
3816    }
3817
3818    fn find_tool_uses(thread: &Thread, tool_name: &str) -> Vec<LanguageModelToolResult> {
3819        thread
3820            .messages()
3821            .flat_map(|message| {
3822                thread
3823                    .tool_results_for_message(message.id)
3824                    .into_iter()
3825                    .filter(|result| result.tool_name == tool_name.into())
3826                    .cloned()
3827                    .collect::<Vec<_>>()
3828            })
3829            .collect()
3830    }
3831
3832    #[gpui::test]
3833    async fn test_storing_profile_setting_per_thread(cx: &mut TestAppContext) {
3834        init_test_settings(cx);
3835
3836        let project = create_test_project(
3837            cx,
3838            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3839        )
3840        .await;
3841
3842        let (_workspace, thread_store, thread, _context_store, _model) =
3843            setup_test_environment(cx, project.clone()).await;
3844
3845        // Check that we are starting with the default profile
3846        let profile = cx.read(|cx| thread.read(cx).profile.clone());
3847        let tool_set = cx.read(|cx| thread_store.read(cx).tools());
3848        assert_eq!(
3849            profile,
3850            AgentProfile::new(AgentProfileId::default(), tool_set)
3851        );
3852    }
3853
3854    #[gpui::test]
3855    async fn test_serializing_thread_profile(cx: &mut TestAppContext) {
3856        init_test_settings(cx);
3857
3858        let project = create_test_project(
3859            cx,
3860            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3861        )
3862        .await;
3863
3864        let (_workspace, thread_store, thread, _context_store, _model) =
3865            setup_test_environment(cx, project.clone()).await;
3866
3867        // Profile gets serialized with default values
3868        let serialized = thread
3869            .update(cx, |thread, cx| thread.serialize(cx))
3870            .await
3871            .unwrap();
3872
3873        assert_eq!(serialized.profile, Some(AgentProfileId::default()));
3874
3875        let deserialized = cx.update(|cx| {
3876            thread.update(cx, |thread, cx| {
3877                Thread::deserialize(
3878                    thread.id.clone(),
3879                    serialized,
3880                    thread.project.clone(),
3881                    thread.tools.clone(),
3882                    thread.prompt_builder.clone(),
3883                    thread.project_context.clone(),
3884                    None,
3885                    cx,
3886                )
3887            })
3888        });
3889        let tool_set = cx.read(|cx| thread_store.read(cx).tools());
3890
3891        assert_eq!(
3892            deserialized.profile,
3893            AgentProfile::new(AgentProfileId::default(), tool_set)
3894        );
3895    }
3896
3897    #[gpui::test]
3898    async fn test_temperature_setting(cx: &mut TestAppContext) {
3899        init_test_settings(cx);
3900
3901        let project = create_test_project(
3902            cx,
3903            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3904        )
3905        .await;
3906
3907        let (_workspace, _thread_store, thread, _context_store, model) =
3908            setup_test_environment(cx, project.clone()).await;
3909
3910        // Both model and provider
3911        cx.update(|cx| {
3912            AgentSettings::override_global(
3913                AgentSettings {
3914                    model_parameters: vec![LanguageModelParameters {
3915                        provider: Some(model.provider_id().0.to_string().into()),
3916                        model: Some(model.id().0.clone()),
3917                        temperature: Some(0.66),
3918                    }],
3919                    ..AgentSettings::get_global(cx).clone()
3920                },
3921                cx,
3922            );
3923        });
3924
3925        let request = thread.update(cx, |thread, cx| {
3926            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3927        });
3928        assert_eq!(request.temperature, Some(0.66));
3929
3930        // Only model
3931        cx.update(|cx| {
3932            AgentSettings::override_global(
3933                AgentSettings {
3934                    model_parameters: vec![LanguageModelParameters {
3935                        provider: None,
3936                        model: Some(model.id().0.clone()),
3937                        temperature: Some(0.66),
3938                    }],
3939                    ..AgentSettings::get_global(cx).clone()
3940                },
3941                cx,
3942            );
3943        });
3944
3945        let request = thread.update(cx, |thread, cx| {
3946            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3947        });
3948        assert_eq!(request.temperature, Some(0.66));
3949
3950        // Only provider
3951        cx.update(|cx| {
3952            AgentSettings::override_global(
3953                AgentSettings {
3954                    model_parameters: vec![LanguageModelParameters {
3955                        provider: Some(model.provider_id().0.to_string().into()),
3956                        model: None,
3957                        temperature: Some(0.66),
3958                    }],
3959                    ..AgentSettings::get_global(cx).clone()
3960                },
3961                cx,
3962            );
3963        });
3964
3965        let request = thread.update(cx, |thread, cx| {
3966            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3967        });
3968        assert_eq!(request.temperature, Some(0.66));
3969
3970        // Same model name, different provider
3971        cx.update(|cx| {
3972            AgentSettings::override_global(
3973                AgentSettings {
3974                    model_parameters: vec![LanguageModelParameters {
3975                        provider: Some("anthropic".into()),
3976                        model: Some(model.id().0.clone()),
3977                        temperature: Some(0.66),
3978                    }],
3979                    ..AgentSettings::get_global(cx).clone()
3980                },
3981                cx,
3982            );
3983        });
3984
3985        let request = thread.update(cx, |thread, cx| {
3986            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3987        });
3988        assert_eq!(request.temperature, None);
3989    }
3990
3991    #[gpui::test]
3992    async fn test_thread_summary(cx: &mut TestAppContext) {
3993        init_test_settings(cx);
3994
3995        let project = create_test_project(cx, json!({})).await;
3996
3997        let (_, _thread_store, thread, _context_store, model) =
3998            setup_test_environment(cx, project.clone()).await;
3999
4000        // Initial state should be pending
4001        thread.read_with(cx, |thread, _| {
4002            assert!(matches!(thread.summary(), ThreadSummary::Pending));
4003            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
4004        });
4005
4006        // Manually setting the summary should not be allowed in this state
4007        thread.update(cx, |thread, cx| {
4008            thread.set_summary("This should not work", cx);
4009        });
4010
4011        thread.read_with(cx, |thread, _| {
4012            assert!(matches!(thread.summary(), ThreadSummary::Pending));
4013        });
4014
4015        // Send a message
4016        thread.update(cx, |thread, cx| {
4017            thread.insert_user_message("Hi!", ContextLoadResult::default(), None, vec![], cx);
4018            thread.send_to_model(
4019                model.clone(),
4020                CompletionIntent::ThreadSummarization,
4021                None,
4022                cx,
4023            );
4024        });
4025
4026        let fake_model = model.as_fake();
4027        simulate_successful_response(&fake_model, cx);
4028
4029        // Should start generating summary when there are >= 2 messages
4030        thread.read_with(cx, |thread, _| {
4031            assert_eq!(*thread.summary(), ThreadSummary::Generating);
4032        });
4033
4034        // Should not be able to set the summary while generating
4035        thread.update(cx, |thread, cx| {
4036            thread.set_summary("This should not work either", cx);
4037        });
4038
4039        thread.read_with(cx, |thread, _| {
4040            assert!(matches!(thread.summary(), ThreadSummary::Generating));
4041            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
4042        });
4043
4044        cx.run_until_parked();
4045        fake_model.stream_last_completion_response("Brief");
4046        fake_model.stream_last_completion_response(" Introduction");
4047        fake_model.end_last_completion_stream();
4048        cx.run_until_parked();
4049
4050        // Summary should be set
4051        thread.read_with(cx, |thread, _| {
4052            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
4053            assert_eq!(thread.summary().or_default(), "Brief Introduction");
4054        });
4055
4056        // Now we should be able to set a summary
4057        thread.update(cx, |thread, cx| {
4058            thread.set_summary("Brief Intro", cx);
4059        });
4060
4061        thread.read_with(cx, |thread, _| {
4062            assert_eq!(thread.summary().or_default(), "Brief Intro");
4063        });
4064
4065        // Test setting an empty summary (should default to DEFAULT)
4066        thread.update(cx, |thread, cx| {
4067            thread.set_summary("", cx);
4068        });
4069
4070        thread.read_with(cx, |thread, _| {
4071            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
4072            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
4073        });
4074    }
4075
4076    #[gpui::test]
4077    async fn test_thread_summary_error_set_manually(cx: &mut TestAppContext) {
4078        init_test_settings(cx);
4079
4080        let project = create_test_project(cx, json!({})).await;
4081
4082        let (_, _thread_store, thread, _context_store, model) =
4083            setup_test_environment(cx, project.clone()).await;
4084
4085        test_summarize_error(&model, &thread, cx);
4086
4087        // Now we should be able to set a summary
4088        thread.update(cx, |thread, cx| {
4089            thread.set_summary("Brief Intro", cx);
4090        });
4091
4092        thread.read_with(cx, |thread, _| {
4093            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
4094            assert_eq!(thread.summary().or_default(), "Brief Intro");
4095        });
4096    }
4097
4098    #[gpui::test]
4099    async fn test_thread_summary_error_retry(cx: &mut TestAppContext) {
4100        init_test_settings(cx);
4101
4102        let project = create_test_project(cx, json!({})).await;
4103
4104        let (_, _thread_store, thread, _context_store, model) =
4105            setup_test_environment(cx, project.clone()).await;
4106
4107        test_summarize_error(&model, &thread, cx);
4108
4109        // Sending another message should not trigger another summarize request
4110        thread.update(cx, |thread, cx| {
4111            thread.insert_user_message(
4112                "How are you?",
4113                ContextLoadResult::default(),
4114                None,
4115                vec![],
4116                cx,
4117            );
4118            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4119        });
4120
4121        let fake_model = model.as_fake();
4122        simulate_successful_response(&fake_model, cx);
4123
4124        thread.read_with(cx, |thread, _| {
4125            // State is still Error, not Generating
4126            assert!(matches!(thread.summary(), ThreadSummary::Error));
4127        });
4128
4129        // But the summarize request can be invoked manually
4130        thread.update(cx, |thread, cx| {
4131            thread.summarize(cx);
4132        });
4133
4134        thread.read_with(cx, |thread, _| {
4135            assert!(matches!(thread.summary(), ThreadSummary::Generating));
4136        });
4137
4138        cx.run_until_parked();
4139        fake_model.stream_last_completion_response("A successful summary");
4140        fake_model.end_last_completion_stream();
4141        cx.run_until_parked();
4142
4143        thread.read_with(cx, |thread, _| {
4144            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
4145            assert_eq!(thread.summary().or_default(), "A successful summary");
4146        });
4147    }
4148
4149    // Helper to create a model that returns errors
4150    enum TestError {
4151        Overloaded,
4152        InternalServerError,
4153    }
4154
4155    struct ErrorInjector {
4156        inner: Arc<FakeLanguageModel>,
4157        error_type: TestError,
4158    }
4159
4160    impl ErrorInjector {
4161        fn new(error_type: TestError) -> Self {
4162            Self {
4163                inner: Arc::new(FakeLanguageModel::default()),
4164                error_type,
4165            }
4166        }
4167    }
4168
4169    impl LanguageModel for ErrorInjector {
4170        fn id(&self) -> LanguageModelId {
4171            self.inner.id()
4172        }
4173
4174        fn name(&self) -> LanguageModelName {
4175            self.inner.name()
4176        }
4177
4178        fn provider_id(&self) -> LanguageModelProviderId {
4179            self.inner.provider_id()
4180        }
4181
4182        fn provider_name(&self) -> LanguageModelProviderName {
4183            self.inner.provider_name()
4184        }
4185
4186        fn supports_tools(&self) -> bool {
4187            self.inner.supports_tools()
4188        }
4189
4190        fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
4191            self.inner.supports_tool_choice(choice)
4192        }
4193
4194        fn supports_images(&self) -> bool {
4195            self.inner.supports_images()
4196        }
4197
4198        fn telemetry_id(&self) -> String {
4199            self.inner.telemetry_id()
4200        }
4201
4202        fn max_token_count(&self) -> u64 {
4203            self.inner.max_token_count()
4204        }
4205
4206        fn count_tokens(
4207            &self,
4208            request: LanguageModelRequest,
4209            cx: &App,
4210        ) -> BoxFuture<'static, Result<u64>> {
4211            self.inner.count_tokens(request, cx)
4212        }
4213
4214        fn stream_completion(
4215            &self,
4216            _request: LanguageModelRequest,
4217            _cx: &AsyncApp,
4218        ) -> BoxFuture<
4219            'static,
4220            Result<
4221                BoxStream<
4222                    'static,
4223                    Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
4224                >,
4225                LanguageModelCompletionError,
4226            >,
4227        > {
4228            let error = match self.error_type {
4229                TestError::Overloaded => LanguageModelCompletionError::ServerOverloaded {
4230                    provider: self.provider_name(),
4231                    retry_after: None,
4232                },
4233                TestError::InternalServerError => {
4234                    LanguageModelCompletionError::ApiInternalServerError {
4235                        provider: self.provider_name(),
4236                        message: "I'm a teapot orbiting the sun".to_string(),
4237                    }
4238                }
4239            };
4240            async move {
4241                let stream = futures::stream::once(async move { Err(error) });
4242                Ok(stream.boxed())
4243            }
4244            .boxed()
4245        }
4246
4247        fn as_fake(&self) -> &FakeLanguageModel {
4248            &self.inner
4249        }
4250    }
4251
4252    #[gpui::test]
4253    async fn test_retry_on_overloaded_error(cx: &mut TestAppContext) {
4254        init_test_settings(cx);
4255
4256        let project = create_test_project(cx, json!({})).await;
4257        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4258
4259        // Enable Burn Mode to allow retries
4260        thread.update(cx, |thread, _| {
4261            thread.set_completion_mode(CompletionMode::Burn);
4262        });
4263
4264        // Create model that returns overloaded error
4265        let model = Arc::new(ErrorInjector::new(TestError::Overloaded));
4266
4267        // Insert a user message
4268        thread.update(cx, |thread, cx| {
4269            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4270        });
4271
4272        // Start completion
4273        thread.update(cx, |thread, cx| {
4274            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4275        });
4276
4277        cx.run_until_parked();
4278
4279        thread.read_with(cx, |thread, _| {
4280            assert!(thread.retry_state.is_some(), "Should have retry state");
4281            let retry_state = thread.retry_state.as_ref().unwrap();
4282            assert_eq!(retry_state.attempt, 1, "Should be first retry attempt");
4283            assert_eq!(
4284                retry_state.max_attempts, MAX_RETRY_ATTEMPTS,
4285                "Should retry MAX_RETRY_ATTEMPTS times for overloaded errors"
4286            );
4287        });
4288
4289        // Check that a retry message was added
4290        thread.read_with(cx, |thread, _| {
4291            let mut messages = thread.messages();
4292            assert!(
4293                messages.any(|msg| {
4294                    msg.role == Role::System
4295                        && msg.ui_only
4296                        && msg.segments.iter().any(|seg| {
4297                            if let MessageSegment::Text(text) = seg {
4298                                text.contains("overloaded")
4299                                    && text
4300                                        .contains(&format!("attempt 1 of {}", MAX_RETRY_ATTEMPTS))
4301                            } else {
4302                                false
4303                            }
4304                        })
4305                }),
4306                "Should have added a system retry message"
4307            );
4308        });
4309
4310        let retry_count = thread.update(cx, |thread, _| {
4311            thread
4312                .messages
4313                .iter()
4314                .filter(|m| {
4315                    m.ui_only
4316                        && m.segments.iter().any(|s| {
4317                            if let MessageSegment::Text(text) = s {
4318                                text.contains("Retrying") && text.contains("seconds")
4319                            } else {
4320                                false
4321                            }
4322                        })
4323                })
4324                .count()
4325        });
4326
4327        assert_eq!(retry_count, 1, "Should have one retry message");
4328    }
4329
4330    #[gpui::test]
4331    async fn test_retry_on_internal_server_error(cx: &mut TestAppContext) {
4332        init_test_settings(cx);
4333
4334        let project = create_test_project(cx, json!({})).await;
4335        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4336
4337        // Enable Burn Mode to allow retries
4338        thread.update(cx, |thread, _| {
4339            thread.set_completion_mode(CompletionMode::Burn);
4340        });
4341
4342        // Create model that returns internal server error
4343        let model = Arc::new(ErrorInjector::new(TestError::InternalServerError));
4344
4345        // Insert a user message
4346        thread.update(cx, |thread, cx| {
4347            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4348        });
4349
4350        // Start completion
4351        thread.update(cx, |thread, cx| {
4352            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4353        });
4354
4355        cx.run_until_parked();
4356
4357        // Check retry state on thread
4358        thread.read_with(cx, |thread, _| {
4359            assert!(thread.retry_state.is_some(), "Should have retry state");
4360            let retry_state = thread.retry_state.as_ref().unwrap();
4361            assert_eq!(retry_state.attempt, 1, "Should be first retry attempt");
4362            assert_eq!(
4363                retry_state.max_attempts, 3,
4364                "Should have correct max attempts"
4365            );
4366        });
4367
4368        // Check that a retry message was added with provider name
4369        thread.read_with(cx, |thread, _| {
4370            let mut messages = thread.messages();
4371            assert!(
4372                messages.any(|msg| {
4373                    msg.role == Role::System
4374                        && msg.ui_only
4375                        && msg.segments.iter().any(|seg| {
4376                            if let MessageSegment::Text(text) = seg {
4377                                text.contains("internal")
4378                                    && text.contains("Fake")
4379                                    && text.contains("Retrying")
4380                                    && text.contains("attempt 1 of 3")
4381                                    && text.contains("seconds")
4382                            } else {
4383                                false
4384                            }
4385                        })
4386                }),
4387                "Should have added a system retry message with provider name"
4388            );
4389        });
4390
4391        // Count retry messages
4392        let retry_count = thread.update(cx, |thread, _| {
4393            thread
4394                .messages
4395                .iter()
4396                .filter(|m| {
4397                    m.ui_only
4398                        && m.segments.iter().any(|s| {
4399                            if let MessageSegment::Text(text) = s {
4400                                text.contains("Retrying") && text.contains("seconds")
4401                            } else {
4402                                false
4403                            }
4404                        })
4405                })
4406                .count()
4407        });
4408
4409        assert_eq!(retry_count, 1, "Should have one retry message");
4410    }
4411
4412    #[gpui::test]
4413    async fn test_exponential_backoff_on_retries(cx: &mut TestAppContext) {
4414        init_test_settings(cx);
4415
4416        let project = create_test_project(cx, json!({})).await;
4417        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4418
4419        // Enable Burn Mode to allow retries
4420        thread.update(cx, |thread, _| {
4421            thread.set_completion_mode(CompletionMode::Burn);
4422        });
4423
4424        // Create model that returns internal server error
4425        let model = Arc::new(ErrorInjector::new(TestError::InternalServerError));
4426
4427        // Insert a user message
4428        thread.update(cx, |thread, cx| {
4429            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4430        });
4431
4432        // Track retry events and completion count
4433        // Track completion events
4434        let completion_count = Arc::new(Mutex::new(0));
4435        let completion_count_clone = completion_count.clone();
4436
4437        let _subscription = thread.update(cx, |_, cx| {
4438            cx.subscribe(&thread, move |_, _, event: &ThreadEvent, _| {
4439                if let ThreadEvent::NewRequest = event {
4440                    *completion_count_clone.lock() += 1;
4441                }
4442            })
4443        });
4444
4445        // First attempt
4446        thread.update(cx, |thread, cx| {
4447            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4448        });
4449        cx.run_until_parked();
4450
4451        // Should have scheduled first retry - count retry messages
4452        let retry_count = thread.update(cx, |thread, _| {
4453            thread
4454                .messages
4455                .iter()
4456                .filter(|m| {
4457                    m.ui_only
4458                        && m.segments.iter().any(|s| {
4459                            if let MessageSegment::Text(text) = s {
4460                                text.contains("Retrying") && text.contains("seconds")
4461                            } else {
4462                                false
4463                            }
4464                        })
4465                })
4466                .count()
4467        });
4468        assert_eq!(retry_count, 1, "Should have scheduled first retry");
4469
4470        // Check retry state
4471        thread.read_with(cx, |thread, _| {
4472            assert!(thread.retry_state.is_some(), "Should have retry state");
4473            let retry_state = thread.retry_state.as_ref().unwrap();
4474            assert_eq!(retry_state.attempt, 1, "Should be first retry attempt");
4475            assert_eq!(
4476                retry_state.max_attempts, 3,
4477                "Internal server errors should retry up to 3 times"
4478            );
4479        });
4480
4481        // Advance clock for first retry
4482        cx.executor().advance_clock(BASE_RETRY_DELAY);
4483        cx.run_until_parked();
4484
4485        // Advance clock for second retry
4486        cx.executor().advance_clock(BASE_RETRY_DELAY);
4487        cx.run_until_parked();
4488
4489        // Advance clock for third retry
4490        cx.executor().advance_clock(BASE_RETRY_DELAY);
4491        cx.run_until_parked();
4492
4493        // Should have completed all retries - count retry messages
4494        let retry_count = thread.update(cx, |thread, _| {
4495            thread
4496                .messages
4497                .iter()
4498                .filter(|m| {
4499                    m.ui_only
4500                        && m.segments.iter().any(|s| {
4501                            if let MessageSegment::Text(text) = s {
4502                                text.contains("Retrying") && text.contains("seconds")
4503                            } else {
4504                                false
4505                            }
4506                        })
4507                })
4508                .count()
4509        });
4510        assert_eq!(
4511            retry_count, 3,
4512            "Should have 3 retries for internal server errors"
4513        );
4514
4515        // For internal server errors, we retry 3 times and then give up
4516        // Check that retry_state is cleared after all retries
4517        thread.read_with(cx, |thread, _| {
4518            assert!(
4519                thread.retry_state.is_none(),
4520                "Retry state should be cleared after all retries"
4521            );
4522        });
4523
4524        // Verify total attempts (1 initial + 3 retries)
4525        assert_eq!(
4526            *completion_count.lock(),
4527            4,
4528            "Should have attempted once plus 3 retries"
4529        );
4530    }
4531
4532    #[gpui::test]
4533    async fn test_max_retries_exceeded(cx: &mut TestAppContext) {
4534        init_test_settings(cx);
4535
4536        let project = create_test_project(cx, json!({})).await;
4537        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4538
4539        // Enable Burn Mode to allow retries
4540        thread.update(cx, |thread, _| {
4541            thread.set_completion_mode(CompletionMode::Burn);
4542        });
4543
4544        // Create model that returns overloaded error
4545        let model = Arc::new(ErrorInjector::new(TestError::Overloaded));
4546
4547        // Insert a user message
4548        thread.update(cx, |thread, cx| {
4549            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4550        });
4551
4552        // Track events
4553        let stopped_with_error = Arc::new(Mutex::new(false));
4554        let stopped_with_error_clone = stopped_with_error.clone();
4555
4556        let _subscription = thread.update(cx, |_, cx| {
4557            cx.subscribe(&thread, move |_, _, event: &ThreadEvent, _| {
4558                if let ThreadEvent::Stopped(Err(_)) = event {
4559                    *stopped_with_error_clone.lock() = true;
4560                }
4561            })
4562        });
4563
4564        // Start initial completion
4565        thread.update(cx, |thread, cx| {
4566            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4567        });
4568        cx.run_until_parked();
4569
4570        // Advance through all retries
4571        for _ in 0..MAX_RETRY_ATTEMPTS {
4572            cx.executor().advance_clock(BASE_RETRY_DELAY);
4573            cx.run_until_parked();
4574        }
4575
4576        let retry_count = thread.update(cx, |thread, _| {
4577            thread
4578                .messages
4579                .iter()
4580                .filter(|m| {
4581                    m.ui_only
4582                        && m.segments.iter().any(|s| {
4583                            if let MessageSegment::Text(text) = s {
4584                                text.contains("Retrying") && text.contains("seconds")
4585                            } else {
4586                                false
4587                            }
4588                        })
4589                })
4590                .count()
4591        });
4592
4593        // After max retries, should emit Stopped(Err(...)) event
4594        assert_eq!(
4595            retry_count, MAX_RETRY_ATTEMPTS as usize,
4596            "Should have attempted MAX_RETRY_ATTEMPTS retries for overloaded errors"
4597        );
4598        assert!(
4599            *stopped_with_error.lock(),
4600            "Should emit Stopped(Err(...)) event after max retries exceeded"
4601        );
4602
4603        // Retry state should be cleared
4604        thread.read_with(cx, |thread, _| {
4605            assert!(
4606                thread.retry_state.is_none(),
4607                "Retry state should be cleared after max retries"
4608            );
4609
4610            // Verify we have the expected number of retry messages
4611            let retry_messages = thread
4612                .messages
4613                .iter()
4614                .filter(|msg| msg.ui_only && msg.role == Role::System)
4615                .count();
4616            assert_eq!(
4617                retry_messages, MAX_RETRY_ATTEMPTS as usize,
4618                "Should have MAX_RETRY_ATTEMPTS retry messages for overloaded errors"
4619            );
4620        });
4621    }
4622
4623    #[gpui::test]
4624    async fn test_retry_message_removed_on_retry(cx: &mut TestAppContext) {
4625        init_test_settings(cx);
4626
4627        let project = create_test_project(cx, json!({})).await;
4628        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4629
4630        // Enable Burn Mode to allow retries
4631        thread.update(cx, |thread, _| {
4632            thread.set_completion_mode(CompletionMode::Burn);
4633        });
4634
4635        // We'll use a wrapper to switch behavior after first failure
4636        struct RetryTestModel {
4637            inner: Arc<FakeLanguageModel>,
4638            failed_once: Arc<Mutex<bool>>,
4639        }
4640
4641        impl LanguageModel for RetryTestModel {
4642            fn id(&self) -> LanguageModelId {
4643                self.inner.id()
4644            }
4645
4646            fn name(&self) -> LanguageModelName {
4647                self.inner.name()
4648            }
4649
4650            fn provider_id(&self) -> LanguageModelProviderId {
4651                self.inner.provider_id()
4652            }
4653
4654            fn provider_name(&self) -> LanguageModelProviderName {
4655                self.inner.provider_name()
4656            }
4657
4658            fn supports_tools(&self) -> bool {
4659                self.inner.supports_tools()
4660            }
4661
4662            fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
4663                self.inner.supports_tool_choice(choice)
4664            }
4665
4666            fn supports_images(&self) -> bool {
4667                self.inner.supports_images()
4668            }
4669
4670            fn telemetry_id(&self) -> String {
4671                self.inner.telemetry_id()
4672            }
4673
4674            fn max_token_count(&self) -> u64 {
4675                self.inner.max_token_count()
4676            }
4677
4678            fn count_tokens(
4679                &self,
4680                request: LanguageModelRequest,
4681                cx: &App,
4682            ) -> BoxFuture<'static, Result<u64>> {
4683                self.inner.count_tokens(request, cx)
4684            }
4685
4686            fn stream_completion(
4687                &self,
4688                request: LanguageModelRequest,
4689                cx: &AsyncApp,
4690            ) -> BoxFuture<
4691                'static,
4692                Result<
4693                    BoxStream<
4694                        'static,
4695                        Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
4696                    >,
4697                    LanguageModelCompletionError,
4698                >,
4699            > {
4700                if !*self.failed_once.lock() {
4701                    *self.failed_once.lock() = true;
4702                    let provider = self.provider_name();
4703                    // Return error on first attempt
4704                    let stream = futures::stream::once(async move {
4705                        Err(LanguageModelCompletionError::ServerOverloaded {
4706                            provider,
4707                            retry_after: None,
4708                        })
4709                    });
4710                    async move { Ok(stream.boxed()) }.boxed()
4711                } else {
4712                    // Succeed on retry
4713                    self.inner.stream_completion(request, cx)
4714                }
4715            }
4716
4717            fn as_fake(&self) -> &FakeLanguageModel {
4718                &self.inner
4719            }
4720        }
4721
4722        let model = Arc::new(RetryTestModel {
4723            inner: Arc::new(FakeLanguageModel::default()),
4724            failed_once: Arc::new(Mutex::new(false)),
4725        });
4726
4727        // Insert a user message
4728        thread.update(cx, |thread, cx| {
4729            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4730        });
4731
4732        // Track message deletions
4733        // Track when retry completes successfully
4734        let retry_completed = Arc::new(Mutex::new(false));
4735        let retry_completed_clone = retry_completed.clone();
4736
4737        let _subscription = thread.update(cx, |_, cx| {
4738            cx.subscribe(&thread, move |_, _, event: &ThreadEvent, _| {
4739                if let ThreadEvent::StreamedCompletion = event {
4740                    *retry_completed_clone.lock() = true;
4741                }
4742            })
4743        });
4744
4745        // Start completion
4746        thread.update(cx, |thread, cx| {
4747            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4748        });
4749        cx.run_until_parked();
4750
4751        // Get the retry message ID
4752        let retry_message_id = thread.read_with(cx, |thread, _| {
4753            thread
4754                .messages()
4755                .find(|msg| msg.role == Role::System && msg.ui_only)
4756                .map(|msg| msg.id)
4757                .expect("Should have a retry message")
4758        });
4759
4760        // Wait for retry
4761        cx.executor().advance_clock(BASE_RETRY_DELAY);
4762        cx.run_until_parked();
4763
4764        // Stream some successful content
4765        let fake_model = model.as_fake();
4766        // After the retry, there should be a new pending completion
4767        let pending = fake_model.pending_completions();
4768        assert!(
4769            !pending.is_empty(),
4770            "Should have a pending completion after retry"
4771        );
4772        fake_model.stream_completion_response(&pending[0], "Success!");
4773        fake_model.end_completion_stream(&pending[0]);
4774        cx.run_until_parked();
4775
4776        // Check that the retry completed successfully
4777        assert!(
4778            *retry_completed.lock(),
4779            "Retry should have completed successfully"
4780        );
4781
4782        // Retry message should still exist but be marked as ui_only
4783        thread.read_with(cx, |thread, _| {
4784            let retry_msg = thread
4785                .message(retry_message_id)
4786                .expect("Retry message should still exist");
4787            assert!(retry_msg.ui_only, "Retry message should be ui_only");
4788            assert_eq!(
4789                retry_msg.role,
4790                Role::System,
4791                "Retry message should have System role"
4792            );
4793        });
4794    }
4795
4796    #[gpui::test]
4797    async fn test_successful_completion_clears_retry_state(cx: &mut TestAppContext) {
4798        init_test_settings(cx);
4799
4800        let project = create_test_project(cx, json!({})).await;
4801        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4802
4803        // Enable Burn Mode to allow retries
4804        thread.update(cx, |thread, _| {
4805            thread.set_completion_mode(CompletionMode::Burn);
4806        });
4807
4808        // Create a model that fails once then succeeds
4809        struct FailOnceModel {
4810            inner: Arc<FakeLanguageModel>,
4811            failed_once: Arc<Mutex<bool>>,
4812        }
4813
4814        impl LanguageModel for FailOnceModel {
4815            fn id(&self) -> LanguageModelId {
4816                self.inner.id()
4817            }
4818
4819            fn name(&self) -> LanguageModelName {
4820                self.inner.name()
4821            }
4822
4823            fn provider_id(&self) -> LanguageModelProviderId {
4824                self.inner.provider_id()
4825            }
4826
4827            fn provider_name(&self) -> LanguageModelProviderName {
4828                self.inner.provider_name()
4829            }
4830
4831            fn supports_tools(&self) -> bool {
4832                self.inner.supports_tools()
4833            }
4834
4835            fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
4836                self.inner.supports_tool_choice(choice)
4837            }
4838
4839            fn supports_images(&self) -> bool {
4840                self.inner.supports_images()
4841            }
4842
4843            fn telemetry_id(&self) -> String {
4844                self.inner.telemetry_id()
4845            }
4846
4847            fn max_token_count(&self) -> u64 {
4848                self.inner.max_token_count()
4849            }
4850
4851            fn count_tokens(
4852                &self,
4853                request: LanguageModelRequest,
4854                cx: &App,
4855            ) -> BoxFuture<'static, Result<u64>> {
4856                self.inner.count_tokens(request, cx)
4857            }
4858
4859            fn stream_completion(
4860                &self,
4861                request: LanguageModelRequest,
4862                cx: &AsyncApp,
4863            ) -> BoxFuture<
4864                'static,
4865                Result<
4866                    BoxStream<
4867                        'static,
4868                        Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
4869                    >,
4870                    LanguageModelCompletionError,
4871                >,
4872            > {
4873                if !*self.failed_once.lock() {
4874                    *self.failed_once.lock() = true;
4875                    let provider = self.provider_name();
4876                    // Return error on first attempt
4877                    let stream = futures::stream::once(async move {
4878                        Err(LanguageModelCompletionError::ServerOverloaded {
4879                            provider,
4880                            retry_after: None,
4881                        })
4882                    });
4883                    async move { Ok(stream.boxed()) }.boxed()
4884                } else {
4885                    // Succeed on retry
4886                    self.inner.stream_completion(request, cx)
4887                }
4888            }
4889        }
4890
4891        let fail_once_model = Arc::new(FailOnceModel {
4892            inner: Arc::new(FakeLanguageModel::default()),
4893            failed_once: Arc::new(Mutex::new(false)),
4894        });
4895
4896        // Insert a user message
4897        thread.update(cx, |thread, cx| {
4898            thread.insert_user_message(
4899                "Test message",
4900                ContextLoadResult::default(),
4901                None,
4902                vec![],
4903                cx,
4904            );
4905        });
4906
4907        // Start completion with fail-once model
4908        thread.update(cx, |thread, cx| {
4909            thread.send_to_model(
4910                fail_once_model.clone(),
4911                CompletionIntent::UserPrompt,
4912                None,
4913                cx,
4914            );
4915        });
4916
4917        cx.run_until_parked();
4918
4919        // Verify retry state exists after first failure
4920        thread.read_with(cx, |thread, _| {
4921            assert!(
4922                thread.retry_state.is_some(),
4923                "Should have retry state after failure"
4924            );
4925        });
4926
4927        // Wait for retry delay
4928        cx.executor().advance_clock(BASE_RETRY_DELAY);
4929        cx.run_until_parked();
4930
4931        // The retry should now use our FailOnceModel which should succeed
4932        // We need to help the FakeLanguageModel complete the stream
4933        let inner_fake = fail_once_model.inner.clone();
4934
4935        // Wait a bit for the retry to start
4936        cx.run_until_parked();
4937
4938        // Check for pending completions and complete them
4939        if let Some(pending) = inner_fake.pending_completions().first() {
4940            inner_fake.stream_completion_response(pending, "Success!");
4941            inner_fake.end_completion_stream(pending);
4942        }
4943        cx.run_until_parked();
4944
4945        thread.read_with(cx, |thread, _| {
4946            assert!(
4947                thread.retry_state.is_none(),
4948                "Retry state should be cleared after successful completion"
4949            );
4950
4951            let has_assistant_message = thread
4952                .messages
4953                .iter()
4954                .any(|msg| msg.role == Role::Assistant && !msg.ui_only);
4955            assert!(
4956                has_assistant_message,
4957                "Should have an assistant message after successful retry"
4958            );
4959        });
4960    }
4961
4962    #[gpui::test]
4963    async fn test_rate_limit_retry_single_attempt(cx: &mut TestAppContext) {
4964        init_test_settings(cx);
4965
4966        let project = create_test_project(cx, json!({})).await;
4967        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4968
4969        // Enable Burn Mode to allow retries
4970        thread.update(cx, |thread, _| {
4971            thread.set_completion_mode(CompletionMode::Burn);
4972        });
4973
4974        // Create a model that returns rate limit error with retry_after
4975        struct RateLimitModel {
4976            inner: Arc<FakeLanguageModel>,
4977        }
4978
4979        impl LanguageModel for RateLimitModel {
4980            fn id(&self) -> LanguageModelId {
4981                self.inner.id()
4982            }
4983
4984            fn name(&self) -> LanguageModelName {
4985                self.inner.name()
4986            }
4987
4988            fn provider_id(&self) -> LanguageModelProviderId {
4989                self.inner.provider_id()
4990            }
4991
4992            fn provider_name(&self) -> LanguageModelProviderName {
4993                self.inner.provider_name()
4994            }
4995
4996            fn supports_tools(&self) -> bool {
4997                self.inner.supports_tools()
4998            }
4999
5000            fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
5001                self.inner.supports_tool_choice(choice)
5002            }
5003
5004            fn supports_images(&self) -> bool {
5005                self.inner.supports_images()
5006            }
5007
5008            fn telemetry_id(&self) -> String {
5009                self.inner.telemetry_id()
5010            }
5011
5012            fn max_token_count(&self) -> u64 {
5013                self.inner.max_token_count()
5014            }
5015
5016            fn count_tokens(
5017                &self,
5018                request: LanguageModelRequest,
5019                cx: &App,
5020            ) -> BoxFuture<'static, Result<u64>> {
5021                self.inner.count_tokens(request, cx)
5022            }
5023
5024            fn stream_completion(
5025                &self,
5026                _request: LanguageModelRequest,
5027                _cx: &AsyncApp,
5028            ) -> BoxFuture<
5029                'static,
5030                Result<
5031                    BoxStream<
5032                        'static,
5033                        Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
5034                    >,
5035                    LanguageModelCompletionError,
5036                >,
5037            > {
5038                let provider = self.provider_name();
5039                async move {
5040                    let stream = futures::stream::once(async move {
5041                        Err(LanguageModelCompletionError::RateLimitExceeded {
5042                            provider,
5043                            retry_after: Some(Duration::from_secs(TEST_RATE_LIMIT_RETRY_SECS)),
5044                        })
5045                    });
5046                    Ok(stream.boxed())
5047                }
5048                .boxed()
5049            }
5050
5051            fn as_fake(&self) -> &FakeLanguageModel {
5052                &self.inner
5053            }
5054        }
5055
5056        let model = Arc::new(RateLimitModel {
5057            inner: Arc::new(FakeLanguageModel::default()),
5058        });
5059
5060        // Insert a user message
5061        thread.update(cx, |thread, cx| {
5062            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
5063        });
5064
5065        // Start completion
5066        thread.update(cx, |thread, cx| {
5067            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
5068        });
5069
5070        cx.run_until_parked();
5071
5072        let retry_count = thread.update(cx, |thread, _| {
5073            thread
5074                .messages
5075                .iter()
5076                .filter(|m| {
5077                    m.ui_only
5078                        && m.segments.iter().any(|s| {
5079                            if let MessageSegment::Text(text) = s {
5080                                text.contains("rate limit exceeded")
5081                            } else {
5082                                false
5083                            }
5084                        })
5085                })
5086                .count()
5087        });
5088        assert_eq!(retry_count, 1, "Should have scheduled one retry");
5089
5090        thread.read_with(cx, |thread, _| {
5091            assert!(
5092                thread.retry_state.is_some(),
5093                "Rate limit errors should set retry_state"
5094            );
5095            if let Some(retry_state) = &thread.retry_state {
5096                assert_eq!(
5097                    retry_state.max_attempts, MAX_RETRY_ATTEMPTS,
5098                    "Rate limit errors should use MAX_RETRY_ATTEMPTS"
5099                );
5100            }
5101        });
5102
5103        // Verify we have one retry message
5104        thread.read_with(cx, |thread, _| {
5105            let retry_messages = thread
5106                .messages
5107                .iter()
5108                .filter(|msg| {
5109                    msg.ui_only
5110                        && msg.segments.iter().any(|seg| {
5111                            if let MessageSegment::Text(text) = seg {
5112                                text.contains("rate limit exceeded")
5113                            } else {
5114                                false
5115                            }
5116                        })
5117                })
5118                .count();
5119            assert_eq!(
5120                retry_messages, 1,
5121                "Should have one rate limit retry message"
5122            );
5123        });
5124
5125        // Check that retry message doesn't include attempt count
5126        thread.read_with(cx, |thread, _| {
5127            let retry_message = thread
5128                .messages
5129                .iter()
5130                .find(|msg| msg.role == Role::System && msg.ui_only)
5131                .expect("Should have a retry message");
5132
5133            // Check that the message contains attempt count since we use retry_state
5134            if let Some(MessageSegment::Text(text)) = retry_message.segments.first() {
5135                assert!(
5136                    text.contains(&format!("attempt 1 of {}", MAX_RETRY_ATTEMPTS)),
5137                    "Rate limit retry message should contain attempt count with MAX_RETRY_ATTEMPTS"
5138                );
5139                assert!(
5140                    text.contains("Retrying"),
5141                    "Rate limit retry message should contain retry text"
5142                );
5143            }
5144        });
5145    }
5146
5147    #[gpui::test]
5148    async fn test_ui_only_messages_not_sent_to_model(cx: &mut TestAppContext) {
5149        init_test_settings(cx);
5150
5151        let project = create_test_project(cx, json!({})).await;
5152        let (_, _, thread, _, model) = setup_test_environment(cx, project.clone()).await;
5153
5154        // Insert a regular user message
5155        thread.update(cx, |thread, cx| {
5156            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
5157        });
5158
5159        // Insert a UI-only message (like our retry notifications)
5160        thread.update(cx, |thread, cx| {
5161            let id = thread.next_message_id.post_inc();
5162            thread.messages.push(Message {
5163                id,
5164                role: Role::System,
5165                segments: vec![MessageSegment::Text(
5166                    "This is a UI-only message that should not be sent to the model".to_string(),
5167                )],
5168                loaded_context: LoadedContext::default(),
5169                creases: Vec::new(),
5170                is_hidden: true,
5171                ui_only: true,
5172            });
5173            cx.emit(ThreadEvent::MessageAdded(id));
5174        });
5175
5176        // Insert another regular message
5177        thread.update(cx, |thread, cx| {
5178            thread.insert_user_message(
5179                "How are you?",
5180                ContextLoadResult::default(),
5181                None,
5182                vec![],
5183                cx,
5184            );
5185        });
5186
5187        // Generate the completion request
5188        let request = thread.update(cx, |thread, cx| {
5189            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
5190        });
5191
5192        // Verify that the request only contains non-UI-only messages
5193        // Should have system prompt + 2 user messages, but not the UI-only message
5194        let user_messages: Vec<_> = request
5195            .messages
5196            .iter()
5197            .filter(|msg| msg.role == Role::User)
5198            .collect();
5199        assert_eq!(
5200            user_messages.len(),
5201            2,
5202            "Should have exactly 2 user messages"
5203        );
5204
5205        // Verify the UI-only content is not present anywhere in the request
5206        let request_text = request
5207            .messages
5208            .iter()
5209            .flat_map(|msg| &msg.content)
5210            .filter_map(|content| match content {
5211                MessageContent::Text(text) => Some(text.as_str()),
5212                _ => None,
5213            })
5214            .collect::<String>();
5215
5216        assert!(
5217            !request_text.contains("UI-only message"),
5218            "UI-only message content should not be in the request"
5219        );
5220
5221        // Verify the thread still has all 3 messages (including UI-only)
5222        thread.read_with(cx, |thread, _| {
5223            assert_eq!(
5224                thread.messages().count(),
5225                3,
5226                "Thread should have 3 messages"
5227            );
5228            assert_eq!(
5229                thread.messages().filter(|m| m.ui_only).count(),
5230                1,
5231                "Thread should have 1 UI-only message"
5232            );
5233        });
5234
5235        // Verify that UI-only messages are not serialized
5236        let serialized = thread
5237            .update(cx, |thread, cx| thread.serialize(cx))
5238            .await
5239            .unwrap();
5240        assert_eq!(
5241            serialized.messages.len(),
5242            2,
5243            "Serialized thread should only have 2 messages (no UI-only)"
5244        );
5245    }
5246
5247    #[gpui::test]
5248    async fn test_no_retry_without_burn_mode(cx: &mut TestAppContext) {
5249        init_test_settings(cx);
5250
5251        let project = create_test_project(cx, json!({})).await;
5252        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
5253
5254        // Ensure we're in Normal mode (not Burn mode)
5255        thread.update(cx, |thread, _| {
5256            thread.set_completion_mode(CompletionMode::Normal);
5257        });
5258
5259        // Track error events
5260        let error_events = Arc::new(Mutex::new(Vec::new()));
5261        let error_events_clone = error_events.clone();
5262
5263        let _subscription = thread.update(cx, |_, cx| {
5264            cx.subscribe(&thread, move |_, _, event: &ThreadEvent, _| {
5265                if let ThreadEvent::ShowError(error) = event {
5266                    error_events_clone.lock().push(error.clone());
5267                }
5268            })
5269        });
5270
5271        // Create model that returns overloaded error
5272        let model = Arc::new(ErrorInjector::new(TestError::Overloaded));
5273
5274        // Insert a user message
5275        thread.update(cx, |thread, cx| {
5276            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
5277        });
5278
5279        // Start completion
5280        thread.update(cx, |thread, cx| {
5281            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
5282        });
5283
5284        cx.run_until_parked();
5285
5286        // Verify no retry state was created
5287        thread.read_with(cx, |thread, _| {
5288            assert!(
5289                thread.retry_state.is_none(),
5290                "Should not have retry state in Normal mode"
5291            );
5292        });
5293
5294        // Check that a retryable error was reported
5295        let errors = error_events.lock();
5296        assert!(!errors.is_empty(), "Should have received an error event");
5297
5298        if let ThreadError::RetryableError {
5299            message: _,
5300            can_enable_burn_mode,
5301        } = &errors[0]
5302        {
5303            assert!(
5304                *can_enable_burn_mode,
5305                "Error should indicate burn mode can be enabled"
5306            );
5307        } else {
5308            panic!("Expected RetryableError, got {:?}", errors[0]);
5309        }
5310
5311        // Verify the thread is no longer generating
5312        thread.read_with(cx, |thread, _| {
5313            assert!(
5314                !thread.is_generating(),
5315                "Should not be generating after error without retry"
5316            );
5317        });
5318    }
5319
5320    #[gpui::test]
5321    async fn test_retry_cancelled_on_stop(cx: &mut TestAppContext) {
5322        init_test_settings(cx);
5323
5324        let project = create_test_project(cx, json!({})).await;
5325        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
5326
5327        // Enable Burn Mode to allow retries
5328        thread.update(cx, |thread, _| {
5329            thread.set_completion_mode(CompletionMode::Burn);
5330        });
5331
5332        // Create model that returns overloaded error
5333        let model = Arc::new(ErrorInjector::new(TestError::Overloaded));
5334
5335        // Insert a user message
5336        thread.update(cx, |thread, cx| {
5337            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
5338        });
5339
5340        // Start completion
5341        thread.update(cx, |thread, cx| {
5342            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
5343        });
5344
5345        cx.run_until_parked();
5346
5347        // Verify retry was scheduled by checking for retry message
5348        let has_retry_message = thread.read_with(cx, |thread, _| {
5349            thread.messages.iter().any(|m| {
5350                m.ui_only
5351                    && m.segments.iter().any(|s| {
5352                        if let MessageSegment::Text(text) = s {
5353                            text.contains("Retrying") && text.contains("seconds")
5354                        } else {
5355                            false
5356                        }
5357                    })
5358            })
5359        });
5360        assert!(has_retry_message, "Should have scheduled a retry");
5361
5362        // Cancel the completion before the retry happens
5363        thread.update(cx, |thread, cx| {
5364            thread.cancel_last_completion(None, cx);
5365        });
5366
5367        cx.run_until_parked();
5368
5369        // The retry should not have happened - no pending completions
5370        let fake_model = model.as_fake();
5371        assert_eq!(
5372            fake_model.pending_completions().len(),
5373            0,
5374            "Should have no pending completions after cancellation"
5375        );
5376
5377        // Verify the retry was cancelled by checking retry state
5378        thread.read_with(cx, |thread, _| {
5379            if let Some(retry_state) = &thread.retry_state {
5380                panic!(
5381                    "retry_state should be cleared after cancellation, but found: attempt={}, max_attempts={}, intent={:?}",
5382                    retry_state.attempt, retry_state.max_attempts, retry_state.intent
5383                );
5384            }
5385        });
5386    }
5387
5388    fn test_summarize_error(
5389        model: &Arc<dyn LanguageModel>,
5390        thread: &Entity<Thread>,
5391        cx: &mut TestAppContext,
5392    ) {
5393        thread.update(cx, |thread, cx| {
5394            thread.insert_user_message("Hi!", ContextLoadResult::default(), None, vec![], cx);
5395            thread.send_to_model(
5396                model.clone(),
5397                CompletionIntent::ThreadSummarization,
5398                None,
5399                cx,
5400            );
5401        });
5402
5403        let fake_model = model.as_fake();
5404        simulate_successful_response(&fake_model, cx);
5405
5406        thread.read_with(cx, |thread, _| {
5407            assert!(matches!(thread.summary(), ThreadSummary::Generating));
5408            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
5409        });
5410
5411        // Simulate summary request ending
5412        cx.run_until_parked();
5413        fake_model.end_last_completion_stream();
5414        cx.run_until_parked();
5415
5416        // State is set to Error and default message
5417        thread.read_with(cx, |thread, _| {
5418            assert!(matches!(thread.summary(), ThreadSummary::Error));
5419            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
5420        });
5421    }
5422
5423    fn simulate_successful_response(fake_model: &FakeLanguageModel, cx: &mut TestAppContext) {
5424        cx.run_until_parked();
5425        fake_model.stream_last_completion_response("Assistant response");
5426        fake_model.end_last_completion_stream();
5427        cx.run_until_parked();
5428    }
5429
5430    fn init_test_settings(cx: &mut TestAppContext) {
5431        cx.update(|cx| {
5432            let settings_store = SettingsStore::test(cx);
5433            cx.set_global(settings_store);
5434            language::init(cx);
5435            Project::init_settings(cx);
5436            AgentSettings::register(cx);
5437            prompt_store::init(cx);
5438            thread_store::init(cx);
5439            workspace::init_settings(cx);
5440            language_model::init_settings(cx);
5441            ThemeSettings::register(cx);
5442            ToolRegistry::default_global(cx);
5443            assistant_tool::init(cx);
5444
5445            let http_client = Arc::new(http_client::HttpClientWithUrl::new(
5446                http_client::FakeHttpClient::with_200_response(),
5447                "http://localhost".to_string(),
5448                None,
5449            ));
5450            assistant_tools::init(http_client, cx);
5451        });
5452    }
5453
5454    // Helper to create a test project with test files
5455    async fn create_test_project(
5456        cx: &mut TestAppContext,
5457        files: serde_json::Value,
5458    ) -> Entity<Project> {
5459        let fs = FakeFs::new(cx.executor());
5460        fs.insert_tree(path!("/test"), files).await;
5461        Project::test(fs, [path!("/test").as_ref()], cx).await
5462    }
5463
5464    async fn setup_test_environment(
5465        cx: &mut TestAppContext,
5466        project: Entity<Project>,
5467    ) -> (
5468        Entity<Workspace>,
5469        Entity<ThreadStore>,
5470        Entity<Thread>,
5471        Entity<ContextStore>,
5472        Arc<dyn LanguageModel>,
5473    ) {
5474        let (workspace, cx) =
5475            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5476
5477        let thread_store = cx
5478            .update(|_, cx| {
5479                ThreadStore::load(
5480                    project.clone(),
5481                    cx.new(|_| ToolWorkingSet::default()),
5482                    None,
5483                    Arc::new(PromptBuilder::new(None).unwrap()),
5484                    cx,
5485                )
5486            })
5487            .await
5488            .unwrap();
5489
5490        let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
5491        let context_store = cx.new(|_cx| ContextStore::new(project.downgrade(), None));
5492
5493        let provider = Arc::new(FakeLanguageModelProvider::default());
5494        let model = provider.test_model();
5495        let model: Arc<dyn LanguageModel> = Arc::new(model);
5496
5497        cx.update(|_, cx| {
5498            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
5499                registry.set_default_model(
5500                    Some(ConfiguredModel {
5501                        provider: provider.clone(),
5502                        model: model.clone(),
5503                    }),
5504                    cx,
5505                );
5506                registry.set_thread_summary_model(
5507                    Some(ConfiguredModel {
5508                        provider,
5509                        model: model.clone(),
5510                    }),
5511                    cx,
5512                );
5513            })
5514        });
5515
5516        (workspace, thread_store, thread, context_store, model)
5517    }
5518
5519    async fn add_file_to_context(
5520        project: &Entity<Project>,
5521        context_store: &Entity<ContextStore>,
5522        path: &str,
5523        cx: &mut TestAppContext,
5524    ) -> Result<Entity<language::Buffer>> {
5525        let buffer_path = project
5526            .read_with(cx, |project, cx| project.find_project_path(path, cx))
5527            .unwrap();
5528
5529        let buffer = project
5530            .update(cx, |project, cx| {
5531                project.open_buffer(buffer_path.clone(), cx)
5532            })
5533            .await
5534            .unwrap();
5535
5536        context_store.update(cx, |context_store, cx| {
5537            context_store.add_file_from_buffer(&buffer_path, buffer.clone(), false, cx);
5538        });
5539
5540        Ok(buffer)
5541    }
5542}