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 _, debug_panic, post_inc};
  51use uuid::Uuid;
  52use zed_llm_client::{CompletionIntent, CompletionRequestStatus, UsageLimit};
  53
  54const MAX_RETRY_ATTEMPTS: u8 = 3;
  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        let action_log = self.action_log.read(cx);
1586
1587        if !action_log.has_unnotified_user_edits() {
1588            return None;
1589        }
1590
1591        // Represent notification as a simulated `project_notifications` tool call
1592        let tool_name = Arc::from("project_notifications");
1593        let Some(tool) = self.tools.read(cx).tool(&tool_name, cx) else {
1594            debug_panic!("`project_notifications` tool not found");
1595            return None;
1596        };
1597
1598        if !self.profile.is_tool_enabled(tool.source(), tool.name(), cx) {
1599            return None;
1600        }
1601
1602        let input = serde_json::json!({});
1603        let request = Arc::new(LanguageModelRequest::default()); // unused
1604        let window = None;
1605        let tool_result = tool.run(
1606            input,
1607            request,
1608            self.project.clone(),
1609            self.action_log.clone(),
1610            model.clone(),
1611            window,
1612            cx,
1613        );
1614
1615        let tool_use_id =
1616            LanguageModelToolUseId::from(format!("project_notifications_{}", self.messages.len()));
1617
1618        let tool_use = LanguageModelToolUse {
1619            id: tool_use_id.clone(),
1620            name: tool_name.clone(),
1621            raw_input: "{}".to_string(),
1622            input: serde_json::json!({}),
1623            is_input_complete: true,
1624        };
1625
1626        let tool_output = cx.background_executor().block(tool_result.output);
1627
1628        // Attach a project_notification tool call to the latest existing
1629        // Assistant message. We cannot create a new Assistant message
1630        // because thinking models require a `thinking` block that we
1631        // cannot mock. We cannot send a notification as a normal
1632        // (non-tool-use) User message because this distracts Agent
1633        // too much.
1634        let tool_message_id = self
1635            .messages
1636            .iter()
1637            .enumerate()
1638            .rfind(|(_, message)| message.role == Role::Assistant)
1639            .map(|(_, message)| message.id)?;
1640
1641        let tool_use_metadata = ToolUseMetadata {
1642            model: model.clone(),
1643            thread_id: self.id.clone(),
1644            prompt_id: self.last_prompt_id.clone(),
1645        };
1646
1647        self.tool_use
1648            .request_tool_use(tool_message_id, tool_use, tool_use_metadata.clone(), cx);
1649
1650        let pending_tool_use = self.tool_use.insert_tool_output(
1651            tool_use_id.clone(),
1652            tool_name,
1653            tool_output,
1654            self.configured_model.as_ref(),
1655            self.completion_mode,
1656        );
1657
1658        pending_tool_use
1659    }
1660
1661    pub fn stream_completion(
1662        &mut self,
1663        request: LanguageModelRequest,
1664        model: Arc<dyn LanguageModel>,
1665        intent: CompletionIntent,
1666        window: Option<AnyWindowHandle>,
1667        cx: &mut Context<Self>,
1668    ) {
1669        self.tool_use_limit_reached = false;
1670
1671        let pending_completion_id = post_inc(&mut self.completion_count);
1672        let mut request_callback_parameters = if self.request_callback.is_some() {
1673            Some((request.clone(), Vec::new()))
1674        } else {
1675            None
1676        };
1677        let prompt_id = self.last_prompt_id.clone();
1678        let tool_use_metadata = ToolUseMetadata {
1679            model: model.clone(),
1680            thread_id: self.id.clone(),
1681            prompt_id: prompt_id.clone(),
1682        };
1683
1684        let completion_mode = request
1685            .mode
1686            .unwrap_or(zed_llm_client::CompletionMode::Normal);
1687
1688        self.last_received_chunk_at = Some(Instant::now());
1689
1690        let task = cx.spawn(async move |thread, cx| {
1691            let stream_completion_future = model.stream_completion(request, &cx);
1692            let initial_token_usage =
1693                thread.read_with(cx, |thread, _cx| thread.cumulative_token_usage);
1694            let stream_completion = async {
1695                let mut events = stream_completion_future.await?;
1696
1697                let mut stop_reason = StopReason::EndTurn;
1698                let mut current_token_usage = TokenUsage::default();
1699
1700                thread
1701                    .update(cx, |_thread, cx| {
1702                        cx.emit(ThreadEvent::NewRequest);
1703                    })
1704                    .ok();
1705
1706                let mut request_assistant_message_id = None;
1707
1708                while let Some(event) = events.next().await {
1709                    if let Some((_, response_events)) = request_callback_parameters.as_mut() {
1710                        response_events
1711                            .push(event.as_ref().map_err(|error| error.to_string()).cloned());
1712                    }
1713
1714                    thread.update(cx, |thread, cx| {
1715                        match event? {
1716                            LanguageModelCompletionEvent::StartMessage { .. } => {
1717                                request_assistant_message_id =
1718                                    Some(thread.insert_assistant_message(
1719                                        vec![MessageSegment::Text(String::new())],
1720                                        cx,
1721                                    ));
1722                            }
1723                            LanguageModelCompletionEvent::Stop(reason) => {
1724                                stop_reason = reason;
1725                            }
1726                            LanguageModelCompletionEvent::UsageUpdate(token_usage) => {
1727                                thread.update_token_usage_at_last_message(token_usage);
1728                                thread.cumulative_token_usage = thread.cumulative_token_usage
1729                                    + token_usage
1730                                    - current_token_usage;
1731                                current_token_usage = token_usage;
1732                            }
1733                            LanguageModelCompletionEvent::Text(chunk) => {
1734                                thread.received_chunk();
1735
1736                                cx.emit(ThreadEvent::ReceivedTextChunk);
1737                                if let Some(last_message) = thread.messages.last_mut() {
1738                                    if last_message.role == Role::Assistant
1739                                        && !thread.tool_use.has_tool_results(last_message.id)
1740                                    {
1741                                        last_message.push_text(&chunk);
1742                                        cx.emit(ThreadEvent::StreamedAssistantText(
1743                                            last_message.id,
1744                                            chunk,
1745                                        ));
1746                                    } else {
1747                                        // If we won't have an Assistant message yet, assume this chunk marks the beginning
1748                                        // of a new Assistant response.
1749                                        //
1750                                        // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
1751                                        // will result in duplicating the text of the chunk in the rendered Markdown.
1752                                        request_assistant_message_id =
1753                                            Some(thread.insert_assistant_message(
1754                                                vec![MessageSegment::Text(chunk.to_string())],
1755                                                cx,
1756                                            ));
1757                                    };
1758                                }
1759                            }
1760                            LanguageModelCompletionEvent::Thinking {
1761                                text: chunk,
1762                                signature,
1763                            } => {
1764                                thread.received_chunk();
1765
1766                                if let Some(last_message) = thread.messages.last_mut() {
1767                                    if last_message.role == Role::Assistant
1768                                        && !thread.tool_use.has_tool_results(last_message.id)
1769                                    {
1770                                        last_message.push_thinking(&chunk, signature);
1771                                        cx.emit(ThreadEvent::StreamedAssistantThinking(
1772                                            last_message.id,
1773                                            chunk,
1774                                        ));
1775                                    } else {
1776                                        // If we won't have an Assistant message yet, assume this chunk marks the beginning
1777                                        // of a new Assistant response.
1778                                        //
1779                                        // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
1780                                        // will result in duplicating the text of the chunk in the rendered Markdown.
1781                                        request_assistant_message_id =
1782                                            Some(thread.insert_assistant_message(
1783                                                vec![MessageSegment::Thinking {
1784                                                    text: chunk.to_string(),
1785                                                    signature,
1786                                                }],
1787                                                cx,
1788                                            ));
1789                                    };
1790                                }
1791                            }
1792                            LanguageModelCompletionEvent::RedactedThinking { data } => {
1793                                thread.received_chunk();
1794
1795                                if let Some(last_message) = thread.messages.last_mut() {
1796                                    if last_message.role == Role::Assistant
1797                                        && !thread.tool_use.has_tool_results(last_message.id)
1798                                    {
1799                                        last_message.push_redacted_thinking(data);
1800                                    } else {
1801                                        request_assistant_message_id =
1802                                            Some(thread.insert_assistant_message(
1803                                                vec![MessageSegment::RedactedThinking(data)],
1804                                                cx,
1805                                            ));
1806                                    };
1807                                }
1808                            }
1809                            LanguageModelCompletionEvent::ToolUse(tool_use) => {
1810                                let last_assistant_message_id = request_assistant_message_id
1811                                    .unwrap_or_else(|| {
1812                                        let new_assistant_message_id =
1813                                            thread.insert_assistant_message(vec![], cx);
1814                                        request_assistant_message_id =
1815                                            Some(new_assistant_message_id);
1816                                        new_assistant_message_id
1817                                    });
1818
1819                                let tool_use_id = tool_use.id.clone();
1820                                let streamed_input = if tool_use.is_input_complete {
1821                                    None
1822                                } else {
1823                                    Some((&tool_use.input).clone())
1824                                };
1825
1826                                let ui_text = thread.tool_use.request_tool_use(
1827                                    last_assistant_message_id,
1828                                    tool_use,
1829                                    tool_use_metadata.clone(),
1830                                    cx,
1831                                );
1832
1833                                if let Some(input) = streamed_input {
1834                                    cx.emit(ThreadEvent::StreamedToolUse {
1835                                        tool_use_id,
1836                                        ui_text,
1837                                        input,
1838                                    });
1839                                }
1840                            }
1841                            LanguageModelCompletionEvent::ToolUseJsonParseError {
1842                                id,
1843                                tool_name,
1844                                raw_input: invalid_input_json,
1845                                json_parse_error,
1846                            } => {
1847                                thread.receive_invalid_tool_json(
1848                                    id,
1849                                    tool_name,
1850                                    invalid_input_json,
1851                                    json_parse_error,
1852                                    window,
1853                                    cx,
1854                                );
1855                            }
1856                            LanguageModelCompletionEvent::StatusUpdate(status_update) => {
1857                                if let Some(completion) = thread
1858                                    .pending_completions
1859                                    .iter_mut()
1860                                    .find(|completion| completion.id == pending_completion_id)
1861                                {
1862                                    match status_update {
1863                                        CompletionRequestStatus::Queued { position } => {
1864                                            completion.queue_state =
1865                                                QueueState::Queued { position };
1866                                        }
1867                                        CompletionRequestStatus::Started => {
1868                                            completion.queue_state = QueueState::Started;
1869                                        }
1870                                        CompletionRequestStatus::Failed {
1871                                            code,
1872                                            message,
1873                                            request_id: _,
1874                                            retry_after,
1875                                        } => {
1876                                            return Err(
1877                                                LanguageModelCompletionError::from_cloud_failure(
1878                                                    model.upstream_provider_name(),
1879                                                    code,
1880                                                    message,
1881                                                    retry_after.map(Duration::from_secs_f64),
1882                                                ),
1883                                            );
1884                                        }
1885                                        CompletionRequestStatus::UsageUpdated { amount, limit } => {
1886                                            thread.update_model_request_usage(
1887                                                amount as u32,
1888                                                limit,
1889                                                cx,
1890                                            );
1891                                        }
1892                                        CompletionRequestStatus::ToolUseLimitReached => {
1893                                            thread.tool_use_limit_reached = true;
1894                                            cx.emit(ThreadEvent::ToolUseLimitReached);
1895                                        }
1896                                    }
1897                                }
1898                            }
1899                        }
1900
1901                        thread.touch_updated_at();
1902                        cx.emit(ThreadEvent::StreamedCompletion);
1903                        cx.notify();
1904
1905                        thread.auto_capture_telemetry(cx);
1906                        Ok(())
1907                    })??;
1908
1909                    smol::future::yield_now().await;
1910                }
1911
1912                thread.update(cx, |thread, cx| {
1913                    thread.last_received_chunk_at = None;
1914                    thread
1915                        .pending_completions
1916                        .retain(|completion| completion.id != pending_completion_id);
1917
1918                    // If there is a response without tool use, summarize the message. Otherwise,
1919                    // allow two tool uses before summarizing.
1920                    if matches!(thread.summary, ThreadSummary::Pending)
1921                        && thread.messages.len() >= 2
1922                        && (!thread.has_pending_tool_uses() || thread.messages.len() >= 6)
1923                    {
1924                        thread.summarize(cx);
1925                    }
1926                })?;
1927
1928                anyhow::Ok(stop_reason)
1929            };
1930
1931            let result = stream_completion.await;
1932            let mut retry_scheduled = false;
1933
1934            thread
1935                .update(cx, |thread, cx| {
1936                    thread.finalize_pending_checkpoint(cx);
1937                    match result.as_ref() {
1938                        Ok(stop_reason) => {
1939                            match stop_reason {
1940                                StopReason::ToolUse => {
1941                                    let tool_uses =
1942                                        thread.use_pending_tools(window, model.clone(), cx);
1943                                    cx.emit(ThreadEvent::UsePendingTools { tool_uses });
1944                                }
1945                                StopReason::EndTurn | StopReason::MaxTokens => {
1946                                    thread.project.update(cx, |project, cx| {
1947                                        project.set_agent_location(None, cx);
1948                                    });
1949                                }
1950                                StopReason::Refusal => {
1951                                    thread.project.update(cx, |project, cx| {
1952                                        project.set_agent_location(None, cx);
1953                                    });
1954
1955                                    // Remove the turn that was refused.
1956                                    //
1957                                    // https://docs.anthropic.com/en/docs/test-and-evaluate/strengthen-guardrails/handle-streaming-refusals#reset-context-after-refusal
1958                                    {
1959                                        let mut messages_to_remove = Vec::new();
1960
1961                                        for (ix, message) in
1962                                            thread.messages.iter().enumerate().rev()
1963                                        {
1964                                            messages_to_remove.push(message.id);
1965
1966                                            if message.role == Role::User {
1967                                                if ix == 0 {
1968                                                    break;
1969                                                }
1970
1971                                                if let Some(prev_message) =
1972                                                    thread.messages.get(ix - 1)
1973                                                {
1974                                                    if prev_message.role == Role::Assistant {
1975                                                        break;
1976                                                    }
1977                                                }
1978                                            }
1979                                        }
1980
1981                                        for message_id in messages_to_remove {
1982                                            thread.delete_message(message_id, cx);
1983                                        }
1984                                    }
1985
1986                                    cx.emit(ThreadEvent::ShowError(ThreadError::Message {
1987                                        header: "Language model refusal".into(),
1988                                        message:
1989                                            "Model refused to generate content for safety reasons."
1990                                                .into(),
1991                                    }));
1992                                }
1993                            }
1994
1995                            // We successfully completed, so cancel any remaining retries.
1996                            thread.retry_state = None;
1997                        }
1998                        Err(error) => {
1999                            thread.project.update(cx, |project, cx| {
2000                                project.set_agent_location(None, cx);
2001                            });
2002
2003                            if error.is::<PaymentRequiredError>() {
2004                                cx.emit(ThreadEvent::ShowError(ThreadError::PaymentRequired));
2005                            } else if let Some(error) =
2006                                error.downcast_ref::<ModelRequestLimitReachedError>()
2007                            {
2008                                cx.emit(ThreadEvent::ShowError(
2009                                    ThreadError::ModelRequestLimitReached { plan: error.plan },
2010                                ));
2011                            } else if let Some(completion_error) =
2012                                error.downcast_ref::<LanguageModelCompletionError>()
2013                            {
2014                                match &completion_error {
2015                                    LanguageModelCompletionError::PromptTooLarge {
2016                                        tokens, ..
2017                                    } => {
2018                                        let tokens = tokens.unwrap_or_else(|| {
2019                                            // We didn't get an exact token count from the API, so fall back on our estimate.
2020                                            thread
2021                                                .total_token_usage()
2022                                                .map(|usage| usage.total)
2023                                                .unwrap_or(0)
2024                                                // We know the context window was exceeded in practice, so if our estimate was
2025                                                // lower than max tokens, the estimate was wrong; return that we exceeded by 1.
2026                                                .max(
2027                                                    model
2028                                                        .max_token_count_for_mode(completion_mode)
2029                                                        .saturating_add(1),
2030                                                )
2031                                        });
2032                                        thread.exceeded_window_error = Some(ExceededWindowError {
2033                                            model_id: model.id(),
2034                                            token_count: tokens,
2035                                        });
2036                                        cx.notify();
2037                                    }
2038                                    _ => {
2039                                        if let Some(retry_strategy) =
2040                                            Thread::get_retry_strategy(completion_error)
2041                                        {
2042                                            retry_scheduled = thread
2043                                                .handle_retryable_error_with_delay(
2044                                                    &completion_error,
2045                                                    Some(retry_strategy),
2046                                                    model.clone(),
2047                                                    intent,
2048                                                    window,
2049                                                    cx,
2050                                                );
2051                                        }
2052                                    }
2053                                }
2054                            }
2055
2056                            if !retry_scheduled {
2057                                thread.cancel_last_completion(window, cx);
2058                            }
2059                        }
2060                    }
2061
2062                    if !retry_scheduled {
2063                        cx.emit(ThreadEvent::Stopped(result.map_err(Arc::new)));
2064                    }
2065
2066                    if let Some((request_callback, (request, response_events))) = thread
2067                        .request_callback
2068                        .as_mut()
2069                        .zip(request_callback_parameters.as_ref())
2070                    {
2071                        request_callback(request, response_events);
2072                    }
2073
2074                    thread.auto_capture_telemetry(cx);
2075
2076                    if let Ok(initial_usage) = initial_token_usage {
2077                        let usage = thread.cumulative_token_usage - initial_usage;
2078
2079                        telemetry::event!(
2080                            "Assistant Thread Completion",
2081                            thread_id = thread.id().to_string(),
2082                            prompt_id = prompt_id,
2083                            model = model.telemetry_id(),
2084                            model_provider = model.provider_id().to_string(),
2085                            input_tokens = usage.input_tokens,
2086                            output_tokens = usage.output_tokens,
2087                            cache_creation_input_tokens = usage.cache_creation_input_tokens,
2088                            cache_read_input_tokens = usage.cache_read_input_tokens,
2089                        );
2090                    }
2091                })
2092                .ok();
2093        });
2094
2095        self.pending_completions.push(PendingCompletion {
2096            id: pending_completion_id,
2097            queue_state: QueueState::Sending,
2098            _task: task,
2099        });
2100    }
2101
2102    pub fn summarize(&mut self, cx: &mut Context<Self>) {
2103        let Some(model) = LanguageModelRegistry::read_global(cx).thread_summary_model() else {
2104            println!("No thread summary model");
2105            return;
2106        };
2107
2108        if !model.provider.is_authenticated(cx) {
2109            return;
2110        }
2111
2112        let added_user_message = include_str!("./prompts/summarize_thread_prompt.txt");
2113
2114        let request = self.to_summarize_request(
2115            &model.model,
2116            CompletionIntent::ThreadSummarization,
2117            added_user_message.into(),
2118            cx,
2119        );
2120
2121        self.summary = ThreadSummary::Generating;
2122
2123        self.pending_summary = cx.spawn(async move |this, cx| {
2124            let result = async {
2125                let mut messages = model.model.stream_completion(request, &cx).await?;
2126
2127                let mut new_summary = String::new();
2128                while let Some(event) = messages.next().await {
2129                    let Ok(event) = event else {
2130                        continue;
2131                    };
2132                    let text = match event {
2133                        LanguageModelCompletionEvent::Text(text) => text,
2134                        LanguageModelCompletionEvent::StatusUpdate(
2135                            CompletionRequestStatus::UsageUpdated { amount, limit },
2136                        ) => {
2137                            this.update(cx, |thread, cx| {
2138                                thread.update_model_request_usage(amount as u32, limit, cx);
2139                            })?;
2140                            continue;
2141                        }
2142                        _ => continue,
2143                    };
2144
2145                    let mut lines = text.lines();
2146                    new_summary.extend(lines.next());
2147
2148                    // Stop if the LLM generated multiple lines.
2149                    if lines.next().is_some() {
2150                        break;
2151                    }
2152                }
2153
2154                anyhow::Ok(new_summary)
2155            }
2156            .await;
2157
2158            this.update(cx, |this, cx| {
2159                match result {
2160                    Ok(new_summary) => {
2161                        if new_summary.is_empty() {
2162                            this.summary = ThreadSummary::Error;
2163                        } else {
2164                            this.summary = ThreadSummary::Ready(new_summary.into());
2165                        }
2166                    }
2167                    Err(err) => {
2168                        this.summary = ThreadSummary::Error;
2169                        log::error!("Failed to generate thread summary: {}", err);
2170                    }
2171                }
2172                cx.emit(ThreadEvent::SummaryGenerated);
2173            })
2174            .log_err()?;
2175
2176            Some(())
2177        });
2178    }
2179
2180    fn get_retry_strategy(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
2181        use LanguageModelCompletionError::*;
2182
2183        // General strategy here:
2184        // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
2185        // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), try multiple times with exponential backoff.
2186        // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), just retry once.
2187        match error {
2188            HttpResponseError {
2189                status_code: StatusCode::TOO_MANY_REQUESTS,
2190                ..
2191            } => Some(RetryStrategy::ExponentialBackoff {
2192                initial_delay: BASE_RETRY_DELAY,
2193                max_attempts: MAX_RETRY_ATTEMPTS,
2194            }),
2195            ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
2196                Some(RetryStrategy::Fixed {
2197                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2198                    max_attempts: MAX_RETRY_ATTEMPTS,
2199                })
2200            }
2201            UpstreamProviderError {
2202                status,
2203                retry_after,
2204                ..
2205            } => match *status {
2206                StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
2207                    Some(RetryStrategy::Fixed {
2208                        delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2209                        max_attempts: MAX_RETRY_ATTEMPTS,
2210                    })
2211                }
2212                StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
2213                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2214                    // Internal Server Error could be anything, so only retry once.
2215                    max_attempts: 1,
2216                }),
2217                status => {
2218                    // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
2219                    // but we frequently get them in practice. See https://http.dev/529
2220                    if status.as_u16() == 529 {
2221                        Some(RetryStrategy::Fixed {
2222                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2223                            max_attempts: MAX_RETRY_ATTEMPTS,
2224                        })
2225                    } else {
2226                        None
2227                    }
2228                }
2229            },
2230            ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
2231                delay: BASE_RETRY_DELAY,
2232                max_attempts: 1,
2233            }),
2234            ApiReadResponseError { .. }
2235            | HttpSend { .. }
2236            | DeserializeResponse { .. }
2237            | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
2238                delay: BASE_RETRY_DELAY,
2239                max_attempts: 1,
2240            }),
2241            // Retrying these errors definitely shouldn't help.
2242            HttpResponseError {
2243                status_code:
2244                    StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
2245                ..
2246            }
2247            | SerializeRequest { .. }
2248            | BuildRequestBody { .. }
2249            | PromptTooLarge { .. }
2250            | AuthenticationError { .. }
2251            | PermissionError { .. }
2252            | ApiEndpointNotFound { .. }
2253            | NoApiKey { .. } => None,
2254            // Retry all other 4xx and 5xx errors once.
2255            HttpResponseError { status_code, .. }
2256                if status_code.is_client_error() || status_code.is_server_error() =>
2257            {
2258                Some(RetryStrategy::Fixed {
2259                    delay: BASE_RETRY_DELAY,
2260                    max_attempts: 1,
2261                })
2262            }
2263            // Conservatively assume that any other errors are non-retryable
2264            HttpResponseError { .. } | Other(..) => None,
2265        }
2266    }
2267
2268    fn handle_retryable_error_with_delay(
2269        &mut self,
2270        error: &LanguageModelCompletionError,
2271        strategy: Option<RetryStrategy>,
2272        model: Arc<dyn LanguageModel>,
2273        intent: CompletionIntent,
2274        window: Option<AnyWindowHandle>,
2275        cx: &mut Context<Self>,
2276    ) -> bool {
2277        // Store context for the Retry button
2278        self.last_error_context = Some((model.clone(), intent));
2279
2280        // Only auto-retry if Burn Mode is enabled
2281        if self.completion_mode != CompletionMode::Burn {
2282            // Show error with retry options
2283            cx.emit(ThreadEvent::ShowError(ThreadError::RetryableError {
2284                message: format!(
2285                    "{}\n\nTo automatically retry when similar errors happen, enable Burn Mode.",
2286                    error
2287                )
2288                .into(),
2289                can_enable_burn_mode: true,
2290            }));
2291            return false;
2292        }
2293
2294        let Some(strategy) = strategy.or_else(|| Self::get_retry_strategy(error)) else {
2295            return false;
2296        };
2297
2298        let max_attempts = match &strategy {
2299            RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
2300            RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
2301        };
2302
2303        let retry_state = self.retry_state.get_or_insert(RetryState {
2304            attempt: 0,
2305            max_attempts,
2306            intent,
2307        });
2308
2309        retry_state.attempt += 1;
2310        let attempt = retry_state.attempt;
2311        let max_attempts = retry_state.max_attempts;
2312        let intent = retry_state.intent;
2313
2314        if attempt <= max_attempts {
2315            let delay = match &strategy {
2316                RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
2317                    let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
2318                    Duration::from_secs(delay_secs)
2319                }
2320                RetryStrategy::Fixed { delay, .. } => *delay,
2321            };
2322
2323            // Add a transient message to inform the user
2324            let delay_secs = delay.as_secs();
2325            let retry_message = if max_attempts == 1 {
2326                format!("{error}. Retrying in {delay_secs} seconds...")
2327            } else {
2328                format!(
2329                    "{error}. Retrying (attempt {attempt} of {max_attempts}) \
2330                    in {delay_secs} seconds..."
2331                )
2332            };
2333            log::warn!(
2334                "Retrying completion request (attempt {attempt} of {max_attempts}) \
2335                in {delay_secs} seconds: {error:?}",
2336            );
2337
2338            // Add a UI-only message instead of a regular message
2339            let id = self.next_message_id.post_inc();
2340            self.messages.push(Message {
2341                id,
2342                role: Role::System,
2343                segments: vec![MessageSegment::Text(retry_message)],
2344                loaded_context: LoadedContext::default(),
2345                creases: Vec::new(),
2346                is_hidden: false,
2347                ui_only: true,
2348            });
2349            cx.emit(ThreadEvent::MessageAdded(id));
2350
2351            // Schedule the retry
2352            let thread_handle = cx.entity().downgrade();
2353
2354            cx.spawn(async move |_thread, cx| {
2355                cx.background_executor().timer(delay).await;
2356
2357                thread_handle
2358                    .update(cx, |thread, cx| {
2359                        // Retry the completion
2360                        thread.send_to_model(model, intent, window, cx);
2361                    })
2362                    .log_err();
2363            })
2364            .detach();
2365
2366            true
2367        } else {
2368            // Max retries exceeded
2369            self.retry_state = None;
2370
2371            // Stop generating since we're giving up on retrying.
2372            self.pending_completions.clear();
2373
2374            // Show error alongside a Retry button, but no
2375            // Enable Burn Mode button (since it's already enabled)
2376            cx.emit(ThreadEvent::ShowError(ThreadError::RetryableError {
2377                message: format!("Failed after retrying: {}", error).into(),
2378                can_enable_burn_mode: false,
2379            }));
2380
2381            false
2382        }
2383    }
2384
2385    pub fn start_generating_detailed_summary_if_needed(
2386        &mut self,
2387        thread_store: WeakEntity<ThreadStore>,
2388        cx: &mut Context<Self>,
2389    ) {
2390        let Some(last_message_id) = self.messages.last().map(|message| message.id) else {
2391            return;
2392        };
2393
2394        match &*self.detailed_summary_rx.borrow() {
2395            DetailedSummaryState::Generating { message_id, .. }
2396            | DetailedSummaryState::Generated { message_id, .. }
2397                if *message_id == last_message_id =>
2398            {
2399                // Already up-to-date
2400                return;
2401            }
2402            _ => {}
2403        }
2404
2405        let Some(ConfiguredModel { model, provider }) =
2406            LanguageModelRegistry::read_global(cx).thread_summary_model()
2407        else {
2408            return;
2409        };
2410
2411        if !provider.is_authenticated(cx) {
2412            return;
2413        }
2414
2415        let added_user_message = include_str!("./prompts/summarize_thread_detailed_prompt.txt");
2416
2417        let request = self.to_summarize_request(
2418            &model,
2419            CompletionIntent::ThreadContextSummarization,
2420            added_user_message.into(),
2421            cx,
2422        );
2423
2424        *self.detailed_summary_tx.borrow_mut() = DetailedSummaryState::Generating {
2425            message_id: last_message_id,
2426        };
2427
2428        // Replace the detailed summarization task if there is one, cancelling it. It would probably
2429        // be better to allow the old task to complete, but this would require logic for choosing
2430        // which result to prefer (the old task could complete after the new one, resulting in a
2431        // stale summary).
2432        self.detailed_summary_task = cx.spawn(async move |thread, cx| {
2433            let stream = model.stream_completion_text(request, &cx);
2434            let Some(mut messages) = stream.await.log_err() else {
2435                thread
2436                    .update(cx, |thread, _cx| {
2437                        *thread.detailed_summary_tx.borrow_mut() =
2438                            DetailedSummaryState::NotGenerated;
2439                    })
2440                    .ok()?;
2441                return None;
2442            };
2443
2444            let mut new_detailed_summary = String::new();
2445
2446            while let Some(chunk) = messages.stream.next().await {
2447                if let Some(chunk) = chunk.log_err() {
2448                    new_detailed_summary.push_str(&chunk);
2449                }
2450            }
2451
2452            thread
2453                .update(cx, |thread, _cx| {
2454                    *thread.detailed_summary_tx.borrow_mut() = DetailedSummaryState::Generated {
2455                        text: new_detailed_summary.into(),
2456                        message_id: last_message_id,
2457                    };
2458                })
2459                .ok()?;
2460
2461            // Save thread so its summary can be reused later
2462            if let Some(thread) = thread.upgrade() {
2463                if let Ok(Ok(save_task)) = cx.update(|cx| {
2464                    thread_store
2465                        .update(cx, |thread_store, cx| thread_store.save_thread(&thread, cx))
2466                }) {
2467                    save_task.await.log_err();
2468                }
2469            }
2470
2471            Some(())
2472        });
2473    }
2474
2475    pub async fn wait_for_detailed_summary_or_text(
2476        this: &Entity<Self>,
2477        cx: &mut AsyncApp,
2478    ) -> Option<SharedString> {
2479        let mut detailed_summary_rx = this
2480            .read_with(cx, |this, _cx| this.detailed_summary_rx.clone())
2481            .ok()?;
2482        loop {
2483            match detailed_summary_rx.recv().await? {
2484                DetailedSummaryState::Generating { .. } => {}
2485                DetailedSummaryState::NotGenerated => {
2486                    return this.read_with(cx, |this, _cx| this.text().into()).ok();
2487                }
2488                DetailedSummaryState::Generated { text, .. } => return Some(text),
2489            }
2490        }
2491    }
2492
2493    pub fn latest_detailed_summary_or_text(&self) -> SharedString {
2494        self.detailed_summary_rx
2495            .borrow()
2496            .text()
2497            .unwrap_or_else(|| self.text().into())
2498    }
2499
2500    pub fn is_generating_detailed_summary(&self) -> bool {
2501        matches!(
2502            &*self.detailed_summary_rx.borrow(),
2503            DetailedSummaryState::Generating { .. }
2504        )
2505    }
2506
2507    pub fn use_pending_tools(
2508        &mut self,
2509        window: Option<AnyWindowHandle>,
2510        model: Arc<dyn LanguageModel>,
2511        cx: &mut Context<Self>,
2512    ) -> Vec<PendingToolUse> {
2513        self.auto_capture_telemetry(cx);
2514        let request =
2515            Arc::new(self.to_completion_request(model.clone(), CompletionIntent::ToolResults, cx));
2516        let pending_tool_uses = self
2517            .tool_use
2518            .pending_tool_uses()
2519            .into_iter()
2520            .filter(|tool_use| tool_use.status.is_idle())
2521            .cloned()
2522            .collect::<Vec<_>>();
2523
2524        for tool_use in pending_tool_uses.iter() {
2525            self.use_pending_tool(tool_use.clone(), request.clone(), model.clone(), window, cx);
2526        }
2527
2528        pending_tool_uses
2529    }
2530
2531    fn use_pending_tool(
2532        &mut self,
2533        tool_use: PendingToolUse,
2534        request: Arc<LanguageModelRequest>,
2535        model: Arc<dyn LanguageModel>,
2536        window: Option<AnyWindowHandle>,
2537        cx: &mut Context<Self>,
2538    ) {
2539        let Some(tool) = self.tools.read(cx).tool(&tool_use.name, cx) else {
2540            return self.handle_hallucinated_tool_use(tool_use.id, tool_use.name, window, cx);
2541        };
2542
2543        if !self.profile.is_tool_enabled(tool.source(), tool.name(), cx) {
2544            return self.handle_hallucinated_tool_use(tool_use.id, tool_use.name, window, cx);
2545        }
2546
2547        if tool.needs_confirmation(&tool_use.input, cx)
2548            && !AgentSettings::get_global(cx).always_allow_tool_actions
2549        {
2550            self.tool_use.confirm_tool_use(
2551                tool_use.id,
2552                tool_use.ui_text,
2553                tool_use.input,
2554                request,
2555                tool,
2556            );
2557            cx.emit(ThreadEvent::ToolConfirmationNeeded);
2558        } else {
2559            self.run_tool(
2560                tool_use.id,
2561                tool_use.ui_text,
2562                tool_use.input,
2563                request,
2564                tool,
2565                model,
2566                window,
2567                cx,
2568            );
2569        }
2570    }
2571
2572    pub fn handle_hallucinated_tool_use(
2573        &mut self,
2574        tool_use_id: LanguageModelToolUseId,
2575        hallucinated_tool_name: Arc<str>,
2576        window: Option<AnyWindowHandle>,
2577        cx: &mut Context<Thread>,
2578    ) {
2579        let available_tools = self.profile.enabled_tools(cx);
2580
2581        let tool_list = available_tools
2582            .iter()
2583            .map(|(name, tool)| format!("- {}: {}", name, tool.description()))
2584            .collect::<Vec<_>>()
2585            .join("\n");
2586
2587        let error_message = format!(
2588            "The tool '{}' doesn't exist or is not enabled. Available tools:\n{}",
2589            hallucinated_tool_name, tool_list
2590        );
2591
2592        let pending_tool_use = self.tool_use.insert_tool_output(
2593            tool_use_id.clone(),
2594            hallucinated_tool_name,
2595            Err(anyhow!("Missing tool call: {error_message}")),
2596            self.configured_model.as_ref(),
2597            self.completion_mode,
2598        );
2599
2600        cx.emit(ThreadEvent::MissingToolUse {
2601            tool_use_id: tool_use_id.clone(),
2602            ui_text: error_message.into(),
2603        });
2604
2605        self.tool_finished(tool_use_id, pending_tool_use, false, window, cx);
2606    }
2607
2608    pub fn receive_invalid_tool_json(
2609        &mut self,
2610        tool_use_id: LanguageModelToolUseId,
2611        tool_name: Arc<str>,
2612        invalid_json: Arc<str>,
2613        error: String,
2614        window: Option<AnyWindowHandle>,
2615        cx: &mut Context<Thread>,
2616    ) {
2617        log::error!("The model returned invalid input JSON: {invalid_json}");
2618
2619        let pending_tool_use = self.tool_use.insert_tool_output(
2620            tool_use_id.clone(),
2621            tool_name,
2622            Err(anyhow!("Error parsing input JSON: {error}")),
2623            self.configured_model.as_ref(),
2624            self.completion_mode,
2625        );
2626        let ui_text = if let Some(pending_tool_use) = &pending_tool_use {
2627            pending_tool_use.ui_text.clone()
2628        } else {
2629            log::error!(
2630                "There was no pending tool use for tool use {tool_use_id}, even though it finished (with invalid input JSON)."
2631            );
2632            format!("Unknown tool {}", tool_use_id).into()
2633        };
2634
2635        cx.emit(ThreadEvent::InvalidToolInput {
2636            tool_use_id: tool_use_id.clone(),
2637            ui_text,
2638            invalid_input_json: invalid_json,
2639        });
2640
2641        self.tool_finished(tool_use_id, pending_tool_use, false, window, cx);
2642    }
2643
2644    pub fn run_tool(
2645        &mut self,
2646        tool_use_id: LanguageModelToolUseId,
2647        ui_text: impl Into<SharedString>,
2648        input: serde_json::Value,
2649        request: Arc<LanguageModelRequest>,
2650        tool: Arc<dyn Tool>,
2651        model: Arc<dyn LanguageModel>,
2652        window: Option<AnyWindowHandle>,
2653        cx: &mut Context<Thread>,
2654    ) {
2655        let task =
2656            self.spawn_tool_use(tool_use_id.clone(), request, input, tool, model, window, cx);
2657        self.tool_use
2658            .run_pending_tool(tool_use_id, ui_text.into(), task);
2659    }
2660
2661    fn spawn_tool_use(
2662        &mut self,
2663        tool_use_id: LanguageModelToolUseId,
2664        request: Arc<LanguageModelRequest>,
2665        input: serde_json::Value,
2666        tool: Arc<dyn Tool>,
2667        model: Arc<dyn LanguageModel>,
2668        window: Option<AnyWindowHandle>,
2669        cx: &mut Context<Thread>,
2670    ) -> Task<()> {
2671        let tool_name: Arc<str> = tool.name().into();
2672
2673        let tool_result = tool.run(
2674            input,
2675            request,
2676            self.project.clone(),
2677            self.action_log.clone(),
2678            model,
2679            window,
2680            cx,
2681        );
2682
2683        // Store the card separately if it exists
2684        if let Some(card) = tool_result.card.clone() {
2685            self.tool_use
2686                .insert_tool_result_card(tool_use_id.clone(), card);
2687        }
2688
2689        cx.spawn({
2690            async move |thread: WeakEntity<Thread>, cx| {
2691                let output = tool_result.output.await;
2692
2693                thread
2694                    .update(cx, |thread, cx| {
2695                        let pending_tool_use = thread.tool_use.insert_tool_output(
2696                            tool_use_id.clone(),
2697                            tool_name,
2698                            output,
2699                            thread.configured_model.as_ref(),
2700                            thread.completion_mode,
2701                        );
2702                        thread.tool_finished(tool_use_id, pending_tool_use, false, window, cx);
2703                    })
2704                    .ok();
2705            }
2706        })
2707    }
2708
2709    fn tool_finished(
2710        &mut self,
2711        tool_use_id: LanguageModelToolUseId,
2712        pending_tool_use: Option<PendingToolUse>,
2713        canceled: bool,
2714        window: Option<AnyWindowHandle>,
2715        cx: &mut Context<Self>,
2716    ) {
2717        if self.all_tools_finished() {
2718            if let Some(ConfiguredModel { model, .. }) = self.configured_model.as_ref() {
2719                if !canceled {
2720                    self.send_to_model(model.clone(), CompletionIntent::ToolResults, window, cx);
2721                }
2722                self.auto_capture_telemetry(cx);
2723            }
2724        }
2725
2726        cx.emit(ThreadEvent::ToolFinished {
2727            tool_use_id,
2728            pending_tool_use,
2729        });
2730    }
2731
2732    /// Cancels the last pending completion, if there are any pending.
2733    ///
2734    /// Returns whether a completion was canceled.
2735    pub fn cancel_last_completion(
2736        &mut self,
2737        window: Option<AnyWindowHandle>,
2738        cx: &mut Context<Self>,
2739    ) -> bool {
2740        let mut canceled = self.pending_completions.pop().is_some() || self.retry_state.is_some();
2741
2742        self.retry_state = None;
2743
2744        for pending_tool_use in self.tool_use.cancel_pending() {
2745            canceled = true;
2746            self.tool_finished(
2747                pending_tool_use.id.clone(),
2748                Some(pending_tool_use),
2749                true,
2750                window,
2751                cx,
2752            );
2753        }
2754
2755        if canceled {
2756            cx.emit(ThreadEvent::CompletionCanceled);
2757
2758            // When canceled, we always want to insert the checkpoint.
2759            // (We skip over finalize_pending_checkpoint, because it
2760            // would conclude we didn't have anything to insert here.)
2761            if let Some(checkpoint) = self.pending_checkpoint.take() {
2762                self.insert_checkpoint(checkpoint, cx);
2763            }
2764        } else {
2765            self.finalize_pending_checkpoint(cx);
2766        }
2767
2768        canceled
2769    }
2770
2771    /// Signals that any in-progress editing should be canceled.
2772    ///
2773    /// This method is used to notify listeners (like ActiveThread) that
2774    /// they should cancel any editing operations.
2775    pub fn cancel_editing(&mut self, cx: &mut Context<Self>) {
2776        cx.emit(ThreadEvent::CancelEditing);
2777    }
2778
2779    pub fn feedback(&self) -> Option<ThreadFeedback> {
2780        self.feedback
2781    }
2782
2783    pub fn message_feedback(&self, message_id: MessageId) -> Option<ThreadFeedback> {
2784        self.message_feedback.get(&message_id).copied()
2785    }
2786
2787    pub fn report_message_feedback(
2788        &mut self,
2789        message_id: MessageId,
2790        feedback: ThreadFeedback,
2791        cx: &mut Context<Self>,
2792    ) -> Task<Result<()>> {
2793        if self.message_feedback.get(&message_id) == Some(&feedback) {
2794            return Task::ready(Ok(()));
2795        }
2796
2797        let final_project_snapshot = Self::project_snapshot(self.project.clone(), cx);
2798        let serialized_thread = self.serialize(cx);
2799        let thread_id = self.id().clone();
2800        let client = self.project.read(cx).client();
2801
2802        let enabled_tool_names: Vec<String> = self
2803            .profile
2804            .enabled_tools(cx)
2805            .iter()
2806            .map(|(name, _)| name.clone().into())
2807            .collect();
2808
2809        self.message_feedback.insert(message_id, feedback);
2810
2811        cx.notify();
2812
2813        let message_content = self
2814            .message(message_id)
2815            .map(|msg| msg.to_string())
2816            .unwrap_or_default();
2817
2818        cx.background_spawn(async move {
2819            let final_project_snapshot = final_project_snapshot.await;
2820            let serialized_thread = serialized_thread.await?;
2821            let thread_data =
2822                serde_json::to_value(serialized_thread).unwrap_or_else(|_| serde_json::Value::Null);
2823
2824            let rating = match feedback {
2825                ThreadFeedback::Positive => "positive",
2826                ThreadFeedback::Negative => "negative",
2827            };
2828            telemetry::event!(
2829                "Assistant Thread Rated",
2830                rating,
2831                thread_id,
2832                enabled_tool_names,
2833                message_id = message_id.0,
2834                message_content,
2835                thread_data,
2836                final_project_snapshot
2837            );
2838            client.telemetry().flush_events().await;
2839
2840            Ok(())
2841        })
2842    }
2843
2844    pub fn report_feedback(
2845        &mut self,
2846        feedback: ThreadFeedback,
2847        cx: &mut Context<Self>,
2848    ) -> Task<Result<()>> {
2849        let last_assistant_message_id = self
2850            .messages
2851            .iter()
2852            .rev()
2853            .find(|msg| msg.role == Role::Assistant)
2854            .map(|msg| msg.id);
2855
2856        if let Some(message_id) = last_assistant_message_id {
2857            self.report_message_feedback(message_id, feedback, cx)
2858        } else {
2859            let final_project_snapshot = Self::project_snapshot(self.project.clone(), cx);
2860            let serialized_thread = self.serialize(cx);
2861            let thread_id = self.id().clone();
2862            let client = self.project.read(cx).client();
2863            self.feedback = Some(feedback);
2864            cx.notify();
2865
2866            cx.background_spawn(async move {
2867                let final_project_snapshot = final_project_snapshot.await;
2868                let serialized_thread = serialized_thread.await?;
2869                let thread_data = serde_json::to_value(serialized_thread)
2870                    .unwrap_or_else(|_| serde_json::Value::Null);
2871
2872                let rating = match feedback {
2873                    ThreadFeedback::Positive => "positive",
2874                    ThreadFeedback::Negative => "negative",
2875                };
2876                telemetry::event!(
2877                    "Assistant Thread Rated",
2878                    rating,
2879                    thread_id,
2880                    thread_data,
2881                    final_project_snapshot
2882                );
2883                client.telemetry().flush_events().await;
2884
2885                Ok(())
2886            })
2887        }
2888    }
2889
2890    /// Create a snapshot of the current project state including git information and unsaved buffers.
2891    fn project_snapshot(
2892        project: Entity<Project>,
2893        cx: &mut Context<Self>,
2894    ) -> Task<Arc<ProjectSnapshot>> {
2895        let git_store = project.read(cx).git_store().clone();
2896        let worktree_snapshots: Vec<_> = project
2897            .read(cx)
2898            .visible_worktrees(cx)
2899            .map(|worktree| Self::worktree_snapshot(worktree, git_store.clone(), cx))
2900            .collect();
2901
2902        cx.spawn(async move |_, cx| {
2903            let worktree_snapshots = futures::future::join_all(worktree_snapshots).await;
2904
2905            let mut unsaved_buffers = Vec::new();
2906            cx.update(|app_cx| {
2907                let buffer_store = project.read(app_cx).buffer_store();
2908                for buffer_handle in buffer_store.read(app_cx).buffers() {
2909                    let buffer = buffer_handle.read(app_cx);
2910                    if buffer.is_dirty() {
2911                        if let Some(file) = buffer.file() {
2912                            let path = file.path().to_string_lossy().to_string();
2913                            unsaved_buffers.push(path);
2914                        }
2915                    }
2916                }
2917            })
2918            .ok();
2919
2920            Arc::new(ProjectSnapshot {
2921                worktree_snapshots,
2922                unsaved_buffer_paths: unsaved_buffers,
2923                timestamp: Utc::now(),
2924            })
2925        })
2926    }
2927
2928    fn worktree_snapshot(
2929        worktree: Entity<project::Worktree>,
2930        git_store: Entity<GitStore>,
2931        cx: &App,
2932    ) -> Task<WorktreeSnapshot> {
2933        cx.spawn(async move |cx| {
2934            // Get worktree path and snapshot
2935            let worktree_info = cx.update(|app_cx| {
2936                let worktree = worktree.read(app_cx);
2937                let path = worktree.abs_path().to_string_lossy().to_string();
2938                let snapshot = worktree.snapshot();
2939                (path, snapshot)
2940            });
2941
2942            let Ok((worktree_path, _snapshot)) = worktree_info else {
2943                return WorktreeSnapshot {
2944                    worktree_path: String::new(),
2945                    git_state: None,
2946                };
2947            };
2948
2949            let git_state = git_store
2950                .update(cx, |git_store, cx| {
2951                    git_store
2952                        .repositories()
2953                        .values()
2954                        .find(|repo| {
2955                            repo.read(cx)
2956                                .abs_path_to_repo_path(&worktree.read(cx).abs_path())
2957                                .is_some()
2958                        })
2959                        .cloned()
2960                })
2961                .ok()
2962                .flatten()
2963                .map(|repo| {
2964                    repo.update(cx, |repo, _| {
2965                        let current_branch =
2966                            repo.branch.as_ref().map(|branch| branch.name().to_owned());
2967                        repo.send_job(None, |state, _| async move {
2968                            let RepositoryState::Local { backend, .. } = state else {
2969                                return GitState {
2970                                    remote_url: None,
2971                                    head_sha: None,
2972                                    current_branch,
2973                                    diff: None,
2974                                };
2975                            };
2976
2977                            let remote_url = backend.remote_url("origin");
2978                            let head_sha = backend.head_sha().await;
2979                            let diff = backend.diff(DiffType::HeadToWorktree).await.ok();
2980
2981                            GitState {
2982                                remote_url,
2983                                head_sha,
2984                                current_branch,
2985                                diff,
2986                            }
2987                        })
2988                    })
2989                });
2990
2991            let git_state = match git_state {
2992                Some(git_state) => match git_state.ok() {
2993                    Some(git_state) => git_state.await.ok(),
2994                    None => None,
2995                },
2996                None => None,
2997            };
2998
2999            WorktreeSnapshot {
3000                worktree_path,
3001                git_state,
3002            }
3003        })
3004    }
3005
3006    pub fn to_markdown(&self, cx: &App) -> Result<String> {
3007        let mut markdown = Vec::new();
3008
3009        let summary = self.summary().or_default();
3010        writeln!(markdown, "# {summary}\n")?;
3011
3012        for message in self.messages() {
3013            writeln!(
3014                markdown,
3015                "## {role}\n",
3016                role = match message.role {
3017                    Role::User => "User",
3018                    Role::Assistant => "Agent",
3019                    Role::System => "System",
3020                }
3021            )?;
3022
3023            if !message.loaded_context.text.is_empty() {
3024                writeln!(markdown, "{}", message.loaded_context.text)?;
3025            }
3026
3027            if !message.loaded_context.images.is_empty() {
3028                writeln!(
3029                    markdown,
3030                    "\n{} images attached as context.\n",
3031                    message.loaded_context.images.len()
3032                )?;
3033            }
3034
3035            for segment in &message.segments {
3036                match segment {
3037                    MessageSegment::Text(text) => writeln!(markdown, "{}\n", text)?,
3038                    MessageSegment::Thinking { text, .. } => {
3039                        writeln!(markdown, "<think>\n{}\n</think>\n", text)?
3040                    }
3041                    MessageSegment::RedactedThinking(_) => {}
3042                }
3043            }
3044
3045            for tool_use in self.tool_uses_for_message(message.id, cx) {
3046                writeln!(
3047                    markdown,
3048                    "**Use Tool: {} ({})**",
3049                    tool_use.name, tool_use.id
3050                )?;
3051                writeln!(markdown, "```json")?;
3052                writeln!(
3053                    markdown,
3054                    "{}",
3055                    serde_json::to_string_pretty(&tool_use.input)?
3056                )?;
3057                writeln!(markdown, "```")?;
3058            }
3059
3060            for tool_result in self.tool_results_for_message(message.id) {
3061                write!(markdown, "\n**Tool Results: {}", tool_result.tool_use_id)?;
3062                if tool_result.is_error {
3063                    write!(markdown, " (Error)")?;
3064                }
3065
3066                writeln!(markdown, "**\n")?;
3067                match &tool_result.content {
3068                    LanguageModelToolResultContent::Text(text) => {
3069                        writeln!(markdown, "{text}")?;
3070                    }
3071                    LanguageModelToolResultContent::Image(image) => {
3072                        writeln!(markdown, "![Image](data:base64,{})", image.source)?;
3073                    }
3074                }
3075
3076                if let Some(output) = tool_result.output.as_ref() {
3077                    writeln!(
3078                        markdown,
3079                        "\n\nDebug Output:\n\n```json\n{}\n```\n",
3080                        serde_json::to_string_pretty(output)?
3081                    )?;
3082                }
3083            }
3084        }
3085
3086        Ok(String::from_utf8_lossy(&markdown).to_string())
3087    }
3088
3089    pub fn keep_edits_in_range(
3090        &mut self,
3091        buffer: Entity<language::Buffer>,
3092        buffer_range: Range<language::Anchor>,
3093        cx: &mut Context<Self>,
3094    ) {
3095        self.action_log.update(cx, |action_log, cx| {
3096            action_log.keep_edits_in_range(buffer, buffer_range, cx)
3097        });
3098    }
3099
3100    pub fn keep_all_edits(&mut self, cx: &mut Context<Self>) {
3101        self.action_log
3102            .update(cx, |action_log, cx| action_log.keep_all_edits(cx));
3103    }
3104
3105    pub fn reject_edits_in_ranges(
3106        &mut self,
3107        buffer: Entity<language::Buffer>,
3108        buffer_ranges: Vec<Range<language::Anchor>>,
3109        cx: &mut Context<Self>,
3110    ) -> Task<Result<()>> {
3111        self.action_log.update(cx, |action_log, cx| {
3112            action_log.reject_edits_in_ranges(buffer, buffer_ranges, cx)
3113        })
3114    }
3115
3116    pub fn action_log(&self) -> &Entity<ActionLog> {
3117        &self.action_log
3118    }
3119
3120    pub fn project(&self) -> &Entity<Project> {
3121        &self.project
3122    }
3123
3124    pub fn auto_capture_telemetry(&mut self, cx: &mut Context<Self>) {
3125        if !cx.has_flag::<feature_flags::ThreadAutoCaptureFeatureFlag>() {
3126            return;
3127        }
3128
3129        let now = Instant::now();
3130        if let Some(last) = self.last_auto_capture_at {
3131            if now.duration_since(last).as_secs() < 10 {
3132                return;
3133            }
3134        }
3135
3136        self.last_auto_capture_at = Some(now);
3137
3138        let thread_id = self.id().clone();
3139        let github_login = self
3140            .project
3141            .read(cx)
3142            .user_store()
3143            .read(cx)
3144            .current_user()
3145            .map(|user| user.github_login.clone());
3146        let client = self.project.read(cx).client();
3147        let serialize_task = self.serialize(cx);
3148
3149        cx.background_executor()
3150            .spawn(async move {
3151                if let Ok(serialized_thread) = serialize_task.await {
3152                    if let Ok(thread_data) = serde_json::to_value(serialized_thread) {
3153                        telemetry::event!(
3154                            "Agent Thread Auto-Captured",
3155                            thread_id = thread_id.to_string(),
3156                            thread_data = thread_data,
3157                            auto_capture_reason = "tracked_user",
3158                            github_login = github_login
3159                        );
3160
3161                        client.telemetry().flush_events().await;
3162                    }
3163                }
3164            })
3165            .detach();
3166    }
3167
3168    pub fn cumulative_token_usage(&self) -> TokenUsage {
3169        self.cumulative_token_usage
3170    }
3171
3172    pub fn token_usage_up_to_message(&self, message_id: MessageId) -> TotalTokenUsage {
3173        let Some(model) = self.configured_model.as_ref() else {
3174            return TotalTokenUsage::default();
3175        };
3176
3177        let max = model
3178            .model
3179            .max_token_count_for_mode(self.completion_mode().into());
3180
3181        let index = self
3182            .messages
3183            .iter()
3184            .position(|msg| msg.id == message_id)
3185            .unwrap_or(0);
3186
3187        if index == 0 {
3188            return TotalTokenUsage { total: 0, max };
3189        }
3190
3191        let token_usage = &self
3192            .request_token_usage
3193            .get(index - 1)
3194            .cloned()
3195            .unwrap_or_default();
3196
3197        TotalTokenUsage {
3198            total: token_usage.total_tokens(),
3199            max,
3200        }
3201    }
3202
3203    pub fn total_token_usage(&self) -> Option<TotalTokenUsage> {
3204        let model = self.configured_model.as_ref()?;
3205
3206        let max = model
3207            .model
3208            .max_token_count_for_mode(self.completion_mode().into());
3209
3210        if let Some(exceeded_error) = &self.exceeded_window_error {
3211            if model.model.id() == exceeded_error.model_id {
3212                return Some(TotalTokenUsage {
3213                    total: exceeded_error.token_count,
3214                    max,
3215                });
3216            }
3217        }
3218
3219        let total = self
3220            .token_usage_at_last_message()
3221            .unwrap_or_default()
3222            .total_tokens();
3223
3224        Some(TotalTokenUsage { total, max })
3225    }
3226
3227    fn token_usage_at_last_message(&self) -> Option<TokenUsage> {
3228        self.request_token_usage
3229            .get(self.messages.len().saturating_sub(1))
3230            .or_else(|| self.request_token_usage.last())
3231            .cloned()
3232    }
3233
3234    fn update_token_usage_at_last_message(&mut self, token_usage: TokenUsage) {
3235        let placeholder = self.token_usage_at_last_message().unwrap_or_default();
3236        self.request_token_usage
3237            .resize(self.messages.len(), placeholder);
3238
3239        if let Some(last) = self.request_token_usage.last_mut() {
3240            *last = token_usage;
3241        }
3242    }
3243
3244    fn update_model_request_usage(&self, amount: u32, limit: UsageLimit, cx: &mut Context<Self>) {
3245        self.project.update(cx, |project, cx| {
3246            project.user_store().update(cx, |user_store, cx| {
3247                user_store.update_model_request_usage(
3248                    ModelRequestUsage(RequestUsage {
3249                        amount: amount as i32,
3250                        limit,
3251                    }),
3252                    cx,
3253                )
3254            })
3255        });
3256    }
3257
3258    pub fn deny_tool_use(
3259        &mut self,
3260        tool_use_id: LanguageModelToolUseId,
3261        tool_name: Arc<str>,
3262        window: Option<AnyWindowHandle>,
3263        cx: &mut Context<Self>,
3264    ) {
3265        let err = Err(anyhow::anyhow!(
3266            "Permission to run tool action denied by user"
3267        ));
3268
3269        self.tool_use.insert_tool_output(
3270            tool_use_id.clone(),
3271            tool_name,
3272            err,
3273            self.configured_model.as_ref(),
3274            self.completion_mode,
3275        );
3276        self.tool_finished(tool_use_id.clone(), None, true, window, cx);
3277    }
3278}
3279
3280#[derive(Debug, Clone, Error)]
3281pub enum ThreadError {
3282    #[error("Payment required")]
3283    PaymentRequired,
3284    #[error("Model request limit reached")]
3285    ModelRequestLimitReached { plan: Plan },
3286    #[error("Message {header}: {message}")]
3287    Message {
3288        header: SharedString,
3289        message: SharedString,
3290    },
3291    #[error("Retryable error: {message}")]
3292    RetryableError {
3293        message: SharedString,
3294        can_enable_burn_mode: bool,
3295    },
3296}
3297
3298#[derive(Debug, Clone)]
3299pub enum ThreadEvent {
3300    ShowError(ThreadError),
3301    StreamedCompletion,
3302    ReceivedTextChunk,
3303    NewRequest,
3304    StreamedAssistantText(MessageId, String),
3305    StreamedAssistantThinking(MessageId, String),
3306    StreamedToolUse {
3307        tool_use_id: LanguageModelToolUseId,
3308        ui_text: Arc<str>,
3309        input: serde_json::Value,
3310    },
3311    MissingToolUse {
3312        tool_use_id: LanguageModelToolUseId,
3313        ui_text: Arc<str>,
3314    },
3315    InvalidToolInput {
3316        tool_use_id: LanguageModelToolUseId,
3317        ui_text: Arc<str>,
3318        invalid_input_json: Arc<str>,
3319    },
3320    Stopped(Result<StopReason, Arc<anyhow::Error>>),
3321    MessageAdded(MessageId),
3322    MessageEdited(MessageId),
3323    MessageDeleted(MessageId),
3324    SummaryGenerated,
3325    SummaryChanged,
3326    UsePendingTools {
3327        tool_uses: Vec<PendingToolUse>,
3328    },
3329    ToolFinished {
3330        #[allow(unused)]
3331        tool_use_id: LanguageModelToolUseId,
3332        /// The pending tool use that corresponds to this tool.
3333        pending_tool_use: Option<PendingToolUse>,
3334    },
3335    CheckpointChanged,
3336    ToolConfirmationNeeded,
3337    ToolUseLimitReached,
3338    CancelEditing,
3339    CompletionCanceled,
3340    ProfileChanged,
3341}
3342
3343impl EventEmitter<ThreadEvent> for Thread {}
3344
3345struct PendingCompletion {
3346    id: usize,
3347    queue_state: QueueState,
3348    _task: Task<()>,
3349}
3350
3351#[cfg(test)]
3352mod tests {
3353    use super::*;
3354    use crate::{
3355        context::load_context, context_store::ContextStore, thread_store, thread_store::ThreadStore,
3356    };
3357
3358    // Test-specific constants
3359    const TEST_RATE_LIMIT_RETRY_SECS: u64 = 30;
3360    use agent_settings::{AgentProfileId, AgentSettings, LanguageModelParameters};
3361    use assistant_tool::ToolRegistry;
3362    use assistant_tools;
3363    use futures::StreamExt;
3364    use futures::future::BoxFuture;
3365    use futures::stream::BoxStream;
3366    use gpui::TestAppContext;
3367    use http_client;
3368    use language_model::fake_provider::{FakeLanguageModel, FakeLanguageModelProvider};
3369    use language_model::{
3370        LanguageModelCompletionError, LanguageModelName, LanguageModelProviderId,
3371        LanguageModelProviderName, LanguageModelToolChoice,
3372    };
3373    use parking_lot::Mutex;
3374    use project::{FakeFs, Project};
3375    use prompt_store::PromptBuilder;
3376    use serde_json::json;
3377    use settings::{Settings, SettingsStore};
3378    use std::sync::Arc;
3379    use std::time::Duration;
3380    use theme::ThemeSettings;
3381    use util::path;
3382    use workspace::Workspace;
3383
3384    #[gpui::test]
3385    async fn test_message_with_context(cx: &mut TestAppContext) {
3386        init_test_settings(cx);
3387
3388        let project = create_test_project(
3389            cx,
3390            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3391        )
3392        .await;
3393
3394        let (_workspace, _thread_store, thread, context_store, model) =
3395            setup_test_environment(cx, project.clone()).await;
3396
3397        add_file_to_context(&project, &context_store, "test/code.rs", cx)
3398            .await
3399            .unwrap();
3400
3401        let context =
3402            context_store.read_with(cx, |store, _| store.context().next().cloned().unwrap());
3403        let loaded_context = cx
3404            .update(|cx| load_context(vec![context], &project, &None, cx))
3405            .await;
3406
3407        // Insert user message with context
3408        let message_id = thread.update(cx, |thread, cx| {
3409            thread.insert_user_message(
3410                "Please explain this code",
3411                loaded_context,
3412                None,
3413                Vec::new(),
3414                cx,
3415            )
3416        });
3417
3418        // Check content and context in message object
3419        let message = thread.read_with(cx, |thread, _| thread.message(message_id).unwrap().clone());
3420
3421        // Use different path format strings based on platform for the test
3422        #[cfg(windows)]
3423        let path_part = r"test\code.rs";
3424        #[cfg(not(windows))]
3425        let path_part = "test/code.rs";
3426
3427        let expected_context = format!(
3428            r#"
3429<context>
3430The following items were attached by the user. They are up-to-date and don't need to be re-read.
3431
3432<files>
3433```rs {path_part}
3434fn main() {{
3435    println!("Hello, world!");
3436}}
3437```
3438</files>
3439</context>
3440"#
3441        );
3442
3443        assert_eq!(message.role, Role::User);
3444        assert_eq!(message.segments.len(), 1);
3445        assert_eq!(
3446            message.segments[0],
3447            MessageSegment::Text("Please explain this code".to_string())
3448        );
3449        assert_eq!(message.loaded_context.text, expected_context);
3450
3451        // Check message in request
3452        let request = thread.update(cx, |thread, cx| {
3453            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3454        });
3455
3456        assert_eq!(request.messages.len(), 2);
3457        let expected_full_message = format!("{}Please explain this code", expected_context);
3458        assert_eq!(request.messages[1].string_contents(), expected_full_message);
3459    }
3460
3461    #[gpui::test]
3462    async fn test_only_include_new_contexts(cx: &mut TestAppContext) {
3463        init_test_settings(cx);
3464
3465        let project = create_test_project(
3466            cx,
3467            json!({
3468                "file1.rs": "fn function1() {}\n",
3469                "file2.rs": "fn function2() {}\n",
3470                "file3.rs": "fn function3() {}\n",
3471                "file4.rs": "fn function4() {}\n",
3472            }),
3473        )
3474        .await;
3475
3476        let (_, _thread_store, thread, context_store, model) =
3477            setup_test_environment(cx, project.clone()).await;
3478
3479        // First message with context 1
3480        add_file_to_context(&project, &context_store, "test/file1.rs", cx)
3481            .await
3482            .unwrap();
3483        let new_contexts = context_store.update(cx, |store, cx| {
3484            store.new_context_for_thread(thread.read(cx), None)
3485        });
3486        assert_eq!(new_contexts.len(), 1);
3487        let loaded_context = cx
3488            .update(|cx| load_context(new_contexts, &project, &None, cx))
3489            .await;
3490        let message1_id = thread.update(cx, |thread, cx| {
3491            thread.insert_user_message("Message 1", loaded_context, None, Vec::new(), cx)
3492        });
3493
3494        // Second message with contexts 1 and 2 (context 1 should be skipped as it's already included)
3495        add_file_to_context(&project, &context_store, "test/file2.rs", cx)
3496            .await
3497            .unwrap();
3498        let new_contexts = context_store.update(cx, |store, cx| {
3499            store.new_context_for_thread(thread.read(cx), None)
3500        });
3501        assert_eq!(new_contexts.len(), 1);
3502        let loaded_context = cx
3503            .update(|cx| load_context(new_contexts, &project, &None, cx))
3504            .await;
3505        let message2_id = thread.update(cx, |thread, cx| {
3506            thread.insert_user_message("Message 2", loaded_context, None, Vec::new(), cx)
3507        });
3508
3509        // Third message with all three contexts (contexts 1 and 2 should be skipped)
3510        //
3511        add_file_to_context(&project, &context_store, "test/file3.rs", cx)
3512            .await
3513            .unwrap();
3514        let new_contexts = context_store.update(cx, |store, cx| {
3515            store.new_context_for_thread(thread.read(cx), None)
3516        });
3517        assert_eq!(new_contexts.len(), 1);
3518        let loaded_context = cx
3519            .update(|cx| load_context(new_contexts, &project, &None, cx))
3520            .await;
3521        let message3_id = thread.update(cx, |thread, cx| {
3522            thread.insert_user_message("Message 3", loaded_context, None, Vec::new(), cx)
3523        });
3524
3525        // Check what contexts are included in each message
3526        let (message1, message2, message3) = thread.read_with(cx, |thread, _| {
3527            (
3528                thread.message(message1_id).unwrap().clone(),
3529                thread.message(message2_id).unwrap().clone(),
3530                thread.message(message3_id).unwrap().clone(),
3531            )
3532        });
3533
3534        // First message should include context 1
3535        assert!(message1.loaded_context.text.contains("file1.rs"));
3536
3537        // Second message should include only context 2 (not 1)
3538        assert!(!message2.loaded_context.text.contains("file1.rs"));
3539        assert!(message2.loaded_context.text.contains("file2.rs"));
3540
3541        // Third message should include only context 3 (not 1 or 2)
3542        assert!(!message3.loaded_context.text.contains("file1.rs"));
3543        assert!(!message3.loaded_context.text.contains("file2.rs"));
3544        assert!(message3.loaded_context.text.contains("file3.rs"));
3545
3546        // Check entire request to make sure all contexts are properly included
3547        let request = thread.update(cx, |thread, cx| {
3548            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3549        });
3550
3551        // The request should contain all 3 messages
3552        assert_eq!(request.messages.len(), 4);
3553
3554        // Check that the contexts are properly formatted in each message
3555        assert!(request.messages[1].string_contents().contains("file1.rs"));
3556        assert!(!request.messages[1].string_contents().contains("file2.rs"));
3557        assert!(!request.messages[1].string_contents().contains("file3.rs"));
3558
3559        assert!(!request.messages[2].string_contents().contains("file1.rs"));
3560        assert!(request.messages[2].string_contents().contains("file2.rs"));
3561        assert!(!request.messages[2].string_contents().contains("file3.rs"));
3562
3563        assert!(!request.messages[3].string_contents().contains("file1.rs"));
3564        assert!(!request.messages[3].string_contents().contains("file2.rs"));
3565        assert!(request.messages[3].string_contents().contains("file3.rs"));
3566
3567        add_file_to_context(&project, &context_store, "test/file4.rs", cx)
3568            .await
3569            .unwrap();
3570        let new_contexts = context_store.update(cx, |store, cx| {
3571            store.new_context_for_thread(thread.read(cx), Some(message2_id))
3572        });
3573        assert_eq!(new_contexts.len(), 3);
3574        let loaded_context = cx
3575            .update(|cx| load_context(new_contexts, &project, &None, cx))
3576            .await
3577            .loaded_context;
3578
3579        assert!(!loaded_context.text.contains("file1.rs"));
3580        assert!(loaded_context.text.contains("file2.rs"));
3581        assert!(loaded_context.text.contains("file3.rs"));
3582        assert!(loaded_context.text.contains("file4.rs"));
3583
3584        let new_contexts = context_store.update(cx, |store, cx| {
3585            // Remove file4.rs
3586            store.remove_context(&loaded_context.contexts[2].handle(), cx);
3587            store.new_context_for_thread(thread.read(cx), Some(message2_id))
3588        });
3589        assert_eq!(new_contexts.len(), 2);
3590        let loaded_context = cx
3591            .update(|cx| load_context(new_contexts, &project, &None, cx))
3592            .await
3593            .loaded_context;
3594
3595        assert!(!loaded_context.text.contains("file1.rs"));
3596        assert!(loaded_context.text.contains("file2.rs"));
3597        assert!(loaded_context.text.contains("file3.rs"));
3598        assert!(!loaded_context.text.contains("file4.rs"));
3599
3600        let new_contexts = context_store.update(cx, |store, cx| {
3601            // Remove file3.rs
3602            store.remove_context(&loaded_context.contexts[1].handle(), cx);
3603            store.new_context_for_thread(thread.read(cx), Some(message2_id))
3604        });
3605        assert_eq!(new_contexts.len(), 1);
3606        let loaded_context = cx
3607            .update(|cx| load_context(new_contexts, &project, &None, cx))
3608            .await
3609            .loaded_context;
3610
3611        assert!(!loaded_context.text.contains("file1.rs"));
3612        assert!(loaded_context.text.contains("file2.rs"));
3613        assert!(!loaded_context.text.contains("file3.rs"));
3614        assert!(!loaded_context.text.contains("file4.rs"));
3615    }
3616
3617    #[gpui::test]
3618    async fn test_message_without_files(cx: &mut TestAppContext) {
3619        init_test_settings(cx);
3620
3621        let project = create_test_project(
3622            cx,
3623            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3624        )
3625        .await;
3626
3627        let (_, _thread_store, thread, _context_store, model) =
3628            setup_test_environment(cx, project.clone()).await;
3629
3630        // Insert user message without any context (empty context vector)
3631        let message_id = thread.update(cx, |thread, cx| {
3632            thread.insert_user_message(
3633                "What is the best way to learn Rust?",
3634                ContextLoadResult::default(),
3635                None,
3636                Vec::new(),
3637                cx,
3638            )
3639        });
3640
3641        // Check content and context in message object
3642        let message = thread.read_with(cx, |thread, _| thread.message(message_id).unwrap().clone());
3643
3644        // Context should be empty when no files are included
3645        assert_eq!(message.role, Role::User);
3646        assert_eq!(message.segments.len(), 1);
3647        assert_eq!(
3648            message.segments[0],
3649            MessageSegment::Text("What is the best way to learn Rust?".to_string())
3650        );
3651        assert_eq!(message.loaded_context.text, "");
3652
3653        // Check message in request
3654        let request = thread.update(cx, |thread, cx| {
3655            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3656        });
3657
3658        assert_eq!(request.messages.len(), 2);
3659        assert_eq!(
3660            request.messages[1].string_contents(),
3661            "What is the best way to learn Rust?"
3662        );
3663
3664        // Add second message, also without context
3665        let message2_id = thread.update(cx, |thread, cx| {
3666            thread.insert_user_message(
3667                "Are there any good books?",
3668                ContextLoadResult::default(),
3669                None,
3670                Vec::new(),
3671                cx,
3672            )
3673        });
3674
3675        let message2 =
3676            thread.read_with(cx, |thread, _| thread.message(message2_id).unwrap().clone());
3677        assert_eq!(message2.loaded_context.text, "");
3678
3679        // Check that both messages appear in the request
3680        let request = thread.update(cx, |thread, cx| {
3681            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3682        });
3683
3684        assert_eq!(request.messages.len(), 3);
3685        assert_eq!(
3686            request.messages[1].string_contents(),
3687            "What is the best way to learn Rust?"
3688        );
3689        assert_eq!(
3690            request.messages[2].string_contents(),
3691            "Are there any good books?"
3692        );
3693    }
3694
3695    #[gpui::test]
3696    #[ignore] // turn this test on when project_notifications tool is re-enabled
3697    async fn test_stale_buffer_notification(cx: &mut TestAppContext) {
3698        init_test_settings(cx);
3699
3700        let project = create_test_project(
3701            cx,
3702            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3703        )
3704        .await;
3705
3706        let (_workspace, _thread_store, thread, context_store, model) =
3707            setup_test_environment(cx, project.clone()).await;
3708
3709        // Add a buffer to the context. This will be a tracked buffer
3710        let buffer = add_file_to_context(&project, &context_store, "test/code.rs", cx)
3711            .await
3712            .unwrap();
3713
3714        let context = context_store
3715            .read_with(cx, |store, _| store.context().next().cloned())
3716            .unwrap();
3717        let loaded_context = cx
3718            .update(|cx| load_context(vec![context], &project, &None, cx))
3719            .await;
3720
3721        // Insert user message and assistant response
3722        thread.update(cx, |thread, cx| {
3723            thread.insert_user_message("Explain this code", loaded_context, None, Vec::new(), cx);
3724            thread.insert_assistant_message(
3725                vec![MessageSegment::Text("This code prints 42.".into())],
3726                cx,
3727            );
3728        });
3729        cx.run_until_parked();
3730
3731        // We shouldn't have a stale buffer notification yet
3732        let notifications = thread.read_with(cx, |thread, _| {
3733            find_tool_uses(thread, "project_notifications")
3734        });
3735        assert!(
3736            notifications.is_empty(),
3737            "Should not have stale buffer notification before buffer is modified"
3738        );
3739
3740        // Modify the buffer
3741        buffer.update(cx, |buffer, cx| {
3742            buffer.edit(
3743                [(1..1, "\n    println!(\"Added a new line\");\n")],
3744                None,
3745                cx,
3746            );
3747        });
3748
3749        // Insert another user message
3750        thread.update(cx, |thread, cx| {
3751            thread.insert_user_message(
3752                "What does the code do now?",
3753                ContextLoadResult::default(),
3754                None,
3755                Vec::new(),
3756                cx,
3757            )
3758        });
3759        cx.run_until_parked();
3760
3761        // Check for the stale buffer warning
3762        thread.update(cx, |thread, cx| {
3763            thread.flush_notifications(model.clone(), CompletionIntent::UserPrompt, cx)
3764        });
3765        cx.run_until_parked();
3766
3767        let notifications = thread.read_with(cx, |thread, _cx| {
3768            find_tool_uses(thread, "project_notifications")
3769        });
3770
3771        let [notification] = notifications.as_slice() else {
3772            panic!("Should have a `project_notifications` tool use");
3773        };
3774
3775        let Some(notification_content) = notification.content.to_str() else {
3776            panic!("`project_notifications` should return text");
3777        };
3778
3779        assert!(notification_content.contains("These files have changed since the last read:"));
3780        assert!(notification_content.contains("code.rs"));
3781
3782        // Insert another user message and flush notifications again
3783        thread.update(cx, |thread, cx| {
3784            thread.insert_user_message(
3785                "Can you tell me more?",
3786                ContextLoadResult::default(),
3787                None,
3788                Vec::new(),
3789                cx,
3790            )
3791        });
3792
3793        thread.update(cx, |thread, cx| {
3794            thread.flush_notifications(model.clone(), CompletionIntent::UserPrompt, cx)
3795        });
3796        cx.run_until_parked();
3797
3798        // There should be no new notifications (we already flushed one)
3799        let notifications = thread.read_with(cx, |thread, _cx| {
3800            find_tool_uses(thread, "project_notifications")
3801        });
3802
3803        assert_eq!(
3804            notifications.len(),
3805            1,
3806            "Should still have only one notification after second flush - no duplicates"
3807        );
3808    }
3809
3810    fn find_tool_uses(thread: &Thread, tool_name: &str) -> Vec<LanguageModelToolResult> {
3811        thread
3812            .messages()
3813            .flat_map(|message| {
3814                thread
3815                    .tool_results_for_message(message.id)
3816                    .into_iter()
3817                    .filter(|result| result.tool_name == tool_name.into())
3818                    .cloned()
3819                    .collect::<Vec<_>>()
3820            })
3821            .collect()
3822    }
3823
3824    #[gpui::test]
3825    async fn test_storing_profile_setting_per_thread(cx: &mut TestAppContext) {
3826        init_test_settings(cx);
3827
3828        let project = create_test_project(
3829            cx,
3830            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3831        )
3832        .await;
3833
3834        let (_workspace, thread_store, thread, _context_store, _model) =
3835            setup_test_environment(cx, project.clone()).await;
3836
3837        // Check that we are starting with the default profile
3838        let profile = cx.read(|cx| thread.read(cx).profile.clone());
3839        let tool_set = cx.read(|cx| thread_store.read(cx).tools());
3840        assert_eq!(
3841            profile,
3842            AgentProfile::new(AgentProfileId::default(), tool_set)
3843        );
3844    }
3845
3846    #[gpui::test]
3847    async fn test_serializing_thread_profile(cx: &mut TestAppContext) {
3848        init_test_settings(cx);
3849
3850        let project = create_test_project(
3851            cx,
3852            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3853        )
3854        .await;
3855
3856        let (_workspace, thread_store, thread, _context_store, _model) =
3857            setup_test_environment(cx, project.clone()).await;
3858
3859        // Profile gets serialized with default values
3860        let serialized = thread
3861            .update(cx, |thread, cx| thread.serialize(cx))
3862            .await
3863            .unwrap();
3864
3865        assert_eq!(serialized.profile, Some(AgentProfileId::default()));
3866
3867        let deserialized = cx.update(|cx| {
3868            thread.update(cx, |thread, cx| {
3869                Thread::deserialize(
3870                    thread.id.clone(),
3871                    serialized,
3872                    thread.project.clone(),
3873                    thread.tools.clone(),
3874                    thread.prompt_builder.clone(),
3875                    thread.project_context.clone(),
3876                    None,
3877                    cx,
3878                )
3879            })
3880        });
3881        let tool_set = cx.read(|cx| thread_store.read(cx).tools());
3882
3883        assert_eq!(
3884            deserialized.profile,
3885            AgentProfile::new(AgentProfileId::default(), tool_set)
3886        );
3887    }
3888
3889    #[gpui::test]
3890    async fn test_temperature_setting(cx: &mut TestAppContext) {
3891        init_test_settings(cx);
3892
3893        let project = create_test_project(
3894            cx,
3895            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3896        )
3897        .await;
3898
3899        let (_workspace, _thread_store, thread, _context_store, model) =
3900            setup_test_environment(cx, project.clone()).await;
3901
3902        // Both model and provider
3903        cx.update(|cx| {
3904            AgentSettings::override_global(
3905                AgentSettings {
3906                    model_parameters: vec![LanguageModelParameters {
3907                        provider: Some(model.provider_id().0.to_string().into()),
3908                        model: Some(model.id().0.clone()),
3909                        temperature: Some(0.66),
3910                    }],
3911                    ..AgentSettings::get_global(cx).clone()
3912                },
3913                cx,
3914            );
3915        });
3916
3917        let request = thread.update(cx, |thread, cx| {
3918            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3919        });
3920        assert_eq!(request.temperature, Some(0.66));
3921
3922        // Only model
3923        cx.update(|cx| {
3924            AgentSettings::override_global(
3925                AgentSettings {
3926                    model_parameters: vec![LanguageModelParameters {
3927                        provider: None,
3928                        model: Some(model.id().0.clone()),
3929                        temperature: Some(0.66),
3930                    }],
3931                    ..AgentSettings::get_global(cx).clone()
3932                },
3933                cx,
3934            );
3935        });
3936
3937        let request = thread.update(cx, |thread, cx| {
3938            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3939        });
3940        assert_eq!(request.temperature, Some(0.66));
3941
3942        // Only provider
3943        cx.update(|cx| {
3944            AgentSettings::override_global(
3945                AgentSettings {
3946                    model_parameters: vec![LanguageModelParameters {
3947                        provider: Some(model.provider_id().0.to_string().into()),
3948                        model: None,
3949                        temperature: Some(0.66),
3950                    }],
3951                    ..AgentSettings::get_global(cx).clone()
3952                },
3953                cx,
3954            );
3955        });
3956
3957        let request = thread.update(cx, |thread, cx| {
3958            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3959        });
3960        assert_eq!(request.temperature, Some(0.66));
3961
3962        // Same model name, different provider
3963        cx.update(|cx| {
3964            AgentSettings::override_global(
3965                AgentSettings {
3966                    model_parameters: vec![LanguageModelParameters {
3967                        provider: Some("anthropic".into()),
3968                        model: Some(model.id().0.clone()),
3969                        temperature: Some(0.66),
3970                    }],
3971                    ..AgentSettings::get_global(cx).clone()
3972                },
3973                cx,
3974            );
3975        });
3976
3977        let request = thread.update(cx, |thread, cx| {
3978            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3979        });
3980        assert_eq!(request.temperature, None);
3981    }
3982
3983    #[gpui::test]
3984    async fn test_thread_summary(cx: &mut TestAppContext) {
3985        init_test_settings(cx);
3986
3987        let project = create_test_project(cx, json!({})).await;
3988
3989        let (_, _thread_store, thread, _context_store, model) =
3990            setup_test_environment(cx, project.clone()).await;
3991
3992        // Initial state should be pending
3993        thread.read_with(cx, |thread, _| {
3994            assert!(matches!(thread.summary(), ThreadSummary::Pending));
3995            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
3996        });
3997
3998        // Manually setting the summary should not be allowed in this state
3999        thread.update(cx, |thread, cx| {
4000            thread.set_summary("This should not work", cx);
4001        });
4002
4003        thread.read_with(cx, |thread, _| {
4004            assert!(matches!(thread.summary(), ThreadSummary::Pending));
4005        });
4006
4007        // Send a message
4008        thread.update(cx, |thread, cx| {
4009            thread.insert_user_message("Hi!", ContextLoadResult::default(), None, vec![], cx);
4010            thread.send_to_model(
4011                model.clone(),
4012                CompletionIntent::ThreadSummarization,
4013                None,
4014                cx,
4015            );
4016        });
4017
4018        let fake_model = model.as_fake();
4019        simulate_successful_response(&fake_model, cx);
4020
4021        // Should start generating summary when there are >= 2 messages
4022        thread.read_with(cx, |thread, _| {
4023            assert_eq!(*thread.summary(), ThreadSummary::Generating);
4024        });
4025
4026        // Should not be able to set the summary while generating
4027        thread.update(cx, |thread, cx| {
4028            thread.set_summary("This should not work either", cx);
4029        });
4030
4031        thread.read_with(cx, |thread, _| {
4032            assert!(matches!(thread.summary(), ThreadSummary::Generating));
4033            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
4034        });
4035
4036        cx.run_until_parked();
4037        fake_model.stream_last_completion_response("Brief");
4038        fake_model.stream_last_completion_response(" Introduction");
4039        fake_model.end_last_completion_stream();
4040        cx.run_until_parked();
4041
4042        // Summary should be set
4043        thread.read_with(cx, |thread, _| {
4044            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
4045            assert_eq!(thread.summary().or_default(), "Brief Introduction");
4046        });
4047
4048        // Now we should be able to set a summary
4049        thread.update(cx, |thread, cx| {
4050            thread.set_summary("Brief Intro", cx);
4051        });
4052
4053        thread.read_with(cx, |thread, _| {
4054            assert_eq!(thread.summary().or_default(), "Brief Intro");
4055        });
4056
4057        // Test setting an empty summary (should default to DEFAULT)
4058        thread.update(cx, |thread, cx| {
4059            thread.set_summary("", cx);
4060        });
4061
4062        thread.read_with(cx, |thread, _| {
4063            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
4064            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
4065        });
4066    }
4067
4068    #[gpui::test]
4069    async fn test_thread_summary_error_set_manually(cx: &mut TestAppContext) {
4070        init_test_settings(cx);
4071
4072        let project = create_test_project(cx, json!({})).await;
4073
4074        let (_, _thread_store, thread, _context_store, model) =
4075            setup_test_environment(cx, project.clone()).await;
4076
4077        test_summarize_error(&model, &thread, cx);
4078
4079        // Now we should be able to set a summary
4080        thread.update(cx, |thread, cx| {
4081            thread.set_summary("Brief Intro", cx);
4082        });
4083
4084        thread.read_with(cx, |thread, _| {
4085            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
4086            assert_eq!(thread.summary().or_default(), "Brief Intro");
4087        });
4088    }
4089
4090    #[gpui::test]
4091    async fn test_thread_summary_error_retry(cx: &mut TestAppContext) {
4092        init_test_settings(cx);
4093
4094        let project = create_test_project(cx, json!({})).await;
4095
4096        let (_, _thread_store, thread, _context_store, model) =
4097            setup_test_environment(cx, project.clone()).await;
4098
4099        test_summarize_error(&model, &thread, cx);
4100
4101        // Sending another message should not trigger another summarize request
4102        thread.update(cx, |thread, cx| {
4103            thread.insert_user_message(
4104                "How are you?",
4105                ContextLoadResult::default(),
4106                None,
4107                vec![],
4108                cx,
4109            );
4110            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4111        });
4112
4113        let fake_model = model.as_fake();
4114        simulate_successful_response(&fake_model, cx);
4115
4116        thread.read_with(cx, |thread, _| {
4117            // State is still Error, not Generating
4118            assert!(matches!(thread.summary(), ThreadSummary::Error));
4119        });
4120
4121        // But the summarize request can be invoked manually
4122        thread.update(cx, |thread, cx| {
4123            thread.summarize(cx);
4124        });
4125
4126        thread.read_with(cx, |thread, _| {
4127            assert!(matches!(thread.summary(), ThreadSummary::Generating));
4128        });
4129
4130        cx.run_until_parked();
4131        fake_model.stream_last_completion_response("A successful summary");
4132        fake_model.end_last_completion_stream();
4133        cx.run_until_parked();
4134
4135        thread.read_with(cx, |thread, _| {
4136            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
4137            assert_eq!(thread.summary().or_default(), "A successful summary");
4138        });
4139    }
4140
4141    // Helper to create a model that returns errors
4142    enum TestError {
4143        Overloaded,
4144        InternalServerError,
4145    }
4146
4147    struct ErrorInjector {
4148        inner: Arc<FakeLanguageModel>,
4149        error_type: TestError,
4150    }
4151
4152    impl ErrorInjector {
4153        fn new(error_type: TestError) -> Self {
4154            Self {
4155                inner: Arc::new(FakeLanguageModel::default()),
4156                error_type,
4157            }
4158        }
4159    }
4160
4161    impl LanguageModel for ErrorInjector {
4162        fn id(&self) -> LanguageModelId {
4163            self.inner.id()
4164        }
4165
4166        fn name(&self) -> LanguageModelName {
4167            self.inner.name()
4168        }
4169
4170        fn provider_id(&self) -> LanguageModelProviderId {
4171            self.inner.provider_id()
4172        }
4173
4174        fn provider_name(&self) -> LanguageModelProviderName {
4175            self.inner.provider_name()
4176        }
4177
4178        fn supports_tools(&self) -> bool {
4179            self.inner.supports_tools()
4180        }
4181
4182        fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
4183            self.inner.supports_tool_choice(choice)
4184        }
4185
4186        fn supports_images(&self) -> bool {
4187            self.inner.supports_images()
4188        }
4189
4190        fn telemetry_id(&self) -> String {
4191            self.inner.telemetry_id()
4192        }
4193
4194        fn max_token_count(&self) -> u64 {
4195            self.inner.max_token_count()
4196        }
4197
4198        fn count_tokens(
4199            &self,
4200            request: LanguageModelRequest,
4201            cx: &App,
4202        ) -> BoxFuture<'static, Result<u64>> {
4203            self.inner.count_tokens(request, cx)
4204        }
4205
4206        fn stream_completion(
4207            &self,
4208            _request: LanguageModelRequest,
4209            _cx: &AsyncApp,
4210        ) -> BoxFuture<
4211            'static,
4212            Result<
4213                BoxStream<
4214                    'static,
4215                    Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
4216                >,
4217                LanguageModelCompletionError,
4218            >,
4219        > {
4220            let error = match self.error_type {
4221                TestError::Overloaded => LanguageModelCompletionError::ServerOverloaded {
4222                    provider: self.provider_name(),
4223                    retry_after: None,
4224                },
4225                TestError::InternalServerError => {
4226                    LanguageModelCompletionError::ApiInternalServerError {
4227                        provider: self.provider_name(),
4228                        message: "I'm a teapot orbiting the sun".to_string(),
4229                    }
4230                }
4231            };
4232            async move {
4233                let stream = futures::stream::once(async move { Err(error) });
4234                Ok(stream.boxed())
4235            }
4236            .boxed()
4237        }
4238
4239        fn as_fake(&self) -> &FakeLanguageModel {
4240            &self.inner
4241        }
4242    }
4243
4244    #[gpui::test]
4245    async fn test_retry_on_overloaded_error(cx: &mut TestAppContext) {
4246        init_test_settings(cx);
4247
4248        let project = create_test_project(cx, json!({})).await;
4249        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4250
4251        // Enable Burn Mode to allow retries
4252        thread.update(cx, |thread, _| {
4253            thread.set_completion_mode(CompletionMode::Burn);
4254        });
4255
4256        // Create model that returns overloaded error
4257        let model = Arc::new(ErrorInjector::new(TestError::Overloaded));
4258
4259        // Insert a user message
4260        thread.update(cx, |thread, cx| {
4261            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4262        });
4263
4264        // Start completion
4265        thread.update(cx, |thread, cx| {
4266            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4267        });
4268
4269        cx.run_until_parked();
4270
4271        thread.read_with(cx, |thread, _| {
4272            assert!(thread.retry_state.is_some(), "Should have retry state");
4273            let retry_state = thread.retry_state.as_ref().unwrap();
4274            assert_eq!(retry_state.attempt, 1, "Should be first retry attempt");
4275            assert_eq!(
4276                retry_state.max_attempts, MAX_RETRY_ATTEMPTS,
4277                "Should retry MAX_RETRY_ATTEMPTS times for overloaded errors"
4278            );
4279        });
4280
4281        // Check that a retry message was added
4282        thread.read_with(cx, |thread, _| {
4283            let mut messages = thread.messages();
4284            assert!(
4285                messages.any(|msg| {
4286                    msg.role == Role::System
4287                        && msg.ui_only
4288                        && msg.segments.iter().any(|seg| {
4289                            if let MessageSegment::Text(text) = seg {
4290                                text.contains("overloaded")
4291                                    && text
4292                                        .contains(&format!("attempt 1 of {}", MAX_RETRY_ATTEMPTS))
4293                            } else {
4294                                false
4295                            }
4296                        })
4297                }),
4298                "Should have added a system retry message"
4299            );
4300        });
4301
4302        let retry_count = thread.update(cx, |thread, _| {
4303            thread
4304                .messages
4305                .iter()
4306                .filter(|m| {
4307                    m.ui_only
4308                        && m.segments.iter().any(|s| {
4309                            if let MessageSegment::Text(text) = s {
4310                                text.contains("Retrying") && text.contains("seconds")
4311                            } else {
4312                                false
4313                            }
4314                        })
4315                })
4316                .count()
4317        });
4318
4319        assert_eq!(retry_count, 1, "Should have one retry message");
4320    }
4321
4322    #[gpui::test]
4323    async fn test_retry_on_internal_server_error(cx: &mut TestAppContext) {
4324        init_test_settings(cx);
4325
4326        let project = create_test_project(cx, json!({})).await;
4327        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4328
4329        // Enable Burn Mode to allow retries
4330        thread.update(cx, |thread, _| {
4331            thread.set_completion_mode(CompletionMode::Burn);
4332        });
4333
4334        // Create model that returns internal server error
4335        let model = Arc::new(ErrorInjector::new(TestError::InternalServerError));
4336
4337        // Insert a user message
4338        thread.update(cx, |thread, cx| {
4339            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4340        });
4341
4342        // Start completion
4343        thread.update(cx, |thread, cx| {
4344            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4345        });
4346
4347        cx.run_until_parked();
4348
4349        // Check retry state on thread
4350        thread.read_with(cx, |thread, _| {
4351            assert!(thread.retry_state.is_some(), "Should have retry state");
4352            let retry_state = thread.retry_state.as_ref().unwrap();
4353            assert_eq!(retry_state.attempt, 1, "Should be first retry attempt");
4354            assert_eq!(
4355                retry_state.max_attempts, 1,
4356                "Should have correct max attempts"
4357            );
4358        });
4359
4360        // Check that a retry message was added with provider name
4361        thread.read_with(cx, |thread, _| {
4362            let mut messages = thread.messages();
4363            assert!(
4364                messages.any(|msg| {
4365                    msg.role == Role::System
4366                        && msg.ui_only
4367                        && msg.segments.iter().any(|seg| {
4368                            if let MessageSegment::Text(text) = seg {
4369                                text.contains("internal")
4370                                    && text.contains("Fake")
4371                                    && text.contains("Retrying in")
4372                                    && !text.contains("attempt")
4373                            } else {
4374                                false
4375                            }
4376                        })
4377                }),
4378                "Should have added a system retry message with provider name"
4379            );
4380        });
4381
4382        // Count retry messages
4383        let retry_count = thread.update(cx, |thread, _| {
4384            thread
4385                .messages
4386                .iter()
4387                .filter(|m| {
4388                    m.ui_only
4389                        && m.segments.iter().any(|s| {
4390                            if let MessageSegment::Text(text) = s {
4391                                text.contains("Retrying") && text.contains("seconds")
4392                            } else {
4393                                false
4394                            }
4395                        })
4396                })
4397                .count()
4398        });
4399
4400        assert_eq!(retry_count, 1, "Should have one retry message");
4401    }
4402
4403    #[gpui::test]
4404    async fn test_exponential_backoff_on_retries(cx: &mut TestAppContext) {
4405        init_test_settings(cx);
4406
4407        let project = create_test_project(cx, json!({})).await;
4408        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4409
4410        // Enable Burn Mode to allow retries
4411        thread.update(cx, |thread, _| {
4412            thread.set_completion_mode(CompletionMode::Burn);
4413        });
4414
4415        // Create model that returns internal server error
4416        let model = Arc::new(ErrorInjector::new(TestError::InternalServerError));
4417
4418        // Insert a user message
4419        thread.update(cx, |thread, cx| {
4420            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4421        });
4422
4423        // Track retry events and completion count
4424        // Track completion events
4425        let completion_count = Arc::new(Mutex::new(0));
4426        let completion_count_clone = completion_count.clone();
4427
4428        let _subscription = thread.update(cx, |_, cx| {
4429            cx.subscribe(&thread, move |_, _, event: &ThreadEvent, _| {
4430                if let ThreadEvent::NewRequest = event {
4431                    *completion_count_clone.lock() += 1;
4432                }
4433            })
4434        });
4435
4436        // First attempt
4437        thread.update(cx, |thread, cx| {
4438            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4439        });
4440        cx.run_until_parked();
4441
4442        // Should have scheduled first retry - count retry messages
4443        let retry_count = thread.update(cx, |thread, _| {
4444            thread
4445                .messages
4446                .iter()
4447                .filter(|m| {
4448                    m.ui_only
4449                        && m.segments.iter().any(|s| {
4450                            if let MessageSegment::Text(text) = s {
4451                                text.contains("Retrying") && text.contains("seconds")
4452                            } else {
4453                                false
4454                            }
4455                        })
4456                })
4457                .count()
4458        });
4459        assert_eq!(retry_count, 1, "Should have scheduled first retry");
4460
4461        // Check retry state
4462        thread.read_with(cx, |thread, _| {
4463            assert!(thread.retry_state.is_some(), "Should have retry state");
4464            let retry_state = thread.retry_state.as_ref().unwrap();
4465            assert_eq!(retry_state.attempt, 1, "Should be first retry attempt");
4466            assert_eq!(
4467                retry_state.max_attempts, 1,
4468                "Internal server errors should only retry once"
4469            );
4470        });
4471
4472        // Advance clock for first retry
4473        cx.executor().advance_clock(BASE_RETRY_DELAY);
4474        cx.run_until_parked();
4475
4476        // Should have scheduled second retry - count retry messages
4477        let retry_count = thread.update(cx, |thread, _| {
4478            thread
4479                .messages
4480                .iter()
4481                .filter(|m| {
4482                    m.ui_only
4483                        && m.segments.iter().any(|s| {
4484                            if let MessageSegment::Text(text) = s {
4485                                text.contains("Retrying") && text.contains("seconds")
4486                            } else {
4487                                false
4488                            }
4489                        })
4490                })
4491                .count()
4492        });
4493        assert_eq!(
4494            retry_count, 1,
4495            "Should have only one retry for internal server errors"
4496        );
4497
4498        // For internal server errors, we only retry once and then give up
4499        // Check that retry_state is cleared after the single retry
4500        thread.read_with(cx, |thread, _| {
4501            assert!(
4502                thread.retry_state.is_none(),
4503                "Retry state should be cleared after single retry"
4504            );
4505        });
4506
4507        // Verify total attempts (1 initial + 1 retry)
4508        assert_eq!(
4509            *completion_count.lock(),
4510            2,
4511            "Should have attempted once plus 1 retry"
4512        );
4513    }
4514
4515    #[gpui::test]
4516    async fn test_max_retries_exceeded(cx: &mut TestAppContext) {
4517        init_test_settings(cx);
4518
4519        let project = create_test_project(cx, json!({})).await;
4520        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4521
4522        // Enable Burn Mode to allow retries
4523        thread.update(cx, |thread, _| {
4524            thread.set_completion_mode(CompletionMode::Burn);
4525        });
4526
4527        // Create model that returns overloaded error
4528        let model = Arc::new(ErrorInjector::new(TestError::Overloaded));
4529
4530        // Insert a user message
4531        thread.update(cx, |thread, cx| {
4532            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4533        });
4534
4535        // Track events
4536        let stopped_with_error = Arc::new(Mutex::new(false));
4537        let stopped_with_error_clone = stopped_with_error.clone();
4538
4539        let _subscription = thread.update(cx, |_, cx| {
4540            cx.subscribe(&thread, move |_, _, event: &ThreadEvent, _| {
4541                if let ThreadEvent::Stopped(Err(_)) = event {
4542                    *stopped_with_error_clone.lock() = true;
4543                }
4544            })
4545        });
4546
4547        // Start initial completion
4548        thread.update(cx, |thread, cx| {
4549            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4550        });
4551        cx.run_until_parked();
4552
4553        // Advance through all retries
4554        for _ in 0..MAX_RETRY_ATTEMPTS {
4555            cx.executor().advance_clock(BASE_RETRY_DELAY);
4556            cx.run_until_parked();
4557        }
4558
4559        let retry_count = thread.update(cx, |thread, _| {
4560            thread
4561                .messages
4562                .iter()
4563                .filter(|m| {
4564                    m.ui_only
4565                        && m.segments.iter().any(|s| {
4566                            if let MessageSegment::Text(text) = s {
4567                                text.contains("Retrying") && text.contains("seconds")
4568                            } else {
4569                                false
4570                            }
4571                        })
4572                })
4573                .count()
4574        });
4575
4576        // After max retries, should emit Stopped(Err(...)) event
4577        assert_eq!(
4578            retry_count, MAX_RETRY_ATTEMPTS as usize,
4579            "Should have attempted MAX_RETRY_ATTEMPTS retries for overloaded errors"
4580        );
4581        assert!(
4582            *stopped_with_error.lock(),
4583            "Should emit Stopped(Err(...)) event after max retries exceeded"
4584        );
4585
4586        // Retry state should be cleared
4587        thread.read_with(cx, |thread, _| {
4588            assert!(
4589                thread.retry_state.is_none(),
4590                "Retry state should be cleared after max retries"
4591            );
4592
4593            // Verify we have the expected number of retry messages
4594            let retry_messages = thread
4595                .messages
4596                .iter()
4597                .filter(|msg| msg.ui_only && msg.role == Role::System)
4598                .count();
4599            assert_eq!(
4600                retry_messages, MAX_RETRY_ATTEMPTS as usize,
4601                "Should have MAX_RETRY_ATTEMPTS retry messages for overloaded errors"
4602            );
4603        });
4604    }
4605
4606    #[gpui::test]
4607    async fn test_retry_message_removed_on_retry(cx: &mut TestAppContext) {
4608        init_test_settings(cx);
4609
4610        let project = create_test_project(cx, json!({})).await;
4611        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4612
4613        // Enable Burn Mode to allow retries
4614        thread.update(cx, |thread, _| {
4615            thread.set_completion_mode(CompletionMode::Burn);
4616        });
4617
4618        // We'll use a wrapper to switch behavior after first failure
4619        struct RetryTestModel {
4620            inner: Arc<FakeLanguageModel>,
4621            failed_once: Arc<Mutex<bool>>,
4622        }
4623
4624        impl LanguageModel for RetryTestModel {
4625            fn id(&self) -> LanguageModelId {
4626                self.inner.id()
4627            }
4628
4629            fn name(&self) -> LanguageModelName {
4630                self.inner.name()
4631            }
4632
4633            fn provider_id(&self) -> LanguageModelProviderId {
4634                self.inner.provider_id()
4635            }
4636
4637            fn provider_name(&self) -> LanguageModelProviderName {
4638                self.inner.provider_name()
4639            }
4640
4641            fn supports_tools(&self) -> bool {
4642                self.inner.supports_tools()
4643            }
4644
4645            fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
4646                self.inner.supports_tool_choice(choice)
4647            }
4648
4649            fn supports_images(&self) -> bool {
4650                self.inner.supports_images()
4651            }
4652
4653            fn telemetry_id(&self) -> String {
4654                self.inner.telemetry_id()
4655            }
4656
4657            fn max_token_count(&self) -> u64 {
4658                self.inner.max_token_count()
4659            }
4660
4661            fn count_tokens(
4662                &self,
4663                request: LanguageModelRequest,
4664                cx: &App,
4665            ) -> BoxFuture<'static, Result<u64>> {
4666                self.inner.count_tokens(request, cx)
4667            }
4668
4669            fn stream_completion(
4670                &self,
4671                request: LanguageModelRequest,
4672                cx: &AsyncApp,
4673            ) -> BoxFuture<
4674                'static,
4675                Result<
4676                    BoxStream<
4677                        'static,
4678                        Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
4679                    >,
4680                    LanguageModelCompletionError,
4681                >,
4682            > {
4683                if !*self.failed_once.lock() {
4684                    *self.failed_once.lock() = true;
4685                    let provider = self.provider_name();
4686                    // Return error on first attempt
4687                    let stream = futures::stream::once(async move {
4688                        Err(LanguageModelCompletionError::ServerOverloaded {
4689                            provider,
4690                            retry_after: None,
4691                        })
4692                    });
4693                    async move { Ok(stream.boxed()) }.boxed()
4694                } else {
4695                    // Succeed on retry
4696                    self.inner.stream_completion(request, cx)
4697                }
4698            }
4699
4700            fn as_fake(&self) -> &FakeLanguageModel {
4701                &self.inner
4702            }
4703        }
4704
4705        let model = Arc::new(RetryTestModel {
4706            inner: Arc::new(FakeLanguageModel::default()),
4707            failed_once: Arc::new(Mutex::new(false)),
4708        });
4709
4710        // Insert a user message
4711        thread.update(cx, |thread, cx| {
4712            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4713        });
4714
4715        // Track message deletions
4716        // Track when retry completes successfully
4717        let retry_completed = Arc::new(Mutex::new(false));
4718        let retry_completed_clone = retry_completed.clone();
4719
4720        let _subscription = thread.update(cx, |_, cx| {
4721            cx.subscribe(&thread, move |_, _, event: &ThreadEvent, _| {
4722                if let ThreadEvent::StreamedCompletion = event {
4723                    *retry_completed_clone.lock() = true;
4724                }
4725            })
4726        });
4727
4728        // Start completion
4729        thread.update(cx, |thread, cx| {
4730            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4731        });
4732        cx.run_until_parked();
4733
4734        // Get the retry message ID
4735        let retry_message_id = thread.read_with(cx, |thread, _| {
4736            thread
4737                .messages()
4738                .find(|msg| msg.role == Role::System && msg.ui_only)
4739                .map(|msg| msg.id)
4740                .expect("Should have a retry message")
4741        });
4742
4743        // Wait for retry
4744        cx.executor().advance_clock(BASE_RETRY_DELAY);
4745        cx.run_until_parked();
4746
4747        // Stream some successful content
4748        let fake_model = model.as_fake();
4749        // After the retry, there should be a new pending completion
4750        let pending = fake_model.pending_completions();
4751        assert!(
4752            !pending.is_empty(),
4753            "Should have a pending completion after retry"
4754        );
4755        fake_model.stream_completion_response(&pending[0], "Success!");
4756        fake_model.end_completion_stream(&pending[0]);
4757        cx.run_until_parked();
4758
4759        // Check that the retry completed successfully
4760        assert!(
4761            *retry_completed.lock(),
4762            "Retry should have completed successfully"
4763        );
4764
4765        // Retry message should still exist but be marked as ui_only
4766        thread.read_with(cx, |thread, _| {
4767            let retry_msg = thread
4768                .message(retry_message_id)
4769                .expect("Retry message should still exist");
4770            assert!(retry_msg.ui_only, "Retry message should be ui_only");
4771            assert_eq!(
4772                retry_msg.role,
4773                Role::System,
4774                "Retry message should have System role"
4775            );
4776        });
4777    }
4778
4779    #[gpui::test]
4780    async fn test_successful_completion_clears_retry_state(cx: &mut TestAppContext) {
4781        init_test_settings(cx);
4782
4783        let project = create_test_project(cx, json!({})).await;
4784        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4785
4786        // Enable Burn Mode to allow retries
4787        thread.update(cx, |thread, _| {
4788            thread.set_completion_mode(CompletionMode::Burn);
4789        });
4790
4791        // Create a model that fails once then succeeds
4792        struct FailOnceModel {
4793            inner: Arc<FakeLanguageModel>,
4794            failed_once: Arc<Mutex<bool>>,
4795        }
4796
4797        impl LanguageModel for FailOnceModel {
4798            fn id(&self) -> LanguageModelId {
4799                self.inner.id()
4800            }
4801
4802            fn name(&self) -> LanguageModelName {
4803                self.inner.name()
4804            }
4805
4806            fn provider_id(&self) -> LanguageModelProviderId {
4807                self.inner.provider_id()
4808            }
4809
4810            fn provider_name(&self) -> LanguageModelProviderName {
4811                self.inner.provider_name()
4812            }
4813
4814            fn supports_tools(&self) -> bool {
4815                self.inner.supports_tools()
4816            }
4817
4818            fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
4819                self.inner.supports_tool_choice(choice)
4820            }
4821
4822            fn supports_images(&self) -> bool {
4823                self.inner.supports_images()
4824            }
4825
4826            fn telemetry_id(&self) -> String {
4827                self.inner.telemetry_id()
4828            }
4829
4830            fn max_token_count(&self) -> u64 {
4831                self.inner.max_token_count()
4832            }
4833
4834            fn count_tokens(
4835                &self,
4836                request: LanguageModelRequest,
4837                cx: &App,
4838            ) -> BoxFuture<'static, Result<u64>> {
4839                self.inner.count_tokens(request, cx)
4840            }
4841
4842            fn stream_completion(
4843                &self,
4844                request: LanguageModelRequest,
4845                cx: &AsyncApp,
4846            ) -> BoxFuture<
4847                'static,
4848                Result<
4849                    BoxStream<
4850                        'static,
4851                        Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
4852                    >,
4853                    LanguageModelCompletionError,
4854                >,
4855            > {
4856                if !*self.failed_once.lock() {
4857                    *self.failed_once.lock() = true;
4858                    let provider = self.provider_name();
4859                    // Return error on first attempt
4860                    let stream = futures::stream::once(async move {
4861                        Err(LanguageModelCompletionError::ServerOverloaded {
4862                            provider,
4863                            retry_after: None,
4864                        })
4865                    });
4866                    async move { Ok(stream.boxed()) }.boxed()
4867                } else {
4868                    // Succeed on retry
4869                    self.inner.stream_completion(request, cx)
4870                }
4871            }
4872        }
4873
4874        let fail_once_model = Arc::new(FailOnceModel {
4875            inner: Arc::new(FakeLanguageModel::default()),
4876            failed_once: Arc::new(Mutex::new(false)),
4877        });
4878
4879        // Insert a user message
4880        thread.update(cx, |thread, cx| {
4881            thread.insert_user_message(
4882                "Test message",
4883                ContextLoadResult::default(),
4884                None,
4885                vec![],
4886                cx,
4887            );
4888        });
4889
4890        // Start completion with fail-once model
4891        thread.update(cx, |thread, cx| {
4892            thread.send_to_model(
4893                fail_once_model.clone(),
4894                CompletionIntent::UserPrompt,
4895                None,
4896                cx,
4897            );
4898        });
4899
4900        cx.run_until_parked();
4901
4902        // Verify retry state exists after first failure
4903        thread.read_with(cx, |thread, _| {
4904            assert!(
4905                thread.retry_state.is_some(),
4906                "Should have retry state after failure"
4907            );
4908        });
4909
4910        // Wait for retry delay
4911        cx.executor().advance_clock(BASE_RETRY_DELAY);
4912        cx.run_until_parked();
4913
4914        // The retry should now use our FailOnceModel which should succeed
4915        // We need to help the FakeLanguageModel complete the stream
4916        let inner_fake = fail_once_model.inner.clone();
4917
4918        // Wait a bit for the retry to start
4919        cx.run_until_parked();
4920
4921        // Check for pending completions and complete them
4922        if let Some(pending) = inner_fake.pending_completions().first() {
4923            inner_fake.stream_completion_response(pending, "Success!");
4924            inner_fake.end_completion_stream(pending);
4925        }
4926        cx.run_until_parked();
4927
4928        thread.read_with(cx, |thread, _| {
4929            assert!(
4930                thread.retry_state.is_none(),
4931                "Retry state should be cleared after successful completion"
4932            );
4933
4934            let has_assistant_message = thread
4935                .messages
4936                .iter()
4937                .any(|msg| msg.role == Role::Assistant && !msg.ui_only);
4938            assert!(
4939                has_assistant_message,
4940                "Should have an assistant message after successful retry"
4941            );
4942        });
4943    }
4944
4945    #[gpui::test]
4946    async fn test_rate_limit_retry_single_attempt(cx: &mut TestAppContext) {
4947        init_test_settings(cx);
4948
4949        let project = create_test_project(cx, json!({})).await;
4950        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4951
4952        // Enable Burn Mode to allow retries
4953        thread.update(cx, |thread, _| {
4954            thread.set_completion_mode(CompletionMode::Burn);
4955        });
4956
4957        // Create a model that returns rate limit error with retry_after
4958        struct RateLimitModel {
4959            inner: Arc<FakeLanguageModel>,
4960        }
4961
4962        impl LanguageModel for RateLimitModel {
4963            fn id(&self) -> LanguageModelId {
4964                self.inner.id()
4965            }
4966
4967            fn name(&self) -> LanguageModelName {
4968                self.inner.name()
4969            }
4970
4971            fn provider_id(&self) -> LanguageModelProviderId {
4972                self.inner.provider_id()
4973            }
4974
4975            fn provider_name(&self) -> LanguageModelProviderName {
4976                self.inner.provider_name()
4977            }
4978
4979            fn supports_tools(&self) -> bool {
4980                self.inner.supports_tools()
4981            }
4982
4983            fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
4984                self.inner.supports_tool_choice(choice)
4985            }
4986
4987            fn supports_images(&self) -> bool {
4988                self.inner.supports_images()
4989            }
4990
4991            fn telemetry_id(&self) -> String {
4992                self.inner.telemetry_id()
4993            }
4994
4995            fn max_token_count(&self) -> u64 {
4996                self.inner.max_token_count()
4997            }
4998
4999            fn count_tokens(
5000                &self,
5001                request: LanguageModelRequest,
5002                cx: &App,
5003            ) -> BoxFuture<'static, Result<u64>> {
5004                self.inner.count_tokens(request, cx)
5005            }
5006
5007            fn stream_completion(
5008                &self,
5009                _request: LanguageModelRequest,
5010                _cx: &AsyncApp,
5011            ) -> BoxFuture<
5012                'static,
5013                Result<
5014                    BoxStream<
5015                        'static,
5016                        Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
5017                    >,
5018                    LanguageModelCompletionError,
5019                >,
5020            > {
5021                let provider = self.provider_name();
5022                async move {
5023                    let stream = futures::stream::once(async move {
5024                        Err(LanguageModelCompletionError::RateLimitExceeded {
5025                            provider,
5026                            retry_after: Some(Duration::from_secs(TEST_RATE_LIMIT_RETRY_SECS)),
5027                        })
5028                    });
5029                    Ok(stream.boxed())
5030                }
5031                .boxed()
5032            }
5033
5034            fn as_fake(&self) -> &FakeLanguageModel {
5035                &self.inner
5036            }
5037        }
5038
5039        let model = Arc::new(RateLimitModel {
5040            inner: Arc::new(FakeLanguageModel::default()),
5041        });
5042
5043        // Insert a user message
5044        thread.update(cx, |thread, cx| {
5045            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
5046        });
5047
5048        // Start completion
5049        thread.update(cx, |thread, cx| {
5050            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
5051        });
5052
5053        cx.run_until_parked();
5054
5055        let retry_count = thread.update(cx, |thread, _| {
5056            thread
5057                .messages
5058                .iter()
5059                .filter(|m| {
5060                    m.ui_only
5061                        && m.segments.iter().any(|s| {
5062                            if let MessageSegment::Text(text) = s {
5063                                text.contains("rate limit exceeded")
5064                            } else {
5065                                false
5066                            }
5067                        })
5068                })
5069                .count()
5070        });
5071        assert_eq!(retry_count, 1, "Should have scheduled one retry");
5072
5073        thread.read_with(cx, |thread, _| {
5074            assert!(
5075                thread.retry_state.is_some(),
5076                "Rate limit errors should set retry_state"
5077            );
5078            if let Some(retry_state) = &thread.retry_state {
5079                assert_eq!(
5080                    retry_state.max_attempts, MAX_RETRY_ATTEMPTS,
5081                    "Rate limit errors should use MAX_RETRY_ATTEMPTS"
5082                );
5083            }
5084        });
5085
5086        // Verify we have one retry message
5087        thread.read_with(cx, |thread, _| {
5088            let retry_messages = thread
5089                .messages
5090                .iter()
5091                .filter(|msg| {
5092                    msg.ui_only
5093                        && msg.segments.iter().any(|seg| {
5094                            if let MessageSegment::Text(text) = seg {
5095                                text.contains("rate limit exceeded")
5096                            } else {
5097                                false
5098                            }
5099                        })
5100                })
5101                .count();
5102            assert_eq!(
5103                retry_messages, 1,
5104                "Should have one rate limit retry message"
5105            );
5106        });
5107
5108        // Check that retry message doesn't include attempt count
5109        thread.read_with(cx, |thread, _| {
5110            let retry_message = thread
5111                .messages
5112                .iter()
5113                .find(|msg| msg.role == Role::System && msg.ui_only)
5114                .expect("Should have a retry message");
5115
5116            // Check that the message contains attempt count since we use retry_state
5117            if let Some(MessageSegment::Text(text)) = retry_message.segments.first() {
5118                assert!(
5119                    text.contains(&format!("attempt 1 of {}", MAX_RETRY_ATTEMPTS)),
5120                    "Rate limit retry message should contain attempt count with MAX_RETRY_ATTEMPTS"
5121                );
5122                assert!(
5123                    text.contains("Retrying"),
5124                    "Rate limit retry message should contain retry text"
5125                );
5126            }
5127        });
5128    }
5129
5130    #[gpui::test]
5131    async fn test_ui_only_messages_not_sent_to_model(cx: &mut TestAppContext) {
5132        init_test_settings(cx);
5133
5134        let project = create_test_project(cx, json!({})).await;
5135        let (_, _, thread, _, model) = setup_test_environment(cx, project.clone()).await;
5136
5137        // Insert a regular user message
5138        thread.update(cx, |thread, cx| {
5139            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
5140        });
5141
5142        // Insert a UI-only message (like our retry notifications)
5143        thread.update(cx, |thread, cx| {
5144            let id = thread.next_message_id.post_inc();
5145            thread.messages.push(Message {
5146                id,
5147                role: Role::System,
5148                segments: vec![MessageSegment::Text(
5149                    "This is a UI-only message that should not be sent to the model".to_string(),
5150                )],
5151                loaded_context: LoadedContext::default(),
5152                creases: Vec::new(),
5153                is_hidden: true,
5154                ui_only: true,
5155            });
5156            cx.emit(ThreadEvent::MessageAdded(id));
5157        });
5158
5159        // Insert another regular message
5160        thread.update(cx, |thread, cx| {
5161            thread.insert_user_message(
5162                "How are you?",
5163                ContextLoadResult::default(),
5164                None,
5165                vec![],
5166                cx,
5167            );
5168        });
5169
5170        // Generate the completion request
5171        let request = thread.update(cx, |thread, cx| {
5172            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
5173        });
5174
5175        // Verify that the request only contains non-UI-only messages
5176        // Should have system prompt + 2 user messages, but not the UI-only message
5177        let user_messages: Vec<_> = request
5178            .messages
5179            .iter()
5180            .filter(|msg| msg.role == Role::User)
5181            .collect();
5182        assert_eq!(
5183            user_messages.len(),
5184            2,
5185            "Should have exactly 2 user messages"
5186        );
5187
5188        // Verify the UI-only content is not present anywhere in the request
5189        let request_text = request
5190            .messages
5191            .iter()
5192            .flat_map(|msg| &msg.content)
5193            .filter_map(|content| match content {
5194                MessageContent::Text(text) => Some(text.as_str()),
5195                _ => None,
5196            })
5197            .collect::<String>();
5198
5199        assert!(
5200            !request_text.contains("UI-only message"),
5201            "UI-only message content should not be in the request"
5202        );
5203
5204        // Verify the thread still has all 3 messages (including UI-only)
5205        thread.read_with(cx, |thread, _| {
5206            assert_eq!(
5207                thread.messages().count(),
5208                3,
5209                "Thread should have 3 messages"
5210            );
5211            assert_eq!(
5212                thread.messages().filter(|m| m.ui_only).count(),
5213                1,
5214                "Thread should have 1 UI-only message"
5215            );
5216        });
5217
5218        // Verify that UI-only messages are not serialized
5219        let serialized = thread
5220            .update(cx, |thread, cx| thread.serialize(cx))
5221            .await
5222            .unwrap();
5223        assert_eq!(
5224            serialized.messages.len(),
5225            2,
5226            "Serialized thread should only have 2 messages (no UI-only)"
5227        );
5228    }
5229
5230    #[gpui::test]
5231    async fn test_no_retry_without_burn_mode(cx: &mut TestAppContext) {
5232        init_test_settings(cx);
5233
5234        let project = create_test_project(cx, json!({})).await;
5235        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
5236
5237        // Ensure we're in Normal mode (not Burn mode)
5238        thread.update(cx, |thread, _| {
5239            thread.set_completion_mode(CompletionMode::Normal);
5240        });
5241
5242        // Track error events
5243        let error_events = Arc::new(Mutex::new(Vec::new()));
5244        let error_events_clone = error_events.clone();
5245
5246        let _subscription = thread.update(cx, |_, cx| {
5247            cx.subscribe(&thread, move |_, _, event: &ThreadEvent, _| {
5248                if let ThreadEvent::ShowError(error) = event {
5249                    error_events_clone.lock().push(error.clone());
5250                }
5251            })
5252        });
5253
5254        // Create model that returns overloaded error
5255        let model = Arc::new(ErrorInjector::new(TestError::Overloaded));
5256
5257        // Insert a user message
5258        thread.update(cx, |thread, cx| {
5259            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
5260        });
5261
5262        // Start completion
5263        thread.update(cx, |thread, cx| {
5264            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
5265        });
5266
5267        cx.run_until_parked();
5268
5269        // Verify no retry state was created
5270        thread.read_with(cx, |thread, _| {
5271            assert!(
5272                thread.retry_state.is_none(),
5273                "Should not have retry state in Normal mode"
5274            );
5275        });
5276
5277        // Check that a retryable error was reported
5278        let errors = error_events.lock();
5279        assert!(!errors.is_empty(), "Should have received an error event");
5280
5281        if let ThreadError::RetryableError {
5282            message: _,
5283            can_enable_burn_mode,
5284        } = &errors[0]
5285        {
5286            assert!(
5287                *can_enable_burn_mode,
5288                "Error should indicate burn mode can be enabled"
5289            );
5290        } else {
5291            panic!("Expected RetryableError, got {:?}", errors[0]);
5292        }
5293
5294        // Verify the thread is no longer generating
5295        thread.read_with(cx, |thread, _| {
5296            assert!(
5297                !thread.is_generating(),
5298                "Should not be generating after error without retry"
5299            );
5300        });
5301    }
5302
5303    #[gpui::test]
5304    async fn test_retry_cancelled_on_stop(cx: &mut TestAppContext) {
5305        init_test_settings(cx);
5306
5307        let project = create_test_project(cx, json!({})).await;
5308        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
5309
5310        // Enable Burn Mode to allow retries
5311        thread.update(cx, |thread, _| {
5312            thread.set_completion_mode(CompletionMode::Burn);
5313        });
5314
5315        // Create model that returns overloaded error
5316        let model = Arc::new(ErrorInjector::new(TestError::Overloaded));
5317
5318        // Insert a user message
5319        thread.update(cx, |thread, cx| {
5320            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
5321        });
5322
5323        // Start completion
5324        thread.update(cx, |thread, cx| {
5325            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
5326        });
5327
5328        cx.run_until_parked();
5329
5330        // Verify retry was scheduled by checking for retry message
5331        let has_retry_message = thread.read_with(cx, |thread, _| {
5332            thread.messages.iter().any(|m| {
5333                m.ui_only
5334                    && m.segments.iter().any(|s| {
5335                        if let MessageSegment::Text(text) = s {
5336                            text.contains("Retrying") && text.contains("seconds")
5337                        } else {
5338                            false
5339                        }
5340                    })
5341            })
5342        });
5343        assert!(has_retry_message, "Should have scheduled a retry");
5344
5345        // Cancel the completion before the retry happens
5346        thread.update(cx, |thread, cx| {
5347            thread.cancel_last_completion(None, cx);
5348        });
5349
5350        cx.run_until_parked();
5351
5352        // The retry should not have happened - no pending completions
5353        let fake_model = model.as_fake();
5354        assert_eq!(
5355            fake_model.pending_completions().len(),
5356            0,
5357            "Should have no pending completions after cancellation"
5358        );
5359
5360        // Verify the retry was cancelled by checking retry state
5361        thread.read_with(cx, |thread, _| {
5362            if let Some(retry_state) = &thread.retry_state {
5363                panic!(
5364                    "retry_state should be cleared after cancellation, but found: attempt={}, max_attempts={}, intent={:?}",
5365                    retry_state.attempt, retry_state.max_attempts, retry_state.intent
5366                );
5367            }
5368        });
5369    }
5370
5371    fn test_summarize_error(
5372        model: &Arc<dyn LanguageModel>,
5373        thread: &Entity<Thread>,
5374        cx: &mut TestAppContext,
5375    ) {
5376        thread.update(cx, |thread, cx| {
5377            thread.insert_user_message("Hi!", ContextLoadResult::default(), None, vec![], cx);
5378            thread.send_to_model(
5379                model.clone(),
5380                CompletionIntent::ThreadSummarization,
5381                None,
5382                cx,
5383            );
5384        });
5385
5386        let fake_model = model.as_fake();
5387        simulate_successful_response(&fake_model, cx);
5388
5389        thread.read_with(cx, |thread, _| {
5390            assert!(matches!(thread.summary(), ThreadSummary::Generating));
5391            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
5392        });
5393
5394        // Simulate summary request ending
5395        cx.run_until_parked();
5396        fake_model.end_last_completion_stream();
5397        cx.run_until_parked();
5398
5399        // State is set to Error and default message
5400        thread.read_with(cx, |thread, _| {
5401            assert!(matches!(thread.summary(), ThreadSummary::Error));
5402            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
5403        });
5404    }
5405
5406    fn simulate_successful_response(fake_model: &FakeLanguageModel, cx: &mut TestAppContext) {
5407        cx.run_until_parked();
5408        fake_model.stream_last_completion_response("Assistant response");
5409        fake_model.end_last_completion_stream();
5410        cx.run_until_parked();
5411    }
5412
5413    fn init_test_settings(cx: &mut TestAppContext) {
5414        cx.update(|cx| {
5415            let settings_store = SettingsStore::test(cx);
5416            cx.set_global(settings_store);
5417            language::init(cx);
5418            Project::init_settings(cx);
5419            AgentSettings::register(cx);
5420            prompt_store::init(cx);
5421            thread_store::init(cx);
5422            workspace::init_settings(cx);
5423            language_model::init_settings(cx);
5424            ThemeSettings::register(cx);
5425            ToolRegistry::default_global(cx);
5426            assistant_tool::init(cx);
5427
5428            let http_client = Arc::new(http_client::HttpClientWithUrl::new(
5429                http_client::FakeHttpClient::with_200_response(),
5430                "http://localhost".to_string(),
5431                None,
5432            ));
5433            assistant_tools::init(http_client, cx);
5434        });
5435    }
5436
5437    // Helper to create a test project with test files
5438    async fn create_test_project(
5439        cx: &mut TestAppContext,
5440        files: serde_json::Value,
5441    ) -> Entity<Project> {
5442        let fs = FakeFs::new(cx.executor());
5443        fs.insert_tree(path!("/test"), files).await;
5444        Project::test(fs, [path!("/test").as_ref()], cx).await
5445    }
5446
5447    async fn setup_test_environment(
5448        cx: &mut TestAppContext,
5449        project: Entity<Project>,
5450    ) -> (
5451        Entity<Workspace>,
5452        Entity<ThreadStore>,
5453        Entity<Thread>,
5454        Entity<ContextStore>,
5455        Arc<dyn LanguageModel>,
5456    ) {
5457        let (workspace, cx) =
5458            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5459
5460        let thread_store = cx
5461            .update(|_, cx| {
5462                ThreadStore::load(
5463                    project.clone(),
5464                    cx.new(|_| ToolWorkingSet::default()),
5465                    None,
5466                    Arc::new(PromptBuilder::new(None).unwrap()),
5467                    cx,
5468                )
5469            })
5470            .await
5471            .unwrap();
5472
5473        let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
5474        let context_store = cx.new(|_cx| ContextStore::new(project.downgrade(), None));
5475
5476        let provider = Arc::new(FakeLanguageModelProvider);
5477        let model = provider.test_model();
5478        let model: Arc<dyn LanguageModel> = Arc::new(model);
5479
5480        cx.update(|_, cx| {
5481            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
5482                registry.set_default_model(
5483                    Some(ConfiguredModel {
5484                        provider: provider.clone(),
5485                        model: model.clone(),
5486                    }),
5487                    cx,
5488                );
5489                registry.set_thread_summary_model(
5490                    Some(ConfiguredModel {
5491                        provider,
5492                        model: model.clone(),
5493                    }),
5494                    cx,
5495                );
5496            })
5497        });
5498
5499        (workspace, thread_store, thread, context_store, model)
5500    }
5501
5502    async fn add_file_to_context(
5503        project: &Entity<Project>,
5504        context_store: &Entity<ContextStore>,
5505        path: &str,
5506        cx: &mut TestAppContext,
5507    ) -> Result<Entity<language::Buffer>> {
5508        let buffer_path = project
5509            .read_with(cx, |project, cx| project.find_project_path(path, cx))
5510            .unwrap();
5511
5512        let buffer = project
5513            .update(cx, |project, cx| {
5514                project.open_buffer(buffer_path.clone(), cx)
5515            })
5516            .await
5517            .unwrap();
5518
5519        context_store.update(cx, |context_store, cx| {
5520            context_store.add_file_from_buffer(&buffer_path, buffer.clone(), false, cx);
5521        });
5522
5523        Ok(buffer)
5524    }
5525}