thread.rs

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