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    #[ignore] // turn this test on when project_notifications tool is re-enabled
3587    async fn test_stale_buffer_notification(cx: &mut TestAppContext) {
3588        init_test_settings(cx);
3589
3590        let project = create_test_project(
3591            cx,
3592            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3593        )
3594        .await;
3595
3596        let (_workspace, _thread_store, thread, context_store, model) =
3597            setup_test_environment(cx, project.clone()).await;
3598
3599        // Add a buffer to the context. This will be a tracked buffer
3600        let buffer = add_file_to_context(&project, &context_store, "test/code.rs", cx)
3601            .await
3602            .unwrap();
3603
3604        let context = context_store
3605            .read_with(cx, |store, _| store.context().next().cloned())
3606            .unwrap();
3607        let loaded_context = cx
3608            .update(|cx| load_context(vec![context], &project, &None, cx))
3609            .await;
3610
3611        // Insert user message and assistant response
3612        thread.update(cx, |thread, cx| {
3613            thread.insert_user_message("Explain this code", loaded_context, None, Vec::new(), cx);
3614            thread.insert_assistant_message(
3615                vec![MessageSegment::Text("This code prints 42.".into())],
3616                cx,
3617            );
3618        });
3619        cx.run_until_parked();
3620
3621        // We shouldn't have a stale buffer notification yet
3622        let notifications = thread.read_with(cx, |thread, _| {
3623            find_tool_uses(thread, "project_notifications")
3624        });
3625        assert!(
3626            notifications.is_empty(),
3627            "Should not have stale buffer notification before buffer is modified"
3628        );
3629
3630        // Modify the buffer
3631        buffer.update(cx, |buffer, cx| {
3632            buffer.edit(
3633                [(1..1, "\n    println!(\"Added a new line\");\n")],
3634                None,
3635                cx,
3636            );
3637        });
3638
3639        // Insert another user message
3640        thread.update(cx, |thread, cx| {
3641            thread.insert_user_message(
3642                "What does the code do now?",
3643                ContextLoadResult::default(),
3644                None,
3645                Vec::new(),
3646                cx,
3647            )
3648        });
3649        cx.run_until_parked();
3650
3651        // Check for the stale buffer warning
3652        thread.update(cx, |thread, cx| {
3653            thread.flush_notifications(model.clone(), CompletionIntent::UserPrompt, cx)
3654        });
3655        cx.run_until_parked();
3656
3657        let notifications = thread.read_with(cx, |thread, _cx| {
3658            find_tool_uses(thread, "project_notifications")
3659        });
3660
3661        let [notification] = notifications.as_slice() else {
3662            panic!("Should have a `project_notifications` tool use");
3663        };
3664
3665        let Some(notification_content) = notification.content.to_str() else {
3666            panic!("`project_notifications` should return text");
3667        };
3668
3669        assert!(notification_content.contains("These files have changed since the last read:"));
3670        assert!(notification_content.contains("code.rs"));
3671
3672        // Insert another user message and flush notifications again
3673        thread.update(cx, |thread, cx| {
3674            thread.insert_user_message(
3675                "Can you tell me more?",
3676                ContextLoadResult::default(),
3677                None,
3678                Vec::new(),
3679                cx,
3680            )
3681        });
3682
3683        thread.update(cx, |thread, cx| {
3684            thread.flush_notifications(model.clone(), CompletionIntent::UserPrompt, cx)
3685        });
3686        cx.run_until_parked();
3687
3688        // There should be no new notifications (we already flushed one)
3689        let notifications = thread.read_with(cx, |thread, _cx| {
3690            find_tool_uses(thread, "project_notifications")
3691        });
3692
3693        assert_eq!(
3694            notifications.len(),
3695            1,
3696            "Should still have only one notification after second flush - no duplicates"
3697        );
3698    }
3699
3700    fn find_tool_uses(thread: &Thread, tool_name: &str) -> Vec<LanguageModelToolResult> {
3701        thread
3702            .messages()
3703            .flat_map(|message| {
3704                thread
3705                    .tool_results_for_message(message.id)
3706                    .into_iter()
3707                    .filter(|result| result.tool_name == tool_name.into())
3708                    .cloned()
3709                    .collect::<Vec<_>>()
3710            })
3711            .collect()
3712    }
3713
3714    #[gpui::test]
3715    async fn test_storing_profile_setting_per_thread(cx: &mut TestAppContext) {
3716        init_test_settings(cx);
3717
3718        let project = create_test_project(
3719            cx,
3720            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3721        )
3722        .await;
3723
3724        let (_workspace, thread_store, thread, _context_store, _model) =
3725            setup_test_environment(cx, project.clone()).await;
3726
3727        // Check that we are starting with the default profile
3728        let profile = cx.read(|cx| thread.read(cx).profile.clone());
3729        let tool_set = cx.read(|cx| thread_store.read(cx).tools());
3730        assert_eq!(
3731            profile,
3732            AgentProfile::new(AgentProfileId::default(), tool_set)
3733        );
3734    }
3735
3736    #[gpui::test]
3737    async fn test_serializing_thread_profile(cx: &mut TestAppContext) {
3738        init_test_settings(cx);
3739
3740        let project = create_test_project(
3741            cx,
3742            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3743        )
3744        .await;
3745
3746        let (_workspace, thread_store, thread, _context_store, _model) =
3747            setup_test_environment(cx, project.clone()).await;
3748
3749        // Profile gets serialized with default values
3750        let serialized = thread
3751            .update(cx, |thread, cx| thread.serialize(cx))
3752            .await
3753            .unwrap();
3754
3755        assert_eq!(serialized.profile, Some(AgentProfileId::default()));
3756
3757        let deserialized = cx.update(|cx| {
3758            thread.update(cx, |thread, cx| {
3759                Thread::deserialize(
3760                    thread.id.clone(),
3761                    serialized,
3762                    thread.project.clone(),
3763                    thread.tools.clone(),
3764                    thread.prompt_builder.clone(),
3765                    thread.project_context.clone(),
3766                    None,
3767                    cx,
3768                )
3769            })
3770        });
3771        let tool_set = cx.read(|cx| thread_store.read(cx).tools());
3772
3773        assert_eq!(
3774            deserialized.profile,
3775            AgentProfile::new(AgentProfileId::default(), tool_set)
3776        );
3777    }
3778
3779    #[gpui::test]
3780    async fn test_temperature_setting(cx: &mut TestAppContext) {
3781        init_test_settings(cx);
3782
3783        let project = create_test_project(
3784            cx,
3785            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3786        )
3787        .await;
3788
3789        let (_workspace, _thread_store, thread, _context_store, model) =
3790            setup_test_environment(cx, project.clone()).await;
3791
3792        // Both model and provider
3793        cx.update(|cx| {
3794            AgentSettings::override_global(
3795                AgentSettings {
3796                    model_parameters: vec![LanguageModelParameters {
3797                        provider: Some(model.provider_id().0.to_string().into()),
3798                        model: Some(model.id().0.clone()),
3799                        temperature: Some(0.66),
3800                    }],
3801                    ..AgentSettings::get_global(cx).clone()
3802                },
3803                cx,
3804            );
3805        });
3806
3807        let request = thread.update(cx, |thread, cx| {
3808            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3809        });
3810        assert_eq!(request.temperature, Some(0.66));
3811
3812        // Only model
3813        cx.update(|cx| {
3814            AgentSettings::override_global(
3815                AgentSettings {
3816                    model_parameters: vec![LanguageModelParameters {
3817                        provider: None,
3818                        model: Some(model.id().0.clone()),
3819                        temperature: Some(0.66),
3820                    }],
3821                    ..AgentSettings::get_global(cx).clone()
3822                },
3823                cx,
3824            );
3825        });
3826
3827        let request = thread.update(cx, |thread, cx| {
3828            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3829        });
3830        assert_eq!(request.temperature, Some(0.66));
3831
3832        // Only provider
3833        cx.update(|cx| {
3834            AgentSettings::override_global(
3835                AgentSettings {
3836                    model_parameters: vec![LanguageModelParameters {
3837                        provider: Some(model.provider_id().0.to_string().into()),
3838                        model: None,
3839                        temperature: Some(0.66),
3840                    }],
3841                    ..AgentSettings::get_global(cx).clone()
3842                },
3843                cx,
3844            );
3845        });
3846
3847        let request = thread.update(cx, |thread, cx| {
3848            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3849        });
3850        assert_eq!(request.temperature, Some(0.66));
3851
3852        // Same model name, different provider
3853        cx.update(|cx| {
3854            AgentSettings::override_global(
3855                AgentSettings {
3856                    model_parameters: vec![LanguageModelParameters {
3857                        provider: Some("anthropic".into()),
3858                        model: Some(model.id().0.clone()),
3859                        temperature: Some(0.66),
3860                    }],
3861                    ..AgentSettings::get_global(cx).clone()
3862                },
3863                cx,
3864            );
3865        });
3866
3867        let request = thread.update(cx, |thread, cx| {
3868            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3869        });
3870        assert_eq!(request.temperature, None);
3871    }
3872
3873    #[gpui::test]
3874    async fn test_thread_summary(cx: &mut TestAppContext) {
3875        init_test_settings(cx);
3876
3877        let project = create_test_project(cx, json!({})).await;
3878
3879        let (_, _thread_store, thread, _context_store, model) =
3880            setup_test_environment(cx, project.clone()).await;
3881
3882        // Initial state should be pending
3883        thread.read_with(cx, |thread, _| {
3884            assert!(matches!(thread.summary(), ThreadSummary::Pending));
3885            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
3886        });
3887
3888        // Manually setting the summary should not be allowed in this state
3889        thread.update(cx, |thread, cx| {
3890            thread.set_summary("This should not work", cx);
3891        });
3892
3893        thread.read_with(cx, |thread, _| {
3894            assert!(matches!(thread.summary(), ThreadSummary::Pending));
3895        });
3896
3897        // Send a message
3898        thread.update(cx, |thread, cx| {
3899            thread.insert_user_message("Hi!", ContextLoadResult::default(), None, vec![], cx);
3900            thread.send_to_model(
3901                model.clone(),
3902                CompletionIntent::ThreadSummarization,
3903                None,
3904                cx,
3905            );
3906        });
3907
3908        let fake_model = model.as_fake();
3909        simulate_successful_response(&fake_model, cx);
3910
3911        // Should start generating summary when there are >= 2 messages
3912        thread.read_with(cx, |thread, _| {
3913            assert_eq!(*thread.summary(), ThreadSummary::Generating);
3914        });
3915
3916        // Should not be able to set the summary while generating
3917        thread.update(cx, |thread, cx| {
3918            thread.set_summary("This should not work either", cx);
3919        });
3920
3921        thread.read_with(cx, |thread, _| {
3922            assert!(matches!(thread.summary(), ThreadSummary::Generating));
3923            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
3924        });
3925
3926        cx.run_until_parked();
3927        fake_model.stream_last_completion_response("Brief");
3928        fake_model.stream_last_completion_response(" Introduction");
3929        fake_model.end_last_completion_stream();
3930        cx.run_until_parked();
3931
3932        // Summary should be set
3933        thread.read_with(cx, |thread, _| {
3934            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
3935            assert_eq!(thread.summary().or_default(), "Brief Introduction");
3936        });
3937
3938        // Now we should be able to set a summary
3939        thread.update(cx, |thread, cx| {
3940            thread.set_summary("Brief Intro", cx);
3941        });
3942
3943        thread.read_with(cx, |thread, _| {
3944            assert_eq!(thread.summary().or_default(), "Brief Intro");
3945        });
3946
3947        // Test setting an empty summary (should default to DEFAULT)
3948        thread.update(cx, |thread, cx| {
3949            thread.set_summary("", cx);
3950        });
3951
3952        thread.read_with(cx, |thread, _| {
3953            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
3954            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
3955        });
3956    }
3957
3958    #[gpui::test]
3959    async fn test_thread_summary_error_set_manually(cx: &mut TestAppContext) {
3960        init_test_settings(cx);
3961
3962        let project = create_test_project(cx, json!({})).await;
3963
3964        let (_, _thread_store, thread, _context_store, model) =
3965            setup_test_environment(cx, project.clone()).await;
3966
3967        test_summarize_error(&model, &thread, cx);
3968
3969        // Now we should be able to set a summary
3970        thread.update(cx, |thread, cx| {
3971            thread.set_summary("Brief Intro", cx);
3972        });
3973
3974        thread.read_with(cx, |thread, _| {
3975            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
3976            assert_eq!(thread.summary().or_default(), "Brief Intro");
3977        });
3978    }
3979
3980    #[gpui::test]
3981    async fn test_thread_summary_error_retry(cx: &mut TestAppContext) {
3982        init_test_settings(cx);
3983
3984        let project = create_test_project(cx, json!({})).await;
3985
3986        let (_, _thread_store, thread, _context_store, model) =
3987            setup_test_environment(cx, project.clone()).await;
3988
3989        test_summarize_error(&model, &thread, cx);
3990
3991        // Sending another message should not trigger another summarize request
3992        thread.update(cx, |thread, cx| {
3993            thread.insert_user_message(
3994                "How are you?",
3995                ContextLoadResult::default(),
3996                None,
3997                vec![],
3998                cx,
3999            );
4000            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4001        });
4002
4003        let fake_model = model.as_fake();
4004        simulate_successful_response(&fake_model, cx);
4005
4006        thread.read_with(cx, |thread, _| {
4007            // State is still Error, not Generating
4008            assert!(matches!(thread.summary(), ThreadSummary::Error));
4009        });
4010
4011        // But the summarize request can be invoked manually
4012        thread.update(cx, |thread, cx| {
4013            thread.summarize(cx);
4014        });
4015
4016        thread.read_with(cx, |thread, _| {
4017            assert!(matches!(thread.summary(), ThreadSummary::Generating));
4018        });
4019
4020        cx.run_until_parked();
4021        fake_model.stream_last_completion_response("A successful summary");
4022        fake_model.end_last_completion_stream();
4023        cx.run_until_parked();
4024
4025        thread.read_with(cx, |thread, _| {
4026            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
4027            assert_eq!(thread.summary().or_default(), "A successful summary");
4028        });
4029    }
4030
4031    // Helper to create a model that returns errors
4032    enum TestError {
4033        Overloaded,
4034        InternalServerError,
4035    }
4036
4037    struct ErrorInjector {
4038        inner: Arc<FakeLanguageModel>,
4039        error_type: TestError,
4040    }
4041
4042    impl ErrorInjector {
4043        fn new(error_type: TestError) -> Self {
4044            Self {
4045                inner: Arc::new(FakeLanguageModel::default()),
4046                error_type,
4047            }
4048        }
4049    }
4050
4051    impl LanguageModel for ErrorInjector {
4052        fn id(&self) -> LanguageModelId {
4053            self.inner.id()
4054        }
4055
4056        fn name(&self) -> LanguageModelName {
4057            self.inner.name()
4058        }
4059
4060        fn provider_id(&self) -> LanguageModelProviderId {
4061            self.inner.provider_id()
4062        }
4063
4064        fn provider_name(&self) -> LanguageModelProviderName {
4065            self.inner.provider_name()
4066        }
4067
4068        fn supports_tools(&self) -> bool {
4069            self.inner.supports_tools()
4070        }
4071
4072        fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
4073            self.inner.supports_tool_choice(choice)
4074        }
4075
4076        fn supports_images(&self) -> bool {
4077            self.inner.supports_images()
4078        }
4079
4080        fn telemetry_id(&self) -> String {
4081            self.inner.telemetry_id()
4082        }
4083
4084        fn max_token_count(&self) -> u64 {
4085            self.inner.max_token_count()
4086        }
4087
4088        fn count_tokens(
4089            &self,
4090            request: LanguageModelRequest,
4091            cx: &App,
4092        ) -> BoxFuture<'static, Result<u64>> {
4093            self.inner.count_tokens(request, cx)
4094        }
4095
4096        fn stream_completion(
4097            &self,
4098            _request: LanguageModelRequest,
4099            _cx: &AsyncApp,
4100        ) -> BoxFuture<
4101            'static,
4102            Result<
4103                BoxStream<
4104                    'static,
4105                    Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
4106                >,
4107                LanguageModelCompletionError,
4108            >,
4109        > {
4110            let error = match self.error_type {
4111                TestError::Overloaded => LanguageModelCompletionError::ServerOverloaded {
4112                    provider: self.provider_name(),
4113                    retry_after: None,
4114                },
4115                TestError::InternalServerError => {
4116                    LanguageModelCompletionError::ApiInternalServerError {
4117                        provider: self.provider_name(),
4118                        message: "I'm a teapot orbiting the sun".to_string(),
4119                    }
4120                }
4121            };
4122            async move {
4123                let stream = futures::stream::once(async move { Err(error) });
4124                Ok(stream.boxed())
4125            }
4126            .boxed()
4127        }
4128
4129        fn as_fake(&self) -> &FakeLanguageModel {
4130            &self.inner
4131        }
4132    }
4133
4134    #[gpui::test]
4135    async fn test_retry_on_overloaded_error(cx: &mut TestAppContext) {
4136        init_test_settings(cx);
4137
4138        let project = create_test_project(cx, json!({})).await;
4139        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4140
4141        // Create model that returns overloaded error
4142        let model = Arc::new(ErrorInjector::new(TestError::Overloaded));
4143
4144        // Insert a user message
4145        thread.update(cx, |thread, cx| {
4146            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4147        });
4148
4149        // Start completion
4150        thread.update(cx, |thread, cx| {
4151            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4152        });
4153
4154        cx.run_until_parked();
4155
4156        thread.read_with(cx, |thread, _| {
4157            assert!(thread.retry_state.is_some(), "Should have retry state");
4158            let retry_state = thread.retry_state.as_ref().unwrap();
4159            assert_eq!(retry_state.attempt, 1, "Should be first retry attempt");
4160            assert_eq!(
4161                retry_state.max_attempts, MAX_RETRY_ATTEMPTS,
4162                "Should retry MAX_RETRY_ATTEMPTS times for overloaded errors"
4163            );
4164        });
4165
4166        // Check that a retry message was added
4167        thread.read_with(cx, |thread, _| {
4168            let mut messages = thread.messages();
4169            assert!(
4170                messages.any(|msg| {
4171                    msg.role == Role::System
4172                        && msg.ui_only
4173                        && msg.segments.iter().any(|seg| {
4174                            if let MessageSegment::Text(text) = seg {
4175                                text.contains("overloaded")
4176                                    && text
4177                                        .contains(&format!("attempt 1 of {}", MAX_RETRY_ATTEMPTS))
4178                            } else {
4179                                false
4180                            }
4181                        })
4182                }),
4183                "Should have added a system retry message"
4184            );
4185        });
4186
4187        let retry_count = thread.update(cx, |thread, _| {
4188            thread
4189                .messages
4190                .iter()
4191                .filter(|m| {
4192                    m.ui_only
4193                        && m.segments.iter().any(|s| {
4194                            if let MessageSegment::Text(text) = s {
4195                                text.contains("Retrying") && text.contains("seconds")
4196                            } else {
4197                                false
4198                            }
4199                        })
4200                })
4201                .count()
4202        });
4203
4204        assert_eq!(retry_count, 1, "Should have one retry message");
4205    }
4206
4207    #[gpui::test]
4208    async fn test_retry_on_internal_server_error(cx: &mut TestAppContext) {
4209        init_test_settings(cx);
4210
4211        let project = create_test_project(cx, json!({})).await;
4212        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4213
4214        // Create model that returns internal server error
4215        let model = Arc::new(ErrorInjector::new(TestError::InternalServerError));
4216
4217        // Insert a user message
4218        thread.update(cx, |thread, cx| {
4219            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4220        });
4221
4222        // Start completion
4223        thread.update(cx, |thread, cx| {
4224            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4225        });
4226
4227        cx.run_until_parked();
4228
4229        // Check retry state on thread
4230        thread.read_with(cx, |thread, _| {
4231            assert!(thread.retry_state.is_some(), "Should have retry state");
4232            let retry_state = thread.retry_state.as_ref().unwrap();
4233            assert_eq!(retry_state.attempt, 1, "Should be first retry attempt");
4234            assert_eq!(
4235                retry_state.max_attempts, 1,
4236                "Should have correct max attempts"
4237            );
4238        });
4239
4240        // Check that a retry message was added with provider name
4241        thread.read_with(cx, |thread, _| {
4242            let mut messages = thread.messages();
4243            assert!(
4244                messages.any(|msg| {
4245                    msg.role == Role::System
4246                        && msg.ui_only
4247                        && msg.segments.iter().any(|seg| {
4248                            if let MessageSegment::Text(text) = seg {
4249                                text.contains("internal")
4250                                    && text.contains("Fake")
4251                                    && text.contains("Retrying in")
4252                                    && !text.contains("attempt")
4253                            } else {
4254                                false
4255                            }
4256                        })
4257                }),
4258                "Should have added a system retry message with provider name"
4259            );
4260        });
4261
4262        // Count retry messages
4263        let retry_count = thread.update(cx, |thread, _| {
4264            thread
4265                .messages
4266                .iter()
4267                .filter(|m| {
4268                    m.ui_only
4269                        && m.segments.iter().any(|s| {
4270                            if let MessageSegment::Text(text) = s {
4271                                text.contains("Retrying") && text.contains("seconds")
4272                            } else {
4273                                false
4274                            }
4275                        })
4276                })
4277                .count()
4278        });
4279
4280        assert_eq!(retry_count, 1, "Should have one retry message");
4281    }
4282
4283    #[gpui::test]
4284    async fn test_exponential_backoff_on_retries(cx: &mut TestAppContext) {
4285        init_test_settings(cx);
4286
4287        let project = create_test_project(cx, json!({})).await;
4288        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4289
4290        // Create model that returns internal server error
4291        let model = Arc::new(ErrorInjector::new(TestError::InternalServerError));
4292
4293        // Insert a user message
4294        thread.update(cx, |thread, cx| {
4295            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4296        });
4297
4298        // Track retry events and completion count
4299        // Track completion events
4300        let completion_count = Arc::new(Mutex::new(0));
4301        let completion_count_clone = completion_count.clone();
4302
4303        let _subscription = thread.update(cx, |_, cx| {
4304            cx.subscribe(&thread, move |_, _, event: &ThreadEvent, _| {
4305                if let ThreadEvent::NewRequest = event {
4306                    *completion_count_clone.lock() += 1;
4307                }
4308            })
4309        });
4310
4311        // First attempt
4312        thread.update(cx, |thread, cx| {
4313            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4314        });
4315        cx.run_until_parked();
4316
4317        // Should have scheduled first retry - count retry messages
4318        let retry_count = thread.update(cx, |thread, _| {
4319            thread
4320                .messages
4321                .iter()
4322                .filter(|m| {
4323                    m.ui_only
4324                        && m.segments.iter().any(|s| {
4325                            if let MessageSegment::Text(text) = s {
4326                                text.contains("Retrying") && text.contains("seconds")
4327                            } else {
4328                                false
4329                            }
4330                        })
4331                })
4332                .count()
4333        });
4334        assert_eq!(retry_count, 1, "Should have scheduled first retry");
4335
4336        // Check retry state
4337        thread.read_with(cx, |thread, _| {
4338            assert!(thread.retry_state.is_some(), "Should have retry state");
4339            let retry_state = thread.retry_state.as_ref().unwrap();
4340            assert_eq!(retry_state.attempt, 1, "Should be first retry attempt");
4341            assert_eq!(
4342                retry_state.max_attempts, 1,
4343                "Internal server errors should only retry once"
4344            );
4345        });
4346
4347        // Advance clock for first retry
4348        cx.executor().advance_clock(BASE_RETRY_DELAY);
4349        cx.run_until_parked();
4350
4351        // Should have scheduled second retry - count retry messages
4352        let retry_count = thread.update(cx, |thread, _| {
4353            thread
4354                .messages
4355                .iter()
4356                .filter(|m| {
4357                    m.ui_only
4358                        && m.segments.iter().any(|s| {
4359                            if let MessageSegment::Text(text) = s {
4360                                text.contains("Retrying") && text.contains("seconds")
4361                            } else {
4362                                false
4363                            }
4364                        })
4365                })
4366                .count()
4367        });
4368        assert_eq!(
4369            retry_count, 1,
4370            "Should have only one retry for internal server errors"
4371        );
4372
4373        // For internal server errors, we only retry once and then give up
4374        // Check that retry_state is cleared after the single retry
4375        thread.read_with(cx, |thread, _| {
4376            assert!(
4377                thread.retry_state.is_none(),
4378                "Retry state should be cleared after single retry"
4379            );
4380        });
4381
4382        // Verify total attempts (1 initial + 1 retry)
4383        assert_eq!(
4384            *completion_count.lock(),
4385            2,
4386            "Should have attempted once plus 1 retry"
4387        );
4388    }
4389
4390    #[gpui::test]
4391    async fn test_max_retries_exceeded(cx: &mut TestAppContext) {
4392        init_test_settings(cx);
4393
4394        let project = create_test_project(cx, json!({})).await;
4395        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4396
4397        // Create model that returns overloaded error
4398        let model = Arc::new(ErrorInjector::new(TestError::Overloaded));
4399
4400        // Insert a user message
4401        thread.update(cx, |thread, cx| {
4402            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4403        });
4404
4405        // Track events
4406        let stopped_with_error = Arc::new(Mutex::new(false));
4407        let stopped_with_error_clone = stopped_with_error.clone();
4408
4409        let _subscription = thread.update(cx, |_, cx| {
4410            cx.subscribe(&thread, move |_, _, event: &ThreadEvent, _| {
4411                if let ThreadEvent::Stopped(Err(_)) = event {
4412                    *stopped_with_error_clone.lock() = true;
4413                }
4414            })
4415        });
4416
4417        // Start initial completion
4418        thread.update(cx, |thread, cx| {
4419            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4420        });
4421        cx.run_until_parked();
4422
4423        // Advance through all retries
4424        for _ in 0..MAX_RETRY_ATTEMPTS {
4425            cx.executor().advance_clock(BASE_RETRY_DELAY);
4426            cx.run_until_parked();
4427        }
4428
4429        let retry_count = thread.update(cx, |thread, _| {
4430            thread
4431                .messages
4432                .iter()
4433                .filter(|m| {
4434                    m.ui_only
4435                        && m.segments.iter().any(|s| {
4436                            if let MessageSegment::Text(text) = s {
4437                                text.contains("Retrying") && text.contains("seconds")
4438                            } else {
4439                                false
4440                            }
4441                        })
4442                })
4443                .count()
4444        });
4445
4446        // After max retries, should emit Stopped(Err(...)) event
4447        assert_eq!(
4448            retry_count, MAX_RETRY_ATTEMPTS as usize,
4449            "Should have attempted MAX_RETRY_ATTEMPTS retries for overloaded errors"
4450        );
4451        assert!(
4452            *stopped_with_error.lock(),
4453            "Should emit Stopped(Err(...)) event after max retries exceeded"
4454        );
4455
4456        // Retry state should be cleared
4457        thread.read_with(cx, |thread, _| {
4458            assert!(
4459                thread.retry_state.is_none(),
4460                "Retry state should be cleared after max retries"
4461            );
4462
4463            // Verify we have the expected number of retry messages
4464            let retry_messages = thread
4465                .messages
4466                .iter()
4467                .filter(|msg| msg.ui_only && msg.role == Role::System)
4468                .count();
4469            assert_eq!(
4470                retry_messages, MAX_RETRY_ATTEMPTS as usize,
4471                "Should have MAX_RETRY_ATTEMPTS retry messages for overloaded errors"
4472            );
4473        });
4474    }
4475
4476    #[gpui::test]
4477    async fn test_retry_message_removed_on_retry(cx: &mut TestAppContext) {
4478        init_test_settings(cx);
4479
4480        let project = create_test_project(cx, json!({})).await;
4481        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4482
4483        // We'll use a wrapper to switch behavior after first failure
4484        struct RetryTestModel {
4485            inner: Arc<FakeLanguageModel>,
4486            failed_once: Arc<Mutex<bool>>,
4487        }
4488
4489        impl LanguageModel for RetryTestModel {
4490            fn id(&self) -> LanguageModelId {
4491                self.inner.id()
4492            }
4493
4494            fn name(&self) -> LanguageModelName {
4495                self.inner.name()
4496            }
4497
4498            fn provider_id(&self) -> LanguageModelProviderId {
4499                self.inner.provider_id()
4500            }
4501
4502            fn provider_name(&self) -> LanguageModelProviderName {
4503                self.inner.provider_name()
4504            }
4505
4506            fn supports_tools(&self) -> bool {
4507                self.inner.supports_tools()
4508            }
4509
4510            fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
4511                self.inner.supports_tool_choice(choice)
4512            }
4513
4514            fn supports_images(&self) -> bool {
4515                self.inner.supports_images()
4516            }
4517
4518            fn telemetry_id(&self) -> String {
4519                self.inner.telemetry_id()
4520            }
4521
4522            fn max_token_count(&self) -> u64 {
4523                self.inner.max_token_count()
4524            }
4525
4526            fn count_tokens(
4527                &self,
4528                request: LanguageModelRequest,
4529                cx: &App,
4530            ) -> BoxFuture<'static, Result<u64>> {
4531                self.inner.count_tokens(request, cx)
4532            }
4533
4534            fn stream_completion(
4535                &self,
4536                request: LanguageModelRequest,
4537                cx: &AsyncApp,
4538            ) -> BoxFuture<
4539                'static,
4540                Result<
4541                    BoxStream<
4542                        'static,
4543                        Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
4544                    >,
4545                    LanguageModelCompletionError,
4546                >,
4547            > {
4548                if !*self.failed_once.lock() {
4549                    *self.failed_once.lock() = true;
4550                    let provider = self.provider_name();
4551                    // Return error on first attempt
4552                    let stream = futures::stream::once(async move {
4553                        Err(LanguageModelCompletionError::ServerOverloaded {
4554                            provider,
4555                            retry_after: None,
4556                        })
4557                    });
4558                    async move { Ok(stream.boxed()) }.boxed()
4559                } else {
4560                    // Succeed on retry
4561                    self.inner.stream_completion(request, cx)
4562                }
4563            }
4564
4565            fn as_fake(&self) -> &FakeLanguageModel {
4566                &self.inner
4567            }
4568        }
4569
4570        let model = Arc::new(RetryTestModel {
4571            inner: Arc::new(FakeLanguageModel::default()),
4572            failed_once: Arc::new(Mutex::new(false)),
4573        });
4574
4575        // Insert a user message
4576        thread.update(cx, |thread, cx| {
4577            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4578        });
4579
4580        // Track message deletions
4581        // Track when retry completes successfully
4582        let retry_completed = Arc::new(Mutex::new(false));
4583        let retry_completed_clone = retry_completed.clone();
4584
4585        let _subscription = thread.update(cx, |_, cx| {
4586            cx.subscribe(&thread, move |_, _, event: &ThreadEvent, _| {
4587                if let ThreadEvent::StreamedCompletion = event {
4588                    *retry_completed_clone.lock() = true;
4589                }
4590            })
4591        });
4592
4593        // Start completion
4594        thread.update(cx, |thread, cx| {
4595            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4596        });
4597        cx.run_until_parked();
4598
4599        // Get the retry message ID
4600        let retry_message_id = thread.read_with(cx, |thread, _| {
4601            thread
4602                .messages()
4603                .find(|msg| msg.role == Role::System && msg.ui_only)
4604                .map(|msg| msg.id)
4605                .expect("Should have a retry message")
4606        });
4607
4608        // Wait for retry
4609        cx.executor().advance_clock(BASE_RETRY_DELAY);
4610        cx.run_until_parked();
4611
4612        // Stream some successful content
4613        let fake_model = model.as_fake();
4614        // After the retry, there should be a new pending completion
4615        let pending = fake_model.pending_completions();
4616        assert!(
4617            !pending.is_empty(),
4618            "Should have a pending completion after retry"
4619        );
4620        fake_model.stream_completion_response(&pending[0], "Success!");
4621        fake_model.end_completion_stream(&pending[0]);
4622        cx.run_until_parked();
4623
4624        // Check that the retry completed successfully
4625        assert!(
4626            *retry_completed.lock(),
4627            "Retry should have completed successfully"
4628        );
4629
4630        // Retry message should still exist but be marked as ui_only
4631        thread.read_with(cx, |thread, _| {
4632            let retry_msg = thread
4633                .message(retry_message_id)
4634                .expect("Retry message should still exist");
4635            assert!(retry_msg.ui_only, "Retry message should be ui_only");
4636            assert_eq!(
4637                retry_msg.role,
4638                Role::System,
4639                "Retry message should have System role"
4640            );
4641        });
4642    }
4643
4644    #[gpui::test]
4645    async fn test_successful_completion_clears_retry_state(cx: &mut TestAppContext) {
4646        init_test_settings(cx);
4647
4648        let project = create_test_project(cx, json!({})).await;
4649        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4650
4651        // Create a model that fails once then succeeds
4652        struct FailOnceModel {
4653            inner: Arc<FakeLanguageModel>,
4654            failed_once: Arc<Mutex<bool>>,
4655        }
4656
4657        impl LanguageModel for FailOnceModel {
4658            fn id(&self) -> LanguageModelId {
4659                self.inner.id()
4660            }
4661
4662            fn name(&self) -> LanguageModelName {
4663                self.inner.name()
4664            }
4665
4666            fn provider_id(&self) -> LanguageModelProviderId {
4667                self.inner.provider_id()
4668            }
4669
4670            fn provider_name(&self) -> LanguageModelProviderName {
4671                self.inner.provider_name()
4672            }
4673
4674            fn supports_tools(&self) -> bool {
4675                self.inner.supports_tools()
4676            }
4677
4678            fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
4679                self.inner.supports_tool_choice(choice)
4680            }
4681
4682            fn supports_images(&self) -> bool {
4683                self.inner.supports_images()
4684            }
4685
4686            fn telemetry_id(&self) -> String {
4687                self.inner.telemetry_id()
4688            }
4689
4690            fn max_token_count(&self) -> u64 {
4691                self.inner.max_token_count()
4692            }
4693
4694            fn count_tokens(
4695                &self,
4696                request: LanguageModelRequest,
4697                cx: &App,
4698            ) -> BoxFuture<'static, Result<u64>> {
4699                self.inner.count_tokens(request, cx)
4700            }
4701
4702            fn stream_completion(
4703                &self,
4704                request: LanguageModelRequest,
4705                cx: &AsyncApp,
4706            ) -> BoxFuture<
4707                'static,
4708                Result<
4709                    BoxStream<
4710                        'static,
4711                        Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
4712                    >,
4713                    LanguageModelCompletionError,
4714                >,
4715            > {
4716                if !*self.failed_once.lock() {
4717                    *self.failed_once.lock() = true;
4718                    let provider = self.provider_name();
4719                    // Return error on first attempt
4720                    let stream = futures::stream::once(async move {
4721                        Err(LanguageModelCompletionError::ServerOverloaded {
4722                            provider,
4723                            retry_after: None,
4724                        })
4725                    });
4726                    async move { Ok(stream.boxed()) }.boxed()
4727                } else {
4728                    // Succeed on retry
4729                    self.inner.stream_completion(request, cx)
4730                }
4731            }
4732        }
4733
4734        let fail_once_model = Arc::new(FailOnceModel {
4735            inner: Arc::new(FakeLanguageModel::default()),
4736            failed_once: Arc::new(Mutex::new(false)),
4737        });
4738
4739        // Insert a user message
4740        thread.update(cx, |thread, cx| {
4741            thread.insert_user_message(
4742                "Test message",
4743                ContextLoadResult::default(),
4744                None,
4745                vec![],
4746                cx,
4747            );
4748        });
4749
4750        // Start completion with fail-once model
4751        thread.update(cx, |thread, cx| {
4752            thread.send_to_model(
4753                fail_once_model.clone(),
4754                CompletionIntent::UserPrompt,
4755                None,
4756                cx,
4757            );
4758        });
4759
4760        cx.run_until_parked();
4761
4762        // Verify retry state exists after first failure
4763        thread.read_with(cx, |thread, _| {
4764            assert!(
4765                thread.retry_state.is_some(),
4766                "Should have retry state after failure"
4767            );
4768        });
4769
4770        // Wait for retry delay
4771        cx.executor().advance_clock(BASE_RETRY_DELAY);
4772        cx.run_until_parked();
4773
4774        // The retry should now use our FailOnceModel which should succeed
4775        // We need to help the FakeLanguageModel complete the stream
4776        let inner_fake = fail_once_model.inner.clone();
4777
4778        // Wait a bit for the retry to start
4779        cx.run_until_parked();
4780
4781        // Check for pending completions and complete them
4782        if let Some(pending) = inner_fake.pending_completions().first() {
4783            inner_fake.stream_completion_response(pending, "Success!");
4784            inner_fake.end_completion_stream(pending);
4785        }
4786        cx.run_until_parked();
4787
4788        thread.read_with(cx, |thread, _| {
4789            assert!(
4790                thread.retry_state.is_none(),
4791                "Retry state should be cleared after successful completion"
4792            );
4793
4794            let has_assistant_message = thread
4795                .messages
4796                .iter()
4797                .any(|msg| msg.role == Role::Assistant && !msg.ui_only);
4798            assert!(
4799                has_assistant_message,
4800                "Should have an assistant message after successful retry"
4801            );
4802        });
4803    }
4804
4805    #[gpui::test]
4806    async fn test_rate_limit_retry_single_attempt(cx: &mut TestAppContext) {
4807        init_test_settings(cx);
4808
4809        let project = create_test_project(cx, json!({})).await;
4810        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
4811
4812        // Create a model that returns rate limit error with retry_after
4813        struct RateLimitModel {
4814            inner: Arc<FakeLanguageModel>,
4815        }
4816
4817        impl LanguageModel for RateLimitModel {
4818            fn id(&self) -> LanguageModelId {
4819                self.inner.id()
4820            }
4821
4822            fn name(&self) -> LanguageModelName {
4823                self.inner.name()
4824            }
4825
4826            fn provider_id(&self) -> LanguageModelProviderId {
4827                self.inner.provider_id()
4828            }
4829
4830            fn provider_name(&self) -> LanguageModelProviderName {
4831                self.inner.provider_name()
4832            }
4833
4834            fn supports_tools(&self) -> bool {
4835                self.inner.supports_tools()
4836            }
4837
4838            fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
4839                self.inner.supports_tool_choice(choice)
4840            }
4841
4842            fn supports_images(&self) -> bool {
4843                self.inner.supports_images()
4844            }
4845
4846            fn telemetry_id(&self) -> String {
4847                self.inner.telemetry_id()
4848            }
4849
4850            fn max_token_count(&self) -> u64 {
4851                self.inner.max_token_count()
4852            }
4853
4854            fn count_tokens(
4855                &self,
4856                request: LanguageModelRequest,
4857                cx: &App,
4858            ) -> BoxFuture<'static, Result<u64>> {
4859                self.inner.count_tokens(request, cx)
4860            }
4861
4862            fn stream_completion(
4863                &self,
4864                _request: LanguageModelRequest,
4865                _cx: &AsyncApp,
4866            ) -> BoxFuture<
4867                'static,
4868                Result<
4869                    BoxStream<
4870                        'static,
4871                        Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
4872                    >,
4873                    LanguageModelCompletionError,
4874                >,
4875            > {
4876                let provider = self.provider_name();
4877                async move {
4878                    let stream = futures::stream::once(async move {
4879                        Err(LanguageModelCompletionError::RateLimitExceeded {
4880                            provider,
4881                            retry_after: Some(Duration::from_secs(TEST_RATE_LIMIT_RETRY_SECS)),
4882                        })
4883                    });
4884                    Ok(stream.boxed())
4885                }
4886                .boxed()
4887            }
4888
4889            fn as_fake(&self) -> &FakeLanguageModel {
4890                &self.inner
4891            }
4892        }
4893
4894        let model = Arc::new(RateLimitModel {
4895            inner: Arc::new(FakeLanguageModel::default()),
4896        });
4897
4898        // Insert a user message
4899        thread.update(cx, |thread, cx| {
4900            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4901        });
4902
4903        // Start completion
4904        thread.update(cx, |thread, cx| {
4905            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
4906        });
4907
4908        cx.run_until_parked();
4909
4910        let retry_count = thread.update(cx, |thread, _| {
4911            thread
4912                .messages
4913                .iter()
4914                .filter(|m| {
4915                    m.ui_only
4916                        && m.segments.iter().any(|s| {
4917                            if let MessageSegment::Text(text) = s {
4918                                text.contains("rate limit exceeded")
4919                            } else {
4920                                false
4921                            }
4922                        })
4923                })
4924                .count()
4925        });
4926        assert_eq!(retry_count, 1, "Should have scheduled one retry");
4927
4928        thread.read_with(cx, |thread, _| {
4929            assert!(
4930                thread.retry_state.is_some(),
4931                "Rate limit errors should set retry_state"
4932            );
4933            if let Some(retry_state) = &thread.retry_state {
4934                assert_eq!(
4935                    retry_state.max_attempts, MAX_RETRY_ATTEMPTS,
4936                    "Rate limit errors should use MAX_RETRY_ATTEMPTS"
4937                );
4938            }
4939        });
4940
4941        // Verify we have one retry message
4942        thread.read_with(cx, |thread, _| {
4943            let retry_messages = thread
4944                .messages
4945                .iter()
4946                .filter(|msg| {
4947                    msg.ui_only
4948                        && msg.segments.iter().any(|seg| {
4949                            if let MessageSegment::Text(text) = seg {
4950                                text.contains("rate limit exceeded")
4951                            } else {
4952                                false
4953                            }
4954                        })
4955                })
4956                .count();
4957            assert_eq!(
4958                retry_messages, 1,
4959                "Should have one rate limit retry message"
4960            );
4961        });
4962
4963        // Check that retry message doesn't include attempt count
4964        thread.read_with(cx, |thread, _| {
4965            let retry_message = thread
4966                .messages
4967                .iter()
4968                .find(|msg| msg.role == Role::System && msg.ui_only)
4969                .expect("Should have a retry message");
4970
4971            // Check that the message contains attempt count since we use retry_state
4972            if let Some(MessageSegment::Text(text)) = retry_message.segments.first() {
4973                assert!(
4974                    text.contains(&format!("attempt 1 of {}", MAX_RETRY_ATTEMPTS)),
4975                    "Rate limit retry message should contain attempt count with MAX_RETRY_ATTEMPTS"
4976                );
4977                assert!(
4978                    text.contains("Retrying"),
4979                    "Rate limit retry message should contain retry text"
4980                );
4981            }
4982        });
4983    }
4984
4985    #[gpui::test]
4986    async fn test_ui_only_messages_not_sent_to_model(cx: &mut TestAppContext) {
4987        init_test_settings(cx);
4988
4989        let project = create_test_project(cx, json!({})).await;
4990        let (_, _, thread, _, model) = setup_test_environment(cx, project.clone()).await;
4991
4992        // Insert a regular user message
4993        thread.update(cx, |thread, cx| {
4994            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
4995        });
4996
4997        // Insert a UI-only message (like our retry notifications)
4998        thread.update(cx, |thread, cx| {
4999            let id = thread.next_message_id.post_inc();
5000            thread.messages.push(Message {
5001                id,
5002                role: Role::System,
5003                segments: vec![MessageSegment::Text(
5004                    "This is a UI-only message that should not be sent to the model".to_string(),
5005                )],
5006                loaded_context: LoadedContext::default(),
5007                creases: Vec::new(),
5008                is_hidden: true,
5009                ui_only: true,
5010            });
5011            cx.emit(ThreadEvent::MessageAdded(id));
5012        });
5013
5014        // Insert another regular message
5015        thread.update(cx, |thread, cx| {
5016            thread.insert_user_message(
5017                "How are you?",
5018                ContextLoadResult::default(),
5019                None,
5020                vec![],
5021                cx,
5022            );
5023        });
5024
5025        // Generate the completion request
5026        let request = thread.update(cx, |thread, cx| {
5027            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
5028        });
5029
5030        // Verify that the request only contains non-UI-only messages
5031        // Should have system prompt + 2 user messages, but not the UI-only message
5032        let user_messages: Vec<_> = request
5033            .messages
5034            .iter()
5035            .filter(|msg| msg.role == Role::User)
5036            .collect();
5037        assert_eq!(
5038            user_messages.len(),
5039            2,
5040            "Should have exactly 2 user messages"
5041        );
5042
5043        // Verify the UI-only content is not present anywhere in the request
5044        let request_text = request
5045            .messages
5046            .iter()
5047            .flat_map(|msg| &msg.content)
5048            .filter_map(|content| match content {
5049                MessageContent::Text(text) => Some(text.as_str()),
5050                _ => None,
5051            })
5052            .collect::<String>();
5053
5054        assert!(
5055            !request_text.contains("UI-only message"),
5056            "UI-only message content should not be in the request"
5057        );
5058
5059        // Verify the thread still has all 3 messages (including UI-only)
5060        thread.read_with(cx, |thread, _| {
5061            assert_eq!(
5062                thread.messages().count(),
5063                3,
5064                "Thread should have 3 messages"
5065            );
5066            assert_eq!(
5067                thread.messages().filter(|m| m.ui_only).count(),
5068                1,
5069                "Thread should have 1 UI-only message"
5070            );
5071        });
5072
5073        // Verify that UI-only messages are not serialized
5074        let serialized = thread
5075            .update(cx, |thread, cx| thread.serialize(cx))
5076            .await
5077            .unwrap();
5078        assert_eq!(
5079            serialized.messages.len(),
5080            2,
5081            "Serialized thread should only have 2 messages (no UI-only)"
5082        );
5083    }
5084
5085    #[gpui::test]
5086    async fn test_retry_cancelled_on_stop(cx: &mut TestAppContext) {
5087        init_test_settings(cx);
5088
5089        let project = create_test_project(cx, json!({})).await;
5090        let (_, _, thread, _, _base_model) = setup_test_environment(cx, project.clone()).await;
5091
5092        // Create model that returns overloaded error
5093        let model = Arc::new(ErrorInjector::new(TestError::Overloaded));
5094
5095        // Insert a user message
5096        thread.update(cx, |thread, cx| {
5097            thread.insert_user_message("Hello!", ContextLoadResult::default(), None, vec![], cx);
5098        });
5099
5100        // Start completion
5101        thread.update(cx, |thread, cx| {
5102            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
5103        });
5104
5105        cx.run_until_parked();
5106
5107        // Verify retry was scheduled by checking for retry message
5108        let has_retry_message = thread.read_with(cx, |thread, _| {
5109            thread.messages.iter().any(|m| {
5110                m.ui_only
5111                    && m.segments.iter().any(|s| {
5112                        if let MessageSegment::Text(text) = s {
5113                            text.contains("Retrying") && text.contains("seconds")
5114                        } else {
5115                            false
5116                        }
5117                    })
5118            })
5119        });
5120        assert!(has_retry_message, "Should have scheduled a retry");
5121
5122        // Cancel the completion before the retry happens
5123        thread.update(cx, |thread, cx| {
5124            thread.cancel_last_completion(None, cx);
5125        });
5126
5127        cx.run_until_parked();
5128
5129        // The retry should not have happened - no pending completions
5130        let fake_model = model.as_fake();
5131        assert_eq!(
5132            fake_model.pending_completions().len(),
5133            0,
5134            "Should have no pending completions after cancellation"
5135        );
5136
5137        // Verify the retry was cancelled by checking retry state
5138        thread.read_with(cx, |thread, _| {
5139            if let Some(retry_state) = &thread.retry_state {
5140                panic!(
5141                    "retry_state should be cleared after cancellation, but found: attempt={}, max_attempts={}, intent={:?}",
5142                    retry_state.attempt, retry_state.max_attempts, retry_state.intent
5143                );
5144            }
5145        });
5146    }
5147
5148    fn test_summarize_error(
5149        model: &Arc<dyn LanguageModel>,
5150        thread: &Entity<Thread>,
5151        cx: &mut TestAppContext,
5152    ) {
5153        thread.update(cx, |thread, cx| {
5154            thread.insert_user_message("Hi!", ContextLoadResult::default(), None, vec![], cx);
5155            thread.send_to_model(
5156                model.clone(),
5157                CompletionIntent::ThreadSummarization,
5158                None,
5159                cx,
5160            );
5161        });
5162
5163        let fake_model = model.as_fake();
5164        simulate_successful_response(&fake_model, cx);
5165
5166        thread.read_with(cx, |thread, _| {
5167            assert!(matches!(thread.summary(), ThreadSummary::Generating));
5168            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
5169        });
5170
5171        // Simulate summary request ending
5172        cx.run_until_parked();
5173        fake_model.end_last_completion_stream();
5174        cx.run_until_parked();
5175
5176        // State is set to Error and default message
5177        thread.read_with(cx, |thread, _| {
5178            assert!(matches!(thread.summary(), ThreadSummary::Error));
5179            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
5180        });
5181    }
5182
5183    fn simulate_successful_response(fake_model: &FakeLanguageModel, cx: &mut TestAppContext) {
5184        cx.run_until_parked();
5185        fake_model.stream_last_completion_response("Assistant response");
5186        fake_model.end_last_completion_stream();
5187        cx.run_until_parked();
5188    }
5189
5190    fn init_test_settings(cx: &mut TestAppContext) {
5191        cx.update(|cx| {
5192            let settings_store = SettingsStore::test(cx);
5193            cx.set_global(settings_store);
5194            language::init(cx);
5195            Project::init_settings(cx);
5196            AgentSettings::register(cx);
5197            prompt_store::init(cx);
5198            thread_store::init(cx);
5199            workspace::init_settings(cx);
5200            language_model::init_settings(cx);
5201            ThemeSettings::register(cx);
5202            ToolRegistry::default_global(cx);
5203            assistant_tool::init(cx);
5204
5205            let http_client = Arc::new(http_client::HttpClientWithUrl::new(
5206                http_client::FakeHttpClient::with_200_response(),
5207                "http://localhost".to_string(),
5208                None,
5209            ));
5210            assistant_tools::init(http_client, cx);
5211        });
5212    }
5213
5214    // Helper to create a test project with test files
5215    async fn create_test_project(
5216        cx: &mut TestAppContext,
5217        files: serde_json::Value,
5218    ) -> Entity<Project> {
5219        let fs = FakeFs::new(cx.executor());
5220        fs.insert_tree(path!("/test"), files).await;
5221        Project::test(fs, [path!("/test").as_ref()], cx).await
5222    }
5223
5224    async fn setup_test_environment(
5225        cx: &mut TestAppContext,
5226        project: Entity<Project>,
5227    ) -> (
5228        Entity<Workspace>,
5229        Entity<ThreadStore>,
5230        Entity<Thread>,
5231        Entity<ContextStore>,
5232        Arc<dyn LanguageModel>,
5233    ) {
5234        let (workspace, cx) =
5235            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5236
5237        let thread_store = cx
5238            .update(|_, cx| {
5239                ThreadStore::load(
5240                    project.clone(),
5241                    cx.new(|_| ToolWorkingSet::default()),
5242                    None,
5243                    Arc::new(PromptBuilder::new(None).unwrap()),
5244                    cx,
5245                )
5246            })
5247            .await
5248            .unwrap();
5249
5250        let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
5251        let context_store = cx.new(|_cx| ContextStore::new(project.downgrade(), None));
5252
5253        let provider = Arc::new(FakeLanguageModelProvider);
5254        let model = provider.test_model();
5255        let model: Arc<dyn LanguageModel> = Arc::new(model);
5256
5257        cx.update(|_, cx| {
5258            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
5259                registry.set_default_model(
5260                    Some(ConfiguredModel {
5261                        provider: provider.clone(),
5262                        model: model.clone(),
5263                    }),
5264                    cx,
5265                );
5266                registry.set_thread_summary_model(
5267                    Some(ConfiguredModel {
5268                        provider,
5269                        model: model.clone(),
5270                    }),
5271                    cx,
5272                );
5273            })
5274        });
5275
5276        (workspace, thread_store, thread, context_store, model)
5277    }
5278
5279    async fn add_file_to_context(
5280        project: &Entity<Project>,
5281        context_store: &Entity<ContextStore>,
5282        path: &str,
5283        cx: &mut TestAppContext,
5284    ) -> Result<Entity<language::Buffer>> {
5285        let buffer_path = project
5286            .read_with(cx, |project, cx| project.find_project_path(path, cx))
5287            .unwrap();
5288
5289        let buffer = project
5290            .update(cx, |project, cx| {
5291                project.open_buffer(buffer_path.clone(), cx)
5292            })
5293            .await
5294            .unwrap();
5295
5296        context_store.update(cx, |context_store, cx| {
5297            context_store.add_file_from_buffer(&buffer_path, buffer.clone(), false, cx);
5298        });
5299
5300        Ok(buffer)
5301    }
5302}