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