thread.rs

   1use std::fmt::Write as _;
   2use std::io::Write;
   3use std::ops::Range;
   4use std::sync::Arc;
   5
   6use anyhow::{Context as _, Result};
   7use assistant_settings::AssistantSettings;
   8use assistant_tool::{ActionLog, Tool, ToolWorkingSet};
   9use chrono::{DateTime, Utc};
  10use collections::{BTreeMap, HashMap, HashSet};
  11use fs::Fs;
  12use futures::future::Shared;
  13use futures::{FutureExt, StreamExt as _};
  14use git;
  15use gpui::{App, AppContext, Context, Entity, EventEmitter, SharedString, Task, WeakEntity};
  16use language_model::{
  17    LanguageModel, LanguageModelCompletionEvent, LanguageModelRegistry, LanguageModelRequest,
  18    LanguageModelRequestMessage, LanguageModelRequestTool, LanguageModelToolResult,
  19    LanguageModelToolUseId, MaxMonthlySpendReachedError, MessageContent, PaymentRequiredError,
  20    Role, StopReason, TokenUsage,
  21};
  22use project::git_store::{GitStore, GitStoreCheckpoint};
  23use project::{Project, Worktree};
  24use prompt_store::{
  25    AssistantSystemPromptContext, PromptBuilder, RulesFile, WorktreeInfoForSystemPrompt,
  26};
  27use serde::{Deserialize, Serialize};
  28use settings::Settings;
  29use util::{ResultExt as _, TryFutureExt as _, maybe, post_inc};
  30use uuid::Uuid;
  31
  32use crate::context::{ContextId, ContextSnapshot, attach_context_to_message};
  33use crate::thread_store::{
  34    SerializedMessage, SerializedMessageSegment, SerializedThread, SerializedToolResult,
  35    SerializedToolUse,
  36};
  37use crate::tool_use::{PendingToolUse, ToolUse, ToolUseState};
  38
  39#[derive(Debug, Clone, Copy)]
  40pub enum RequestKind {
  41    Chat,
  42    /// Used when summarizing a thread.
  43    Summarize,
  44}
  45
  46#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
  47pub struct ThreadId(Arc<str>);
  48
  49impl ThreadId {
  50    pub fn new() -> Self {
  51        Self(Uuid::new_v4().to_string().into())
  52    }
  53}
  54
  55impl std::fmt::Display for ThreadId {
  56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  57        write!(f, "{}", self.0)
  58    }
  59}
  60
  61#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
  62pub struct MessageId(pub(crate) usize);
  63
  64impl MessageId {
  65    fn post_inc(&mut self) -> Self {
  66        Self(post_inc(&mut self.0))
  67    }
  68}
  69
  70/// A message in a [`Thread`].
  71#[derive(Debug, Clone)]
  72pub struct Message {
  73    pub id: MessageId,
  74    pub role: Role,
  75    pub segments: Vec<MessageSegment>,
  76}
  77
  78impl Message {
  79    pub fn push_thinking(&mut self, text: &str) {
  80        if let Some(MessageSegment::Thinking(segment)) = self.segments.last_mut() {
  81            segment.push_str(text);
  82        } else {
  83            self.segments
  84                .push(MessageSegment::Thinking(text.to_string()));
  85        }
  86    }
  87
  88    pub fn push_text(&mut self, text: &str) {
  89        if let Some(MessageSegment::Text(segment)) = self.segments.last_mut() {
  90            segment.push_str(text);
  91        } else {
  92            self.segments.push(MessageSegment::Text(text.to_string()));
  93        }
  94    }
  95
  96    pub fn to_string(&self) -> String {
  97        let mut result = String::new();
  98        for segment in &self.segments {
  99            match segment {
 100                MessageSegment::Text(text) => result.push_str(text),
 101                MessageSegment::Thinking(text) => {
 102                    result.push_str("<think>");
 103                    result.push_str(text);
 104                    result.push_str("</think>");
 105                }
 106            }
 107        }
 108        result
 109    }
 110}
 111
 112#[derive(Debug, Clone)]
 113pub enum MessageSegment {
 114    Text(String),
 115    Thinking(String),
 116}
 117
 118#[derive(Debug, Clone, Serialize, Deserialize)]
 119pub struct ProjectSnapshot {
 120    pub worktree_snapshots: Vec<WorktreeSnapshot>,
 121    pub unsaved_buffer_paths: Vec<String>,
 122    pub timestamp: DateTime<Utc>,
 123}
 124
 125#[derive(Debug, Clone, Serialize, Deserialize)]
 126pub struct WorktreeSnapshot {
 127    pub worktree_path: String,
 128    pub git_state: Option<GitState>,
 129}
 130
 131#[derive(Debug, Clone, Serialize, Deserialize)]
 132pub struct GitState {
 133    pub remote_url: Option<String>,
 134    pub head_sha: Option<String>,
 135    pub current_branch: Option<String>,
 136    pub diff: Option<String>,
 137}
 138
 139#[derive(Clone)]
 140pub struct ThreadCheckpoint {
 141    message_id: MessageId,
 142    git_checkpoint: GitStoreCheckpoint,
 143}
 144
 145#[derive(Copy, Clone, Debug)]
 146pub enum ThreadFeedback {
 147    Positive,
 148    Negative,
 149}
 150
 151pub enum LastRestoreCheckpoint {
 152    Pending {
 153        message_id: MessageId,
 154    },
 155    Error {
 156        message_id: MessageId,
 157        error: String,
 158    },
 159}
 160
 161impl LastRestoreCheckpoint {
 162    pub fn message_id(&self) -> MessageId {
 163        match self {
 164            LastRestoreCheckpoint::Pending { message_id } => *message_id,
 165            LastRestoreCheckpoint::Error { message_id, .. } => *message_id,
 166        }
 167    }
 168}
 169
 170/// A thread of conversation with the LLM.
 171pub struct Thread {
 172    id: ThreadId,
 173    updated_at: DateTime<Utc>,
 174    summary: Option<SharedString>,
 175    pending_summary: Task<Option<()>>,
 176    messages: Vec<Message>,
 177    next_message_id: MessageId,
 178    context: BTreeMap<ContextId, ContextSnapshot>,
 179    context_by_message: HashMap<MessageId, Vec<ContextId>>,
 180    system_prompt_context: Option<AssistantSystemPromptContext>,
 181    checkpoints_by_message: HashMap<MessageId, ThreadCheckpoint>,
 182    completion_count: usize,
 183    pending_completions: Vec<PendingCompletion>,
 184    project: Entity<Project>,
 185    prompt_builder: Arc<PromptBuilder>,
 186    tools: Arc<ToolWorkingSet>,
 187    tool_use: ToolUseState,
 188    action_log: Entity<ActionLog>,
 189    last_restore_checkpoint: Option<LastRestoreCheckpoint>,
 190    pending_checkpoint: Option<ThreadCheckpoint>,
 191    initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
 192    cumulative_token_usage: TokenUsage,
 193    feedback: Option<ThreadFeedback>,
 194}
 195
 196impl Thread {
 197    pub fn new(
 198        project: Entity<Project>,
 199        tools: Arc<ToolWorkingSet>,
 200        prompt_builder: Arc<PromptBuilder>,
 201        cx: &mut Context<Self>,
 202    ) -> Self {
 203        Self {
 204            id: ThreadId::new(),
 205            updated_at: Utc::now(),
 206            summary: None,
 207            pending_summary: Task::ready(None),
 208            messages: Vec::new(),
 209            next_message_id: MessageId(0),
 210            context: BTreeMap::default(),
 211            context_by_message: HashMap::default(),
 212            system_prompt_context: None,
 213            checkpoints_by_message: HashMap::default(),
 214            completion_count: 0,
 215            pending_completions: Vec::new(),
 216            project: project.clone(),
 217            prompt_builder,
 218            tools: tools.clone(),
 219            last_restore_checkpoint: None,
 220            pending_checkpoint: None,
 221            tool_use: ToolUseState::new(tools.clone()),
 222            action_log: cx.new(|_| ActionLog::new()),
 223            initial_project_snapshot: {
 224                let project_snapshot = Self::project_snapshot(project, cx);
 225                cx.foreground_executor()
 226                    .spawn(async move { Some(project_snapshot.await) })
 227                    .shared()
 228            },
 229            cumulative_token_usage: TokenUsage::default(),
 230            feedback: None,
 231        }
 232    }
 233
 234    pub fn deserialize(
 235        id: ThreadId,
 236        serialized: SerializedThread,
 237        project: Entity<Project>,
 238        tools: Arc<ToolWorkingSet>,
 239        prompt_builder: Arc<PromptBuilder>,
 240        cx: &mut Context<Self>,
 241    ) -> Self {
 242        let next_message_id = MessageId(
 243            serialized
 244                .messages
 245                .last()
 246                .map(|message| message.id.0 + 1)
 247                .unwrap_or(0),
 248        );
 249        let tool_use =
 250            ToolUseState::from_serialized_messages(tools.clone(), &serialized.messages, |_| true);
 251
 252        Self {
 253            id,
 254            updated_at: serialized.updated_at,
 255            summary: Some(serialized.summary),
 256            pending_summary: Task::ready(None),
 257            messages: serialized
 258                .messages
 259                .into_iter()
 260                .map(|message| Message {
 261                    id: message.id,
 262                    role: message.role,
 263                    segments: message
 264                        .segments
 265                        .into_iter()
 266                        .map(|segment| match segment {
 267                            SerializedMessageSegment::Text { text } => MessageSegment::Text(text),
 268                            SerializedMessageSegment::Thinking { text } => {
 269                                MessageSegment::Thinking(text)
 270                            }
 271                        })
 272                        .collect(),
 273                })
 274                .collect(),
 275            next_message_id,
 276            context: BTreeMap::default(),
 277            context_by_message: HashMap::default(),
 278            system_prompt_context: None,
 279            checkpoints_by_message: HashMap::default(),
 280            completion_count: 0,
 281            pending_completions: Vec::new(),
 282            last_restore_checkpoint: None,
 283            pending_checkpoint: None,
 284            project,
 285            prompt_builder,
 286            tools,
 287            tool_use,
 288            action_log: cx.new(|_| ActionLog::new()),
 289            initial_project_snapshot: Task::ready(serialized.initial_project_snapshot).shared(),
 290            cumulative_token_usage: serialized.cumulative_token_usage,
 291            feedback: None,
 292        }
 293    }
 294
 295    pub fn id(&self) -> &ThreadId {
 296        &self.id
 297    }
 298
 299    pub fn is_empty(&self) -> bool {
 300        self.messages.is_empty()
 301    }
 302
 303    pub fn updated_at(&self) -> DateTime<Utc> {
 304        self.updated_at
 305    }
 306
 307    pub fn touch_updated_at(&mut self) {
 308        self.updated_at = Utc::now();
 309    }
 310
 311    pub fn summary(&self) -> Option<SharedString> {
 312        self.summary.clone()
 313    }
 314
 315    pub fn summary_or_default(&self) -> SharedString {
 316        const DEFAULT: SharedString = SharedString::new_static("New Thread");
 317        self.summary.clone().unwrap_or(DEFAULT)
 318    }
 319
 320    pub fn set_summary(&mut self, summary: impl Into<SharedString>, cx: &mut Context<Self>) {
 321        self.summary = Some(summary.into());
 322        cx.emit(ThreadEvent::SummaryChanged);
 323    }
 324
 325    pub fn message(&self, id: MessageId) -> Option<&Message> {
 326        self.messages.iter().find(|message| message.id == id)
 327    }
 328
 329    pub fn messages(&self) -> impl Iterator<Item = &Message> {
 330        self.messages.iter()
 331    }
 332
 333    pub fn is_generating(&self) -> bool {
 334        !self.pending_completions.is_empty() || !self.all_tools_finished()
 335    }
 336
 337    pub fn tools(&self) -> &Arc<ToolWorkingSet> {
 338        &self.tools
 339    }
 340
 341    pub fn pending_tool(&self, id: &LanguageModelToolUseId) -> Option<&PendingToolUse> {
 342        self.tool_use
 343            .pending_tool_uses()
 344            .into_iter()
 345            .find(|tool_use| &tool_use.id == id)
 346    }
 347
 348    pub fn tools_needing_confirmation(&self) -> impl Iterator<Item = &PendingToolUse> {
 349        self.tool_use
 350            .pending_tool_uses()
 351            .into_iter()
 352            .filter(|tool_use| tool_use.status.needs_confirmation())
 353    }
 354
 355    pub fn has_pending_tool_uses(&self) -> bool {
 356        !self.tool_use.pending_tool_uses().is_empty()
 357    }
 358
 359    pub fn checkpoint_for_message(&self, id: MessageId) -> Option<ThreadCheckpoint> {
 360        self.checkpoints_by_message.get(&id).cloned()
 361    }
 362
 363    pub fn restore_checkpoint(
 364        &mut self,
 365        checkpoint: ThreadCheckpoint,
 366        cx: &mut Context<Self>,
 367    ) -> Task<Result<()>> {
 368        self.last_restore_checkpoint = Some(LastRestoreCheckpoint::Pending {
 369            message_id: checkpoint.message_id,
 370        });
 371        cx.emit(ThreadEvent::CheckpointChanged);
 372        cx.notify();
 373
 374        let project = self.project.read(cx);
 375        let restore = project
 376            .git_store()
 377            .read(cx)
 378            .restore_checkpoint(checkpoint.git_checkpoint.clone(), cx);
 379        cx.spawn(async move |this, cx| {
 380            let result = restore.await;
 381            this.update(cx, |this, cx| {
 382                if let Err(err) = result.as_ref() {
 383                    this.last_restore_checkpoint = Some(LastRestoreCheckpoint::Error {
 384                        message_id: checkpoint.message_id,
 385                        error: err.to_string(),
 386                    });
 387                } else {
 388                    this.truncate(checkpoint.message_id, cx);
 389                    this.last_restore_checkpoint = None;
 390                }
 391                this.pending_checkpoint = None;
 392                cx.emit(ThreadEvent::CheckpointChanged);
 393                cx.notify();
 394            })?;
 395            result
 396        })
 397    }
 398
 399    fn finalize_pending_checkpoint(&mut self, cx: &mut Context<Self>) {
 400        let pending_checkpoint = if self.is_generating() {
 401            return;
 402        } else if let Some(checkpoint) = self.pending_checkpoint.take() {
 403            checkpoint
 404        } else {
 405            return;
 406        };
 407
 408        let git_store = self.project.read(cx).git_store().clone();
 409        let final_checkpoint = git_store.read(cx).checkpoint(cx);
 410        cx.spawn(async move |this, cx| match final_checkpoint.await {
 411            Ok(final_checkpoint) => {
 412                let equal = git_store
 413                    .read_with(cx, |store, cx| {
 414                        store.compare_checkpoints(
 415                            pending_checkpoint.git_checkpoint.clone(),
 416                            final_checkpoint.clone(),
 417                            cx,
 418                        )
 419                    })?
 420                    .await
 421                    .unwrap_or(false);
 422
 423                if equal {
 424                    git_store
 425                        .read_with(cx, |store, cx| {
 426                            store.delete_checkpoint(pending_checkpoint.git_checkpoint, cx)
 427                        })?
 428                        .detach();
 429                } else {
 430                    this.update(cx, |this, cx| {
 431                        this.insert_checkpoint(pending_checkpoint, cx)
 432                    })?;
 433                }
 434
 435                git_store
 436                    .read_with(cx, |store, cx| {
 437                        store.delete_checkpoint(final_checkpoint, cx)
 438                    })?
 439                    .detach();
 440
 441                Ok(())
 442            }
 443            Err(_) => this.update(cx, |this, cx| {
 444                this.insert_checkpoint(pending_checkpoint, cx)
 445            }),
 446        })
 447        .detach();
 448    }
 449
 450    fn insert_checkpoint(&mut self, checkpoint: ThreadCheckpoint, cx: &mut Context<Self>) {
 451        self.checkpoints_by_message
 452            .insert(checkpoint.message_id, checkpoint);
 453        cx.emit(ThreadEvent::CheckpointChanged);
 454        cx.notify();
 455    }
 456
 457    pub fn last_restore_checkpoint(&self) -> Option<&LastRestoreCheckpoint> {
 458        self.last_restore_checkpoint.as_ref()
 459    }
 460
 461    pub fn truncate(&mut self, message_id: MessageId, cx: &mut Context<Self>) {
 462        let Some(message_ix) = self
 463            .messages
 464            .iter()
 465            .rposition(|message| message.id == message_id)
 466        else {
 467            return;
 468        };
 469        for deleted_message in self.messages.drain(message_ix..) {
 470            self.context_by_message.remove(&deleted_message.id);
 471            self.checkpoints_by_message.remove(&deleted_message.id);
 472        }
 473        cx.notify();
 474    }
 475
 476    pub fn context_for_message(&self, id: MessageId) -> Option<Vec<ContextSnapshot>> {
 477        let context = self.context_by_message.get(&id)?;
 478        Some(
 479            context
 480                .into_iter()
 481                .filter_map(|context_id| self.context.get(&context_id))
 482                .cloned()
 483                .collect::<Vec<_>>(),
 484        )
 485    }
 486
 487    /// Returns whether all of the tool uses have finished running.
 488    pub fn all_tools_finished(&self) -> bool {
 489        // If the only pending tool uses left are the ones with errors, then
 490        // that means that we've finished running all of the pending tools.
 491        self.tool_use
 492            .pending_tool_uses()
 493            .iter()
 494            .all(|tool_use| tool_use.status.is_error())
 495    }
 496
 497    pub fn tool_uses_for_message(&self, id: MessageId, cx: &App) -> Vec<ToolUse> {
 498        self.tool_use.tool_uses_for_message(id, cx)
 499    }
 500
 501    pub fn tool_results_for_message(&self, id: MessageId) -> Vec<&LanguageModelToolResult> {
 502        self.tool_use.tool_results_for_message(id)
 503    }
 504
 505    pub fn tool_result(&self, id: &LanguageModelToolUseId) -> Option<&LanguageModelToolResult> {
 506        self.tool_use.tool_result(id)
 507    }
 508
 509    pub fn message_has_tool_results(&self, message_id: MessageId) -> bool {
 510        self.tool_use.message_has_tool_results(message_id)
 511    }
 512
 513    pub fn insert_user_message(
 514        &mut self,
 515        text: impl Into<String>,
 516        context: Vec<ContextSnapshot>,
 517        git_checkpoint: Option<GitStoreCheckpoint>,
 518        cx: &mut Context<Self>,
 519    ) -> MessageId {
 520        let message_id =
 521            self.insert_message(Role::User, vec![MessageSegment::Text(text.into())], cx);
 522        let context_ids = context.iter().map(|context| context.id).collect::<Vec<_>>();
 523        self.context
 524            .extend(context.into_iter().map(|context| (context.id, context)));
 525        self.context_by_message.insert(message_id, context_ids);
 526        if let Some(git_checkpoint) = git_checkpoint {
 527            self.pending_checkpoint = Some(ThreadCheckpoint {
 528                message_id,
 529                git_checkpoint,
 530            });
 531        }
 532        message_id
 533    }
 534
 535    pub fn insert_message(
 536        &mut self,
 537        role: Role,
 538        segments: Vec<MessageSegment>,
 539        cx: &mut Context<Self>,
 540    ) -> MessageId {
 541        let id = self.next_message_id.post_inc();
 542        self.messages.push(Message { id, role, segments });
 543        self.touch_updated_at();
 544        cx.emit(ThreadEvent::MessageAdded(id));
 545        id
 546    }
 547
 548    pub fn edit_message(
 549        &mut self,
 550        id: MessageId,
 551        new_role: Role,
 552        new_segments: Vec<MessageSegment>,
 553        cx: &mut Context<Self>,
 554    ) -> bool {
 555        let Some(message) = self.messages.iter_mut().find(|message| message.id == id) else {
 556            return false;
 557        };
 558        message.role = new_role;
 559        message.segments = new_segments;
 560        self.touch_updated_at();
 561        cx.emit(ThreadEvent::MessageEdited(id));
 562        true
 563    }
 564
 565    pub fn delete_message(&mut self, id: MessageId, cx: &mut Context<Self>) -> bool {
 566        let Some(index) = self.messages.iter().position(|message| message.id == id) else {
 567            return false;
 568        };
 569        self.messages.remove(index);
 570        self.context_by_message.remove(&id);
 571        self.touch_updated_at();
 572        cx.emit(ThreadEvent::MessageDeleted(id));
 573        true
 574    }
 575
 576    /// Returns the representation of this [`Thread`] in a textual form.
 577    ///
 578    /// This is the representation we use when attaching a thread as context to another thread.
 579    pub fn text(&self) -> String {
 580        let mut text = String::new();
 581
 582        for message in &self.messages {
 583            text.push_str(match message.role {
 584                language_model::Role::User => "User:",
 585                language_model::Role::Assistant => "Assistant:",
 586                language_model::Role::System => "System:",
 587            });
 588            text.push('\n');
 589
 590            for segment in &message.segments {
 591                match segment {
 592                    MessageSegment::Text(content) => text.push_str(content),
 593                    MessageSegment::Thinking(content) => {
 594                        text.push_str(&format!("<think>{}</think>", content))
 595                    }
 596                }
 597            }
 598            text.push('\n');
 599        }
 600
 601        text
 602    }
 603
 604    /// Serializes this thread into a format for storage or telemetry.
 605    pub fn serialize(&self, cx: &mut Context<Self>) -> Task<Result<SerializedThread>> {
 606        let initial_project_snapshot = self.initial_project_snapshot.clone();
 607        cx.spawn(async move |this, cx| {
 608            let initial_project_snapshot = initial_project_snapshot.await;
 609            this.read_with(cx, |this, cx| SerializedThread {
 610                version: SerializedThread::VERSION.to_string(),
 611                summary: this.summary_or_default(),
 612                updated_at: this.updated_at(),
 613                messages: this
 614                    .messages()
 615                    .map(|message| SerializedMessage {
 616                        id: message.id,
 617                        role: message.role,
 618                        segments: message
 619                            .segments
 620                            .iter()
 621                            .map(|segment| match segment {
 622                                MessageSegment::Text(text) => {
 623                                    SerializedMessageSegment::Text { text: text.clone() }
 624                                }
 625                                MessageSegment::Thinking(text) => {
 626                                    SerializedMessageSegment::Thinking { text: text.clone() }
 627                                }
 628                            })
 629                            .collect(),
 630                        tool_uses: this
 631                            .tool_uses_for_message(message.id, cx)
 632                            .into_iter()
 633                            .map(|tool_use| SerializedToolUse {
 634                                id: tool_use.id,
 635                                name: tool_use.name,
 636                                input: tool_use.input,
 637                            })
 638                            .collect(),
 639                        tool_results: this
 640                            .tool_results_for_message(message.id)
 641                            .into_iter()
 642                            .map(|tool_result| SerializedToolResult {
 643                                tool_use_id: tool_result.tool_use_id.clone(),
 644                                is_error: tool_result.is_error,
 645                                content: tool_result.content.clone(),
 646                            })
 647                            .collect(),
 648                    })
 649                    .collect(),
 650                initial_project_snapshot,
 651                cumulative_token_usage: this.cumulative_token_usage.clone(),
 652            })
 653        })
 654    }
 655
 656    pub fn set_system_prompt_context(&mut self, context: AssistantSystemPromptContext) {
 657        self.system_prompt_context = Some(context);
 658    }
 659
 660    pub fn system_prompt_context(&self) -> &Option<AssistantSystemPromptContext> {
 661        &self.system_prompt_context
 662    }
 663
 664    pub fn load_system_prompt_context(
 665        &self,
 666        cx: &App,
 667    ) -> Task<(AssistantSystemPromptContext, Option<ThreadError>)> {
 668        let project = self.project.read(cx);
 669        let tasks = project
 670            .visible_worktrees(cx)
 671            .map(|worktree| {
 672                Self::load_worktree_info_for_system_prompt(
 673                    project.fs().clone(),
 674                    worktree.read(cx),
 675                    cx,
 676                )
 677            })
 678            .collect::<Vec<_>>();
 679
 680        cx.spawn(async |_cx| {
 681            let results = futures::future::join_all(tasks).await;
 682            let mut first_err = None;
 683            let worktrees = results
 684                .into_iter()
 685                .map(|(worktree, err)| {
 686                    if first_err.is_none() && err.is_some() {
 687                        first_err = err;
 688                    }
 689                    worktree
 690                })
 691                .collect::<Vec<_>>();
 692            (AssistantSystemPromptContext::new(worktrees), first_err)
 693        })
 694    }
 695
 696    fn load_worktree_info_for_system_prompt(
 697        fs: Arc<dyn Fs>,
 698        worktree: &Worktree,
 699        cx: &App,
 700    ) -> Task<(WorktreeInfoForSystemPrompt, Option<ThreadError>)> {
 701        let root_name = worktree.root_name().into();
 702        let abs_path = worktree.abs_path();
 703
 704        // Note that Cline supports `.clinerules` being a directory, but that is not currently
 705        // supported. This doesn't seem to occur often in GitHub repositories.
 706        const RULES_FILE_NAMES: [&'static str; 6] = [
 707            ".rules",
 708            ".cursorrules",
 709            ".windsurfrules",
 710            ".clinerules",
 711            ".github/copilot-instructions.md",
 712            "CLAUDE.md",
 713        ];
 714        let selected_rules_file = RULES_FILE_NAMES
 715            .into_iter()
 716            .filter_map(|name| {
 717                worktree
 718                    .entry_for_path(name)
 719                    .filter(|entry| entry.is_file())
 720                    .map(|entry| (entry.path.clone(), worktree.absolutize(&entry.path)))
 721            })
 722            .next();
 723
 724        if let Some((rel_rules_path, abs_rules_path)) = selected_rules_file {
 725            cx.spawn(async move |_| {
 726                let rules_file_result = maybe!(async move {
 727                    let abs_rules_path = abs_rules_path?;
 728                    let text = fs.load(&abs_rules_path).await.with_context(|| {
 729                        format!("Failed to load assistant rules file {:?}", abs_rules_path)
 730                    })?;
 731                    anyhow::Ok(RulesFile {
 732                        rel_path: rel_rules_path,
 733                        abs_path: abs_rules_path.into(),
 734                        text: text.trim().to_string(),
 735                    })
 736                })
 737                .await;
 738                let (rules_file, rules_file_error) = match rules_file_result {
 739                    Ok(rules_file) => (Some(rules_file), None),
 740                    Err(err) => (
 741                        None,
 742                        Some(ThreadError::Message {
 743                            header: "Error loading rules file".into(),
 744                            message: format!("{err}").into(),
 745                        }),
 746                    ),
 747                };
 748                let worktree_info = WorktreeInfoForSystemPrompt {
 749                    root_name,
 750                    abs_path,
 751                    rules_file,
 752                };
 753                (worktree_info, rules_file_error)
 754            })
 755        } else {
 756            Task::ready((
 757                WorktreeInfoForSystemPrompt {
 758                    root_name,
 759                    abs_path,
 760                    rules_file: None,
 761                },
 762                None,
 763            ))
 764        }
 765    }
 766
 767    pub fn send_to_model(
 768        &mut self,
 769        model: Arc<dyn LanguageModel>,
 770        request_kind: RequestKind,
 771        cx: &mut Context<Self>,
 772    ) {
 773        let mut request = self.to_completion_request(request_kind, cx);
 774        request.tools = {
 775            let mut tools = Vec::new();
 776            tools.extend(self.tools().enabled_tools(cx).into_iter().map(|tool| {
 777                LanguageModelRequestTool {
 778                    name: tool.name(),
 779                    description: tool.description(),
 780                    input_schema: tool.input_schema(model.tool_input_format()),
 781                }
 782            }));
 783
 784            tools
 785        };
 786
 787        self.stream_completion(request, model, cx);
 788    }
 789
 790    pub fn used_tools_since_last_user_message(&self) -> bool {
 791        for message in self.messages.iter().rev() {
 792            if self.tool_use.message_has_tool_results(message.id) {
 793                return true;
 794            } else if message.role == Role::User {
 795                return false;
 796            }
 797        }
 798
 799        false
 800    }
 801
 802    pub fn to_completion_request(
 803        &self,
 804        request_kind: RequestKind,
 805        cx: &App,
 806    ) -> LanguageModelRequest {
 807        let mut request = LanguageModelRequest {
 808            messages: vec![],
 809            tools: Vec::new(),
 810            stop: Vec::new(),
 811            temperature: None,
 812        };
 813
 814        if let Some(system_prompt_context) = self.system_prompt_context.as_ref() {
 815            if let Some(system_prompt) = self
 816                .prompt_builder
 817                .generate_assistant_system_prompt(system_prompt_context)
 818                .context("failed to generate assistant system prompt")
 819                .log_err()
 820            {
 821                request.messages.push(LanguageModelRequestMessage {
 822                    role: Role::System,
 823                    content: vec![MessageContent::Text(system_prompt)],
 824                    cache: true,
 825                });
 826            }
 827        } else {
 828            log::error!("system_prompt_context not set.")
 829        }
 830
 831        let mut referenced_context_ids = HashSet::default();
 832
 833        for message in &self.messages {
 834            if let Some(context_ids) = self.context_by_message.get(&message.id) {
 835                referenced_context_ids.extend(context_ids);
 836            }
 837
 838            let mut request_message = LanguageModelRequestMessage {
 839                role: message.role,
 840                content: Vec::new(),
 841                cache: false,
 842            };
 843
 844            match request_kind {
 845                RequestKind::Chat => {
 846                    self.tool_use
 847                        .attach_tool_results(message.id, &mut request_message);
 848                }
 849                RequestKind::Summarize => {
 850                    // We don't care about tool use during summarization.
 851                    if self.tool_use.message_has_tool_results(message.id) {
 852                        continue;
 853                    }
 854                }
 855            }
 856
 857            if !message.segments.is_empty() {
 858                request_message
 859                    .content
 860                    .push(MessageContent::Text(message.to_string()));
 861            }
 862
 863            match request_kind {
 864                RequestKind::Chat => {
 865                    self.tool_use
 866                        .attach_tool_uses(message.id, &mut request_message);
 867                }
 868                RequestKind::Summarize => {
 869                    // We don't care about tool use during summarization.
 870                }
 871            };
 872
 873            request.messages.push(request_message);
 874        }
 875
 876        // Set a cache breakpoint at the second-to-last message.
 877        // https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
 878        let breakpoint_index = request.messages.len() - 2;
 879        for (index, message) in request.messages.iter_mut().enumerate() {
 880            message.cache = index == breakpoint_index;
 881        }
 882
 883        if !referenced_context_ids.is_empty() {
 884            let mut context_message = LanguageModelRequestMessage {
 885                role: Role::User,
 886                content: Vec::new(),
 887                cache: false,
 888            };
 889
 890            let referenced_context = referenced_context_ids
 891                .into_iter()
 892                .filter_map(|context_id| self.context.get(context_id))
 893                .cloned();
 894            attach_context_to_message(&mut context_message, referenced_context);
 895
 896            request.messages.push(context_message);
 897        }
 898
 899        self.attached_tracked_files_state(&mut request.messages, cx);
 900
 901        request
 902    }
 903
 904    fn attached_tracked_files_state(
 905        &self,
 906        messages: &mut Vec<LanguageModelRequestMessage>,
 907        cx: &App,
 908    ) {
 909        const STALE_FILES_HEADER: &str = "These files changed since last read:";
 910
 911        let mut stale_message = String::new();
 912
 913        let action_log = self.action_log.read(cx);
 914
 915        for stale_file in action_log.stale_buffers(cx) {
 916            let Some(file) = stale_file.read(cx).file() else {
 917                continue;
 918            };
 919
 920            if stale_message.is_empty() {
 921                write!(&mut stale_message, "{}", STALE_FILES_HEADER).ok();
 922            }
 923
 924            writeln!(&mut stale_message, "- {}", file.path().display()).ok();
 925        }
 926
 927        let mut content = Vec::with_capacity(2);
 928
 929        if !stale_message.is_empty() {
 930            content.push(stale_message.into());
 931        }
 932
 933        if action_log.has_edited_files_since_project_diagnostics_check() {
 934            content.push(
 935                "\n\nWhen you're done making changes, make sure to check project diagnostics \
 936                and fix all errors AND warnings you introduced! \
 937                DO NOT mention you're going to do this until you're done."
 938                    .into(),
 939            );
 940        }
 941
 942        if !content.is_empty() {
 943            let context_message = LanguageModelRequestMessage {
 944                role: Role::User,
 945                content,
 946                cache: false,
 947            };
 948
 949            messages.push(context_message);
 950        }
 951    }
 952
 953    pub fn stream_completion(
 954        &mut self,
 955        request: LanguageModelRequest,
 956        model: Arc<dyn LanguageModel>,
 957        cx: &mut Context<Self>,
 958    ) {
 959        let pending_completion_id = post_inc(&mut self.completion_count);
 960
 961        let task = cx.spawn(async move |thread, cx| {
 962            let stream = model.stream_completion(request, &cx);
 963            let initial_token_usage =
 964                thread.read_with(cx, |thread, _cx| thread.cumulative_token_usage.clone());
 965            let stream_completion = async {
 966                let mut events = stream.await?;
 967                let mut stop_reason = StopReason::EndTurn;
 968                let mut current_token_usage = TokenUsage::default();
 969
 970                while let Some(event) = events.next().await {
 971                    let event = event?;
 972
 973                    thread.update(cx, |thread, cx| {
 974                        match event {
 975                            LanguageModelCompletionEvent::StartMessage { .. } => {
 976                                thread.insert_message(
 977                                    Role::Assistant,
 978                                    vec![MessageSegment::Text(String::new())],
 979                                    cx,
 980                                );
 981                            }
 982                            LanguageModelCompletionEvent::Stop(reason) => {
 983                                stop_reason = reason;
 984                            }
 985                            LanguageModelCompletionEvent::UsageUpdate(token_usage) => {
 986                                thread.cumulative_token_usage =
 987                                    thread.cumulative_token_usage.clone() + token_usage.clone()
 988                                        - current_token_usage.clone();
 989                                current_token_usage = token_usage;
 990                            }
 991                            LanguageModelCompletionEvent::Text(chunk) => {
 992                                if let Some(last_message) = thread.messages.last_mut() {
 993                                    if last_message.role == Role::Assistant {
 994                                        last_message.push_text(&chunk);
 995                                        cx.emit(ThreadEvent::StreamedAssistantText(
 996                                            last_message.id,
 997                                            chunk,
 998                                        ));
 999                                    } else {
1000                                        // If we won't have an Assistant message yet, assume this chunk marks the beginning
1001                                        // of a new Assistant response.
1002                                        //
1003                                        // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
1004                                        // will result in duplicating the text of the chunk in the rendered Markdown.
1005                                        thread.insert_message(
1006                                            Role::Assistant,
1007                                            vec![MessageSegment::Text(chunk.to_string())],
1008                                            cx,
1009                                        );
1010                                    };
1011                                }
1012                            }
1013                            LanguageModelCompletionEvent::Thinking(chunk) => {
1014                                if let Some(last_message) = thread.messages.last_mut() {
1015                                    if last_message.role == Role::Assistant {
1016                                        last_message.push_thinking(&chunk);
1017                                        cx.emit(ThreadEvent::StreamedAssistantThinking(
1018                                            last_message.id,
1019                                            chunk,
1020                                        ));
1021                                    } else {
1022                                        // If we won't have an Assistant message yet, assume this chunk marks the beginning
1023                                        // of a new Assistant response.
1024                                        //
1025                                        // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
1026                                        // will result in duplicating the text of the chunk in the rendered Markdown.
1027                                        thread.insert_message(
1028                                            Role::Assistant,
1029                                            vec![MessageSegment::Thinking(chunk.to_string())],
1030                                            cx,
1031                                        );
1032                                    };
1033                                }
1034                            }
1035                            LanguageModelCompletionEvent::ToolUse(tool_use) => {
1036                                let last_assistant_message_id = thread
1037                                    .messages
1038                                    .iter()
1039                                    .rfind(|message| message.role == Role::Assistant)
1040                                    .map(|message| message.id)
1041                                    .unwrap_or_else(|| {
1042                                        thread.insert_message(
1043                                            Role::Assistant,
1044                                            vec![MessageSegment::Text("Using tool...".to_string())],
1045                                            cx,
1046                                        )
1047                                    });
1048                                thread.tool_use.request_tool_use(
1049                                    last_assistant_message_id,
1050                                    tool_use,
1051                                    cx,
1052                                );
1053                            }
1054                        }
1055
1056                        thread.touch_updated_at();
1057                        cx.emit(ThreadEvent::StreamedCompletion);
1058                        cx.notify();
1059                    })?;
1060
1061                    smol::future::yield_now().await;
1062                }
1063
1064                thread.update(cx, |thread, cx| {
1065                    thread
1066                        .pending_completions
1067                        .retain(|completion| completion.id != pending_completion_id);
1068
1069                    if thread.summary.is_none() && thread.messages.len() >= 2 {
1070                        thread.summarize(cx);
1071                    }
1072                })?;
1073
1074                anyhow::Ok(stop_reason)
1075            };
1076
1077            let result = stream_completion.await;
1078
1079            thread
1080                .update(cx, |thread, cx| {
1081                    thread.finalize_pending_checkpoint(cx);
1082                    match result.as_ref() {
1083                        Ok(stop_reason) => match stop_reason {
1084                            StopReason::ToolUse => {
1085                                cx.emit(ThreadEvent::UsePendingTools);
1086                            }
1087                            StopReason::EndTurn => {}
1088                            StopReason::MaxTokens => {}
1089                        },
1090                        Err(error) => {
1091                            if error.is::<PaymentRequiredError>() {
1092                                cx.emit(ThreadEvent::ShowError(ThreadError::PaymentRequired));
1093                            } else if error.is::<MaxMonthlySpendReachedError>() {
1094                                cx.emit(ThreadEvent::ShowError(
1095                                    ThreadError::MaxMonthlySpendReached,
1096                                ));
1097                            } else {
1098                                let error_message = error
1099                                    .chain()
1100                                    .map(|err| err.to_string())
1101                                    .collect::<Vec<_>>()
1102                                    .join("\n");
1103                                cx.emit(ThreadEvent::ShowError(ThreadError::Message {
1104                                    header: "Error interacting with language model".into(),
1105                                    message: SharedString::from(error_message.clone()),
1106                                }));
1107                            }
1108
1109                            thread.cancel_last_completion(cx);
1110                        }
1111                    }
1112                    cx.emit(ThreadEvent::DoneStreaming);
1113
1114                    if let Ok(initial_usage) = initial_token_usage {
1115                        let usage = thread.cumulative_token_usage.clone() - initial_usage;
1116
1117                        telemetry::event!(
1118                            "Assistant Thread Completion",
1119                            thread_id = thread.id().to_string(),
1120                            model = model.telemetry_id(),
1121                            model_provider = model.provider_id().to_string(),
1122                            input_tokens = usage.input_tokens,
1123                            output_tokens = usage.output_tokens,
1124                            cache_creation_input_tokens = usage.cache_creation_input_tokens,
1125                            cache_read_input_tokens = usage.cache_read_input_tokens,
1126                        );
1127                    }
1128                })
1129                .ok();
1130        });
1131
1132        self.pending_completions.push(PendingCompletion {
1133            id: pending_completion_id,
1134            _task: task,
1135        });
1136    }
1137
1138    pub fn summarize(&mut self, cx: &mut Context<Self>) {
1139        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
1140            return;
1141        };
1142        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
1143            return;
1144        };
1145
1146        if !provider.is_authenticated(cx) {
1147            return;
1148        }
1149
1150        let mut request = self.to_completion_request(RequestKind::Summarize, cx);
1151        request.messages.push(LanguageModelRequestMessage {
1152            role: Role::User,
1153            content: vec![
1154                "Generate a concise 3-7 word title for this conversation, omitting punctuation. \
1155                 Go straight to the title, without any preamble and prefix like `Here's a concise suggestion:...` or `Title:`. \
1156                 If the conversation is about a specific subject, include it in the title. \
1157                 Be descriptive. DO NOT speak in the first person."
1158                    .into(),
1159            ],
1160            cache: false,
1161        });
1162
1163        self.pending_summary = cx.spawn(async move |this, cx| {
1164            async move {
1165                let stream = model.stream_completion_text(request, &cx);
1166                let mut messages = stream.await?;
1167
1168                let mut new_summary = String::new();
1169                while let Some(message) = messages.stream.next().await {
1170                    let text = message?;
1171                    let mut lines = text.lines();
1172                    new_summary.extend(lines.next());
1173
1174                    // Stop if the LLM generated multiple lines.
1175                    if lines.next().is_some() {
1176                        break;
1177                    }
1178                }
1179
1180                this.update(cx, |this, cx| {
1181                    if !new_summary.is_empty() {
1182                        this.summary = Some(new_summary.into());
1183                    }
1184
1185                    cx.emit(ThreadEvent::SummaryChanged);
1186                })?;
1187
1188                anyhow::Ok(())
1189            }
1190            .log_err()
1191            .await
1192        });
1193    }
1194
1195    pub fn use_pending_tools(
1196        &mut self,
1197        cx: &mut Context<Self>,
1198    ) -> impl IntoIterator<Item = PendingToolUse> + use<> {
1199        let request = self.to_completion_request(RequestKind::Chat, cx);
1200        let messages = Arc::new(request.messages);
1201        let pending_tool_uses = self
1202            .tool_use
1203            .pending_tool_uses()
1204            .into_iter()
1205            .filter(|tool_use| tool_use.status.is_idle())
1206            .cloned()
1207            .collect::<Vec<_>>();
1208
1209        for tool_use in pending_tool_uses.iter() {
1210            if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
1211                if tool.needs_confirmation()
1212                    && !AssistantSettings::get_global(cx).always_allow_tool_actions
1213                {
1214                    self.tool_use.confirm_tool_use(
1215                        tool_use.id.clone(),
1216                        tool_use.ui_text.clone(),
1217                        tool_use.input.clone(),
1218                        messages.clone(),
1219                        tool,
1220                    );
1221                    cx.emit(ThreadEvent::ToolConfirmationNeeded);
1222                } else {
1223                    self.run_tool(
1224                        tool_use.id.clone(),
1225                        tool_use.ui_text.clone(),
1226                        tool_use.input.clone(),
1227                        &messages,
1228                        tool,
1229                        cx,
1230                    );
1231                }
1232            } else if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
1233                self.run_tool(
1234                    tool_use.id.clone(),
1235                    tool_use.ui_text.clone(),
1236                    tool_use.input.clone(),
1237                    &messages,
1238                    tool,
1239                    cx,
1240                );
1241            }
1242        }
1243
1244        pending_tool_uses
1245    }
1246
1247    pub fn run_tool(
1248        &mut self,
1249        tool_use_id: LanguageModelToolUseId,
1250        ui_text: impl Into<SharedString>,
1251        input: serde_json::Value,
1252        messages: &[LanguageModelRequestMessage],
1253        tool: Arc<dyn Tool>,
1254        cx: &mut Context<Thread>,
1255    ) {
1256        let task = self.spawn_tool_use(tool_use_id.clone(), messages, input, tool, cx);
1257        self.tool_use
1258            .run_pending_tool(tool_use_id, ui_text.into(), task);
1259    }
1260
1261    fn spawn_tool_use(
1262        &mut self,
1263        tool_use_id: LanguageModelToolUseId,
1264        messages: &[LanguageModelRequestMessage],
1265        input: serde_json::Value,
1266        tool: Arc<dyn Tool>,
1267        cx: &mut Context<Thread>,
1268    ) -> Task<()> {
1269        let tool_name: Arc<str> = tool.name().into();
1270        let run_tool = tool.run(
1271            input,
1272            messages,
1273            self.project.clone(),
1274            self.action_log.clone(),
1275            cx,
1276        );
1277
1278        cx.spawn({
1279            async move |thread: WeakEntity<Thread>, cx| {
1280                let output = run_tool.await;
1281
1282                thread
1283                    .update(cx, |thread, cx| {
1284                        let pending_tool_use = thread.tool_use.insert_tool_output(
1285                            tool_use_id.clone(),
1286                            tool_name,
1287                            output,
1288                        );
1289
1290                        cx.emit(ThreadEvent::ToolFinished {
1291                            tool_use_id,
1292                            pending_tool_use,
1293                            canceled: false,
1294                        });
1295                    })
1296                    .ok();
1297            }
1298        })
1299    }
1300
1301    pub fn attach_tool_results(
1302        &mut self,
1303        updated_context: Vec<ContextSnapshot>,
1304        cx: &mut Context<Self>,
1305    ) {
1306        self.context.extend(
1307            updated_context
1308                .into_iter()
1309                .map(|context| (context.id, context)),
1310        );
1311
1312        // Insert a user message to contain the tool results.
1313        self.insert_user_message(
1314            // TODO: Sending up a user message without any content results in the model sending back
1315            // responses that also don't have any content. We currently don't handle this case well,
1316            // so for now we provide some text to keep the model on track.
1317            "Here are the tool results.",
1318            Vec::new(),
1319            None,
1320            cx,
1321        );
1322    }
1323
1324    /// Cancels the last pending completion, if there are any pending.
1325    ///
1326    /// Returns whether a completion was canceled.
1327    pub fn cancel_last_completion(&mut self, cx: &mut Context<Self>) -> bool {
1328        let canceled = if self.pending_completions.pop().is_some() {
1329            true
1330        } else {
1331            let mut canceled = false;
1332            for pending_tool_use in self.tool_use.cancel_pending() {
1333                canceled = true;
1334                cx.emit(ThreadEvent::ToolFinished {
1335                    tool_use_id: pending_tool_use.id.clone(),
1336                    pending_tool_use: Some(pending_tool_use),
1337                    canceled: true,
1338                });
1339            }
1340            canceled
1341        };
1342        self.finalize_pending_checkpoint(cx);
1343        canceled
1344    }
1345
1346    /// Returns the feedback given to the thread, if any.
1347    pub fn feedback(&self) -> Option<ThreadFeedback> {
1348        self.feedback
1349    }
1350
1351    /// Reports feedback about the thread and stores it in our telemetry backend.
1352    pub fn report_feedback(
1353        &mut self,
1354        feedback: ThreadFeedback,
1355        cx: &mut Context<Self>,
1356    ) -> Task<Result<()>> {
1357        let final_project_snapshot = Self::project_snapshot(self.project.clone(), cx);
1358        let serialized_thread = self.serialize(cx);
1359        let thread_id = self.id().clone();
1360        let client = self.project.read(cx).client();
1361        self.feedback = Some(feedback);
1362        cx.notify();
1363
1364        cx.background_spawn(async move {
1365            let final_project_snapshot = final_project_snapshot.await;
1366            let serialized_thread = serialized_thread.await?;
1367            let thread_data =
1368                serde_json::to_value(serialized_thread).unwrap_or_else(|_| serde_json::Value::Null);
1369
1370            let rating = match feedback {
1371                ThreadFeedback::Positive => "positive",
1372                ThreadFeedback::Negative => "negative",
1373            };
1374            telemetry::event!(
1375                "Assistant Thread Rated",
1376                rating,
1377                thread_id,
1378                thread_data,
1379                final_project_snapshot
1380            );
1381            client.telemetry().flush_events();
1382
1383            Ok(())
1384        })
1385    }
1386
1387    /// Create a snapshot of the current project state including git information and unsaved buffers.
1388    fn project_snapshot(
1389        project: Entity<Project>,
1390        cx: &mut Context<Self>,
1391    ) -> Task<Arc<ProjectSnapshot>> {
1392        let git_store = project.read(cx).git_store().clone();
1393        let worktree_snapshots: Vec<_> = project
1394            .read(cx)
1395            .visible_worktrees(cx)
1396            .map(|worktree| Self::worktree_snapshot(worktree, git_store.clone(), cx))
1397            .collect();
1398
1399        cx.spawn(async move |_, cx| {
1400            let worktree_snapshots = futures::future::join_all(worktree_snapshots).await;
1401
1402            let mut unsaved_buffers = Vec::new();
1403            cx.update(|app_cx| {
1404                let buffer_store = project.read(app_cx).buffer_store();
1405                for buffer_handle in buffer_store.read(app_cx).buffers() {
1406                    let buffer = buffer_handle.read(app_cx);
1407                    if buffer.is_dirty() {
1408                        if let Some(file) = buffer.file() {
1409                            let path = file.path().to_string_lossy().to_string();
1410                            unsaved_buffers.push(path);
1411                        }
1412                    }
1413                }
1414            })
1415            .ok();
1416
1417            Arc::new(ProjectSnapshot {
1418                worktree_snapshots,
1419                unsaved_buffer_paths: unsaved_buffers,
1420                timestamp: Utc::now(),
1421            })
1422        })
1423    }
1424
1425    fn worktree_snapshot(
1426        worktree: Entity<project::Worktree>,
1427        git_store: Entity<GitStore>,
1428        cx: &App,
1429    ) -> Task<WorktreeSnapshot> {
1430        cx.spawn(async move |cx| {
1431            // Get worktree path and snapshot
1432            let worktree_info = cx.update(|app_cx| {
1433                let worktree = worktree.read(app_cx);
1434                let path = worktree.abs_path().to_string_lossy().to_string();
1435                let snapshot = worktree.snapshot();
1436                (path, snapshot)
1437            });
1438
1439            let Ok((worktree_path, snapshot)) = worktree_info else {
1440                return WorktreeSnapshot {
1441                    worktree_path: String::new(),
1442                    git_state: None,
1443                };
1444            };
1445
1446            let repo_info = git_store
1447                .update(cx, |git_store, cx| {
1448                    git_store
1449                        .repositories()
1450                        .values()
1451                        .find(|repo| repo.read(cx).worktree_id == Some(snapshot.id()))
1452                        .and_then(|repo| {
1453                            let repo = repo.read(cx);
1454                            Some((repo.branch().cloned(), repo.local_repository()?))
1455                        })
1456                })
1457                .ok()
1458                .flatten();
1459
1460            // Extract git information
1461            let git_state = match repo_info {
1462                None => None,
1463                Some((branch, repo)) => {
1464                    let current_branch = branch.map(|branch| branch.name.to_string());
1465                    let remote_url = repo.remote_url("origin");
1466                    let head_sha = repo.head_sha();
1467
1468                    // Get diff asynchronously
1469                    let diff = repo
1470                        .diff(git::repository::DiffType::HeadToWorktree)
1471                        .await
1472                        .ok();
1473
1474                    Some(GitState {
1475                        remote_url,
1476                        head_sha,
1477                        current_branch,
1478                        diff,
1479                    })
1480                }
1481            };
1482
1483            WorktreeSnapshot {
1484                worktree_path,
1485                git_state,
1486            }
1487        })
1488    }
1489
1490    pub fn to_markdown(&self, cx: &App) -> Result<String> {
1491        let mut markdown = Vec::new();
1492
1493        if let Some(summary) = self.summary() {
1494            writeln!(markdown, "# {summary}\n")?;
1495        };
1496
1497        for message in self.messages() {
1498            writeln!(
1499                markdown,
1500                "## {role}\n",
1501                role = match message.role {
1502                    Role::User => "User",
1503                    Role::Assistant => "Assistant",
1504                    Role::System => "System",
1505                }
1506            )?;
1507            for segment in &message.segments {
1508                match segment {
1509                    MessageSegment::Text(text) => writeln!(markdown, "{}\n", text)?,
1510                    MessageSegment::Thinking(text) => {
1511                        writeln!(markdown, "<think>{}</think>\n", text)?
1512                    }
1513                }
1514            }
1515
1516            for tool_use in self.tool_uses_for_message(message.id, cx) {
1517                writeln!(
1518                    markdown,
1519                    "**Use Tool: {} ({})**",
1520                    tool_use.name, tool_use.id
1521                )?;
1522                writeln!(markdown, "```json")?;
1523                writeln!(
1524                    markdown,
1525                    "{}",
1526                    serde_json::to_string_pretty(&tool_use.input)?
1527                )?;
1528                writeln!(markdown, "```")?;
1529            }
1530
1531            for tool_result in self.tool_results_for_message(message.id) {
1532                write!(markdown, "**Tool Results: {}", tool_result.tool_use_id)?;
1533                if tool_result.is_error {
1534                    write!(markdown, " (Error)")?;
1535                }
1536
1537                writeln!(markdown, "**\n")?;
1538                writeln!(markdown, "{}", tool_result.content)?;
1539            }
1540        }
1541
1542        Ok(String::from_utf8_lossy(&markdown).to_string())
1543    }
1544
1545    pub fn review_edits_in_range(
1546        &mut self,
1547        buffer: Entity<language::Buffer>,
1548        buffer_range: Range<language::Anchor>,
1549        accept: bool,
1550        cx: &mut Context<Self>,
1551    ) {
1552        self.action_log.update(cx, |action_log, cx| {
1553            action_log.review_edits_in_range(buffer, buffer_range, accept, cx)
1554        });
1555    }
1556
1557    /// Keeps all edits across all buffers at once.
1558    /// This provides a more performant alternative to calling review_edits_in_range for each buffer.
1559    pub fn keep_all_edits(&mut self, cx: &mut Context<Self>) {
1560        self.action_log
1561            .update(cx, |action_log, _cx| action_log.keep_all_edits());
1562    }
1563
1564    pub fn action_log(&self) -> &Entity<ActionLog> {
1565        &self.action_log
1566    }
1567
1568    pub fn project(&self) -> &Entity<Project> {
1569        &self.project
1570    }
1571
1572    pub fn cumulative_token_usage(&self) -> TokenUsage {
1573        self.cumulative_token_usage.clone()
1574    }
1575
1576    pub fn deny_tool_use(
1577        &mut self,
1578        tool_use_id: LanguageModelToolUseId,
1579        tool_name: Arc<str>,
1580        cx: &mut Context<Self>,
1581    ) {
1582        let err = Err(anyhow::anyhow!(
1583            "Permission to run tool action denied by user"
1584        ));
1585
1586        self.tool_use
1587            .insert_tool_output(tool_use_id.clone(), tool_name, err);
1588
1589        cx.emit(ThreadEvent::ToolFinished {
1590            tool_use_id,
1591            pending_tool_use: None,
1592            canceled: true,
1593        });
1594    }
1595}
1596
1597#[derive(Debug, Clone)]
1598pub enum ThreadError {
1599    PaymentRequired,
1600    MaxMonthlySpendReached,
1601    Message {
1602        header: SharedString,
1603        message: SharedString,
1604    },
1605}
1606
1607#[derive(Debug, Clone)]
1608pub enum ThreadEvent {
1609    ShowError(ThreadError),
1610    StreamedCompletion,
1611    StreamedAssistantText(MessageId, String),
1612    StreamedAssistantThinking(MessageId, String),
1613    DoneStreaming,
1614    MessageAdded(MessageId),
1615    MessageEdited(MessageId),
1616    MessageDeleted(MessageId),
1617    SummaryChanged,
1618    UsePendingTools,
1619    ToolFinished {
1620        #[allow(unused)]
1621        tool_use_id: LanguageModelToolUseId,
1622        /// The pending tool use that corresponds to this tool.
1623        pending_tool_use: Option<PendingToolUse>,
1624        /// Whether the tool was canceled by the user.
1625        canceled: bool,
1626    },
1627    CheckpointChanged,
1628    ToolConfirmationNeeded,
1629}
1630
1631impl EventEmitter<ThreadEvent> for Thread {}
1632
1633struct PendingCompletion {
1634    id: usize,
1635    _task: Task<()>,
1636}