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::{maybe, post_inc, ResultExt as _, TryFutureExt as _};
  30use uuid::Uuid;
  31
  32use crate::context::{attach_context_to_message, ContextId, ContextSnapshot};
  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                "When you're done making changes, make sure to check project diagnostics and fix all errors AND warnings you introduced!".into(),
 936            );
 937        }
 938
 939        if !content.is_empty() {
 940            let context_message = LanguageModelRequestMessage {
 941                role: Role::User,
 942                content,
 943                cache: false,
 944            };
 945
 946            messages.push(context_message);
 947        }
 948    }
 949
 950    pub fn stream_completion(
 951        &mut self,
 952        request: LanguageModelRequest,
 953        model: Arc<dyn LanguageModel>,
 954        cx: &mut Context<Self>,
 955    ) {
 956        let pending_completion_id = post_inc(&mut self.completion_count);
 957
 958        let task = cx.spawn(async move |thread, cx| {
 959            let stream = model.stream_completion(request, &cx);
 960            let initial_token_usage =
 961                thread.read_with(cx, |thread, _cx| thread.cumulative_token_usage.clone());
 962            let stream_completion = async {
 963                let mut events = stream.await?;
 964                let mut stop_reason = StopReason::EndTurn;
 965                let mut current_token_usage = TokenUsage::default();
 966
 967                while let Some(event) = events.next().await {
 968                    let event = event?;
 969
 970                    thread.update(cx, |thread, cx| {
 971                        match event {
 972                            LanguageModelCompletionEvent::StartMessage { .. } => {
 973                                thread.insert_message(
 974                                    Role::Assistant,
 975                                    vec![MessageSegment::Text(String::new())],
 976                                    cx,
 977                                );
 978                            }
 979                            LanguageModelCompletionEvent::Stop(reason) => {
 980                                stop_reason = reason;
 981                            }
 982                            LanguageModelCompletionEvent::UsageUpdate(token_usage) => {
 983                                thread.cumulative_token_usage =
 984                                    thread.cumulative_token_usage.clone() + token_usage.clone()
 985                                        - current_token_usage.clone();
 986                                current_token_usage = token_usage;
 987                            }
 988                            LanguageModelCompletionEvent::Text(chunk) => {
 989                                if let Some(last_message) = thread.messages.last_mut() {
 990                                    if last_message.role == Role::Assistant {
 991                                        last_message.push_text(&chunk);
 992                                        cx.emit(ThreadEvent::StreamedAssistantText(
 993                                            last_message.id,
 994                                            chunk,
 995                                        ));
 996                                    } else {
 997                                        // If we won't have an Assistant message yet, assume this chunk marks the beginning
 998                                        // of a new Assistant response.
 999                                        //
1000                                        // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
1001                                        // will result in duplicating the text of the chunk in the rendered Markdown.
1002                                        thread.insert_message(
1003                                            Role::Assistant,
1004                                            vec![MessageSegment::Text(chunk.to_string())],
1005                                            cx,
1006                                        );
1007                                    };
1008                                }
1009                            }
1010                            LanguageModelCompletionEvent::Thinking(chunk) => {
1011                                if let Some(last_message) = thread.messages.last_mut() {
1012                                    if last_message.role == Role::Assistant {
1013                                        last_message.push_thinking(&chunk);
1014                                        cx.emit(ThreadEvent::StreamedAssistantThinking(
1015                                            last_message.id,
1016                                            chunk,
1017                                        ));
1018                                    } else {
1019                                        // If we won't have an Assistant message yet, assume this chunk marks the beginning
1020                                        // of a new Assistant response.
1021                                        //
1022                                        // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
1023                                        // will result in duplicating the text of the chunk in the rendered Markdown.
1024                                        thread.insert_message(
1025                                            Role::Assistant,
1026                                            vec![MessageSegment::Thinking(chunk.to_string())],
1027                                            cx,
1028                                        );
1029                                    };
1030                                }
1031                            }
1032                            LanguageModelCompletionEvent::ToolUse(tool_use) => {
1033                                let last_assistant_message_id = thread
1034                                    .messages
1035                                    .iter()
1036                                    .rfind(|message| message.role == Role::Assistant)
1037                                    .map(|message| message.id)
1038                                    .unwrap_or_else(|| {
1039                                        thread.insert_message(
1040                                            Role::Assistant,
1041                                            vec![MessageSegment::Text("Using tool...".to_string())],
1042                                            cx,
1043                                        )
1044                                    });
1045                                thread.tool_use.request_tool_use(
1046                                    last_assistant_message_id,
1047                                    tool_use,
1048                                    cx,
1049                                );
1050                            }
1051                        }
1052
1053                        thread.touch_updated_at();
1054                        cx.emit(ThreadEvent::StreamedCompletion);
1055                        cx.notify();
1056                    })?;
1057
1058                    smol::future::yield_now().await;
1059                }
1060
1061                thread.update(cx, |thread, cx| {
1062                    thread
1063                        .pending_completions
1064                        .retain(|completion| completion.id != pending_completion_id);
1065
1066                    if thread.summary.is_none() && thread.messages.len() >= 2 {
1067                        thread.summarize(cx);
1068                    }
1069                })?;
1070
1071                anyhow::Ok(stop_reason)
1072            };
1073
1074            let result = stream_completion.await;
1075
1076            thread
1077                .update(cx, |thread, cx| {
1078                    thread.finalize_pending_checkpoint(cx);
1079                    match result.as_ref() {
1080                        Ok(stop_reason) => match stop_reason {
1081                            StopReason::ToolUse => {
1082                                cx.emit(ThreadEvent::UsePendingTools);
1083                            }
1084                            StopReason::EndTurn => {}
1085                            StopReason::MaxTokens => {}
1086                        },
1087                        Err(error) => {
1088                            if error.is::<PaymentRequiredError>() {
1089                                cx.emit(ThreadEvent::ShowError(ThreadError::PaymentRequired));
1090                            } else if error.is::<MaxMonthlySpendReachedError>() {
1091                                cx.emit(ThreadEvent::ShowError(
1092                                    ThreadError::MaxMonthlySpendReached,
1093                                ));
1094                            } else {
1095                                let error_message = error
1096                                    .chain()
1097                                    .map(|err| err.to_string())
1098                                    .collect::<Vec<_>>()
1099                                    .join("\n");
1100                                cx.emit(ThreadEvent::ShowError(ThreadError::Message {
1101                                    header: "Error interacting with language model".into(),
1102                                    message: SharedString::from(error_message.clone()),
1103                                }));
1104                            }
1105
1106                            thread.cancel_last_completion(cx);
1107                        }
1108                    }
1109                    cx.emit(ThreadEvent::DoneStreaming);
1110
1111                    if let Ok(initial_usage) = initial_token_usage {
1112                        let usage = thread.cumulative_token_usage.clone() - initial_usage;
1113
1114                        telemetry::event!(
1115                            "Assistant Thread Completion",
1116                            thread_id = thread.id().to_string(),
1117                            model = model.telemetry_id(),
1118                            model_provider = model.provider_id().to_string(),
1119                            input_tokens = usage.input_tokens,
1120                            output_tokens = usage.output_tokens,
1121                            cache_creation_input_tokens = usage.cache_creation_input_tokens,
1122                            cache_read_input_tokens = usage.cache_read_input_tokens,
1123                        );
1124                    }
1125                })
1126                .ok();
1127        });
1128
1129        self.pending_completions.push(PendingCompletion {
1130            id: pending_completion_id,
1131            _task: task,
1132        });
1133    }
1134
1135    pub fn summarize(&mut self, cx: &mut Context<Self>) {
1136        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
1137            return;
1138        };
1139        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
1140            return;
1141        };
1142
1143        if !provider.is_authenticated(cx) {
1144            return;
1145        }
1146
1147        let mut request = self.to_completion_request(RequestKind::Summarize, cx);
1148        request.messages.push(LanguageModelRequestMessage {
1149            role: Role::User,
1150            content: vec![
1151                "Generate a concise 3-7 word title for this conversation, omitting punctuation. \
1152                 Go straight to the title, without any preamble and prefix like `Here's a concise suggestion:...` or `Title:`. \
1153                 If the conversation is about a specific subject, include it in the title. \
1154                 Be descriptive. DO NOT speak in the first person."
1155                    .into(),
1156            ],
1157            cache: false,
1158        });
1159
1160        self.pending_summary = cx.spawn(async move |this, cx| {
1161            async move {
1162                let stream = model.stream_completion_text(request, &cx);
1163                let mut messages = stream.await?;
1164
1165                let mut new_summary = String::new();
1166                while let Some(message) = messages.stream.next().await {
1167                    let text = message?;
1168                    let mut lines = text.lines();
1169                    new_summary.extend(lines.next());
1170
1171                    // Stop if the LLM generated multiple lines.
1172                    if lines.next().is_some() {
1173                        break;
1174                    }
1175                }
1176
1177                this.update(cx, |this, cx| {
1178                    if !new_summary.is_empty() {
1179                        this.summary = Some(new_summary.into());
1180                    }
1181
1182                    cx.emit(ThreadEvent::SummaryChanged);
1183                })?;
1184
1185                anyhow::Ok(())
1186            }
1187            .log_err()
1188            .await
1189        });
1190    }
1191
1192    pub fn use_pending_tools(
1193        &mut self,
1194        cx: &mut Context<Self>,
1195    ) -> impl IntoIterator<Item = PendingToolUse> + use<> {
1196        let request = self.to_completion_request(RequestKind::Chat, cx);
1197        let messages = Arc::new(request.messages);
1198        let pending_tool_uses = self
1199            .tool_use
1200            .pending_tool_uses()
1201            .into_iter()
1202            .filter(|tool_use| tool_use.status.is_idle())
1203            .cloned()
1204            .collect::<Vec<_>>();
1205
1206        for tool_use in pending_tool_uses.iter() {
1207            if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
1208                if tool.needs_confirmation()
1209                    && !AssistantSettings::get_global(cx).always_allow_tool_actions
1210                {
1211                    self.tool_use.confirm_tool_use(
1212                        tool_use.id.clone(),
1213                        tool_use.ui_text.clone(),
1214                        tool_use.input.clone(),
1215                        messages.clone(),
1216                        tool,
1217                    );
1218                    cx.emit(ThreadEvent::ToolConfirmationNeeded);
1219                } else {
1220                    self.run_tool(
1221                        tool_use.id.clone(),
1222                        tool_use.ui_text.clone(),
1223                        tool_use.input.clone(),
1224                        &messages,
1225                        tool,
1226                        cx,
1227                    );
1228                }
1229            } else if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
1230                self.run_tool(
1231                    tool_use.id.clone(),
1232                    tool_use.ui_text.clone(),
1233                    tool_use.input.clone(),
1234                    &messages,
1235                    tool,
1236                    cx,
1237                );
1238            }
1239        }
1240
1241        pending_tool_uses
1242    }
1243
1244    pub fn run_tool(
1245        &mut self,
1246        tool_use_id: LanguageModelToolUseId,
1247        ui_text: impl Into<SharedString>,
1248        input: serde_json::Value,
1249        messages: &[LanguageModelRequestMessage],
1250        tool: Arc<dyn Tool>,
1251        cx: &mut Context<Thread>,
1252    ) {
1253        let task = self.spawn_tool_use(tool_use_id.clone(), messages, input, tool, cx);
1254        self.tool_use
1255            .run_pending_tool(tool_use_id, ui_text.into(), task);
1256    }
1257
1258    fn spawn_tool_use(
1259        &mut self,
1260        tool_use_id: LanguageModelToolUseId,
1261        messages: &[LanguageModelRequestMessage],
1262        input: serde_json::Value,
1263        tool: Arc<dyn Tool>,
1264        cx: &mut Context<Thread>,
1265    ) -> Task<()> {
1266        let tool_name: Arc<str> = tool.name().into();
1267        let run_tool = tool.run(
1268            input,
1269            messages,
1270            self.project.clone(),
1271            self.action_log.clone(),
1272            cx,
1273        );
1274
1275        cx.spawn({
1276            async move |thread: WeakEntity<Thread>, cx| {
1277                let output = run_tool.await;
1278
1279                thread
1280                    .update(cx, |thread, cx| {
1281                        let pending_tool_use = thread.tool_use.insert_tool_output(
1282                            tool_use_id.clone(),
1283                            tool_name,
1284                            output,
1285                        );
1286
1287                        cx.emit(ThreadEvent::ToolFinished {
1288                            tool_use_id,
1289                            pending_tool_use,
1290                            canceled: false,
1291                        });
1292                    })
1293                    .ok();
1294            }
1295        })
1296    }
1297
1298    pub fn attach_tool_results(
1299        &mut self,
1300        updated_context: Vec<ContextSnapshot>,
1301        cx: &mut Context<Self>,
1302    ) {
1303        self.context.extend(
1304            updated_context
1305                .into_iter()
1306                .map(|context| (context.id, context)),
1307        );
1308
1309        // Insert a user message to contain the tool results.
1310        self.insert_user_message(
1311            // TODO: Sending up a user message without any content results in the model sending back
1312            // responses that also don't have any content. We currently don't handle this case well,
1313            // so for now we provide some text to keep the model on track.
1314            "Here are the tool results.",
1315            Vec::new(),
1316            None,
1317            cx,
1318        );
1319    }
1320
1321    /// Cancels the last pending completion, if there are any pending.
1322    ///
1323    /// Returns whether a completion was canceled.
1324    pub fn cancel_last_completion(&mut self, cx: &mut Context<Self>) -> bool {
1325        let canceled = if self.pending_completions.pop().is_some() {
1326            true
1327        } else {
1328            let mut canceled = false;
1329            for pending_tool_use in self.tool_use.cancel_pending() {
1330                canceled = true;
1331                cx.emit(ThreadEvent::ToolFinished {
1332                    tool_use_id: pending_tool_use.id.clone(),
1333                    pending_tool_use: Some(pending_tool_use),
1334                    canceled: true,
1335                });
1336            }
1337            canceled
1338        };
1339        self.finalize_pending_checkpoint(cx);
1340        canceled
1341    }
1342
1343    /// Returns the feedback given to the thread, if any.
1344    pub fn feedback(&self) -> Option<ThreadFeedback> {
1345        self.feedback
1346    }
1347
1348    /// Reports feedback about the thread and stores it in our telemetry backend.
1349    pub fn report_feedback(
1350        &mut self,
1351        feedback: ThreadFeedback,
1352        cx: &mut Context<Self>,
1353    ) -> Task<Result<()>> {
1354        let final_project_snapshot = Self::project_snapshot(self.project.clone(), cx);
1355        let serialized_thread = self.serialize(cx);
1356        let thread_id = self.id().clone();
1357        let client = self.project.read(cx).client();
1358        self.feedback = Some(feedback);
1359        cx.notify();
1360
1361        cx.background_spawn(async move {
1362            let final_project_snapshot = final_project_snapshot.await;
1363            let serialized_thread = serialized_thread.await?;
1364            let thread_data =
1365                serde_json::to_value(serialized_thread).unwrap_or_else(|_| serde_json::Value::Null);
1366
1367            let rating = match feedback {
1368                ThreadFeedback::Positive => "positive",
1369                ThreadFeedback::Negative => "negative",
1370            };
1371            telemetry::event!(
1372                "Assistant Thread Rated",
1373                rating,
1374                thread_id,
1375                thread_data,
1376                final_project_snapshot
1377            );
1378            client.telemetry().flush_events();
1379
1380            Ok(())
1381        })
1382    }
1383
1384    /// Create a snapshot of the current project state including git information and unsaved buffers.
1385    fn project_snapshot(
1386        project: Entity<Project>,
1387        cx: &mut Context<Self>,
1388    ) -> Task<Arc<ProjectSnapshot>> {
1389        let git_store = project.read(cx).git_store().clone();
1390        let worktree_snapshots: Vec<_> = project
1391            .read(cx)
1392            .visible_worktrees(cx)
1393            .map(|worktree| Self::worktree_snapshot(worktree, git_store.clone(), cx))
1394            .collect();
1395
1396        cx.spawn(async move |_, cx| {
1397            let worktree_snapshots = futures::future::join_all(worktree_snapshots).await;
1398
1399            let mut unsaved_buffers = Vec::new();
1400            cx.update(|app_cx| {
1401                let buffer_store = project.read(app_cx).buffer_store();
1402                for buffer_handle in buffer_store.read(app_cx).buffers() {
1403                    let buffer = buffer_handle.read(app_cx);
1404                    if buffer.is_dirty() {
1405                        if let Some(file) = buffer.file() {
1406                            let path = file.path().to_string_lossy().to_string();
1407                            unsaved_buffers.push(path);
1408                        }
1409                    }
1410                }
1411            })
1412            .ok();
1413
1414            Arc::new(ProjectSnapshot {
1415                worktree_snapshots,
1416                unsaved_buffer_paths: unsaved_buffers,
1417                timestamp: Utc::now(),
1418            })
1419        })
1420    }
1421
1422    fn worktree_snapshot(
1423        worktree: Entity<project::Worktree>,
1424        git_store: Entity<GitStore>,
1425        cx: &App,
1426    ) -> Task<WorktreeSnapshot> {
1427        cx.spawn(async move |cx| {
1428            // Get worktree path and snapshot
1429            let worktree_info = cx.update(|app_cx| {
1430                let worktree = worktree.read(app_cx);
1431                let path = worktree.abs_path().to_string_lossy().to_string();
1432                let snapshot = worktree.snapshot();
1433                (path, snapshot)
1434            });
1435
1436            let Ok((worktree_path, snapshot)) = worktree_info else {
1437                return WorktreeSnapshot {
1438                    worktree_path: String::new(),
1439                    git_state: None,
1440                };
1441            };
1442
1443            let repo_info = git_store
1444                .update(cx, |git_store, cx| {
1445                    git_store
1446                        .repositories()
1447                        .values()
1448                        .find(|repo| repo.read(cx).worktree_id == Some(snapshot.id()))
1449                        .and_then(|repo| {
1450                            let repo = repo.read(cx);
1451                            Some((repo.branch().cloned(), repo.local_repository()?))
1452                        })
1453                })
1454                .ok()
1455                .flatten();
1456
1457            // Extract git information
1458            let git_state = match repo_info {
1459                None => None,
1460                Some((branch, repo)) => {
1461                    let current_branch = branch.map(|branch| branch.name.to_string());
1462                    let remote_url = repo.remote_url("origin");
1463                    let head_sha = repo.head_sha();
1464
1465                    // Get diff asynchronously
1466                    let diff = repo
1467                        .diff(git::repository::DiffType::HeadToWorktree)
1468                        .await
1469                        .ok();
1470
1471                    Some(GitState {
1472                        remote_url,
1473                        head_sha,
1474                        current_branch,
1475                        diff,
1476                    })
1477                }
1478            };
1479
1480            WorktreeSnapshot {
1481                worktree_path,
1482                git_state,
1483            }
1484        })
1485    }
1486
1487    pub fn to_markdown(&self, cx: &App) -> Result<String> {
1488        let mut markdown = Vec::new();
1489
1490        if let Some(summary) = self.summary() {
1491            writeln!(markdown, "# {summary}\n")?;
1492        };
1493
1494        for message in self.messages() {
1495            writeln!(
1496                markdown,
1497                "## {role}\n",
1498                role = match message.role {
1499                    Role::User => "User",
1500                    Role::Assistant => "Assistant",
1501                    Role::System => "System",
1502                }
1503            )?;
1504            for segment in &message.segments {
1505                match segment {
1506                    MessageSegment::Text(text) => writeln!(markdown, "{}\n", text)?,
1507                    MessageSegment::Thinking(text) => {
1508                        writeln!(markdown, "<think>{}</think>\n", text)?
1509                    }
1510                }
1511            }
1512
1513            for tool_use in self.tool_uses_for_message(message.id, cx) {
1514                writeln!(
1515                    markdown,
1516                    "**Use Tool: {} ({})**",
1517                    tool_use.name, tool_use.id
1518                )?;
1519                writeln!(markdown, "```json")?;
1520                writeln!(
1521                    markdown,
1522                    "{}",
1523                    serde_json::to_string_pretty(&tool_use.input)?
1524                )?;
1525                writeln!(markdown, "```")?;
1526            }
1527
1528            for tool_result in self.tool_results_for_message(message.id) {
1529                write!(markdown, "**Tool Results: {}", tool_result.tool_use_id)?;
1530                if tool_result.is_error {
1531                    write!(markdown, " (Error)")?;
1532                }
1533
1534                writeln!(markdown, "**\n")?;
1535                writeln!(markdown, "{}", tool_result.content)?;
1536            }
1537        }
1538
1539        Ok(String::from_utf8_lossy(&markdown).to_string())
1540    }
1541
1542    pub fn review_edits_in_range(
1543        &mut self,
1544        buffer: Entity<language::Buffer>,
1545        buffer_range: Range<language::Anchor>,
1546        accept: bool,
1547        cx: &mut Context<Self>,
1548    ) {
1549        self.action_log.update(cx, |action_log, cx| {
1550            action_log.review_edits_in_range(buffer, buffer_range, accept, cx)
1551        });
1552    }
1553
1554    /// Keeps all edits across all buffers at once.
1555    /// This provides a more performant alternative to calling review_edits_in_range for each buffer.
1556    pub fn keep_all_edits(&mut self, cx: &mut Context<Self>) {
1557        self.action_log
1558            .update(cx, |action_log, _cx| action_log.keep_all_edits());
1559    }
1560
1561    pub fn action_log(&self) -> &Entity<ActionLog> {
1562        &self.action_log
1563    }
1564
1565    pub fn project(&self) -> &Entity<Project> {
1566        &self.project
1567    }
1568
1569    pub fn cumulative_token_usage(&self) -> TokenUsage {
1570        self.cumulative_token_usage.clone()
1571    }
1572
1573    pub fn deny_tool_use(
1574        &mut self,
1575        tool_use_id: LanguageModelToolUseId,
1576        tool_name: Arc<str>,
1577        cx: &mut Context<Self>,
1578    ) {
1579        let err = Err(anyhow::anyhow!(
1580            "Permission to run tool action denied by user"
1581        ));
1582
1583        self.tool_use
1584            .insert_tool_output(tool_use_id.clone(), tool_name, err);
1585
1586        cx.emit(ThreadEvent::ToolFinished {
1587            tool_use_id,
1588            pending_tool_use: None,
1589            canceled: true,
1590        });
1591    }
1592}
1593
1594#[derive(Debug, Clone)]
1595pub enum ThreadError {
1596    PaymentRequired,
1597    MaxMonthlySpendReached,
1598    Message {
1599        header: SharedString,
1600        message: SharedString,
1601    },
1602}
1603
1604#[derive(Debug, Clone)]
1605pub enum ThreadEvent {
1606    ShowError(ThreadError),
1607    StreamedCompletion,
1608    StreamedAssistantText(MessageId, String),
1609    StreamedAssistantThinking(MessageId, String),
1610    DoneStreaming,
1611    MessageAdded(MessageId),
1612    MessageEdited(MessageId),
1613    MessageDeleted(MessageId),
1614    SummaryChanged,
1615    UsePendingTools,
1616    ToolFinished {
1617        #[allow(unused)]
1618        tool_use_id: LanguageModelToolUseId,
1619        /// The pending tool use that corresponds to this tool.
1620        pending_tool_use: Option<PendingToolUse>,
1621        /// Whether the tool was canceled by the user.
1622        canceled: bool,
1623    },
1624    CheckpointChanged,
1625    ToolConfirmationNeeded,
1626}
1627
1628impl EventEmitter<ThreadEvent> for Thread {}
1629
1630struct PendingCompletion {
1631    id: usize,
1632    _task: Task<()>,
1633}