thread.rs

   1use std::fmt::Write as _;
   2use std::io::Write;
   3use std::ops::Range;
   4use std::sync::Arc;
   5use std::time::Instant;
   6
   7use agent_settings::{AgentProfileId, AgentSettings, CompletionMode};
   8use anyhow::{Result, anyhow};
   9use assistant_tool::{ActionLog, AnyToolCard, Tool, ToolWorkingSet};
  10use chrono::{DateTime, Utc};
  11use collections::HashMap;
  12use editor::display_map::CreaseMetadata;
  13use feature_flags::{self, FeatureFlagAppExt};
  14use futures::future::Shared;
  15use futures::{FutureExt, StreamExt as _};
  16use git::repository::DiffType;
  17use gpui::{
  18    AnyWindowHandle, App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task,
  19    WeakEntity,
  20};
  21use language_model::{
  22    ConfiguredModel, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
  23    LanguageModelId, LanguageModelKnownError, LanguageModelRegistry, LanguageModelRequest,
  24    LanguageModelRequestMessage, LanguageModelRequestTool, LanguageModelToolResult,
  25    LanguageModelToolResultContent, LanguageModelToolUseId, MessageContent,
  26    ModelRequestLimitReachedError, PaymentRequiredError, RequestUsage, Role, SelectedModel,
  27    StopReason, TokenUsage,
  28};
  29use postage::stream::Stream as _;
  30use project::Project;
  31use project::git_store::{GitStore, GitStoreCheckpoint, RepositoryState};
  32use prompt_store::{ModelContext, PromptBuilder};
  33use proto::Plan;
  34use schemars::JsonSchema;
  35use serde::{Deserialize, Serialize};
  36use settings::Settings;
  37use thiserror::Error;
  38use ui::Window;
  39use util::{ResultExt as _, post_inc};
  40use uuid::Uuid;
  41use zed_llm_client::{CompletionIntent, CompletionRequestStatus};
  42
  43use crate::ThreadStore;
  44use crate::agent_profile::AgentProfile;
  45use crate::context::{AgentContext, AgentContextHandle, ContextLoadResult, LoadedContext};
  46use crate::thread_store::{
  47    SerializedCrease, SerializedLanguageModel, SerializedMessage, SerializedMessageSegment,
  48    SerializedThread, SerializedToolResult, SerializedToolUse, SharedProjectContext,
  49};
  50use crate::tool_use::{PendingToolUse, ToolUse, ToolUseMetadata, ToolUseState};
  51
  52#[derive(
  53    Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize, JsonSchema,
  54)]
  55pub struct ThreadId(Arc<str>);
  56
  57impl ThreadId {
  58    pub fn new() -> Self {
  59        Self(Uuid::new_v4().to_string().into())
  60    }
  61}
  62
  63impl std::fmt::Display for ThreadId {
  64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  65        write!(f, "{}", self.0)
  66    }
  67}
  68
  69impl From<&str> for ThreadId {
  70    fn from(value: &str) -> Self {
  71        Self(value.into())
  72    }
  73}
  74
  75/// The ID of the user prompt that initiated a request.
  76///
  77/// This equates to the user physically submitting a message to the model (e.g., by pressing the Enter key).
  78#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
  79pub struct PromptId(Arc<str>);
  80
  81impl PromptId {
  82    pub fn new() -> Self {
  83        Self(Uuid::new_v4().to_string().into())
  84    }
  85}
  86
  87impl std::fmt::Display for PromptId {
  88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  89        write!(f, "{}", self.0)
  90    }
  91}
  92
  93#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
  94pub struct MessageId(pub(crate) usize);
  95
  96impl MessageId {
  97    fn post_inc(&mut self) -> Self {
  98        Self(post_inc(&mut self.0))
  99    }
 100}
 101
 102/// Stored information that can be used to resurrect a context crease when creating an editor for a past message.
 103#[derive(Clone, Debug)]
 104pub struct MessageCrease {
 105    pub range: Range<usize>,
 106    pub metadata: CreaseMetadata,
 107    /// None for a deserialized message, Some otherwise.
 108    pub context: Option<AgentContextHandle>,
 109}
 110
 111/// A message in a [`Thread`].
 112#[derive(Debug, Clone)]
 113pub struct Message {
 114    pub id: MessageId,
 115    pub role: Role,
 116    pub segments: Vec<MessageSegment>,
 117    pub loaded_context: LoadedContext,
 118    pub creases: Vec<MessageCrease>,
 119    pub is_hidden: bool,
 120}
 121
 122impl Message {
 123    /// Returns whether the message contains any meaningful text that should be displayed
 124    /// The model sometimes runs tool without producing any text or just a marker ([`USING_TOOL_MARKER`])
 125    pub fn should_display_content(&self) -> bool {
 126        self.segments.iter().all(|segment| segment.should_display())
 127    }
 128
 129    pub fn push_thinking(&mut self, text: &str, signature: Option<String>) {
 130        if let Some(MessageSegment::Thinking {
 131            text: segment,
 132            signature: current_signature,
 133        }) = self.segments.last_mut()
 134        {
 135            if let Some(signature) = signature {
 136                *current_signature = Some(signature);
 137            }
 138            segment.push_str(text);
 139        } else {
 140            self.segments.push(MessageSegment::Thinking {
 141                text: text.to_string(),
 142                signature,
 143            });
 144        }
 145    }
 146
 147    pub fn push_text(&mut self, text: &str) {
 148        if let Some(MessageSegment::Text(segment)) = self.segments.last_mut() {
 149            segment.push_str(text);
 150        } else {
 151            self.segments.push(MessageSegment::Text(text.to_string()));
 152        }
 153    }
 154
 155    pub fn to_string(&self) -> String {
 156        let mut result = String::new();
 157
 158        if !self.loaded_context.text.is_empty() {
 159            result.push_str(&self.loaded_context.text);
 160        }
 161
 162        for segment in &self.segments {
 163            match segment {
 164                MessageSegment::Text(text) => result.push_str(text),
 165                MessageSegment::Thinking { text, .. } => {
 166                    result.push_str("<think>\n");
 167                    result.push_str(text);
 168                    result.push_str("\n</think>");
 169                }
 170                MessageSegment::RedactedThinking(_) => {}
 171            }
 172        }
 173
 174        result
 175    }
 176}
 177
 178#[derive(Debug, Clone, PartialEq, Eq)]
 179pub enum MessageSegment {
 180    Text(String),
 181    Thinking {
 182        text: String,
 183        signature: Option<String>,
 184    },
 185    RedactedThinking(Vec<u8>),
 186}
 187
 188impl MessageSegment {
 189    pub fn should_display(&self) -> bool {
 190        match self {
 191            Self::Text(text) => text.is_empty(),
 192            Self::Thinking { text, .. } => text.is_empty(),
 193            Self::RedactedThinking(_) => false,
 194        }
 195    }
 196}
 197
 198#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
 199pub struct ProjectSnapshot {
 200    pub worktree_snapshots: Vec<WorktreeSnapshot>,
 201    pub unsaved_buffer_paths: Vec<String>,
 202    pub timestamp: DateTime<Utc>,
 203}
 204
 205#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
 206pub struct WorktreeSnapshot {
 207    pub worktree_path: String,
 208    pub git_state: Option<GitState>,
 209}
 210
 211#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
 212pub struct GitState {
 213    pub remote_url: Option<String>,
 214    pub head_sha: Option<String>,
 215    pub current_branch: Option<String>,
 216    pub diff: Option<String>,
 217}
 218
 219#[derive(Clone, Debug)]
 220pub struct ThreadCheckpoint {
 221    message_id: MessageId,
 222    git_checkpoint: GitStoreCheckpoint,
 223}
 224
 225#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 226pub enum ThreadFeedback {
 227    Positive,
 228    Negative,
 229}
 230
 231pub enum LastRestoreCheckpoint {
 232    Pending {
 233        message_id: MessageId,
 234    },
 235    Error {
 236        message_id: MessageId,
 237        error: String,
 238    },
 239}
 240
 241impl LastRestoreCheckpoint {
 242    pub fn message_id(&self) -> MessageId {
 243        match self {
 244            LastRestoreCheckpoint::Pending { message_id } => *message_id,
 245            LastRestoreCheckpoint::Error { message_id, .. } => *message_id,
 246        }
 247    }
 248}
 249
 250#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
 251pub enum DetailedSummaryState {
 252    #[default]
 253    NotGenerated,
 254    Generating {
 255        message_id: MessageId,
 256    },
 257    Generated {
 258        text: SharedString,
 259        message_id: MessageId,
 260    },
 261}
 262
 263impl DetailedSummaryState {
 264    fn text(&self) -> Option<SharedString> {
 265        if let Self::Generated { text, .. } = self {
 266            Some(text.clone())
 267        } else {
 268            None
 269        }
 270    }
 271}
 272
 273#[derive(Default, Debug)]
 274pub struct TotalTokenUsage {
 275    pub total: usize,
 276    pub max: usize,
 277}
 278
 279impl TotalTokenUsage {
 280    pub fn ratio(&self) -> TokenUsageRatio {
 281        #[cfg(debug_assertions)]
 282        let warning_threshold: f32 = std::env::var("ZED_THREAD_WARNING_THRESHOLD")
 283            .unwrap_or("0.8".to_string())
 284            .parse()
 285            .unwrap();
 286        #[cfg(not(debug_assertions))]
 287        let warning_threshold: f32 = 0.8;
 288
 289        // When the maximum is unknown because there is no selected model,
 290        // avoid showing the token limit warning.
 291        if self.max == 0 {
 292            TokenUsageRatio::Normal
 293        } else if self.total >= self.max {
 294            TokenUsageRatio::Exceeded
 295        } else if self.total as f32 / self.max as f32 >= warning_threshold {
 296            TokenUsageRatio::Warning
 297        } else {
 298            TokenUsageRatio::Normal
 299        }
 300    }
 301
 302    pub fn add(&self, tokens: usize) -> TotalTokenUsage {
 303        TotalTokenUsage {
 304            total: self.total + tokens,
 305            max: self.max,
 306        }
 307    }
 308}
 309
 310#[derive(Debug, Default, PartialEq, Eq)]
 311pub enum TokenUsageRatio {
 312    #[default]
 313    Normal,
 314    Warning,
 315    Exceeded,
 316}
 317
 318#[derive(Debug, Clone, Copy)]
 319pub enum QueueState {
 320    Sending,
 321    Queued { position: usize },
 322    Started,
 323}
 324
 325/// A thread of conversation with the LLM.
 326pub struct Thread {
 327    id: ThreadId,
 328    updated_at: DateTime<Utc>,
 329    summary: ThreadSummary,
 330    pending_summary: Task<Option<()>>,
 331    detailed_summary_task: Task<Option<()>>,
 332    detailed_summary_tx: postage::watch::Sender<DetailedSummaryState>,
 333    detailed_summary_rx: postage::watch::Receiver<DetailedSummaryState>,
 334    completion_mode: agent_settings::CompletionMode,
 335    messages: Vec<Message>,
 336    next_message_id: MessageId,
 337    last_prompt_id: PromptId,
 338    project_context: SharedProjectContext,
 339    checkpoints_by_message: HashMap<MessageId, ThreadCheckpoint>,
 340    completion_count: usize,
 341    pending_completions: Vec<PendingCompletion>,
 342    project: Entity<Project>,
 343    prompt_builder: Arc<PromptBuilder>,
 344    tools: Entity<ToolWorkingSet>,
 345    tool_use: ToolUseState,
 346    action_log: Entity<ActionLog>,
 347    last_restore_checkpoint: Option<LastRestoreCheckpoint>,
 348    pending_checkpoint: Option<ThreadCheckpoint>,
 349    initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
 350    request_token_usage: Vec<TokenUsage>,
 351    cumulative_token_usage: TokenUsage,
 352    exceeded_window_error: Option<ExceededWindowError>,
 353    last_usage: Option<RequestUsage>,
 354    tool_use_limit_reached: bool,
 355    feedback: Option<ThreadFeedback>,
 356    message_feedback: HashMap<MessageId, ThreadFeedback>,
 357    last_auto_capture_at: Option<Instant>,
 358    last_received_chunk_at: Option<Instant>,
 359    request_callback: Option<
 360        Box<dyn FnMut(&LanguageModelRequest, &[Result<LanguageModelCompletionEvent, String>])>,
 361    >,
 362    remaining_turns: u32,
 363    configured_model: Option<ConfiguredModel>,
 364    profile: AgentProfile,
 365}
 366
 367#[derive(Clone, Debug, PartialEq, Eq)]
 368pub enum ThreadSummary {
 369    Pending,
 370    Generating,
 371    Ready(SharedString),
 372    Error,
 373}
 374
 375impl ThreadSummary {
 376    pub const DEFAULT: SharedString = SharedString::new_static("New Thread");
 377
 378    pub fn or_default(&self) -> SharedString {
 379        self.unwrap_or(Self::DEFAULT)
 380    }
 381
 382    pub fn unwrap_or(&self, message: impl Into<SharedString>) -> SharedString {
 383        self.ready().unwrap_or_else(|| message.into())
 384    }
 385
 386    pub fn ready(&self) -> Option<SharedString> {
 387        match self {
 388            ThreadSummary::Ready(summary) => Some(summary.clone()),
 389            ThreadSummary::Pending | ThreadSummary::Generating | ThreadSummary::Error => None,
 390        }
 391    }
 392}
 393
 394#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
 395pub struct ExceededWindowError {
 396    /// Model used when last message exceeded context window
 397    model_id: LanguageModelId,
 398    /// Token count including last message
 399    token_count: usize,
 400}
 401
 402impl Thread {
 403    pub fn new(
 404        project: Entity<Project>,
 405        tools: Entity<ToolWorkingSet>,
 406        prompt_builder: Arc<PromptBuilder>,
 407        system_prompt: SharedProjectContext,
 408        cx: &mut Context<Self>,
 409    ) -> Self {
 410        let (detailed_summary_tx, detailed_summary_rx) = postage::watch::channel();
 411        let configured_model = LanguageModelRegistry::read_global(cx).default_model();
 412        let profile_id = AgentSettings::get_global(cx).default_profile.clone();
 413
 414        Self {
 415            id: ThreadId::new(),
 416            updated_at: Utc::now(),
 417            summary: ThreadSummary::Pending,
 418            pending_summary: Task::ready(None),
 419            detailed_summary_task: Task::ready(None),
 420            detailed_summary_tx,
 421            detailed_summary_rx,
 422            completion_mode: AgentSettings::get_global(cx).preferred_completion_mode,
 423            messages: Vec::new(),
 424            next_message_id: MessageId(0),
 425            last_prompt_id: PromptId::new(),
 426            project_context: system_prompt,
 427            checkpoints_by_message: HashMap::default(),
 428            completion_count: 0,
 429            pending_completions: Vec::new(),
 430            project: project.clone(),
 431            prompt_builder,
 432            tools: tools.clone(),
 433            last_restore_checkpoint: None,
 434            pending_checkpoint: None,
 435            tool_use: ToolUseState::new(tools.clone()),
 436            action_log: cx.new(|_| ActionLog::new(project.clone())),
 437            initial_project_snapshot: {
 438                let project_snapshot = Self::project_snapshot(project, cx);
 439                cx.foreground_executor()
 440                    .spawn(async move { Some(project_snapshot.await) })
 441                    .shared()
 442            },
 443            request_token_usage: Vec::new(),
 444            cumulative_token_usage: TokenUsage::default(),
 445            exceeded_window_error: None,
 446            last_usage: None,
 447            tool_use_limit_reached: false,
 448            feedback: None,
 449            message_feedback: HashMap::default(),
 450            last_auto_capture_at: None,
 451            last_received_chunk_at: None,
 452            request_callback: None,
 453            remaining_turns: u32::MAX,
 454            configured_model,
 455            profile: AgentProfile::new(profile_id, tools),
 456        }
 457    }
 458
 459    pub fn deserialize(
 460        id: ThreadId,
 461        serialized: SerializedThread,
 462        project: Entity<Project>,
 463        tools: Entity<ToolWorkingSet>,
 464        prompt_builder: Arc<PromptBuilder>,
 465        project_context: SharedProjectContext,
 466        window: Option<&mut Window>, // None in headless mode
 467        cx: &mut Context<Self>,
 468    ) -> Self {
 469        let next_message_id = MessageId(
 470            serialized
 471                .messages
 472                .last()
 473                .map(|message| message.id.0 + 1)
 474                .unwrap_or(0),
 475        );
 476        let tool_use = ToolUseState::from_serialized_messages(
 477            tools.clone(),
 478            &serialized.messages,
 479            project.clone(),
 480            window,
 481            cx,
 482        );
 483        let (detailed_summary_tx, detailed_summary_rx) =
 484            postage::watch::channel_with(serialized.detailed_summary_state);
 485
 486        let configured_model = LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
 487            serialized
 488                .model
 489                .and_then(|model| {
 490                    let model = SelectedModel {
 491                        provider: model.provider.clone().into(),
 492                        model: model.model.clone().into(),
 493                    };
 494                    registry.select_model(&model, cx)
 495                })
 496                .or_else(|| registry.default_model())
 497        });
 498
 499        let completion_mode = serialized
 500            .completion_mode
 501            .unwrap_or_else(|| AgentSettings::get_global(cx).preferred_completion_mode);
 502        let profile_id = serialized
 503            .profile
 504            .unwrap_or_else(|| AgentSettings::get_global(cx).default_profile.clone());
 505
 506        Self {
 507            id,
 508            updated_at: serialized.updated_at,
 509            summary: ThreadSummary::Ready(serialized.summary),
 510            pending_summary: Task::ready(None),
 511            detailed_summary_task: Task::ready(None),
 512            detailed_summary_tx,
 513            detailed_summary_rx,
 514            completion_mode,
 515            messages: serialized
 516                .messages
 517                .into_iter()
 518                .map(|message| Message {
 519                    id: message.id,
 520                    role: message.role,
 521                    segments: message
 522                        .segments
 523                        .into_iter()
 524                        .map(|segment| match segment {
 525                            SerializedMessageSegment::Text { text } => MessageSegment::Text(text),
 526                            SerializedMessageSegment::Thinking { text, signature } => {
 527                                MessageSegment::Thinking { text, signature }
 528                            }
 529                            SerializedMessageSegment::RedactedThinking { data } => {
 530                                MessageSegment::RedactedThinking(data)
 531                            }
 532                        })
 533                        .collect(),
 534                    loaded_context: LoadedContext {
 535                        contexts: Vec::new(),
 536                        text: message.context,
 537                        images: Vec::new(),
 538                    },
 539                    creases: message
 540                        .creases
 541                        .into_iter()
 542                        .map(|crease| MessageCrease {
 543                            range: crease.start..crease.end,
 544                            metadata: CreaseMetadata {
 545                                icon_path: crease.icon_path,
 546                                label: crease.label,
 547                            },
 548                            context: None,
 549                        })
 550                        .collect(),
 551                    is_hidden: message.is_hidden,
 552                })
 553                .collect(),
 554            next_message_id,
 555            last_prompt_id: PromptId::new(),
 556            project_context,
 557            checkpoints_by_message: HashMap::default(),
 558            completion_count: 0,
 559            pending_completions: Vec::new(),
 560            last_restore_checkpoint: None,
 561            pending_checkpoint: None,
 562            project: project.clone(),
 563            prompt_builder,
 564            tools: tools.clone(),
 565            tool_use,
 566            action_log: cx.new(|_| ActionLog::new(project)),
 567            initial_project_snapshot: Task::ready(serialized.initial_project_snapshot).shared(),
 568            request_token_usage: serialized.request_token_usage,
 569            cumulative_token_usage: serialized.cumulative_token_usage,
 570            exceeded_window_error: None,
 571            last_usage: None,
 572            tool_use_limit_reached: serialized.tool_use_limit_reached,
 573            feedback: None,
 574            message_feedback: HashMap::default(),
 575            last_auto_capture_at: None,
 576            last_received_chunk_at: None,
 577            request_callback: None,
 578            remaining_turns: u32::MAX,
 579            configured_model,
 580            profile: AgentProfile::new(profile_id, tools),
 581        }
 582    }
 583
 584    pub fn set_request_callback(
 585        &mut self,
 586        callback: impl 'static
 587        + FnMut(&LanguageModelRequest, &[Result<LanguageModelCompletionEvent, String>]),
 588    ) {
 589        self.request_callback = Some(Box::new(callback));
 590    }
 591
 592    pub fn id(&self) -> &ThreadId {
 593        &self.id
 594    }
 595
 596    pub fn profile(&self) -> &AgentProfile {
 597        &self.profile
 598    }
 599
 600    pub fn set_profile(&mut self, id: AgentProfileId, cx: &mut Context<Self>) {
 601        if &id != self.profile.id() {
 602            self.profile = AgentProfile::new(id, self.tools.clone());
 603            cx.emit(ThreadEvent::ProfileChanged);
 604        }
 605    }
 606
 607    pub fn is_empty(&self) -> bool {
 608        self.messages.is_empty()
 609    }
 610
 611    pub fn updated_at(&self) -> DateTime<Utc> {
 612        self.updated_at
 613    }
 614
 615    pub fn touch_updated_at(&mut self) {
 616        self.updated_at = Utc::now();
 617    }
 618
 619    pub fn advance_prompt_id(&mut self) {
 620        self.last_prompt_id = PromptId::new();
 621    }
 622
 623    pub fn project_context(&self) -> SharedProjectContext {
 624        self.project_context.clone()
 625    }
 626
 627    pub fn get_or_init_configured_model(&mut self, cx: &App) -> Option<ConfiguredModel> {
 628        if self.configured_model.is_none() {
 629            self.configured_model = LanguageModelRegistry::read_global(cx).default_model();
 630        }
 631        self.configured_model.clone()
 632    }
 633
 634    pub fn configured_model(&self) -> Option<ConfiguredModel> {
 635        self.configured_model.clone()
 636    }
 637
 638    pub fn set_configured_model(&mut self, model: Option<ConfiguredModel>, cx: &mut Context<Self>) {
 639        self.configured_model = model;
 640        cx.notify();
 641    }
 642
 643    pub fn summary(&self) -> &ThreadSummary {
 644        &self.summary
 645    }
 646
 647    pub fn set_summary(&mut self, new_summary: impl Into<SharedString>, cx: &mut Context<Self>) {
 648        let current_summary = match &self.summary {
 649            ThreadSummary::Pending | ThreadSummary::Generating => return,
 650            ThreadSummary::Ready(summary) => summary,
 651            ThreadSummary::Error => &ThreadSummary::DEFAULT,
 652        };
 653
 654        let mut new_summary = new_summary.into();
 655
 656        if new_summary.is_empty() {
 657            new_summary = ThreadSummary::DEFAULT;
 658        }
 659
 660        if current_summary != &new_summary {
 661            self.summary = ThreadSummary::Ready(new_summary);
 662            cx.emit(ThreadEvent::SummaryChanged);
 663        }
 664    }
 665
 666    pub fn completion_mode(&self) -> CompletionMode {
 667        self.completion_mode
 668    }
 669
 670    pub fn set_completion_mode(&mut self, mode: CompletionMode) {
 671        self.completion_mode = mode;
 672    }
 673
 674    pub fn message(&self, id: MessageId) -> Option<&Message> {
 675        let index = self
 676            .messages
 677            .binary_search_by(|message| message.id.cmp(&id))
 678            .ok()?;
 679
 680        self.messages.get(index)
 681    }
 682
 683    pub fn messages(&self) -> impl ExactSizeIterator<Item = &Message> {
 684        self.messages.iter()
 685    }
 686
 687    pub fn is_generating(&self) -> bool {
 688        !self.pending_completions.is_empty() || !self.all_tools_finished()
 689    }
 690
 691    /// Indicates whether streaming of language model events is stale.
 692    /// When `is_generating()` is false, this method returns `None`.
 693    pub fn is_generation_stale(&self) -> Option<bool> {
 694        const STALE_THRESHOLD: u128 = 250;
 695
 696        self.last_received_chunk_at
 697            .map(|instant| instant.elapsed().as_millis() > STALE_THRESHOLD)
 698    }
 699
 700    fn received_chunk(&mut self) {
 701        self.last_received_chunk_at = Some(Instant::now());
 702    }
 703
 704    pub fn queue_state(&self) -> Option<QueueState> {
 705        self.pending_completions
 706            .first()
 707            .map(|pending_completion| pending_completion.queue_state)
 708    }
 709
 710    pub fn tools(&self) -> &Entity<ToolWorkingSet> {
 711        &self.tools
 712    }
 713
 714    pub fn pending_tool(&self, id: &LanguageModelToolUseId) -> Option<&PendingToolUse> {
 715        self.tool_use
 716            .pending_tool_uses()
 717            .into_iter()
 718            .find(|tool_use| &tool_use.id == id)
 719    }
 720
 721    pub fn tools_needing_confirmation(&self) -> impl Iterator<Item = &PendingToolUse> {
 722        self.tool_use
 723            .pending_tool_uses()
 724            .into_iter()
 725            .filter(|tool_use| tool_use.status.needs_confirmation())
 726    }
 727
 728    pub fn has_pending_tool_uses(&self) -> bool {
 729        !self.tool_use.pending_tool_uses().is_empty()
 730    }
 731
 732    pub fn checkpoint_for_message(&self, id: MessageId) -> Option<ThreadCheckpoint> {
 733        self.checkpoints_by_message.get(&id).cloned()
 734    }
 735
 736    pub fn restore_checkpoint(
 737        &mut self,
 738        checkpoint: ThreadCheckpoint,
 739        cx: &mut Context<Self>,
 740    ) -> Task<Result<()>> {
 741        self.last_restore_checkpoint = Some(LastRestoreCheckpoint::Pending {
 742            message_id: checkpoint.message_id,
 743        });
 744        cx.emit(ThreadEvent::CheckpointChanged);
 745        cx.notify();
 746
 747        let git_store = self.project().read(cx).git_store().clone();
 748        let restore = git_store.update(cx, |git_store, cx| {
 749            git_store.restore_checkpoint(checkpoint.git_checkpoint.clone(), cx)
 750        });
 751
 752        cx.spawn(async move |this, cx| {
 753            let result = restore.await;
 754            this.update(cx, |this, cx| {
 755                if let Err(err) = result.as_ref() {
 756                    this.last_restore_checkpoint = Some(LastRestoreCheckpoint::Error {
 757                        message_id: checkpoint.message_id,
 758                        error: err.to_string(),
 759                    });
 760                } else {
 761                    this.truncate(checkpoint.message_id, cx);
 762                    this.last_restore_checkpoint = None;
 763                }
 764                this.pending_checkpoint = None;
 765                cx.emit(ThreadEvent::CheckpointChanged);
 766                cx.notify();
 767            })?;
 768            result
 769        })
 770    }
 771
 772    fn finalize_pending_checkpoint(&mut self, cx: &mut Context<Self>) {
 773        let pending_checkpoint = if self.is_generating() {
 774            return;
 775        } else if let Some(checkpoint) = self.pending_checkpoint.take() {
 776            checkpoint
 777        } else {
 778            return;
 779        };
 780
 781        self.finalize_checkpoint(pending_checkpoint, cx);
 782    }
 783
 784    fn finalize_checkpoint(
 785        &mut self,
 786        pending_checkpoint: ThreadCheckpoint,
 787        cx: &mut Context<Self>,
 788    ) {
 789        let git_store = self.project.read(cx).git_store().clone();
 790        let final_checkpoint = git_store.update(cx, |git_store, cx| git_store.checkpoint(cx));
 791        cx.spawn(async move |this, cx| match final_checkpoint.await {
 792            Ok(final_checkpoint) => {
 793                let equal = git_store
 794                    .update(cx, |store, cx| {
 795                        store.compare_checkpoints(
 796                            pending_checkpoint.git_checkpoint.clone(),
 797                            final_checkpoint.clone(),
 798                            cx,
 799                        )
 800                    })?
 801                    .await
 802                    .unwrap_or(false);
 803
 804                if !equal {
 805                    this.update(cx, |this, cx| {
 806                        this.insert_checkpoint(pending_checkpoint, cx)
 807                    })?;
 808                }
 809
 810                Ok(())
 811            }
 812            Err(_) => this.update(cx, |this, cx| {
 813                this.insert_checkpoint(pending_checkpoint, cx)
 814            }),
 815        })
 816        .detach();
 817    }
 818
 819    fn insert_checkpoint(&mut self, checkpoint: ThreadCheckpoint, cx: &mut Context<Self>) {
 820        self.checkpoints_by_message
 821            .insert(checkpoint.message_id, checkpoint);
 822        cx.emit(ThreadEvent::CheckpointChanged);
 823        cx.notify();
 824    }
 825
 826    pub fn last_restore_checkpoint(&self) -> Option<&LastRestoreCheckpoint> {
 827        self.last_restore_checkpoint.as_ref()
 828    }
 829
 830    pub fn truncate(&mut self, message_id: MessageId, cx: &mut Context<Self>) {
 831        let Some(message_ix) = self
 832            .messages
 833            .iter()
 834            .rposition(|message| message.id == message_id)
 835        else {
 836            return;
 837        };
 838        for deleted_message in self.messages.drain(message_ix..) {
 839            self.checkpoints_by_message.remove(&deleted_message.id);
 840        }
 841        cx.notify();
 842    }
 843
 844    pub fn context_for_message(&self, id: MessageId) -> impl Iterator<Item = &AgentContext> {
 845        self.messages
 846            .iter()
 847            .find(|message| message.id == id)
 848            .into_iter()
 849            .flat_map(|message| message.loaded_context.contexts.iter())
 850    }
 851
 852    pub fn is_turn_end(&self, ix: usize) -> bool {
 853        if self.messages.is_empty() {
 854            return false;
 855        }
 856
 857        if !self.is_generating() && ix == self.messages.len() - 1 {
 858            return true;
 859        }
 860
 861        let Some(message) = self.messages.get(ix) else {
 862            return false;
 863        };
 864
 865        if message.role != Role::Assistant {
 866            return false;
 867        }
 868
 869        self.messages
 870            .get(ix + 1)
 871            .and_then(|message| {
 872                self.message(message.id)
 873                    .map(|next_message| next_message.role == Role::User && !next_message.is_hidden)
 874            })
 875            .unwrap_or(false)
 876    }
 877
 878    pub fn last_usage(&self) -> Option<RequestUsage> {
 879        self.last_usage
 880    }
 881
 882    pub fn tool_use_limit_reached(&self) -> bool {
 883        self.tool_use_limit_reached
 884    }
 885
 886    /// Returns whether all of the tool uses have finished running.
 887    pub fn all_tools_finished(&self) -> bool {
 888        // If the only pending tool uses left are the ones with errors, then
 889        // that means that we've finished running all of the pending tools.
 890        self.tool_use
 891            .pending_tool_uses()
 892            .iter()
 893            .all(|pending_tool_use| pending_tool_use.status.is_error())
 894    }
 895
 896    /// Returns whether any pending tool uses may perform edits
 897    pub fn has_pending_edit_tool_uses(&self) -> bool {
 898        self.tool_use
 899            .pending_tool_uses()
 900            .iter()
 901            .filter(|pending_tool_use| !pending_tool_use.status.is_error())
 902            .any(|pending_tool_use| pending_tool_use.may_perform_edits)
 903    }
 904
 905    pub fn tool_uses_for_message(&self, id: MessageId, cx: &App) -> Vec<ToolUse> {
 906        self.tool_use.tool_uses_for_message(id, cx)
 907    }
 908
 909    pub fn tool_results_for_message(
 910        &self,
 911        assistant_message_id: MessageId,
 912    ) -> Vec<&LanguageModelToolResult> {
 913        self.tool_use.tool_results_for_message(assistant_message_id)
 914    }
 915
 916    pub fn tool_result(&self, id: &LanguageModelToolUseId) -> Option<&LanguageModelToolResult> {
 917        self.tool_use.tool_result(id)
 918    }
 919
 920    pub fn output_for_tool(&self, id: &LanguageModelToolUseId) -> Option<&Arc<str>> {
 921        match &self.tool_use.tool_result(id)?.content {
 922            LanguageModelToolResultContent::Text(text) => Some(text),
 923            LanguageModelToolResultContent::Image(_) => {
 924                // TODO: We should display image
 925                None
 926            }
 927        }
 928    }
 929
 930    pub fn card_for_tool(&self, id: &LanguageModelToolUseId) -> Option<AnyToolCard> {
 931        self.tool_use.tool_result_card(id).cloned()
 932    }
 933
 934    /// Return tools that are both enabled and supported by the model
 935    pub fn available_tools(
 936        &self,
 937        cx: &App,
 938        model: Arc<dyn LanguageModel>,
 939    ) -> Vec<LanguageModelRequestTool> {
 940        if model.supports_tools() {
 941            self.profile
 942                .enabled_tools(cx)
 943                .into_iter()
 944                .filter_map(|tool| {
 945                    // Skip tools that cannot be supported
 946                    let input_schema = tool.input_schema(model.tool_input_format()).ok()?;
 947                    Some(LanguageModelRequestTool {
 948                        name: tool.name(),
 949                        description: tool.description(),
 950                        input_schema,
 951                    })
 952                })
 953                .collect()
 954        } else {
 955            Vec::default()
 956        }
 957    }
 958
 959    pub fn insert_user_message(
 960        &mut self,
 961        text: impl Into<String>,
 962        loaded_context: ContextLoadResult,
 963        git_checkpoint: Option<GitStoreCheckpoint>,
 964        creases: Vec<MessageCrease>,
 965        cx: &mut Context<Self>,
 966    ) -> MessageId {
 967        if !loaded_context.referenced_buffers.is_empty() {
 968            self.action_log.update(cx, |log, cx| {
 969                for buffer in loaded_context.referenced_buffers {
 970                    log.buffer_read(buffer, cx);
 971                }
 972            });
 973        }
 974
 975        let message_id = self.insert_message(
 976            Role::User,
 977            vec![MessageSegment::Text(text.into())],
 978            loaded_context.loaded_context,
 979            creases,
 980            false,
 981            cx,
 982        );
 983
 984        if let Some(git_checkpoint) = git_checkpoint {
 985            self.pending_checkpoint = Some(ThreadCheckpoint {
 986                message_id,
 987                git_checkpoint,
 988            });
 989        }
 990
 991        self.auto_capture_telemetry(cx);
 992
 993        message_id
 994    }
 995
 996    pub fn insert_invisible_continue_message(&mut self, cx: &mut Context<Self>) -> MessageId {
 997        let id = self.insert_message(
 998            Role::User,
 999            vec![MessageSegment::Text("Continue where you left off".into())],
1000            LoadedContext::default(),
1001            vec![],
1002            true,
1003            cx,
1004        );
1005        self.pending_checkpoint = None;
1006
1007        id
1008    }
1009
1010    pub fn insert_assistant_message(
1011        &mut self,
1012        segments: Vec<MessageSegment>,
1013        cx: &mut Context<Self>,
1014    ) -> MessageId {
1015        self.insert_message(
1016            Role::Assistant,
1017            segments,
1018            LoadedContext::default(),
1019            Vec::new(),
1020            false,
1021            cx,
1022        )
1023    }
1024
1025    pub fn insert_message(
1026        &mut self,
1027        role: Role,
1028        segments: Vec<MessageSegment>,
1029        loaded_context: LoadedContext,
1030        creases: Vec<MessageCrease>,
1031        is_hidden: bool,
1032        cx: &mut Context<Self>,
1033    ) -> MessageId {
1034        let id = self.next_message_id.post_inc();
1035        self.messages.push(Message {
1036            id,
1037            role,
1038            segments,
1039            loaded_context,
1040            creases,
1041            is_hidden,
1042        });
1043        self.touch_updated_at();
1044        cx.emit(ThreadEvent::MessageAdded(id));
1045        id
1046    }
1047
1048    pub fn edit_message(
1049        &mut self,
1050        id: MessageId,
1051        new_role: Role,
1052        new_segments: Vec<MessageSegment>,
1053        creases: Vec<MessageCrease>,
1054        loaded_context: Option<LoadedContext>,
1055        checkpoint: Option<GitStoreCheckpoint>,
1056        cx: &mut Context<Self>,
1057    ) -> bool {
1058        let Some(message) = self.messages.iter_mut().find(|message| message.id == id) else {
1059            return false;
1060        };
1061        message.role = new_role;
1062        message.segments = new_segments;
1063        message.creases = creases;
1064        if let Some(context) = loaded_context {
1065            message.loaded_context = context;
1066        }
1067        if let Some(git_checkpoint) = checkpoint {
1068            self.checkpoints_by_message.insert(
1069                id,
1070                ThreadCheckpoint {
1071                    message_id: id,
1072                    git_checkpoint,
1073                },
1074            );
1075        }
1076        self.touch_updated_at();
1077        cx.emit(ThreadEvent::MessageEdited(id));
1078        true
1079    }
1080
1081    pub fn delete_message(&mut self, id: MessageId, cx: &mut Context<Self>) -> bool {
1082        let Some(index) = self.messages.iter().position(|message| message.id == id) else {
1083            return false;
1084        };
1085        self.messages.remove(index);
1086        self.touch_updated_at();
1087        cx.emit(ThreadEvent::MessageDeleted(id));
1088        true
1089    }
1090
1091    /// Returns the representation of this [`Thread`] in a textual form.
1092    ///
1093    /// This is the representation we use when attaching a thread as context to another thread.
1094    pub fn text(&self) -> String {
1095        let mut text = String::new();
1096
1097        for message in &self.messages {
1098            text.push_str(match message.role {
1099                language_model::Role::User => "User:",
1100                language_model::Role::Assistant => "Agent:",
1101                language_model::Role::System => "System:",
1102            });
1103            text.push('\n');
1104
1105            for segment in &message.segments {
1106                match segment {
1107                    MessageSegment::Text(content) => text.push_str(content),
1108                    MessageSegment::Thinking { text: content, .. } => {
1109                        text.push_str(&format!("<think>{}</think>", content))
1110                    }
1111                    MessageSegment::RedactedThinking(_) => {}
1112                }
1113            }
1114            text.push('\n');
1115        }
1116
1117        text
1118    }
1119
1120    /// Serializes this thread into a format for storage or telemetry.
1121    pub fn serialize(&self, cx: &mut Context<Self>) -> Task<Result<SerializedThread>> {
1122        let initial_project_snapshot = self.initial_project_snapshot.clone();
1123        cx.spawn(async move |this, cx| {
1124            let initial_project_snapshot = initial_project_snapshot.await;
1125            this.read_with(cx, |this, cx| SerializedThread {
1126                version: SerializedThread::VERSION.to_string(),
1127                summary: this.summary().or_default(),
1128                updated_at: this.updated_at(),
1129                messages: this
1130                    .messages()
1131                    .map(|message| SerializedMessage {
1132                        id: message.id,
1133                        role: message.role,
1134                        segments: message
1135                            .segments
1136                            .iter()
1137                            .map(|segment| match segment {
1138                                MessageSegment::Text(text) => {
1139                                    SerializedMessageSegment::Text { text: text.clone() }
1140                                }
1141                                MessageSegment::Thinking { text, signature } => {
1142                                    SerializedMessageSegment::Thinking {
1143                                        text: text.clone(),
1144                                        signature: signature.clone(),
1145                                    }
1146                                }
1147                                MessageSegment::RedactedThinking(data) => {
1148                                    SerializedMessageSegment::RedactedThinking {
1149                                        data: data.clone(),
1150                                    }
1151                                }
1152                            })
1153                            .collect(),
1154                        tool_uses: this
1155                            .tool_uses_for_message(message.id, cx)
1156                            .into_iter()
1157                            .map(|tool_use| SerializedToolUse {
1158                                id: tool_use.id,
1159                                name: tool_use.name,
1160                                input: tool_use.input,
1161                            })
1162                            .collect(),
1163                        tool_results: this
1164                            .tool_results_for_message(message.id)
1165                            .into_iter()
1166                            .map(|tool_result| SerializedToolResult {
1167                                tool_use_id: tool_result.tool_use_id.clone(),
1168                                is_error: tool_result.is_error,
1169                                content: tool_result.content.clone(),
1170                                output: tool_result.output.clone(),
1171                            })
1172                            .collect(),
1173                        context: message.loaded_context.text.clone(),
1174                        creases: message
1175                            .creases
1176                            .iter()
1177                            .map(|crease| SerializedCrease {
1178                                start: crease.range.start,
1179                                end: crease.range.end,
1180                                icon_path: crease.metadata.icon_path.clone(),
1181                                label: crease.metadata.label.clone(),
1182                            })
1183                            .collect(),
1184                        is_hidden: message.is_hidden,
1185                    })
1186                    .collect(),
1187                initial_project_snapshot,
1188                cumulative_token_usage: this.cumulative_token_usage,
1189                request_token_usage: this.request_token_usage.clone(),
1190                detailed_summary_state: this.detailed_summary_rx.borrow().clone(),
1191                exceeded_window_error: this.exceeded_window_error.clone(),
1192                model: this
1193                    .configured_model
1194                    .as_ref()
1195                    .map(|model| SerializedLanguageModel {
1196                        provider: model.provider.id().0.to_string(),
1197                        model: model.model.id().0.to_string(),
1198                    }),
1199                completion_mode: Some(this.completion_mode),
1200                tool_use_limit_reached: this.tool_use_limit_reached,
1201                profile: Some(this.profile.id().clone()),
1202            })
1203        })
1204    }
1205
1206    pub fn remaining_turns(&self) -> u32 {
1207        self.remaining_turns
1208    }
1209
1210    pub fn set_remaining_turns(&mut self, remaining_turns: u32) {
1211        self.remaining_turns = remaining_turns;
1212    }
1213
1214    pub fn send_to_model(
1215        &mut self,
1216        model: Arc<dyn LanguageModel>,
1217        intent: CompletionIntent,
1218        window: Option<AnyWindowHandle>,
1219        cx: &mut Context<Self>,
1220    ) {
1221        if self.remaining_turns == 0 {
1222            return;
1223        }
1224
1225        self.remaining_turns -= 1;
1226
1227        let request = self.to_completion_request(model.clone(), intent, cx);
1228
1229        self.stream_completion(request, model, window, cx);
1230    }
1231
1232    pub fn used_tools_since_last_user_message(&self) -> bool {
1233        for message in self.messages.iter().rev() {
1234            if self.tool_use.message_has_tool_results(message.id) {
1235                return true;
1236            } else if message.role == Role::User {
1237                return false;
1238            }
1239        }
1240
1241        false
1242    }
1243
1244    pub fn to_completion_request(
1245        &self,
1246        model: Arc<dyn LanguageModel>,
1247        intent: CompletionIntent,
1248        cx: &mut Context<Self>,
1249    ) -> LanguageModelRequest {
1250        let mut request = LanguageModelRequest {
1251            thread_id: Some(self.id.to_string()),
1252            prompt_id: Some(self.last_prompt_id.to_string()),
1253            intent: Some(intent),
1254            mode: None,
1255            messages: vec![],
1256            tools: Vec::new(),
1257            tool_choice: None,
1258            stop: Vec::new(),
1259            temperature: AgentSettings::temperature_for_model(&model, cx),
1260        };
1261
1262        let available_tools = self.available_tools(cx, model.clone());
1263        let available_tool_names = available_tools
1264            .iter()
1265            .map(|tool| tool.name.clone())
1266            .collect();
1267
1268        let model_context = &ModelContext {
1269            available_tools: available_tool_names,
1270        };
1271
1272        if let Some(project_context) = self.project_context.borrow().as_ref() {
1273            match self
1274                .prompt_builder
1275                .generate_assistant_system_prompt(project_context, model_context)
1276            {
1277                Err(err) => {
1278                    let message = format!("{err:?}").into();
1279                    log::error!("{message}");
1280                    cx.emit(ThreadEvent::ShowError(ThreadError::Message {
1281                        header: "Error generating system prompt".into(),
1282                        message,
1283                    }));
1284                }
1285                Ok(system_prompt) => {
1286                    request.messages.push(LanguageModelRequestMessage {
1287                        role: Role::System,
1288                        content: vec![MessageContent::Text(system_prompt)],
1289                        cache: true,
1290                    });
1291                }
1292            }
1293        } else {
1294            let message = "Context for system prompt unexpectedly not ready.".into();
1295            log::error!("{message}");
1296            cx.emit(ThreadEvent::ShowError(ThreadError::Message {
1297                header: "Error generating system prompt".into(),
1298                message,
1299            }));
1300        }
1301
1302        let mut message_ix_to_cache = None;
1303        for message in &self.messages {
1304            let mut request_message = LanguageModelRequestMessage {
1305                role: message.role,
1306                content: Vec::new(),
1307                cache: false,
1308            };
1309
1310            message
1311                .loaded_context
1312                .add_to_request_message(&mut request_message);
1313
1314            for segment in &message.segments {
1315                match segment {
1316                    MessageSegment::Text(text) => {
1317                        if !text.is_empty() {
1318                            request_message
1319                                .content
1320                                .push(MessageContent::Text(text.into()));
1321                        }
1322                    }
1323                    MessageSegment::Thinking { text, signature } => {
1324                        if !text.is_empty() {
1325                            request_message.content.push(MessageContent::Thinking {
1326                                text: text.into(),
1327                                signature: signature.clone(),
1328                            });
1329                        }
1330                    }
1331                    MessageSegment::RedactedThinking(data) => {
1332                        request_message
1333                            .content
1334                            .push(MessageContent::RedactedThinking(data.clone()));
1335                    }
1336                };
1337            }
1338
1339            let mut cache_message = true;
1340            let mut tool_results_message = LanguageModelRequestMessage {
1341                role: Role::User,
1342                content: Vec::new(),
1343                cache: false,
1344            };
1345            for (tool_use, tool_result) in self.tool_use.tool_results(message.id) {
1346                if let Some(tool_result) = tool_result {
1347                    request_message
1348                        .content
1349                        .push(MessageContent::ToolUse(tool_use.clone()));
1350                    tool_results_message
1351                        .content
1352                        .push(MessageContent::ToolResult(LanguageModelToolResult {
1353                            tool_use_id: tool_use.id.clone(),
1354                            tool_name: tool_result.tool_name.clone(),
1355                            is_error: tool_result.is_error,
1356                            content: if tool_result.content.is_empty() {
1357                                // Surprisingly, the API fails if we return an empty string here.
1358                                // It thinks we are sending a tool use without a tool result.
1359                                "<Tool returned an empty string>".into()
1360                            } else {
1361                                tool_result.content.clone()
1362                            },
1363                            output: None,
1364                        }));
1365                } else {
1366                    cache_message = false;
1367                    log::debug!(
1368                        "skipped tool use {:?} because it is still pending",
1369                        tool_use
1370                    );
1371                }
1372            }
1373
1374            if cache_message {
1375                message_ix_to_cache = Some(request.messages.len());
1376            }
1377            request.messages.push(request_message);
1378
1379            if !tool_results_message.content.is_empty() {
1380                if cache_message {
1381                    message_ix_to_cache = Some(request.messages.len());
1382                }
1383                request.messages.push(tool_results_message);
1384            }
1385        }
1386
1387        // https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
1388        if let Some(message_ix_to_cache) = message_ix_to_cache {
1389            request.messages[message_ix_to_cache].cache = true;
1390        }
1391
1392        self.attached_tracked_files_state(&mut request.messages, cx);
1393
1394        request.tools = available_tools;
1395        request.mode = if model.supports_max_mode() {
1396            Some(self.completion_mode.into())
1397        } else {
1398            Some(CompletionMode::Normal.into())
1399        };
1400
1401        request
1402    }
1403
1404    fn to_summarize_request(
1405        &self,
1406        model: &Arc<dyn LanguageModel>,
1407        intent: CompletionIntent,
1408        added_user_message: String,
1409        cx: &App,
1410    ) -> LanguageModelRequest {
1411        let mut request = LanguageModelRequest {
1412            thread_id: None,
1413            prompt_id: None,
1414            intent: Some(intent),
1415            mode: None,
1416            messages: vec![],
1417            tools: Vec::new(),
1418            tool_choice: None,
1419            stop: Vec::new(),
1420            temperature: AgentSettings::temperature_for_model(model, cx),
1421        };
1422
1423        for message in &self.messages {
1424            let mut request_message = LanguageModelRequestMessage {
1425                role: message.role,
1426                content: Vec::new(),
1427                cache: false,
1428            };
1429
1430            for segment in &message.segments {
1431                match segment {
1432                    MessageSegment::Text(text) => request_message
1433                        .content
1434                        .push(MessageContent::Text(text.clone())),
1435                    MessageSegment::Thinking { .. } => {}
1436                    MessageSegment::RedactedThinking(_) => {}
1437                }
1438            }
1439
1440            if request_message.content.is_empty() {
1441                continue;
1442            }
1443
1444            request.messages.push(request_message);
1445        }
1446
1447        request.messages.push(LanguageModelRequestMessage {
1448            role: Role::User,
1449            content: vec![MessageContent::Text(added_user_message)],
1450            cache: false,
1451        });
1452
1453        request
1454    }
1455
1456    fn attached_tracked_files_state(
1457        &self,
1458        messages: &mut Vec<LanguageModelRequestMessage>,
1459        cx: &App,
1460    ) {
1461        const STALE_FILES_HEADER: &str = include_str!("./prompts/stale_files_prompt_header.txt");
1462
1463        let mut stale_message = String::new();
1464
1465        let action_log = self.action_log.read(cx);
1466
1467        for stale_file in action_log.stale_buffers(cx) {
1468            let Some(file) = stale_file.read(cx).file() else {
1469                continue;
1470            };
1471
1472            if stale_message.is_empty() {
1473                write!(&mut stale_message, "{}\n", STALE_FILES_HEADER.trim()).ok();
1474            }
1475
1476            writeln!(&mut stale_message, "- {}", file.path().display()).ok();
1477        }
1478
1479        let mut content = Vec::with_capacity(2);
1480
1481        if !stale_message.is_empty() {
1482            content.push(stale_message.into());
1483        }
1484
1485        if !content.is_empty() {
1486            let context_message = LanguageModelRequestMessage {
1487                role: Role::User,
1488                content,
1489                cache: false,
1490            };
1491
1492            messages.push(context_message);
1493        }
1494    }
1495
1496    pub fn stream_completion(
1497        &mut self,
1498        request: LanguageModelRequest,
1499        model: Arc<dyn LanguageModel>,
1500        window: Option<AnyWindowHandle>,
1501        cx: &mut Context<Self>,
1502    ) {
1503        self.tool_use_limit_reached = false;
1504
1505        let pending_completion_id = post_inc(&mut self.completion_count);
1506        let mut request_callback_parameters = if self.request_callback.is_some() {
1507            Some((request.clone(), Vec::new()))
1508        } else {
1509            None
1510        };
1511        let prompt_id = self.last_prompt_id.clone();
1512        let tool_use_metadata = ToolUseMetadata {
1513            model: model.clone(),
1514            thread_id: self.id.clone(),
1515            prompt_id: prompt_id.clone(),
1516        };
1517
1518        self.last_received_chunk_at = Some(Instant::now());
1519
1520        let task = cx.spawn(async move |thread, cx| {
1521            let stream_completion_future = model.stream_completion(request, &cx);
1522            let initial_token_usage =
1523                thread.read_with(cx, |thread, _cx| thread.cumulative_token_usage);
1524            let stream_completion = async {
1525                let mut events = stream_completion_future.await?;
1526
1527                let mut stop_reason = StopReason::EndTurn;
1528                let mut current_token_usage = TokenUsage::default();
1529
1530                thread
1531                    .update(cx, |_thread, cx| {
1532                        cx.emit(ThreadEvent::NewRequest);
1533                    })
1534                    .ok();
1535
1536                let mut request_assistant_message_id = None;
1537
1538                while let Some(event) = events.next().await {
1539                    if let Some((_, response_events)) = request_callback_parameters.as_mut() {
1540                        response_events
1541                            .push(event.as_ref().map_err(|error| error.to_string()).cloned());
1542                    }
1543
1544                    thread.update(cx, |thread, cx| {
1545                        let event = match event {
1546                            Ok(event) => event,
1547                            Err(LanguageModelCompletionError::BadInputJson {
1548                                id,
1549                                tool_name,
1550                                raw_input: invalid_input_json,
1551                                json_parse_error,
1552                            }) => {
1553                                thread.receive_invalid_tool_json(
1554                                    id,
1555                                    tool_name,
1556                                    invalid_input_json,
1557                                    json_parse_error,
1558                                    window,
1559                                    cx,
1560                                );
1561                                return Ok(());
1562                            }
1563                            Err(LanguageModelCompletionError::Other(error)) => {
1564                                return Err(error);
1565                            }
1566                        };
1567
1568                        match event {
1569                            LanguageModelCompletionEvent::StartMessage { .. } => {
1570                                request_assistant_message_id =
1571                                    Some(thread.insert_assistant_message(
1572                                        vec![MessageSegment::Text(String::new())],
1573                                        cx,
1574                                    ));
1575                            }
1576                            LanguageModelCompletionEvent::Stop(reason) => {
1577                                stop_reason = reason;
1578                            }
1579                            LanguageModelCompletionEvent::UsageUpdate(token_usage) => {
1580                                thread.update_token_usage_at_last_message(token_usage);
1581                                thread.cumulative_token_usage = thread.cumulative_token_usage
1582                                    + token_usage
1583                                    - current_token_usage;
1584                                current_token_usage = token_usage;
1585                            }
1586                            LanguageModelCompletionEvent::Text(chunk) => {
1587                                thread.received_chunk();
1588
1589                                cx.emit(ThreadEvent::ReceivedTextChunk);
1590                                if let Some(last_message) = thread.messages.last_mut() {
1591                                    if last_message.role == Role::Assistant
1592                                        && !thread.tool_use.has_tool_results(last_message.id)
1593                                    {
1594                                        last_message.push_text(&chunk);
1595                                        cx.emit(ThreadEvent::StreamedAssistantText(
1596                                            last_message.id,
1597                                            chunk,
1598                                        ));
1599                                    } else {
1600                                        // If we won't have an Assistant message yet, assume this chunk marks the beginning
1601                                        // of a new Assistant response.
1602                                        //
1603                                        // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
1604                                        // will result in duplicating the text of the chunk in the rendered Markdown.
1605                                        request_assistant_message_id =
1606                                            Some(thread.insert_assistant_message(
1607                                                vec![MessageSegment::Text(chunk.to_string())],
1608                                                cx,
1609                                            ));
1610                                    };
1611                                }
1612                            }
1613                            LanguageModelCompletionEvent::Thinking {
1614                                text: chunk,
1615                                signature,
1616                            } => {
1617                                thread.received_chunk();
1618
1619                                if let Some(last_message) = thread.messages.last_mut() {
1620                                    if last_message.role == Role::Assistant
1621                                        && !thread.tool_use.has_tool_results(last_message.id)
1622                                    {
1623                                        last_message.push_thinking(&chunk, signature);
1624                                        cx.emit(ThreadEvent::StreamedAssistantThinking(
1625                                            last_message.id,
1626                                            chunk,
1627                                        ));
1628                                    } else {
1629                                        // If we won't have an Assistant message yet, assume this chunk marks the beginning
1630                                        // of a new Assistant response.
1631                                        //
1632                                        // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
1633                                        // will result in duplicating the text of the chunk in the rendered Markdown.
1634                                        request_assistant_message_id =
1635                                            Some(thread.insert_assistant_message(
1636                                                vec![MessageSegment::Thinking {
1637                                                    text: chunk.to_string(),
1638                                                    signature,
1639                                                }],
1640                                                cx,
1641                                            ));
1642                                    };
1643                                }
1644                            }
1645                            LanguageModelCompletionEvent::ToolUse(tool_use) => {
1646                                let last_assistant_message_id = request_assistant_message_id
1647                                    .unwrap_or_else(|| {
1648                                        let new_assistant_message_id =
1649                                            thread.insert_assistant_message(vec![], cx);
1650                                        request_assistant_message_id =
1651                                            Some(new_assistant_message_id);
1652                                        new_assistant_message_id
1653                                    });
1654
1655                                let tool_use_id = tool_use.id.clone();
1656                                let streamed_input = if tool_use.is_input_complete {
1657                                    None
1658                                } else {
1659                                    Some((&tool_use.input).clone())
1660                                };
1661
1662                                let ui_text = thread.tool_use.request_tool_use(
1663                                    last_assistant_message_id,
1664                                    tool_use,
1665                                    tool_use_metadata.clone(),
1666                                    cx,
1667                                );
1668
1669                                if let Some(input) = streamed_input {
1670                                    cx.emit(ThreadEvent::StreamedToolUse {
1671                                        tool_use_id,
1672                                        ui_text,
1673                                        input,
1674                                    });
1675                                }
1676                            }
1677                            LanguageModelCompletionEvent::StatusUpdate(status_update) => {
1678                                if let Some(completion) = thread
1679                                    .pending_completions
1680                                    .iter_mut()
1681                                    .find(|completion| completion.id == pending_completion_id)
1682                                {
1683                                    match status_update {
1684                                        CompletionRequestStatus::Queued {
1685                                            position,
1686                                        } => {
1687                                            completion.queue_state = QueueState::Queued { position };
1688                                        }
1689                                        CompletionRequestStatus::Started => {
1690                                            completion.queue_state =  QueueState::Started;
1691                                        }
1692                                        CompletionRequestStatus::Failed {
1693                                            code, message, request_id
1694                                        } => {
1695                                            anyhow::bail!("completion request failed. request_id: {request_id}, code: {code}, message: {message}");
1696                                        }
1697                                        CompletionRequestStatus::UsageUpdated {
1698                                            amount, limit
1699                                        } => {
1700                                            let usage = RequestUsage { limit, amount: amount as i32 };
1701
1702                                            thread.last_usage = Some(usage);
1703                                        }
1704                                        CompletionRequestStatus::ToolUseLimitReached => {
1705                                            thread.tool_use_limit_reached = true;
1706                                            cx.emit(ThreadEvent::ToolUseLimitReached);
1707                                        }
1708                                    }
1709                                }
1710                            }
1711                        }
1712
1713                        thread.touch_updated_at();
1714                        cx.emit(ThreadEvent::StreamedCompletion);
1715                        cx.notify();
1716
1717                        thread.auto_capture_telemetry(cx);
1718                        Ok(())
1719                    })??;
1720
1721                    smol::future::yield_now().await;
1722                }
1723
1724                thread.update(cx, |thread, cx| {
1725                    thread.last_received_chunk_at = None;
1726                    thread
1727                        .pending_completions
1728                        .retain(|completion| completion.id != pending_completion_id);
1729
1730                    // If there is a response without tool use, summarize the message. Otherwise,
1731                    // allow two tool uses before summarizing.
1732                    if matches!(thread.summary, ThreadSummary::Pending)
1733                        && thread.messages.len() >= 2
1734                        && (!thread.has_pending_tool_uses() || thread.messages.len() >= 6)
1735                    {
1736                        thread.summarize(cx);
1737                    }
1738                })?;
1739
1740                anyhow::Ok(stop_reason)
1741            };
1742
1743            let result = stream_completion.await;
1744
1745            thread
1746                .update(cx, |thread, cx| {
1747                    thread.finalize_pending_checkpoint(cx);
1748                    match result.as_ref() {
1749                        Ok(stop_reason) => match stop_reason {
1750                            StopReason::ToolUse => {
1751                                let tool_uses = thread.use_pending_tools(window, cx, model.clone());
1752                                cx.emit(ThreadEvent::UsePendingTools { tool_uses });
1753                            }
1754                            StopReason::EndTurn | StopReason::MaxTokens  => {
1755                                thread.project.update(cx, |project, cx| {
1756                                    project.set_agent_location(None, cx);
1757                                });
1758                            }
1759                            StopReason::Refusal => {
1760                                thread.project.update(cx, |project, cx| {
1761                                    project.set_agent_location(None, cx);
1762                                });
1763
1764                                // Remove the turn that was refused.
1765                                //
1766                                // https://docs.anthropic.com/en/docs/test-and-evaluate/strengthen-guardrails/handle-streaming-refusals#reset-context-after-refusal
1767                                {
1768                                    let mut messages_to_remove = Vec::new();
1769
1770                                    for (ix, message) in thread.messages.iter().enumerate().rev() {
1771                                        messages_to_remove.push(message.id);
1772
1773                                        if message.role == Role::User {
1774                                            if ix == 0 {
1775                                                break;
1776                                            }
1777
1778                                            if let Some(prev_message) = thread.messages.get(ix - 1) {
1779                                                if prev_message.role == Role::Assistant {
1780                                                    break;
1781                                                }
1782                                            }
1783                                        }
1784                                    }
1785
1786                                    for message_id in messages_to_remove {
1787                                        thread.delete_message(message_id, cx);
1788                                    }
1789                                }
1790
1791                                cx.emit(ThreadEvent::ShowError(ThreadError::Message {
1792                                    header: "Language model refusal".into(),
1793                                    message: "Model refused to generate content for safety reasons.".into(),
1794                                }));
1795                            }
1796                        },
1797                        Err(error) => {
1798                            thread.project.update(cx, |project, cx| {
1799                                project.set_agent_location(None, cx);
1800                            });
1801
1802                            if error.is::<PaymentRequiredError>() {
1803                                cx.emit(ThreadEvent::ShowError(ThreadError::PaymentRequired));
1804                            } else if let Some(error) =
1805                                error.downcast_ref::<ModelRequestLimitReachedError>()
1806                            {
1807                                cx.emit(ThreadEvent::ShowError(
1808                                    ThreadError::ModelRequestLimitReached { plan: error.plan },
1809                                ));
1810                            } else if let Some(known_error) =
1811                                error.downcast_ref::<LanguageModelKnownError>()
1812                            {
1813                                match known_error {
1814                                    LanguageModelKnownError::ContextWindowLimitExceeded {
1815                                        tokens,
1816                                    } => {
1817                                        thread.exceeded_window_error = Some(ExceededWindowError {
1818                                            model_id: model.id(),
1819                                            token_count: *tokens,
1820                                        });
1821                                        cx.notify();
1822                                    }
1823                                }
1824                            } else {
1825                                let error_message = error
1826                                    .chain()
1827                                    .map(|err| err.to_string())
1828                                    .collect::<Vec<_>>()
1829                                    .join("\n");
1830                                cx.emit(ThreadEvent::ShowError(ThreadError::Message {
1831                                    header: "Error interacting with language model".into(),
1832                                    message: SharedString::from(error_message.clone()),
1833                                }));
1834                            }
1835
1836                            thread.cancel_last_completion(window, cx);
1837                        }
1838                    }
1839
1840                    cx.emit(ThreadEvent::Stopped(result.map_err(Arc::new)));
1841
1842                    if let Some((request_callback, (request, response_events))) = thread
1843                        .request_callback
1844                        .as_mut()
1845                        .zip(request_callback_parameters.as_ref())
1846                    {
1847                        request_callback(request, response_events);
1848                    }
1849
1850                    thread.auto_capture_telemetry(cx);
1851
1852                    if let Ok(initial_usage) = initial_token_usage {
1853                        let usage = thread.cumulative_token_usage - initial_usage;
1854
1855                        telemetry::event!(
1856                            "Assistant Thread Completion",
1857                            thread_id = thread.id().to_string(),
1858                            prompt_id = prompt_id,
1859                            model = model.telemetry_id(),
1860                            model_provider = model.provider_id().to_string(),
1861                            input_tokens = usage.input_tokens,
1862                            output_tokens = usage.output_tokens,
1863                            cache_creation_input_tokens = usage.cache_creation_input_tokens,
1864                            cache_read_input_tokens = usage.cache_read_input_tokens,
1865                        );
1866                    }
1867                })
1868                .ok();
1869        });
1870
1871        self.pending_completions.push(PendingCompletion {
1872            id: pending_completion_id,
1873            queue_state: QueueState::Sending,
1874            _task: task,
1875        });
1876    }
1877
1878    pub fn summarize(&mut self, cx: &mut Context<Self>) {
1879        let Some(model) = LanguageModelRegistry::read_global(cx).thread_summary_model() else {
1880            println!("No thread summary model");
1881            return;
1882        };
1883
1884        if !model.provider.is_authenticated(cx) {
1885            return;
1886        }
1887
1888        let added_user_message = include_str!("./prompts/summarize_thread_prompt.txt");
1889
1890        let request = self.to_summarize_request(
1891            &model.model,
1892            CompletionIntent::ThreadSummarization,
1893            added_user_message.into(),
1894            cx,
1895        );
1896
1897        self.summary = ThreadSummary::Generating;
1898
1899        self.pending_summary = cx.spawn(async move |this, cx| {
1900            let result = async {
1901                let mut messages = model.model.stream_completion(request, &cx).await?;
1902
1903                let mut new_summary = String::new();
1904                while let Some(event) = messages.next().await {
1905                    let Ok(event) = event else {
1906                        continue;
1907                    };
1908                    let text = match event {
1909                        LanguageModelCompletionEvent::Text(text) => text,
1910                        LanguageModelCompletionEvent::StatusUpdate(
1911                            CompletionRequestStatus::UsageUpdated { amount, limit },
1912                        ) => {
1913                            this.update(cx, |thread, _cx| {
1914                                thread.last_usage = Some(RequestUsage {
1915                                    limit,
1916                                    amount: amount as i32,
1917                                });
1918                            })?;
1919                            continue;
1920                        }
1921                        _ => continue,
1922                    };
1923
1924                    let mut lines = text.lines();
1925                    new_summary.extend(lines.next());
1926
1927                    // Stop if the LLM generated multiple lines.
1928                    if lines.next().is_some() {
1929                        break;
1930                    }
1931                }
1932
1933                anyhow::Ok(new_summary)
1934            }
1935            .await;
1936
1937            this.update(cx, |this, cx| {
1938                match result {
1939                    Ok(new_summary) => {
1940                        if new_summary.is_empty() {
1941                            this.summary = ThreadSummary::Error;
1942                        } else {
1943                            this.summary = ThreadSummary::Ready(new_summary.into());
1944                        }
1945                    }
1946                    Err(err) => {
1947                        this.summary = ThreadSummary::Error;
1948                        log::error!("Failed to generate thread summary: {}", err);
1949                    }
1950                }
1951                cx.emit(ThreadEvent::SummaryGenerated);
1952            })
1953            .log_err()?;
1954
1955            Some(())
1956        });
1957    }
1958
1959    pub fn start_generating_detailed_summary_if_needed(
1960        &mut self,
1961        thread_store: WeakEntity<ThreadStore>,
1962        cx: &mut Context<Self>,
1963    ) {
1964        let Some(last_message_id) = self.messages.last().map(|message| message.id) else {
1965            return;
1966        };
1967
1968        match &*self.detailed_summary_rx.borrow() {
1969            DetailedSummaryState::Generating { message_id, .. }
1970            | DetailedSummaryState::Generated { message_id, .. }
1971                if *message_id == last_message_id =>
1972            {
1973                // Already up-to-date
1974                return;
1975            }
1976            _ => {}
1977        }
1978
1979        let Some(ConfiguredModel { model, provider }) =
1980            LanguageModelRegistry::read_global(cx).thread_summary_model()
1981        else {
1982            return;
1983        };
1984
1985        if !provider.is_authenticated(cx) {
1986            return;
1987        }
1988
1989        let added_user_message = include_str!("./prompts/summarize_thread_detailed_prompt.txt");
1990
1991        let request = self.to_summarize_request(
1992            &model,
1993            CompletionIntent::ThreadContextSummarization,
1994            added_user_message.into(),
1995            cx,
1996        );
1997
1998        *self.detailed_summary_tx.borrow_mut() = DetailedSummaryState::Generating {
1999            message_id: last_message_id,
2000        };
2001
2002        // Replace the detailed summarization task if there is one, cancelling it. It would probably
2003        // be better to allow the old task to complete, but this would require logic for choosing
2004        // which result to prefer (the old task could complete after the new one, resulting in a
2005        // stale summary).
2006        self.detailed_summary_task = cx.spawn(async move |thread, cx| {
2007            let stream = model.stream_completion_text(request, &cx);
2008            let Some(mut messages) = stream.await.log_err() else {
2009                thread
2010                    .update(cx, |thread, _cx| {
2011                        *thread.detailed_summary_tx.borrow_mut() =
2012                            DetailedSummaryState::NotGenerated;
2013                    })
2014                    .ok()?;
2015                return None;
2016            };
2017
2018            let mut new_detailed_summary = String::new();
2019
2020            while let Some(chunk) = messages.stream.next().await {
2021                if let Some(chunk) = chunk.log_err() {
2022                    new_detailed_summary.push_str(&chunk);
2023                }
2024            }
2025
2026            thread
2027                .update(cx, |thread, _cx| {
2028                    *thread.detailed_summary_tx.borrow_mut() = DetailedSummaryState::Generated {
2029                        text: new_detailed_summary.into(),
2030                        message_id: last_message_id,
2031                    };
2032                })
2033                .ok()?;
2034
2035            // Save thread so its summary can be reused later
2036            if let Some(thread) = thread.upgrade() {
2037                if let Ok(Ok(save_task)) = cx.update(|cx| {
2038                    thread_store
2039                        .update(cx, |thread_store, cx| thread_store.save_thread(&thread, cx))
2040                }) {
2041                    save_task.await.log_err();
2042                }
2043            }
2044
2045            Some(())
2046        });
2047    }
2048
2049    pub async fn wait_for_detailed_summary_or_text(
2050        this: &Entity<Self>,
2051        cx: &mut AsyncApp,
2052    ) -> Option<SharedString> {
2053        let mut detailed_summary_rx = this
2054            .read_with(cx, |this, _cx| this.detailed_summary_rx.clone())
2055            .ok()?;
2056        loop {
2057            match detailed_summary_rx.recv().await? {
2058                DetailedSummaryState::Generating { .. } => {}
2059                DetailedSummaryState::NotGenerated => {
2060                    return this.read_with(cx, |this, _cx| this.text().into()).ok();
2061                }
2062                DetailedSummaryState::Generated { text, .. } => return Some(text),
2063            }
2064        }
2065    }
2066
2067    pub fn latest_detailed_summary_or_text(&self) -> SharedString {
2068        self.detailed_summary_rx
2069            .borrow()
2070            .text()
2071            .unwrap_or_else(|| self.text().into())
2072    }
2073
2074    pub fn is_generating_detailed_summary(&self) -> bool {
2075        matches!(
2076            &*self.detailed_summary_rx.borrow(),
2077            DetailedSummaryState::Generating { .. }
2078        )
2079    }
2080
2081    pub fn use_pending_tools(
2082        &mut self,
2083        window: Option<AnyWindowHandle>,
2084        cx: &mut Context<Self>,
2085        model: Arc<dyn LanguageModel>,
2086    ) -> Vec<PendingToolUse> {
2087        self.auto_capture_telemetry(cx);
2088        let request =
2089            Arc::new(self.to_completion_request(model.clone(), CompletionIntent::ToolResults, cx));
2090        let pending_tool_uses = self
2091            .tool_use
2092            .pending_tool_uses()
2093            .into_iter()
2094            .filter(|tool_use| tool_use.status.is_idle())
2095            .cloned()
2096            .collect::<Vec<_>>();
2097
2098        for tool_use in pending_tool_uses.iter() {
2099            if let Some(tool) = self.tools.read(cx).tool(&tool_use.name, cx) {
2100                if tool.needs_confirmation(&tool_use.input, cx)
2101                    && !AgentSettings::get_global(cx).always_allow_tool_actions
2102                {
2103                    self.tool_use.confirm_tool_use(
2104                        tool_use.id.clone(),
2105                        tool_use.ui_text.clone(),
2106                        tool_use.input.clone(),
2107                        request.clone(),
2108                        tool,
2109                    );
2110                    cx.emit(ThreadEvent::ToolConfirmationNeeded);
2111                } else {
2112                    self.run_tool(
2113                        tool_use.id.clone(),
2114                        tool_use.ui_text.clone(),
2115                        tool_use.input.clone(),
2116                        request.clone(),
2117                        tool,
2118                        model.clone(),
2119                        window,
2120                        cx,
2121                    );
2122                }
2123            } else {
2124                self.handle_hallucinated_tool_use(
2125                    tool_use.id.clone(),
2126                    tool_use.name.clone(),
2127                    window,
2128                    cx,
2129                );
2130            }
2131        }
2132
2133        pending_tool_uses
2134    }
2135
2136    pub fn handle_hallucinated_tool_use(
2137        &mut self,
2138        tool_use_id: LanguageModelToolUseId,
2139        hallucinated_tool_name: Arc<str>,
2140        window: Option<AnyWindowHandle>,
2141        cx: &mut Context<Thread>,
2142    ) {
2143        let available_tools = self.profile.enabled_tools(cx);
2144
2145        let tool_list = available_tools
2146            .iter()
2147            .map(|tool| format!("- {}: {}", tool.name(), tool.description()))
2148            .collect::<Vec<_>>()
2149            .join("\n");
2150
2151        let error_message = format!(
2152            "The tool '{}' doesn't exist or is not enabled. Available tools:\n{}",
2153            hallucinated_tool_name, tool_list
2154        );
2155
2156        let pending_tool_use = self.tool_use.insert_tool_output(
2157            tool_use_id.clone(),
2158            hallucinated_tool_name,
2159            Err(anyhow!("Missing tool call: {error_message}")),
2160            self.configured_model.as_ref(),
2161        );
2162
2163        cx.emit(ThreadEvent::MissingToolUse {
2164            tool_use_id: tool_use_id.clone(),
2165            ui_text: error_message.into(),
2166        });
2167
2168        self.tool_finished(tool_use_id, pending_tool_use, false, window, cx);
2169    }
2170
2171    pub fn receive_invalid_tool_json(
2172        &mut self,
2173        tool_use_id: LanguageModelToolUseId,
2174        tool_name: Arc<str>,
2175        invalid_json: Arc<str>,
2176        error: String,
2177        window: Option<AnyWindowHandle>,
2178        cx: &mut Context<Thread>,
2179    ) {
2180        log::error!("The model returned invalid input JSON: {invalid_json}");
2181
2182        let pending_tool_use = self.tool_use.insert_tool_output(
2183            tool_use_id.clone(),
2184            tool_name,
2185            Err(anyhow!("Error parsing input JSON: {error}")),
2186            self.configured_model.as_ref(),
2187        );
2188        let ui_text = if let Some(pending_tool_use) = &pending_tool_use {
2189            pending_tool_use.ui_text.clone()
2190        } else {
2191            log::error!(
2192                "There was no pending tool use for tool use {tool_use_id}, even though it finished (with invalid input JSON)."
2193            );
2194            format!("Unknown tool {}", tool_use_id).into()
2195        };
2196
2197        cx.emit(ThreadEvent::InvalidToolInput {
2198            tool_use_id: tool_use_id.clone(),
2199            ui_text,
2200            invalid_input_json: invalid_json,
2201        });
2202
2203        self.tool_finished(tool_use_id, pending_tool_use, false, window, cx);
2204    }
2205
2206    pub fn run_tool(
2207        &mut self,
2208        tool_use_id: LanguageModelToolUseId,
2209        ui_text: impl Into<SharedString>,
2210        input: serde_json::Value,
2211        request: Arc<LanguageModelRequest>,
2212        tool: Arc<dyn Tool>,
2213        model: Arc<dyn LanguageModel>,
2214        window: Option<AnyWindowHandle>,
2215        cx: &mut Context<Thread>,
2216    ) {
2217        let task =
2218            self.spawn_tool_use(tool_use_id.clone(), request, input, tool, model, window, cx);
2219        self.tool_use
2220            .run_pending_tool(tool_use_id, ui_text.into(), task);
2221    }
2222
2223    fn spawn_tool_use(
2224        &mut self,
2225        tool_use_id: LanguageModelToolUseId,
2226        request: Arc<LanguageModelRequest>,
2227        input: serde_json::Value,
2228        tool: Arc<dyn Tool>,
2229        model: Arc<dyn LanguageModel>,
2230        window: Option<AnyWindowHandle>,
2231        cx: &mut Context<Thread>,
2232    ) -> Task<()> {
2233        let tool_name: Arc<str> = tool.name().into();
2234
2235        let tool_result = tool.run(
2236            input,
2237            request,
2238            self.project.clone(),
2239            self.action_log.clone(),
2240            model,
2241            window,
2242            cx,
2243        );
2244
2245        // Store the card separately if it exists
2246        if let Some(card) = tool_result.card.clone() {
2247            self.tool_use
2248                .insert_tool_result_card(tool_use_id.clone(), card);
2249        }
2250
2251        cx.spawn({
2252            async move |thread: WeakEntity<Thread>, cx| {
2253                let output = tool_result.output.await;
2254
2255                thread
2256                    .update(cx, |thread, cx| {
2257                        let pending_tool_use = thread.tool_use.insert_tool_output(
2258                            tool_use_id.clone(),
2259                            tool_name,
2260                            output,
2261                            thread.configured_model.as_ref(),
2262                        );
2263                        thread.tool_finished(tool_use_id, pending_tool_use, false, window, cx);
2264                    })
2265                    .ok();
2266            }
2267        })
2268    }
2269
2270    fn tool_finished(
2271        &mut self,
2272        tool_use_id: LanguageModelToolUseId,
2273        pending_tool_use: Option<PendingToolUse>,
2274        canceled: bool,
2275        window: Option<AnyWindowHandle>,
2276        cx: &mut Context<Self>,
2277    ) {
2278        if self.all_tools_finished() {
2279            if let Some(ConfiguredModel { model, .. }) = self.configured_model.as_ref() {
2280                if !canceled {
2281                    self.send_to_model(model.clone(), CompletionIntent::ToolResults, window, cx);
2282                }
2283                self.auto_capture_telemetry(cx);
2284            }
2285        }
2286
2287        cx.emit(ThreadEvent::ToolFinished {
2288            tool_use_id,
2289            pending_tool_use,
2290        });
2291    }
2292
2293    /// Cancels the last pending completion, if there are any pending.
2294    ///
2295    /// Returns whether a completion was canceled.
2296    pub fn cancel_last_completion(
2297        &mut self,
2298        window: Option<AnyWindowHandle>,
2299        cx: &mut Context<Self>,
2300    ) -> bool {
2301        let mut canceled = self.pending_completions.pop().is_some();
2302
2303        for pending_tool_use in self.tool_use.cancel_pending() {
2304            canceled = true;
2305            self.tool_finished(
2306                pending_tool_use.id.clone(),
2307                Some(pending_tool_use),
2308                true,
2309                window,
2310                cx,
2311            );
2312        }
2313
2314        if canceled {
2315            cx.emit(ThreadEvent::CompletionCanceled);
2316
2317            // When canceled, we always want to insert the checkpoint.
2318            // (We skip over finalize_pending_checkpoint, because it
2319            // would conclude we didn't have anything to insert here.)
2320            if let Some(checkpoint) = self.pending_checkpoint.take() {
2321                self.insert_checkpoint(checkpoint, cx);
2322            }
2323        } else {
2324            self.finalize_pending_checkpoint(cx);
2325        }
2326
2327        canceled
2328    }
2329
2330    /// Signals that any in-progress editing should be canceled.
2331    ///
2332    /// This method is used to notify listeners (like ActiveThread) that
2333    /// they should cancel any editing operations.
2334    pub fn cancel_editing(&mut self, cx: &mut Context<Self>) {
2335        cx.emit(ThreadEvent::CancelEditing);
2336    }
2337
2338    pub fn feedback(&self) -> Option<ThreadFeedback> {
2339        self.feedback
2340    }
2341
2342    pub fn message_feedback(&self, message_id: MessageId) -> Option<ThreadFeedback> {
2343        self.message_feedback.get(&message_id).copied()
2344    }
2345
2346    pub fn report_message_feedback(
2347        &mut self,
2348        message_id: MessageId,
2349        feedback: ThreadFeedback,
2350        cx: &mut Context<Self>,
2351    ) -> Task<Result<()>> {
2352        if self.message_feedback.get(&message_id) == Some(&feedback) {
2353            return Task::ready(Ok(()));
2354        }
2355
2356        let final_project_snapshot = Self::project_snapshot(self.project.clone(), cx);
2357        let serialized_thread = self.serialize(cx);
2358        let thread_id = self.id().clone();
2359        let client = self.project.read(cx).client();
2360
2361        let enabled_tool_names: Vec<String> = self
2362            .profile
2363            .enabled_tools(cx)
2364            .iter()
2365            .map(|tool| tool.name())
2366            .collect();
2367
2368        self.message_feedback.insert(message_id, feedback);
2369
2370        cx.notify();
2371
2372        let message_content = self
2373            .message(message_id)
2374            .map(|msg| msg.to_string())
2375            .unwrap_or_default();
2376
2377        cx.background_spawn(async move {
2378            let final_project_snapshot = final_project_snapshot.await;
2379            let serialized_thread = serialized_thread.await?;
2380            let thread_data =
2381                serde_json::to_value(serialized_thread).unwrap_or_else(|_| serde_json::Value::Null);
2382
2383            let rating = match feedback {
2384                ThreadFeedback::Positive => "positive",
2385                ThreadFeedback::Negative => "negative",
2386            };
2387            telemetry::event!(
2388                "Assistant Thread Rated",
2389                rating,
2390                thread_id,
2391                enabled_tool_names,
2392                message_id = message_id.0,
2393                message_content,
2394                thread_data,
2395                final_project_snapshot
2396            );
2397            client.telemetry().flush_events().await;
2398
2399            Ok(())
2400        })
2401    }
2402
2403    pub fn report_feedback(
2404        &mut self,
2405        feedback: ThreadFeedback,
2406        cx: &mut Context<Self>,
2407    ) -> Task<Result<()>> {
2408        let last_assistant_message_id = self
2409            .messages
2410            .iter()
2411            .rev()
2412            .find(|msg| msg.role == Role::Assistant)
2413            .map(|msg| msg.id);
2414
2415        if let Some(message_id) = last_assistant_message_id {
2416            self.report_message_feedback(message_id, feedback, cx)
2417        } else {
2418            let final_project_snapshot = Self::project_snapshot(self.project.clone(), cx);
2419            let serialized_thread = self.serialize(cx);
2420            let thread_id = self.id().clone();
2421            let client = self.project.read(cx).client();
2422            self.feedback = Some(feedback);
2423            cx.notify();
2424
2425            cx.background_spawn(async move {
2426                let final_project_snapshot = final_project_snapshot.await;
2427                let serialized_thread = serialized_thread.await?;
2428                let thread_data = serde_json::to_value(serialized_thread)
2429                    .unwrap_or_else(|_| serde_json::Value::Null);
2430
2431                let rating = match feedback {
2432                    ThreadFeedback::Positive => "positive",
2433                    ThreadFeedback::Negative => "negative",
2434                };
2435                telemetry::event!(
2436                    "Assistant Thread Rated",
2437                    rating,
2438                    thread_id,
2439                    thread_data,
2440                    final_project_snapshot
2441                );
2442                client.telemetry().flush_events().await;
2443
2444                Ok(())
2445            })
2446        }
2447    }
2448
2449    /// Create a snapshot of the current project state including git information and unsaved buffers.
2450    fn project_snapshot(
2451        project: Entity<Project>,
2452        cx: &mut Context<Self>,
2453    ) -> Task<Arc<ProjectSnapshot>> {
2454        let git_store = project.read(cx).git_store().clone();
2455        let worktree_snapshots: Vec<_> = project
2456            .read(cx)
2457            .visible_worktrees(cx)
2458            .map(|worktree| Self::worktree_snapshot(worktree, git_store.clone(), cx))
2459            .collect();
2460
2461        cx.spawn(async move |_, cx| {
2462            let worktree_snapshots = futures::future::join_all(worktree_snapshots).await;
2463
2464            let mut unsaved_buffers = Vec::new();
2465            cx.update(|app_cx| {
2466                let buffer_store = project.read(app_cx).buffer_store();
2467                for buffer_handle in buffer_store.read(app_cx).buffers() {
2468                    let buffer = buffer_handle.read(app_cx);
2469                    if buffer.is_dirty() {
2470                        if let Some(file) = buffer.file() {
2471                            let path = file.path().to_string_lossy().to_string();
2472                            unsaved_buffers.push(path);
2473                        }
2474                    }
2475                }
2476            })
2477            .ok();
2478
2479            Arc::new(ProjectSnapshot {
2480                worktree_snapshots,
2481                unsaved_buffer_paths: unsaved_buffers,
2482                timestamp: Utc::now(),
2483            })
2484        })
2485    }
2486
2487    fn worktree_snapshot(
2488        worktree: Entity<project::Worktree>,
2489        git_store: Entity<GitStore>,
2490        cx: &App,
2491    ) -> Task<WorktreeSnapshot> {
2492        cx.spawn(async move |cx| {
2493            // Get worktree path and snapshot
2494            let worktree_info = cx.update(|app_cx| {
2495                let worktree = worktree.read(app_cx);
2496                let path = worktree.abs_path().to_string_lossy().to_string();
2497                let snapshot = worktree.snapshot();
2498                (path, snapshot)
2499            });
2500
2501            let Ok((worktree_path, _snapshot)) = worktree_info else {
2502                return WorktreeSnapshot {
2503                    worktree_path: String::new(),
2504                    git_state: None,
2505                };
2506            };
2507
2508            let git_state = git_store
2509                .update(cx, |git_store, cx| {
2510                    git_store
2511                        .repositories()
2512                        .values()
2513                        .find(|repo| {
2514                            repo.read(cx)
2515                                .abs_path_to_repo_path(&worktree.read(cx).abs_path())
2516                                .is_some()
2517                        })
2518                        .cloned()
2519                })
2520                .ok()
2521                .flatten()
2522                .map(|repo| {
2523                    repo.update(cx, |repo, _| {
2524                        let current_branch =
2525                            repo.branch.as_ref().map(|branch| branch.name().to_owned());
2526                        repo.send_job(None, |state, _| async move {
2527                            let RepositoryState::Local { backend, .. } = state else {
2528                                return GitState {
2529                                    remote_url: None,
2530                                    head_sha: None,
2531                                    current_branch,
2532                                    diff: None,
2533                                };
2534                            };
2535
2536                            let remote_url = backend.remote_url("origin");
2537                            let head_sha = backend.head_sha().await;
2538                            let diff = backend.diff(DiffType::HeadToWorktree).await.ok();
2539
2540                            GitState {
2541                                remote_url,
2542                                head_sha,
2543                                current_branch,
2544                                diff,
2545                            }
2546                        })
2547                    })
2548                });
2549
2550            let git_state = match git_state {
2551                Some(git_state) => match git_state.ok() {
2552                    Some(git_state) => git_state.await.ok(),
2553                    None => None,
2554                },
2555                None => None,
2556            };
2557
2558            WorktreeSnapshot {
2559                worktree_path,
2560                git_state,
2561            }
2562        })
2563    }
2564
2565    pub fn to_markdown(&self, cx: &App) -> Result<String> {
2566        let mut markdown = Vec::new();
2567
2568        let summary = self.summary().or_default();
2569        writeln!(markdown, "# {summary}\n")?;
2570
2571        for message in self.messages() {
2572            writeln!(
2573                markdown,
2574                "## {role}\n",
2575                role = match message.role {
2576                    Role::User => "User",
2577                    Role::Assistant => "Agent",
2578                    Role::System => "System",
2579                }
2580            )?;
2581
2582            if !message.loaded_context.text.is_empty() {
2583                writeln!(markdown, "{}", message.loaded_context.text)?;
2584            }
2585
2586            if !message.loaded_context.images.is_empty() {
2587                writeln!(
2588                    markdown,
2589                    "\n{} images attached as context.\n",
2590                    message.loaded_context.images.len()
2591                )?;
2592            }
2593
2594            for segment in &message.segments {
2595                match segment {
2596                    MessageSegment::Text(text) => writeln!(markdown, "{}\n", text)?,
2597                    MessageSegment::Thinking { text, .. } => {
2598                        writeln!(markdown, "<think>\n{}\n</think>\n", text)?
2599                    }
2600                    MessageSegment::RedactedThinking(_) => {}
2601                }
2602            }
2603
2604            for tool_use in self.tool_uses_for_message(message.id, cx) {
2605                writeln!(
2606                    markdown,
2607                    "**Use Tool: {} ({})**",
2608                    tool_use.name, tool_use.id
2609                )?;
2610                writeln!(markdown, "```json")?;
2611                writeln!(
2612                    markdown,
2613                    "{}",
2614                    serde_json::to_string_pretty(&tool_use.input)?
2615                )?;
2616                writeln!(markdown, "```")?;
2617            }
2618
2619            for tool_result in self.tool_results_for_message(message.id) {
2620                write!(markdown, "\n**Tool Results: {}", tool_result.tool_use_id)?;
2621                if tool_result.is_error {
2622                    write!(markdown, " (Error)")?;
2623                }
2624
2625                writeln!(markdown, "**\n")?;
2626                match &tool_result.content {
2627                    LanguageModelToolResultContent::Text(text) => {
2628                        writeln!(markdown, "{text}")?;
2629                    }
2630                    LanguageModelToolResultContent::Image(image) => {
2631                        writeln!(markdown, "![Image](data:base64,{})", image.source)?;
2632                    }
2633                }
2634
2635                if let Some(output) = tool_result.output.as_ref() {
2636                    writeln!(
2637                        markdown,
2638                        "\n\nDebug Output:\n\n```json\n{}\n```\n",
2639                        serde_json::to_string_pretty(output)?
2640                    )?;
2641                }
2642            }
2643        }
2644
2645        Ok(String::from_utf8_lossy(&markdown).to_string())
2646    }
2647
2648    pub fn keep_edits_in_range(
2649        &mut self,
2650        buffer: Entity<language::Buffer>,
2651        buffer_range: Range<language::Anchor>,
2652        cx: &mut Context<Self>,
2653    ) {
2654        self.action_log.update(cx, |action_log, cx| {
2655            action_log.keep_edits_in_range(buffer, buffer_range, cx)
2656        });
2657    }
2658
2659    pub fn keep_all_edits(&mut self, cx: &mut Context<Self>) {
2660        self.action_log
2661            .update(cx, |action_log, cx| action_log.keep_all_edits(cx));
2662    }
2663
2664    pub fn reject_edits_in_ranges(
2665        &mut self,
2666        buffer: Entity<language::Buffer>,
2667        buffer_ranges: Vec<Range<language::Anchor>>,
2668        cx: &mut Context<Self>,
2669    ) -> Task<Result<()>> {
2670        self.action_log.update(cx, |action_log, cx| {
2671            action_log.reject_edits_in_ranges(buffer, buffer_ranges, cx)
2672        })
2673    }
2674
2675    pub fn action_log(&self) -> &Entity<ActionLog> {
2676        &self.action_log
2677    }
2678
2679    pub fn project(&self) -> &Entity<Project> {
2680        &self.project
2681    }
2682
2683    pub fn auto_capture_telemetry(&mut self, cx: &mut Context<Self>) {
2684        if !cx.has_flag::<feature_flags::ThreadAutoCaptureFeatureFlag>() {
2685            return;
2686        }
2687
2688        let now = Instant::now();
2689        if let Some(last) = self.last_auto_capture_at {
2690            if now.duration_since(last).as_secs() < 10 {
2691                return;
2692            }
2693        }
2694
2695        self.last_auto_capture_at = Some(now);
2696
2697        let thread_id = self.id().clone();
2698        let github_login = self
2699            .project
2700            .read(cx)
2701            .user_store()
2702            .read(cx)
2703            .current_user()
2704            .map(|user| user.github_login.clone());
2705        let client = self.project.read(cx).client();
2706        let serialize_task = self.serialize(cx);
2707
2708        cx.background_executor()
2709            .spawn(async move {
2710                if let Ok(serialized_thread) = serialize_task.await {
2711                    if let Ok(thread_data) = serde_json::to_value(serialized_thread) {
2712                        telemetry::event!(
2713                            "Agent Thread Auto-Captured",
2714                            thread_id = thread_id.to_string(),
2715                            thread_data = thread_data,
2716                            auto_capture_reason = "tracked_user",
2717                            github_login = github_login
2718                        );
2719
2720                        client.telemetry().flush_events().await;
2721                    }
2722                }
2723            })
2724            .detach();
2725    }
2726
2727    pub fn cumulative_token_usage(&self) -> TokenUsage {
2728        self.cumulative_token_usage
2729    }
2730
2731    pub fn token_usage_up_to_message(&self, message_id: MessageId) -> TotalTokenUsage {
2732        let Some(model) = self.configured_model.as_ref() else {
2733            return TotalTokenUsage::default();
2734        };
2735
2736        let max = model.model.max_token_count();
2737
2738        let index = self
2739            .messages
2740            .iter()
2741            .position(|msg| msg.id == message_id)
2742            .unwrap_or(0);
2743
2744        if index == 0 {
2745            return TotalTokenUsage { total: 0, max };
2746        }
2747
2748        let token_usage = &self
2749            .request_token_usage
2750            .get(index - 1)
2751            .cloned()
2752            .unwrap_or_default();
2753
2754        TotalTokenUsage {
2755            total: token_usage.total_tokens() as usize,
2756            max,
2757        }
2758    }
2759
2760    pub fn total_token_usage(&self) -> Option<TotalTokenUsage> {
2761        let model = self.configured_model.as_ref()?;
2762
2763        let max = model.model.max_token_count();
2764
2765        if let Some(exceeded_error) = &self.exceeded_window_error {
2766            if model.model.id() == exceeded_error.model_id {
2767                return Some(TotalTokenUsage {
2768                    total: exceeded_error.token_count,
2769                    max,
2770                });
2771            }
2772        }
2773
2774        let total = self
2775            .token_usage_at_last_message()
2776            .unwrap_or_default()
2777            .total_tokens() as usize;
2778
2779        Some(TotalTokenUsage { total, max })
2780    }
2781
2782    fn token_usage_at_last_message(&self) -> Option<TokenUsage> {
2783        self.request_token_usage
2784            .get(self.messages.len().saturating_sub(1))
2785            .or_else(|| self.request_token_usage.last())
2786            .cloned()
2787    }
2788
2789    fn update_token_usage_at_last_message(&mut self, token_usage: TokenUsage) {
2790        let placeholder = self.token_usage_at_last_message().unwrap_or_default();
2791        self.request_token_usage
2792            .resize(self.messages.len(), placeholder);
2793
2794        if let Some(last) = self.request_token_usage.last_mut() {
2795            *last = token_usage;
2796        }
2797    }
2798
2799    pub fn deny_tool_use(
2800        &mut self,
2801        tool_use_id: LanguageModelToolUseId,
2802        tool_name: Arc<str>,
2803        window: Option<AnyWindowHandle>,
2804        cx: &mut Context<Self>,
2805    ) {
2806        let err = Err(anyhow::anyhow!(
2807            "Permission to run tool action denied by user"
2808        ));
2809
2810        self.tool_use.insert_tool_output(
2811            tool_use_id.clone(),
2812            tool_name,
2813            err,
2814            self.configured_model.as_ref(),
2815        );
2816        self.tool_finished(tool_use_id.clone(), None, true, window, cx);
2817    }
2818}
2819
2820#[derive(Debug, Clone, Error)]
2821pub enum ThreadError {
2822    #[error("Payment required")]
2823    PaymentRequired,
2824    #[error("Model request limit reached")]
2825    ModelRequestLimitReached { plan: Plan },
2826    #[error("Message {header}: {message}")]
2827    Message {
2828        header: SharedString,
2829        message: SharedString,
2830    },
2831}
2832
2833#[derive(Debug, Clone)]
2834pub enum ThreadEvent {
2835    ShowError(ThreadError),
2836    StreamedCompletion,
2837    ReceivedTextChunk,
2838    NewRequest,
2839    StreamedAssistantText(MessageId, String),
2840    StreamedAssistantThinking(MessageId, String),
2841    StreamedToolUse {
2842        tool_use_id: LanguageModelToolUseId,
2843        ui_text: Arc<str>,
2844        input: serde_json::Value,
2845    },
2846    MissingToolUse {
2847        tool_use_id: LanguageModelToolUseId,
2848        ui_text: Arc<str>,
2849    },
2850    InvalidToolInput {
2851        tool_use_id: LanguageModelToolUseId,
2852        ui_text: Arc<str>,
2853        invalid_input_json: Arc<str>,
2854    },
2855    Stopped(Result<StopReason, Arc<anyhow::Error>>),
2856    MessageAdded(MessageId),
2857    MessageEdited(MessageId),
2858    MessageDeleted(MessageId),
2859    SummaryGenerated,
2860    SummaryChanged,
2861    UsePendingTools {
2862        tool_uses: Vec<PendingToolUse>,
2863    },
2864    ToolFinished {
2865        #[allow(unused)]
2866        tool_use_id: LanguageModelToolUseId,
2867        /// The pending tool use that corresponds to this tool.
2868        pending_tool_use: Option<PendingToolUse>,
2869    },
2870    CheckpointChanged,
2871    ToolConfirmationNeeded,
2872    ToolUseLimitReached,
2873    CancelEditing,
2874    CompletionCanceled,
2875    ProfileChanged,
2876}
2877
2878impl EventEmitter<ThreadEvent> for Thread {}
2879
2880struct PendingCompletion {
2881    id: usize,
2882    queue_state: QueueState,
2883    _task: Task<()>,
2884}
2885
2886#[cfg(test)]
2887mod tests {
2888    use super::*;
2889    use crate::{ThreadStore, context::load_context, context_store::ContextStore, thread_store};
2890    use agent_settings::{AgentProfileId, AgentSettings, LanguageModelParameters};
2891    use assistant_tool::ToolRegistry;
2892    use editor::EditorSettings;
2893    use gpui::TestAppContext;
2894    use language_model::fake_provider::{FakeLanguageModel, FakeLanguageModelProvider};
2895    use project::{FakeFs, Project};
2896    use prompt_store::PromptBuilder;
2897    use serde_json::json;
2898    use settings::{Settings, SettingsStore};
2899    use std::sync::Arc;
2900    use theme::ThemeSettings;
2901    use util::path;
2902    use workspace::Workspace;
2903
2904    #[gpui::test]
2905    async fn test_message_with_context(cx: &mut TestAppContext) {
2906        init_test_settings(cx);
2907
2908        let project = create_test_project(
2909            cx,
2910            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
2911        )
2912        .await;
2913
2914        let (_workspace, _thread_store, thread, context_store, model) =
2915            setup_test_environment(cx, project.clone()).await;
2916
2917        add_file_to_context(&project, &context_store, "test/code.rs", cx)
2918            .await
2919            .unwrap();
2920
2921        let context =
2922            context_store.read_with(cx, |store, _| store.context().next().cloned().unwrap());
2923        let loaded_context = cx
2924            .update(|cx| load_context(vec![context], &project, &None, cx))
2925            .await;
2926
2927        // Insert user message with context
2928        let message_id = thread.update(cx, |thread, cx| {
2929            thread.insert_user_message(
2930                "Please explain this code",
2931                loaded_context,
2932                None,
2933                Vec::new(),
2934                cx,
2935            )
2936        });
2937
2938        // Check content and context in message object
2939        let message = thread.read_with(cx, |thread, _| thread.message(message_id).unwrap().clone());
2940
2941        // Use different path format strings based on platform for the test
2942        #[cfg(windows)]
2943        let path_part = r"test\code.rs";
2944        #[cfg(not(windows))]
2945        let path_part = "test/code.rs";
2946
2947        let expected_context = format!(
2948            r#"
2949<context>
2950The following items were attached by the user. They are up-to-date and don't need to be re-read.
2951
2952<files>
2953```rs {path_part}
2954fn main() {{
2955    println!("Hello, world!");
2956}}
2957```
2958</files>
2959</context>
2960"#
2961        );
2962
2963        assert_eq!(message.role, Role::User);
2964        assert_eq!(message.segments.len(), 1);
2965        assert_eq!(
2966            message.segments[0],
2967            MessageSegment::Text("Please explain this code".to_string())
2968        );
2969        assert_eq!(message.loaded_context.text, expected_context);
2970
2971        // Check message in request
2972        let request = thread.update(cx, |thread, cx| {
2973            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
2974        });
2975
2976        assert_eq!(request.messages.len(), 2);
2977        let expected_full_message = format!("{}Please explain this code", expected_context);
2978        assert_eq!(request.messages[1].string_contents(), expected_full_message);
2979    }
2980
2981    #[gpui::test]
2982    async fn test_only_include_new_contexts(cx: &mut TestAppContext) {
2983        init_test_settings(cx);
2984
2985        let project = create_test_project(
2986            cx,
2987            json!({
2988                "file1.rs": "fn function1() {}\n",
2989                "file2.rs": "fn function2() {}\n",
2990                "file3.rs": "fn function3() {}\n",
2991                "file4.rs": "fn function4() {}\n",
2992            }),
2993        )
2994        .await;
2995
2996        let (_, _thread_store, thread, context_store, model) =
2997            setup_test_environment(cx, project.clone()).await;
2998
2999        // First message with context 1
3000        add_file_to_context(&project, &context_store, "test/file1.rs", cx)
3001            .await
3002            .unwrap();
3003        let new_contexts = context_store.update(cx, |store, cx| {
3004            store.new_context_for_thread(thread.read(cx), None)
3005        });
3006        assert_eq!(new_contexts.len(), 1);
3007        let loaded_context = cx
3008            .update(|cx| load_context(new_contexts, &project, &None, cx))
3009            .await;
3010        let message1_id = thread.update(cx, |thread, cx| {
3011            thread.insert_user_message("Message 1", loaded_context, None, Vec::new(), cx)
3012        });
3013
3014        // Second message with contexts 1 and 2 (context 1 should be skipped as it's already included)
3015        add_file_to_context(&project, &context_store, "test/file2.rs", cx)
3016            .await
3017            .unwrap();
3018        let new_contexts = context_store.update(cx, |store, cx| {
3019            store.new_context_for_thread(thread.read(cx), None)
3020        });
3021        assert_eq!(new_contexts.len(), 1);
3022        let loaded_context = cx
3023            .update(|cx| load_context(new_contexts, &project, &None, cx))
3024            .await;
3025        let message2_id = thread.update(cx, |thread, cx| {
3026            thread.insert_user_message("Message 2", loaded_context, None, Vec::new(), cx)
3027        });
3028
3029        // Third message with all three contexts (contexts 1 and 2 should be skipped)
3030        //
3031        add_file_to_context(&project, &context_store, "test/file3.rs", cx)
3032            .await
3033            .unwrap();
3034        let new_contexts = context_store.update(cx, |store, cx| {
3035            store.new_context_for_thread(thread.read(cx), None)
3036        });
3037        assert_eq!(new_contexts.len(), 1);
3038        let loaded_context = cx
3039            .update(|cx| load_context(new_contexts, &project, &None, cx))
3040            .await;
3041        let message3_id = thread.update(cx, |thread, cx| {
3042            thread.insert_user_message("Message 3", loaded_context, None, Vec::new(), cx)
3043        });
3044
3045        // Check what contexts are included in each message
3046        let (message1, message2, message3) = thread.read_with(cx, |thread, _| {
3047            (
3048                thread.message(message1_id).unwrap().clone(),
3049                thread.message(message2_id).unwrap().clone(),
3050                thread.message(message3_id).unwrap().clone(),
3051            )
3052        });
3053
3054        // First message should include context 1
3055        assert!(message1.loaded_context.text.contains("file1.rs"));
3056
3057        // Second message should include only context 2 (not 1)
3058        assert!(!message2.loaded_context.text.contains("file1.rs"));
3059        assert!(message2.loaded_context.text.contains("file2.rs"));
3060
3061        // Third message should include only context 3 (not 1 or 2)
3062        assert!(!message3.loaded_context.text.contains("file1.rs"));
3063        assert!(!message3.loaded_context.text.contains("file2.rs"));
3064        assert!(message3.loaded_context.text.contains("file3.rs"));
3065
3066        // Check entire request to make sure all contexts are properly included
3067        let request = thread.update(cx, |thread, cx| {
3068            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3069        });
3070
3071        // The request should contain all 3 messages
3072        assert_eq!(request.messages.len(), 4);
3073
3074        // Check that the contexts are properly formatted in each message
3075        assert!(request.messages[1].string_contents().contains("file1.rs"));
3076        assert!(!request.messages[1].string_contents().contains("file2.rs"));
3077        assert!(!request.messages[1].string_contents().contains("file3.rs"));
3078
3079        assert!(!request.messages[2].string_contents().contains("file1.rs"));
3080        assert!(request.messages[2].string_contents().contains("file2.rs"));
3081        assert!(!request.messages[2].string_contents().contains("file3.rs"));
3082
3083        assert!(!request.messages[3].string_contents().contains("file1.rs"));
3084        assert!(!request.messages[3].string_contents().contains("file2.rs"));
3085        assert!(request.messages[3].string_contents().contains("file3.rs"));
3086
3087        add_file_to_context(&project, &context_store, "test/file4.rs", cx)
3088            .await
3089            .unwrap();
3090        let new_contexts = context_store.update(cx, |store, cx| {
3091            store.new_context_for_thread(thread.read(cx), Some(message2_id))
3092        });
3093        assert_eq!(new_contexts.len(), 3);
3094        let loaded_context = cx
3095            .update(|cx| load_context(new_contexts, &project, &None, cx))
3096            .await
3097            .loaded_context;
3098
3099        assert!(!loaded_context.text.contains("file1.rs"));
3100        assert!(loaded_context.text.contains("file2.rs"));
3101        assert!(loaded_context.text.contains("file3.rs"));
3102        assert!(loaded_context.text.contains("file4.rs"));
3103
3104        let new_contexts = context_store.update(cx, |store, cx| {
3105            // Remove file4.rs
3106            store.remove_context(&loaded_context.contexts[2].handle(), cx);
3107            store.new_context_for_thread(thread.read(cx), Some(message2_id))
3108        });
3109        assert_eq!(new_contexts.len(), 2);
3110        let loaded_context = cx
3111            .update(|cx| load_context(new_contexts, &project, &None, cx))
3112            .await
3113            .loaded_context;
3114
3115        assert!(!loaded_context.text.contains("file1.rs"));
3116        assert!(loaded_context.text.contains("file2.rs"));
3117        assert!(loaded_context.text.contains("file3.rs"));
3118        assert!(!loaded_context.text.contains("file4.rs"));
3119
3120        let new_contexts = context_store.update(cx, |store, cx| {
3121            // Remove file3.rs
3122            store.remove_context(&loaded_context.contexts[1].handle(), cx);
3123            store.new_context_for_thread(thread.read(cx), Some(message2_id))
3124        });
3125        assert_eq!(new_contexts.len(), 1);
3126        let loaded_context = cx
3127            .update(|cx| load_context(new_contexts, &project, &None, cx))
3128            .await
3129            .loaded_context;
3130
3131        assert!(!loaded_context.text.contains("file1.rs"));
3132        assert!(loaded_context.text.contains("file2.rs"));
3133        assert!(!loaded_context.text.contains("file3.rs"));
3134        assert!(!loaded_context.text.contains("file4.rs"));
3135    }
3136
3137    #[gpui::test]
3138    async fn test_message_without_files(cx: &mut TestAppContext) {
3139        init_test_settings(cx);
3140
3141        let project = create_test_project(
3142            cx,
3143            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3144        )
3145        .await;
3146
3147        let (_, _thread_store, thread, _context_store, model) =
3148            setup_test_environment(cx, project.clone()).await;
3149
3150        // Insert user message without any context (empty context vector)
3151        let message_id = thread.update(cx, |thread, cx| {
3152            thread.insert_user_message(
3153                "What is the best way to learn Rust?",
3154                ContextLoadResult::default(),
3155                None,
3156                Vec::new(),
3157                cx,
3158            )
3159        });
3160
3161        // Check content and context in message object
3162        let message = thread.read_with(cx, |thread, _| thread.message(message_id).unwrap().clone());
3163
3164        // Context should be empty when no files are included
3165        assert_eq!(message.role, Role::User);
3166        assert_eq!(message.segments.len(), 1);
3167        assert_eq!(
3168            message.segments[0],
3169            MessageSegment::Text("What is the best way to learn Rust?".to_string())
3170        );
3171        assert_eq!(message.loaded_context.text, "");
3172
3173        // Check message in request
3174        let request = thread.update(cx, |thread, cx| {
3175            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3176        });
3177
3178        assert_eq!(request.messages.len(), 2);
3179        assert_eq!(
3180            request.messages[1].string_contents(),
3181            "What is the best way to learn Rust?"
3182        );
3183
3184        // Add second message, also without context
3185        let message2_id = thread.update(cx, |thread, cx| {
3186            thread.insert_user_message(
3187                "Are there any good books?",
3188                ContextLoadResult::default(),
3189                None,
3190                Vec::new(),
3191                cx,
3192            )
3193        });
3194
3195        let message2 =
3196            thread.read_with(cx, |thread, _| thread.message(message2_id).unwrap().clone());
3197        assert_eq!(message2.loaded_context.text, "");
3198
3199        // Check that both messages appear in the request
3200        let request = thread.update(cx, |thread, cx| {
3201            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3202        });
3203
3204        assert_eq!(request.messages.len(), 3);
3205        assert_eq!(
3206            request.messages[1].string_contents(),
3207            "What is the best way to learn Rust?"
3208        );
3209        assert_eq!(
3210            request.messages[2].string_contents(),
3211            "Are there any good books?"
3212        );
3213    }
3214
3215    #[gpui::test]
3216    async fn test_stale_buffer_notification(cx: &mut TestAppContext) {
3217        init_test_settings(cx);
3218
3219        let project = create_test_project(
3220            cx,
3221            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3222        )
3223        .await;
3224
3225        let (_workspace, _thread_store, thread, context_store, model) =
3226            setup_test_environment(cx, project.clone()).await;
3227
3228        // Open buffer and add it to context
3229        let buffer = add_file_to_context(&project, &context_store, "test/code.rs", cx)
3230            .await
3231            .unwrap();
3232
3233        let context =
3234            context_store.read_with(cx, |store, _| store.context().next().cloned().unwrap());
3235        let loaded_context = cx
3236            .update(|cx| load_context(vec![context], &project, &None, cx))
3237            .await;
3238
3239        // Insert user message with the buffer as context
3240        thread.update(cx, |thread, cx| {
3241            thread.insert_user_message("Explain this code", loaded_context, None, Vec::new(), cx)
3242        });
3243
3244        // Create a request and check that it doesn't have a stale buffer warning yet
3245        let initial_request = thread.update(cx, |thread, cx| {
3246            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3247        });
3248
3249        // Make sure we don't have a stale file warning yet
3250        let has_stale_warning = initial_request.messages.iter().any(|msg| {
3251            msg.string_contents()
3252                .contains("These files changed since last read:")
3253        });
3254        assert!(
3255            !has_stale_warning,
3256            "Should not have stale buffer warning before buffer is modified"
3257        );
3258
3259        // Modify the buffer
3260        buffer.update(cx, |buffer, cx| {
3261            // Find a position at the end of line 1
3262            buffer.edit(
3263                [(1..1, "\n    println!(\"Added a new line\");\n")],
3264                None,
3265                cx,
3266            );
3267        });
3268
3269        // Insert another user message without context
3270        thread.update(cx, |thread, cx| {
3271            thread.insert_user_message(
3272                "What does the code do now?",
3273                ContextLoadResult::default(),
3274                None,
3275                Vec::new(),
3276                cx,
3277            )
3278        });
3279
3280        // Create a new request and check for the stale buffer warning
3281        let new_request = thread.update(cx, |thread, cx| {
3282            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3283        });
3284
3285        // We should have a stale file warning as the last message
3286        let last_message = new_request
3287            .messages
3288            .last()
3289            .expect("Request should have messages");
3290
3291        // The last message should be the stale buffer notification
3292        assert_eq!(last_message.role, Role::User);
3293
3294        // Check the exact content of the message
3295        let expected_content = "These files changed since last read:\n- code.rs\n";
3296        assert_eq!(
3297            last_message.string_contents(),
3298            expected_content,
3299            "Last message should be exactly the stale buffer notification"
3300        );
3301    }
3302
3303    #[gpui::test]
3304    async fn test_storing_profile_setting_per_thread(cx: &mut TestAppContext) {
3305        init_test_settings(cx);
3306
3307        let project = create_test_project(
3308            cx,
3309            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3310        )
3311        .await;
3312
3313        let (_workspace, thread_store, thread, _context_store, _model) =
3314            setup_test_environment(cx, project.clone()).await;
3315
3316        // Check that we are starting with the default profile
3317        let profile = cx.read(|cx| thread.read(cx).profile.clone());
3318        let tool_set = cx.read(|cx| thread_store.read(cx).tools());
3319        assert_eq!(
3320            profile,
3321            AgentProfile::new(AgentProfileId::default(), tool_set)
3322        );
3323    }
3324
3325    #[gpui::test]
3326    async fn test_serializing_thread_profile(cx: &mut TestAppContext) {
3327        init_test_settings(cx);
3328
3329        let project = create_test_project(
3330            cx,
3331            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3332        )
3333        .await;
3334
3335        let (_workspace, thread_store, thread, _context_store, _model) =
3336            setup_test_environment(cx, project.clone()).await;
3337
3338        // Profile gets serialized with default values
3339        let serialized = thread
3340            .update(cx, |thread, cx| thread.serialize(cx))
3341            .await
3342            .unwrap();
3343
3344        assert_eq!(serialized.profile, Some(AgentProfileId::default()));
3345
3346        let deserialized = cx.update(|cx| {
3347            thread.update(cx, |thread, cx| {
3348                Thread::deserialize(
3349                    thread.id.clone(),
3350                    serialized,
3351                    thread.project.clone(),
3352                    thread.tools.clone(),
3353                    thread.prompt_builder.clone(),
3354                    thread.project_context.clone(),
3355                    None,
3356                    cx,
3357                )
3358            })
3359        });
3360        let tool_set = cx.read(|cx| thread_store.read(cx).tools());
3361
3362        assert_eq!(
3363            deserialized.profile,
3364            AgentProfile::new(AgentProfileId::default(), tool_set)
3365        );
3366    }
3367
3368    #[gpui::test]
3369    async fn test_temperature_setting(cx: &mut TestAppContext) {
3370        init_test_settings(cx);
3371
3372        let project = create_test_project(
3373            cx,
3374            json!({"code.rs": "fn main() {\n    println!(\"Hello, world!\");\n}"}),
3375        )
3376        .await;
3377
3378        let (_workspace, _thread_store, thread, _context_store, model) =
3379            setup_test_environment(cx, project.clone()).await;
3380
3381        // Both model and provider
3382        cx.update(|cx| {
3383            AgentSettings::override_global(
3384                AgentSettings {
3385                    model_parameters: vec![LanguageModelParameters {
3386                        provider: Some(model.provider_id().0.to_string().into()),
3387                        model: Some(model.id().0.clone()),
3388                        temperature: Some(0.66),
3389                    }],
3390                    ..AgentSettings::get_global(cx).clone()
3391                },
3392                cx,
3393            );
3394        });
3395
3396        let request = thread.update(cx, |thread, cx| {
3397            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3398        });
3399        assert_eq!(request.temperature, Some(0.66));
3400
3401        // Only model
3402        cx.update(|cx| {
3403            AgentSettings::override_global(
3404                AgentSettings {
3405                    model_parameters: vec![LanguageModelParameters {
3406                        provider: None,
3407                        model: Some(model.id().0.clone()),
3408                        temperature: Some(0.66),
3409                    }],
3410                    ..AgentSettings::get_global(cx).clone()
3411                },
3412                cx,
3413            );
3414        });
3415
3416        let request = thread.update(cx, |thread, cx| {
3417            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3418        });
3419        assert_eq!(request.temperature, Some(0.66));
3420
3421        // Only provider
3422        cx.update(|cx| {
3423            AgentSettings::override_global(
3424                AgentSettings {
3425                    model_parameters: vec![LanguageModelParameters {
3426                        provider: Some(model.provider_id().0.to_string().into()),
3427                        model: None,
3428                        temperature: Some(0.66),
3429                    }],
3430                    ..AgentSettings::get_global(cx).clone()
3431                },
3432                cx,
3433            );
3434        });
3435
3436        let request = thread.update(cx, |thread, cx| {
3437            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3438        });
3439        assert_eq!(request.temperature, Some(0.66));
3440
3441        // Same model name, different provider
3442        cx.update(|cx| {
3443            AgentSettings::override_global(
3444                AgentSettings {
3445                    model_parameters: vec![LanguageModelParameters {
3446                        provider: Some("anthropic".into()),
3447                        model: Some(model.id().0.clone()),
3448                        temperature: Some(0.66),
3449                    }],
3450                    ..AgentSettings::get_global(cx).clone()
3451                },
3452                cx,
3453            );
3454        });
3455
3456        let request = thread.update(cx, |thread, cx| {
3457            thread.to_completion_request(model.clone(), CompletionIntent::UserPrompt, cx)
3458        });
3459        assert_eq!(request.temperature, None);
3460    }
3461
3462    #[gpui::test]
3463    async fn test_thread_summary(cx: &mut TestAppContext) {
3464        init_test_settings(cx);
3465
3466        let project = create_test_project(cx, json!({})).await;
3467
3468        let (_, _thread_store, thread, _context_store, model) =
3469            setup_test_environment(cx, project.clone()).await;
3470
3471        // Initial state should be pending
3472        thread.read_with(cx, |thread, _| {
3473            assert!(matches!(thread.summary(), ThreadSummary::Pending));
3474            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
3475        });
3476
3477        // Manually setting the summary should not be allowed in this state
3478        thread.update(cx, |thread, cx| {
3479            thread.set_summary("This should not work", cx);
3480        });
3481
3482        thread.read_with(cx, |thread, _| {
3483            assert!(matches!(thread.summary(), ThreadSummary::Pending));
3484        });
3485
3486        // Send a message
3487        thread.update(cx, |thread, cx| {
3488            thread.insert_user_message("Hi!", ContextLoadResult::default(), None, vec![], cx);
3489            thread.send_to_model(
3490                model.clone(),
3491                CompletionIntent::ThreadSummarization,
3492                None,
3493                cx,
3494            );
3495        });
3496
3497        let fake_model = model.as_fake();
3498        simulate_successful_response(&fake_model, cx);
3499
3500        // Should start generating summary when there are >= 2 messages
3501        thread.read_with(cx, |thread, _| {
3502            assert_eq!(*thread.summary(), ThreadSummary::Generating);
3503        });
3504
3505        // Should not be able to set the summary while generating
3506        thread.update(cx, |thread, cx| {
3507            thread.set_summary("This should not work either", cx);
3508        });
3509
3510        thread.read_with(cx, |thread, _| {
3511            assert!(matches!(thread.summary(), ThreadSummary::Generating));
3512            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
3513        });
3514
3515        cx.run_until_parked();
3516        fake_model.stream_last_completion_response("Brief");
3517        fake_model.stream_last_completion_response(" Introduction");
3518        fake_model.end_last_completion_stream();
3519        cx.run_until_parked();
3520
3521        // Summary should be set
3522        thread.read_with(cx, |thread, _| {
3523            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
3524            assert_eq!(thread.summary().or_default(), "Brief Introduction");
3525        });
3526
3527        // Now we should be able to set a summary
3528        thread.update(cx, |thread, cx| {
3529            thread.set_summary("Brief Intro", cx);
3530        });
3531
3532        thread.read_with(cx, |thread, _| {
3533            assert_eq!(thread.summary().or_default(), "Brief Intro");
3534        });
3535
3536        // Test setting an empty summary (should default to DEFAULT)
3537        thread.update(cx, |thread, cx| {
3538            thread.set_summary("", cx);
3539        });
3540
3541        thread.read_with(cx, |thread, _| {
3542            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
3543            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
3544        });
3545    }
3546
3547    #[gpui::test]
3548    async fn test_thread_summary_error_set_manually(cx: &mut TestAppContext) {
3549        init_test_settings(cx);
3550
3551        let project = create_test_project(cx, json!({})).await;
3552
3553        let (_, _thread_store, thread, _context_store, model) =
3554            setup_test_environment(cx, project.clone()).await;
3555
3556        test_summarize_error(&model, &thread, cx);
3557
3558        // Now we should be able to set a summary
3559        thread.update(cx, |thread, cx| {
3560            thread.set_summary("Brief Intro", cx);
3561        });
3562
3563        thread.read_with(cx, |thread, _| {
3564            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
3565            assert_eq!(thread.summary().or_default(), "Brief Intro");
3566        });
3567    }
3568
3569    #[gpui::test]
3570    async fn test_thread_summary_error_retry(cx: &mut TestAppContext) {
3571        init_test_settings(cx);
3572
3573        let project = create_test_project(cx, json!({})).await;
3574
3575        let (_, _thread_store, thread, _context_store, model) =
3576            setup_test_environment(cx, project.clone()).await;
3577
3578        test_summarize_error(&model, &thread, cx);
3579
3580        // Sending another message should not trigger another summarize request
3581        thread.update(cx, |thread, cx| {
3582            thread.insert_user_message(
3583                "How are you?",
3584                ContextLoadResult::default(),
3585                None,
3586                vec![],
3587                cx,
3588            );
3589            thread.send_to_model(model.clone(), CompletionIntent::UserPrompt, None, cx);
3590        });
3591
3592        let fake_model = model.as_fake();
3593        simulate_successful_response(&fake_model, cx);
3594
3595        thread.read_with(cx, |thread, _| {
3596            // State is still Error, not Generating
3597            assert!(matches!(thread.summary(), ThreadSummary::Error));
3598        });
3599
3600        // But the summarize request can be invoked manually
3601        thread.update(cx, |thread, cx| {
3602            thread.summarize(cx);
3603        });
3604
3605        thread.read_with(cx, |thread, _| {
3606            assert!(matches!(thread.summary(), ThreadSummary::Generating));
3607        });
3608
3609        cx.run_until_parked();
3610        fake_model.stream_last_completion_response("A successful summary");
3611        fake_model.end_last_completion_stream();
3612        cx.run_until_parked();
3613
3614        thread.read_with(cx, |thread, _| {
3615            assert!(matches!(thread.summary(), ThreadSummary::Ready(_)));
3616            assert_eq!(thread.summary().or_default(), "A successful summary");
3617        });
3618    }
3619
3620    fn test_summarize_error(
3621        model: &Arc<dyn LanguageModel>,
3622        thread: &Entity<Thread>,
3623        cx: &mut TestAppContext,
3624    ) {
3625        thread.update(cx, |thread, cx| {
3626            thread.insert_user_message("Hi!", ContextLoadResult::default(), None, vec![], cx);
3627            thread.send_to_model(
3628                model.clone(),
3629                CompletionIntent::ThreadSummarization,
3630                None,
3631                cx,
3632            );
3633        });
3634
3635        let fake_model = model.as_fake();
3636        simulate_successful_response(&fake_model, cx);
3637
3638        thread.read_with(cx, |thread, _| {
3639            assert!(matches!(thread.summary(), ThreadSummary::Generating));
3640            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
3641        });
3642
3643        // Simulate summary request ending
3644        cx.run_until_parked();
3645        fake_model.end_last_completion_stream();
3646        cx.run_until_parked();
3647
3648        // State is set to Error and default message
3649        thread.read_with(cx, |thread, _| {
3650            assert!(matches!(thread.summary(), ThreadSummary::Error));
3651            assert_eq!(thread.summary().or_default(), ThreadSummary::DEFAULT);
3652        });
3653    }
3654
3655    fn simulate_successful_response(fake_model: &FakeLanguageModel, cx: &mut TestAppContext) {
3656        cx.run_until_parked();
3657        fake_model.stream_last_completion_response("Assistant response");
3658        fake_model.end_last_completion_stream();
3659        cx.run_until_parked();
3660    }
3661
3662    fn init_test_settings(cx: &mut TestAppContext) {
3663        cx.update(|cx| {
3664            let settings_store = SettingsStore::test(cx);
3665            cx.set_global(settings_store);
3666            language::init(cx);
3667            Project::init_settings(cx);
3668            AgentSettings::register(cx);
3669            prompt_store::init(cx);
3670            thread_store::init(cx);
3671            workspace::init_settings(cx);
3672            language_model::init_settings(cx);
3673            ThemeSettings::register(cx);
3674            EditorSettings::register(cx);
3675            ToolRegistry::default_global(cx);
3676        });
3677    }
3678
3679    // Helper to create a test project with test files
3680    async fn create_test_project(
3681        cx: &mut TestAppContext,
3682        files: serde_json::Value,
3683    ) -> Entity<Project> {
3684        let fs = FakeFs::new(cx.executor());
3685        fs.insert_tree(path!("/test"), files).await;
3686        Project::test(fs, [path!("/test").as_ref()], cx).await
3687    }
3688
3689    async fn setup_test_environment(
3690        cx: &mut TestAppContext,
3691        project: Entity<Project>,
3692    ) -> (
3693        Entity<Workspace>,
3694        Entity<ThreadStore>,
3695        Entity<Thread>,
3696        Entity<ContextStore>,
3697        Arc<dyn LanguageModel>,
3698    ) {
3699        let (workspace, cx) =
3700            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3701
3702        let thread_store = cx
3703            .update(|_, cx| {
3704                ThreadStore::load(
3705                    project.clone(),
3706                    cx.new(|_| ToolWorkingSet::default()),
3707                    None,
3708                    Arc::new(PromptBuilder::new(None).unwrap()),
3709                    cx,
3710                )
3711            })
3712            .await
3713            .unwrap();
3714
3715        let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
3716        let context_store = cx.new(|_cx| ContextStore::new(project.downgrade(), None));
3717
3718        let provider = Arc::new(FakeLanguageModelProvider);
3719        let model = provider.test_model();
3720        let model: Arc<dyn LanguageModel> = Arc::new(model);
3721
3722        cx.update(|_, cx| {
3723            LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
3724                registry.set_default_model(
3725                    Some(ConfiguredModel {
3726                        provider: provider.clone(),
3727                        model: model.clone(),
3728                    }),
3729                    cx,
3730                );
3731                registry.set_thread_summary_model(
3732                    Some(ConfiguredModel {
3733                        provider,
3734                        model: model.clone(),
3735                    }),
3736                    cx,
3737                );
3738            })
3739        });
3740
3741        (workspace, thread_store, thread, context_store, model)
3742    }
3743
3744    async fn add_file_to_context(
3745        project: &Entity<Project>,
3746        context_store: &Entity<ContextStore>,
3747        path: &str,
3748        cx: &mut TestAppContext,
3749    ) -> Result<Entity<language::Buffer>> {
3750        let buffer_path = project
3751            .read_with(cx, |project, cx| project.find_project_path(path, cx))
3752            .unwrap();
3753
3754        let buffer = project
3755            .update(cx, |project, cx| {
3756                project.open_buffer(buffer_path.clone(), cx)
3757            })
3758            .await
3759            .unwrap();
3760
3761        context_store.update(cx, |context_store, cx| {
3762            context_store.add_file_from_buffer(&buffer_path, buffer.clone(), false, cx);
3763        });
3764
3765        Ok(buffer)
3766    }
3767}