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