thread.rs

   1use std::fmt::Write as _;
   2use std::io::Write;
   3use std::sync::Arc;
   4
   5use anyhow::{Context as _, Result};
   6use assistant_settings::AssistantSettings;
   7use assistant_tool::{ActionLog, Tool, ToolWorkingSet};
   8use chrono::{DateTime, Utc};
   9use collections::{BTreeMap, HashMap, HashSet};
  10use fs::Fs;
  11use futures::future::Shared;
  12use futures::{FutureExt, StreamExt as _};
  13use git;
  14use gpui::{App, AppContext, Context, Entity, EventEmitter, SharedString, Task, WeakEntity};
  15use language_model::{
  16    LanguageModel, LanguageModelCompletionEvent, LanguageModelRegistry, LanguageModelRequest,
  17    LanguageModelRequestMessage, LanguageModelRequestTool, LanguageModelToolResult,
  18    LanguageModelToolUseId, MaxMonthlySpendReachedError, MessageContent, PaymentRequiredError,
  19    Role, StopReason, TokenUsage,
  20};
  21use project::git_store::{GitStore, GitStoreCheckpoint};
  22use project::{Project, Worktree};
  23use prompt_store::{
  24    AssistantSystemPromptContext, PromptBuilder, RulesFile, WorktreeInfoForSystemPrompt,
  25};
  26use serde::{Deserialize, Serialize};
  27use settings::Settings;
  28use util::{maybe, post_inc, ResultExt as _, TryFutureExt as _};
  29use uuid::Uuid;
  30
  31use crate::context::{attach_context_to_message, ContextId, ContextSnapshot};
  32use crate::thread_store::{
  33    SerializedMessage, SerializedMessageSegment, SerializedThread, SerializedToolResult,
  34    SerializedToolUse,
  35};
  36use crate::tool_use::{PendingToolUse, ToolUse, ToolUseState};
  37
  38#[derive(Debug, Clone, Copy)]
  39pub enum RequestKind {
  40    Chat,
  41    /// Used when summarizing a thread.
  42    Summarize,
  43}
  44
  45#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
  46pub struct ThreadId(Arc<str>);
  47
  48impl ThreadId {
  49    pub fn new() -> Self {
  50        Self(Uuid::new_v4().to_string().into())
  51    }
  52}
  53
  54impl std::fmt::Display for ThreadId {
  55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  56        write!(f, "{}", self.0)
  57    }
  58}
  59
  60#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
  61pub struct MessageId(pub(crate) usize);
  62
  63impl MessageId {
  64    fn post_inc(&mut self) -> Self {
  65        Self(post_inc(&mut self.0))
  66    }
  67}
  68
  69/// A message in a [`Thread`].
  70#[derive(Debug, Clone)]
  71pub struct Message {
  72    pub id: MessageId,
  73    pub role: Role,
  74    pub segments: Vec<MessageSegment>,
  75}
  76
  77impl Message {
  78    pub fn push_thinking(&mut self, text: &str) {
  79        if let Some(MessageSegment::Thinking(segment)) = self.segments.last_mut() {
  80            segment.push_str(text);
  81        } else {
  82            self.segments
  83                .push(MessageSegment::Thinking(text.to_string()));
  84        }
  85    }
  86
  87    pub fn push_text(&mut self, text: &str) {
  88        if let Some(MessageSegment::Text(segment)) = self.segments.last_mut() {
  89            segment.push_str(text);
  90        } else {
  91            self.segments.push(MessageSegment::Text(text.to_string()));
  92        }
  93    }
  94
  95    pub fn to_string(&self) -> String {
  96        let mut result = String::new();
  97        for segment in &self.segments {
  98            match segment {
  99                MessageSegment::Text(text) => result.push_str(text),
 100                MessageSegment::Thinking(text) => {
 101                    result.push_str("<think>");
 102                    result.push_str(text);
 103                    result.push_str("</think>");
 104                }
 105            }
 106        }
 107        result
 108    }
 109}
 110
 111#[derive(Debug, Clone)]
 112pub enum MessageSegment {
 113    Text(String),
 114    Thinking(String),
 115}
 116
 117#[derive(Debug, Clone, Serialize, Deserialize)]
 118pub struct ProjectSnapshot {
 119    pub worktree_snapshots: Vec<WorktreeSnapshot>,
 120    pub unsaved_buffer_paths: Vec<String>,
 121    pub timestamp: DateTime<Utc>,
 122}
 123
 124#[derive(Debug, Clone, Serialize, Deserialize)]
 125pub struct WorktreeSnapshot {
 126    pub worktree_path: String,
 127    pub git_state: Option<GitState>,
 128}
 129
 130#[derive(Debug, Clone, Serialize, Deserialize)]
 131pub struct GitState {
 132    pub remote_url: Option<String>,
 133    pub head_sha: Option<String>,
 134    pub current_branch: Option<String>,
 135    pub diff: Option<String>,
 136}
 137
 138#[derive(Clone)]
 139pub struct ThreadCheckpoint {
 140    message_id: MessageId,
 141    git_checkpoint: GitStoreCheckpoint,
 142}
 143
 144#[derive(Copy, Clone, Debug)]
 145pub enum ThreadFeedback {
 146    Positive,
 147    Negative,
 148}
 149
 150pub enum LastRestoreCheckpoint {
 151    Pending {
 152        message_id: MessageId,
 153    },
 154    Error {
 155        message_id: MessageId,
 156        error: String,
 157    },
 158}
 159
 160impl LastRestoreCheckpoint {
 161    pub fn message_id(&self) -> MessageId {
 162        match self {
 163            LastRestoreCheckpoint::Pending { message_id } => *message_id,
 164            LastRestoreCheckpoint::Error { message_id, .. } => *message_id,
 165        }
 166    }
 167}
 168
 169/// A thread of conversation with the LLM.
 170pub struct Thread {
 171    id: ThreadId,
 172    updated_at: DateTime<Utc>,
 173    summary: Option<SharedString>,
 174    pending_summary: Task<Option<()>>,
 175    messages: Vec<Message>,
 176    next_message_id: MessageId,
 177    context: BTreeMap<ContextId, ContextSnapshot>,
 178    context_by_message: HashMap<MessageId, Vec<ContextId>>,
 179    system_prompt_context: Option<AssistantSystemPromptContext>,
 180    checkpoints_by_message: HashMap<MessageId, ThreadCheckpoint>,
 181    completion_count: usize,
 182    pending_completions: Vec<PendingCompletion>,
 183    project: Entity<Project>,
 184    prompt_builder: Arc<PromptBuilder>,
 185    tools: Arc<ToolWorkingSet>,
 186    tool_use: ToolUseState,
 187    action_log: Entity<ActionLog>,
 188    last_restore_checkpoint: Option<LastRestoreCheckpoint>,
 189    pending_checkpoint: Option<ThreadCheckpoint>,
 190    initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
 191    cumulative_token_usage: TokenUsage,
 192    feedback: Option<ThreadFeedback>,
 193}
 194
 195impl Thread {
 196    pub fn new(
 197        project: Entity<Project>,
 198        tools: Arc<ToolWorkingSet>,
 199        prompt_builder: Arc<PromptBuilder>,
 200        cx: &mut Context<Self>,
 201    ) -> Self {
 202        Self {
 203            id: ThreadId::new(),
 204            updated_at: Utc::now(),
 205            summary: None,
 206            pending_summary: Task::ready(None),
 207            messages: Vec::new(),
 208            next_message_id: MessageId(0),
 209            context: BTreeMap::default(),
 210            context_by_message: HashMap::default(),
 211            system_prompt_context: None,
 212            checkpoints_by_message: HashMap::default(),
 213            completion_count: 0,
 214            pending_completions: Vec::new(),
 215            project: project.clone(),
 216            prompt_builder,
 217            tools: tools.clone(),
 218            last_restore_checkpoint: None,
 219            pending_checkpoint: None,
 220            tool_use: ToolUseState::new(tools.clone()),
 221            action_log: cx.new(|_| ActionLog::new()),
 222            initial_project_snapshot: {
 223                let project_snapshot = Self::project_snapshot(project, cx);
 224                cx.foreground_executor()
 225                    .spawn(async move { Some(project_snapshot.await) })
 226                    .shared()
 227            },
 228            cumulative_token_usage: TokenUsage::default(),
 229            feedback: None,
 230        }
 231    }
 232
 233    pub fn deserialize(
 234        id: ThreadId,
 235        serialized: SerializedThread,
 236        project: Entity<Project>,
 237        tools: Arc<ToolWorkingSet>,
 238        prompt_builder: Arc<PromptBuilder>,
 239        cx: &mut Context<Self>,
 240    ) -> Self {
 241        let next_message_id = MessageId(
 242            serialized
 243                .messages
 244                .last()
 245                .map(|message| message.id.0 + 1)
 246                .unwrap_or(0),
 247        );
 248        let tool_use =
 249            ToolUseState::from_serialized_messages(tools.clone(), &serialized.messages, |_| true);
 250
 251        Self {
 252            id,
 253            updated_at: serialized.updated_at,
 254            summary: Some(serialized.summary),
 255            pending_summary: Task::ready(None),
 256            messages: serialized
 257                .messages
 258                .into_iter()
 259                .map(|message| Message {
 260                    id: message.id,
 261                    role: message.role,
 262                    segments: message
 263                        .segments
 264                        .into_iter()
 265                        .map(|segment| match segment {
 266                            SerializedMessageSegment::Text { text } => MessageSegment::Text(text),
 267                            SerializedMessageSegment::Thinking { text } => {
 268                                MessageSegment::Thinking(text)
 269                            }
 270                        })
 271                        .collect(),
 272                })
 273                .collect(),
 274            next_message_id,
 275            context: BTreeMap::default(),
 276            context_by_message: HashMap::default(),
 277            system_prompt_context: None,
 278            checkpoints_by_message: HashMap::default(),
 279            completion_count: 0,
 280            pending_completions: Vec::new(),
 281            last_restore_checkpoint: None,
 282            pending_checkpoint: None,
 283            project,
 284            prompt_builder,
 285            tools,
 286            tool_use,
 287            action_log: cx.new(|_| ActionLog::new()),
 288            initial_project_snapshot: Task::ready(serialized.initial_project_snapshot).shared(),
 289            // TODO: persist token usage?
 290            cumulative_token_usage: TokenUsage::default(),
 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            })
 652        })
 653    }
 654
 655    pub fn set_system_prompt_context(&mut self, context: AssistantSystemPromptContext) {
 656        self.system_prompt_context = Some(context);
 657    }
 658
 659    pub fn system_prompt_context(&self) -> &Option<AssistantSystemPromptContext> {
 660        &self.system_prompt_context
 661    }
 662
 663    pub fn load_system_prompt_context(
 664        &self,
 665        cx: &App,
 666    ) -> Task<(AssistantSystemPromptContext, Option<ThreadError>)> {
 667        let project = self.project.read(cx);
 668        let tasks = project
 669            .visible_worktrees(cx)
 670            .map(|worktree| {
 671                Self::load_worktree_info_for_system_prompt(
 672                    project.fs().clone(),
 673                    worktree.read(cx),
 674                    cx,
 675                )
 676            })
 677            .collect::<Vec<_>>();
 678
 679        cx.spawn(async |_cx| {
 680            let results = futures::future::join_all(tasks).await;
 681            let mut first_err = None;
 682            let worktrees = results
 683                .into_iter()
 684                .map(|(worktree, err)| {
 685                    if first_err.is_none() && err.is_some() {
 686                        first_err = err;
 687                    }
 688                    worktree
 689                })
 690                .collect::<Vec<_>>();
 691            (AssistantSystemPromptContext::new(worktrees), first_err)
 692        })
 693    }
 694
 695    fn load_worktree_info_for_system_prompt(
 696        fs: Arc<dyn Fs>,
 697        worktree: &Worktree,
 698        cx: &App,
 699    ) -> Task<(WorktreeInfoForSystemPrompt, Option<ThreadError>)> {
 700        let root_name = worktree.root_name().into();
 701        let abs_path = worktree.abs_path();
 702
 703        // Note that Cline supports `.clinerules` being a directory, but that is not currently
 704        // supported. This doesn't seem to occur often in GitHub repositories.
 705        const RULES_FILE_NAMES: [&'static str; 6] = [
 706            ".rules",
 707            ".cursorrules",
 708            ".windsurfrules",
 709            ".clinerules",
 710            ".github/copilot-instructions.md",
 711            "CLAUDE.md",
 712        ];
 713        let selected_rules_file = RULES_FILE_NAMES
 714            .into_iter()
 715            .filter_map(|name| {
 716                worktree
 717                    .entry_for_path(name)
 718                    .filter(|entry| entry.is_file())
 719                    .map(|entry| (entry.path.clone(), worktree.absolutize(&entry.path)))
 720            })
 721            .next();
 722
 723        if let Some((rel_rules_path, abs_rules_path)) = selected_rules_file {
 724            cx.spawn(async move |_| {
 725                let rules_file_result = maybe!(async move {
 726                    let abs_rules_path = abs_rules_path?;
 727                    let text = fs.load(&abs_rules_path).await.with_context(|| {
 728                        format!("Failed to load assistant rules file {:?}", abs_rules_path)
 729                    })?;
 730                    anyhow::Ok(RulesFile {
 731                        rel_path: rel_rules_path,
 732                        abs_path: abs_rules_path.into(),
 733                        text: text.trim().to_string(),
 734                    })
 735                })
 736                .await;
 737                let (rules_file, rules_file_error) = match rules_file_result {
 738                    Ok(rules_file) => (Some(rules_file), None),
 739                    Err(err) => (
 740                        None,
 741                        Some(ThreadError::Message {
 742                            header: "Error loading rules file".into(),
 743                            message: format!("{err}").into(),
 744                        }),
 745                    ),
 746                };
 747                let worktree_info = WorktreeInfoForSystemPrompt {
 748                    root_name,
 749                    abs_path,
 750                    rules_file,
 751                };
 752                (worktree_info, rules_file_error)
 753            })
 754        } else {
 755            Task::ready((
 756                WorktreeInfoForSystemPrompt {
 757                    root_name,
 758                    abs_path,
 759                    rules_file: None,
 760                },
 761                None,
 762            ))
 763        }
 764    }
 765
 766    pub fn send_to_model(
 767        &mut self,
 768        model: Arc<dyn LanguageModel>,
 769        request_kind: RequestKind,
 770        cx: &mut Context<Self>,
 771    ) {
 772        let mut request = self.to_completion_request(request_kind, cx);
 773        request.tools = {
 774            let mut tools = Vec::new();
 775            tools.extend(self.tools().enabled_tools(cx).into_iter().map(|tool| {
 776                LanguageModelRequestTool {
 777                    name: tool.name(),
 778                    description: tool.description(),
 779                    input_schema: tool.input_schema(),
 780                }
 781            }));
 782
 783            tools
 784        };
 785
 786        self.stream_completion(request, model, cx);
 787    }
 788
 789    pub fn to_completion_request(
 790        &self,
 791        request_kind: RequestKind,
 792        cx: &App,
 793    ) -> LanguageModelRequest {
 794        let mut request = LanguageModelRequest {
 795            messages: vec![],
 796            tools: Vec::new(),
 797            stop: Vec::new(),
 798            temperature: None,
 799        };
 800
 801        if let Some(system_prompt_context) = self.system_prompt_context.as_ref() {
 802            if let Some(system_prompt) = self
 803                .prompt_builder
 804                .generate_assistant_system_prompt(system_prompt_context)
 805                .context("failed to generate assistant system prompt")
 806                .log_err()
 807            {
 808                request.messages.push(LanguageModelRequestMessage {
 809                    role: Role::System,
 810                    content: vec![MessageContent::Text(system_prompt)],
 811                    cache: true,
 812                });
 813            }
 814        } else {
 815            log::error!("system_prompt_context not set.")
 816        }
 817
 818        let mut referenced_context_ids = HashSet::default();
 819
 820        for message in &self.messages {
 821            if let Some(context_ids) = self.context_by_message.get(&message.id) {
 822                referenced_context_ids.extend(context_ids);
 823            }
 824
 825            let mut request_message = LanguageModelRequestMessage {
 826                role: message.role,
 827                content: Vec::new(),
 828                cache: false,
 829            };
 830
 831            match request_kind {
 832                RequestKind::Chat => {
 833                    self.tool_use
 834                        .attach_tool_results(message.id, &mut request_message);
 835                }
 836                RequestKind::Summarize => {
 837                    // We don't care about tool use during summarization.
 838                }
 839            }
 840
 841            if !message.segments.is_empty() {
 842                request_message
 843                    .content
 844                    .push(MessageContent::Text(message.to_string()));
 845            }
 846
 847            match request_kind {
 848                RequestKind::Chat => {
 849                    self.tool_use
 850                        .attach_tool_uses(message.id, &mut request_message);
 851                }
 852                RequestKind::Summarize => {
 853                    // We don't care about tool use during summarization.
 854                }
 855            };
 856
 857            request.messages.push(request_message);
 858        }
 859
 860        if !referenced_context_ids.is_empty() {
 861            let mut context_message = LanguageModelRequestMessage {
 862                role: Role::User,
 863                content: Vec::new(),
 864                cache: false,
 865            };
 866
 867            let referenced_context = referenced_context_ids
 868                .into_iter()
 869                .filter_map(|context_id| self.context.get(context_id))
 870                .cloned();
 871            attach_context_to_message(&mut context_message, referenced_context);
 872
 873            request.messages.push(context_message);
 874        }
 875
 876        self.attached_tracked_files_state(&mut request.messages, cx);
 877
 878        request
 879    }
 880
 881    fn attached_tracked_files_state(
 882        &self,
 883        messages: &mut Vec<LanguageModelRequestMessage>,
 884        cx: &App,
 885    ) {
 886        const STALE_FILES_HEADER: &str = "These files changed since last read:";
 887
 888        let mut stale_message = String::new();
 889
 890        let action_log = self.action_log.read(cx);
 891
 892        for stale_file in action_log.stale_buffers(cx) {
 893            let Some(file) = stale_file.read(cx).file() else {
 894                continue;
 895            };
 896
 897            if stale_message.is_empty() {
 898                write!(&mut stale_message, "{}", STALE_FILES_HEADER).ok();
 899            }
 900
 901            writeln!(&mut stale_message, "- {}", file.path().display()).ok();
 902        }
 903
 904        let mut content = Vec::with_capacity(2);
 905
 906        if !stale_message.is_empty() {
 907            content.push(stale_message.into());
 908        }
 909
 910        if action_log.has_edited_files_since_project_diagnostics_check() {
 911            content.push(
 912                "When you're done making changes, make sure to check project diagnostics and fix all errors AND warnings you introduced!".into(),
 913            );
 914        }
 915
 916        if !content.is_empty() {
 917            let context_message = LanguageModelRequestMessage {
 918                role: Role::User,
 919                content,
 920                cache: false,
 921            };
 922
 923            messages.push(context_message);
 924        }
 925    }
 926
 927    pub fn stream_completion(
 928        &mut self,
 929        request: LanguageModelRequest,
 930        model: Arc<dyn LanguageModel>,
 931        cx: &mut Context<Self>,
 932    ) {
 933        let pending_completion_id = post_inc(&mut self.completion_count);
 934
 935        let task = cx.spawn(async move |thread, cx| {
 936            let stream = model.stream_completion(request, &cx);
 937            let initial_token_usage =
 938                thread.read_with(cx, |thread, _cx| thread.cumulative_token_usage.clone());
 939            let stream_completion = async {
 940                let mut events = stream.await?;
 941                let mut stop_reason = StopReason::EndTurn;
 942                let mut current_token_usage = TokenUsage::default();
 943
 944                while let Some(event) = events.next().await {
 945                    let event = event?;
 946
 947                    thread.update(cx, |thread, cx| {
 948                        match event {
 949                            LanguageModelCompletionEvent::StartMessage { .. } => {
 950                                thread.insert_message(
 951                                    Role::Assistant,
 952                                    vec![MessageSegment::Text(String::new())],
 953                                    cx,
 954                                );
 955                            }
 956                            LanguageModelCompletionEvent::Stop(reason) => {
 957                                stop_reason = reason;
 958                            }
 959                            LanguageModelCompletionEvent::UsageUpdate(token_usage) => {
 960                                thread.cumulative_token_usage =
 961                                    thread.cumulative_token_usage.clone() + token_usage.clone()
 962                                        - current_token_usage.clone();
 963                                current_token_usage = token_usage;
 964                            }
 965                            LanguageModelCompletionEvent::Text(chunk) => {
 966                                if let Some(last_message) = thread.messages.last_mut() {
 967                                    if last_message.role == Role::Assistant {
 968                                        last_message.push_text(&chunk);
 969                                        cx.emit(ThreadEvent::StreamedAssistantText(
 970                                            last_message.id,
 971                                            chunk,
 972                                        ));
 973                                    } else {
 974                                        // If we won't have an Assistant message yet, assume this chunk marks the beginning
 975                                        // of a new Assistant response.
 976                                        //
 977                                        // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
 978                                        // will result in duplicating the text of the chunk in the rendered Markdown.
 979                                        thread.insert_message(
 980                                            Role::Assistant,
 981                                            vec![MessageSegment::Text(chunk.to_string())],
 982                                            cx,
 983                                        );
 984                                    };
 985                                }
 986                            }
 987                            LanguageModelCompletionEvent::Thinking(chunk) => {
 988                                if let Some(last_message) = thread.messages.last_mut() {
 989                                    if last_message.role == Role::Assistant {
 990                                        last_message.push_thinking(&chunk);
 991                                        cx.emit(ThreadEvent::StreamedAssistantThinking(
 992                                            last_message.id,
 993                                            chunk,
 994                                        ));
 995                                    } else {
 996                                        // If we won't have an Assistant message yet, assume this chunk marks the beginning
 997                                        // of a new Assistant response.
 998                                        //
 999                                        // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
1000                                        // will result in duplicating the text of the chunk in the rendered Markdown.
1001                                        thread.insert_message(
1002                                            Role::Assistant,
1003                                            vec![MessageSegment::Thinking(chunk.to_string())],
1004                                            cx,
1005                                        );
1006                                    };
1007                                }
1008                            }
1009                            LanguageModelCompletionEvent::ToolUse(tool_use) => {
1010                                if let Some(last_assistant_message) = thread
1011                                    .messages
1012                                    .iter()
1013                                    .rfind(|message| message.role == Role::Assistant)
1014                                {
1015                                    thread.tool_use.request_tool_use(
1016                                        last_assistant_message.id,
1017                                        tool_use,
1018                                        cx,
1019                                    );
1020                                }
1021                            }
1022                        }
1023
1024                        thread.touch_updated_at();
1025                        cx.emit(ThreadEvent::StreamedCompletion);
1026                        cx.notify();
1027                    })?;
1028
1029                    smol::future::yield_now().await;
1030                }
1031
1032                thread.update(cx, |thread, cx| {
1033                    thread
1034                        .pending_completions
1035                        .retain(|completion| completion.id != pending_completion_id);
1036
1037                    if thread.summary.is_none() && thread.messages.len() >= 2 {
1038                        thread.summarize(cx);
1039                    }
1040                })?;
1041
1042                anyhow::Ok(stop_reason)
1043            };
1044
1045            let result = stream_completion.await;
1046
1047            thread
1048                .update(cx, |thread, cx| {
1049                    thread.finalize_pending_checkpoint(cx);
1050                    match result.as_ref() {
1051                        Ok(stop_reason) => match stop_reason {
1052                            StopReason::ToolUse => {
1053                                cx.emit(ThreadEvent::UsePendingTools);
1054                            }
1055                            StopReason::EndTurn => {}
1056                            StopReason::MaxTokens => {}
1057                        },
1058                        Err(error) => {
1059                            if error.is::<PaymentRequiredError>() {
1060                                cx.emit(ThreadEvent::ShowError(ThreadError::PaymentRequired));
1061                            } else if error.is::<MaxMonthlySpendReachedError>() {
1062                                cx.emit(ThreadEvent::ShowError(
1063                                    ThreadError::MaxMonthlySpendReached,
1064                                ));
1065                            } else {
1066                                let error_message = error
1067                                    .chain()
1068                                    .map(|err| err.to_string())
1069                                    .collect::<Vec<_>>()
1070                                    .join("\n");
1071                                cx.emit(ThreadEvent::ShowError(ThreadError::Message {
1072                                    header: "Error interacting with language model".into(),
1073                                    message: SharedString::from(error_message.clone()),
1074                                }));
1075                            }
1076
1077                            thread.cancel_last_completion(cx);
1078                        }
1079                    }
1080                    cx.emit(ThreadEvent::DoneStreaming);
1081
1082                    if let Ok(initial_usage) = initial_token_usage {
1083                        let usage = thread.cumulative_token_usage.clone() - initial_usage;
1084
1085                        telemetry::event!(
1086                            "Assistant Thread Completion",
1087                            thread_id = thread.id().to_string(),
1088                            model = model.telemetry_id(),
1089                            model_provider = model.provider_id().to_string(),
1090                            input_tokens = usage.input_tokens,
1091                            output_tokens = usage.output_tokens,
1092                            cache_creation_input_tokens = usage.cache_creation_input_tokens,
1093                            cache_read_input_tokens = usage.cache_read_input_tokens,
1094                        );
1095                    }
1096                })
1097                .ok();
1098        });
1099
1100        self.pending_completions.push(PendingCompletion {
1101            id: pending_completion_id,
1102            _task: task,
1103        });
1104    }
1105
1106    pub fn summarize(&mut self, cx: &mut Context<Self>) {
1107        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
1108            return;
1109        };
1110        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
1111            return;
1112        };
1113
1114        if !provider.is_authenticated(cx) {
1115            return;
1116        }
1117
1118        let mut request = self.to_completion_request(RequestKind::Summarize, cx);
1119        request.messages.push(LanguageModelRequestMessage {
1120            role: Role::User,
1121            content: vec![
1122                "Generate a concise 3-7 word title for this conversation, omitting punctuation. Go straight to the title, without any preamble and prefix like `Here's a concise suggestion:...` or `Title:`"
1123                    .into(),
1124            ],
1125            cache: false,
1126        });
1127
1128        self.pending_summary = cx.spawn(async move |this, cx| {
1129            async move {
1130                let stream = model.stream_completion_text(request, &cx);
1131                let mut messages = stream.await?;
1132
1133                let mut new_summary = String::new();
1134                while let Some(message) = messages.stream.next().await {
1135                    let text = message?;
1136                    let mut lines = text.lines();
1137                    new_summary.extend(lines.next());
1138
1139                    // Stop if the LLM generated multiple lines.
1140                    if lines.next().is_some() {
1141                        break;
1142                    }
1143                }
1144
1145                this.update(cx, |this, cx| {
1146                    if !new_summary.is_empty() {
1147                        this.summary = Some(new_summary.into());
1148                    }
1149
1150                    cx.emit(ThreadEvent::SummaryChanged);
1151                })?;
1152
1153                anyhow::Ok(())
1154            }
1155            .log_err()
1156            .await
1157        });
1158    }
1159
1160    pub fn use_pending_tools(
1161        &mut self,
1162        cx: &mut Context<Self>,
1163    ) -> impl IntoIterator<Item = PendingToolUse> {
1164        let request = self.to_completion_request(RequestKind::Chat, cx);
1165        let messages = Arc::new(request.messages);
1166        let pending_tool_uses = self
1167            .tool_use
1168            .pending_tool_uses()
1169            .into_iter()
1170            .filter(|tool_use| tool_use.status.is_idle())
1171            .cloned()
1172            .collect::<Vec<_>>();
1173
1174        for tool_use in pending_tool_uses.iter() {
1175            if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
1176                if tool.needs_confirmation()
1177                    && !AssistantSettings::get_global(cx).always_allow_tool_actions
1178                {
1179                    self.tool_use.confirm_tool_use(
1180                        tool_use.id.clone(),
1181                        tool_use.ui_text.clone(),
1182                        tool_use.input.clone(),
1183                        messages.clone(),
1184                        tool,
1185                    );
1186                    cx.emit(ThreadEvent::ToolConfirmationNeeded);
1187                } else {
1188                    self.run_tool(
1189                        tool_use.id.clone(),
1190                        tool_use.ui_text.clone(),
1191                        tool_use.input.clone(),
1192                        &messages,
1193                        tool,
1194                        cx,
1195                    );
1196                }
1197            } else if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
1198                self.run_tool(
1199                    tool_use.id.clone(),
1200                    tool_use.ui_text.clone(),
1201                    tool_use.input.clone(),
1202                    &messages,
1203                    tool,
1204                    cx,
1205                );
1206            }
1207        }
1208
1209        pending_tool_uses
1210    }
1211
1212    pub fn run_tool(
1213        &mut self,
1214        tool_use_id: LanguageModelToolUseId,
1215        ui_text: impl Into<SharedString>,
1216        input: serde_json::Value,
1217        messages: &[LanguageModelRequestMessage],
1218        tool: Arc<dyn Tool>,
1219        cx: &mut Context<'_, Thread>,
1220    ) {
1221        let task = self.spawn_tool_use(tool_use_id.clone(), messages, input, tool, cx);
1222        self.tool_use
1223            .run_pending_tool(tool_use_id, ui_text.into(), task);
1224    }
1225
1226    fn spawn_tool_use(
1227        &mut self,
1228        tool_use_id: LanguageModelToolUseId,
1229        messages: &[LanguageModelRequestMessage],
1230        input: serde_json::Value,
1231        tool: Arc<dyn Tool>,
1232        cx: &mut Context<Thread>,
1233    ) -> Task<()> {
1234        let run_tool = tool.run(
1235            input,
1236            messages,
1237            self.project.clone(),
1238            self.action_log.clone(),
1239            cx,
1240        );
1241
1242        cx.spawn({
1243            async move |thread: WeakEntity<Thread>, cx| {
1244                let output = run_tool.await;
1245
1246                thread
1247                    .update(cx, |thread, cx| {
1248                        let pending_tool_use = thread
1249                            .tool_use
1250                            .insert_tool_output(tool_use_id.clone(), output);
1251
1252                        cx.emit(ThreadEvent::ToolFinished {
1253                            tool_use_id,
1254                            pending_tool_use,
1255                            canceled: false,
1256                        });
1257                    })
1258                    .ok();
1259            }
1260        })
1261    }
1262
1263    pub fn attach_tool_results(
1264        &mut self,
1265        updated_context: Vec<ContextSnapshot>,
1266        cx: &mut Context<Self>,
1267    ) {
1268        self.context.extend(
1269            updated_context
1270                .into_iter()
1271                .map(|context| (context.id, context)),
1272        );
1273
1274        // Insert a user message to contain the tool results.
1275        self.insert_user_message(
1276            // TODO: Sending up a user message without any content results in the model sending back
1277            // responses that also don't have any content. We currently don't handle this case well,
1278            // so for now we provide some text to keep the model on track.
1279            "Here are the tool results.",
1280            Vec::new(),
1281            None,
1282            cx,
1283        );
1284    }
1285
1286    /// Cancels the last pending completion, if there are any pending.
1287    ///
1288    /// Returns whether a completion was canceled.
1289    pub fn cancel_last_completion(&mut self, cx: &mut Context<Self>) -> bool {
1290        let canceled = if self.pending_completions.pop().is_some() {
1291            true
1292        } else {
1293            let mut canceled = false;
1294            for pending_tool_use in self.tool_use.cancel_pending() {
1295                canceled = true;
1296                cx.emit(ThreadEvent::ToolFinished {
1297                    tool_use_id: pending_tool_use.id.clone(),
1298                    pending_tool_use: Some(pending_tool_use),
1299                    canceled: true,
1300                });
1301            }
1302            canceled
1303        };
1304        self.finalize_pending_checkpoint(cx);
1305        canceled
1306    }
1307
1308    /// Returns the feedback given to the thread, if any.
1309    pub fn feedback(&self) -> Option<ThreadFeedback> {
1310        self.feedback
1311    }
1312
1313    /// Reports feedback about the thread and stores it in our telemetry backend.
1314    pub fn report_feedback(
1315        &mut self,
1316        feedback: ThreadFeedback,
1317        cx: &mut Context<Self>,
1318    ) -> Task<Result<()>> {
1319        let final_project_snapshot = Self::project_snapshot(self.project.clone(), cx);
1320        let serialized_thread = self.serialize(cx);
1321        let thread_id = self.id().clone();
1322        let client = self.project.read(cx).client();
1323        self.feedback = Some(feedback);
1324        cx.notify();
1325
1326        cx.background_spawn(async move {
1327            let final_project_snapshot = final_project_snapshot.await;
1328            let serialized_thread = serialized_thread.await?;
1329            let thread_data =
1330                serde_json::to_value(serialized_thread).unwrap_or_else(|_| serde_json::Value::Null);
1331
1332            let rating = match feedback {
1333                ThreadFeedback::Positive => "positive",
1334                ThreadFeedback::Negative => "negative",
1335            };
1336            telemetry::event!(
1337                "Assistant Thread Rated",
1338                rating,
1339                thread_id,
1340                thread_data,
1341                final_project_snapshot
1342            );
1343            client.telemetry().flush_events();
1344
1345            Ok(())
1346        })
1347    }
1348
1349    /// Create a snapshot of the current project state including git information and unsaved buffers.
1350    fn project_snapshot(
1351        project: Entity<Project>,
1352        cx: &mut Context<Self>,
1353    ) -> Task<Arc<ProjectSnapshot>> {
1354        let git_store = project.read(cx).git_store().clone();
1355        let worktree_snapshots: Vec<_> = project
1356            .read(cx)
1357            .visible_worktrees(cx)
1358            .map(|worktree| Self::worktree_snapshot(worktree, git_store.clone(), cx))
1359            .collect();
1360
1361        cx.spawn(async move |_, cx| {
1362            let worktree_snapshots = futures::future::join_all(worktree_snapshots).await;
1363
1364            let mut unsaved_buffers = Vec::new();
1365            cx.update(|app_cx| {
1366                let buffer_store = project.read(app_cx).buffer_store();
1367                for buffer_handle in buffer_store.read(app_cx).buffers() {
1368                    let buffer = buffer_handle.read(app_cx);
1369                    if buffer.is_dirty() {
1370                        if let Some(file) = buffer.file() {
1371                            let path = file.path().to_string_lossy().to_string();
1372                            unsaved_buffers.push(path);
1373                        }
1374                    }
1375                }
1376            })
1377            .ok();
1378
1379            Arc::new(ProjectSnapshot {
1380                worktree_snapshots,
1381                unsaved_buffer_paths: unsaved_buffers,
1382                timestamp: Utc::now(),
1383            })
1384        })
1385    }
1386
1387    fn worktree_snapshot(
1388        worktree: Entity<project::Worktree>,
1389        git_store: Entity<GitStore>,
1390        cx: &App,
1391    ) -> Task<WorktreeSnapshot> {
1392        cx.spawn(async move |cx| {
1393            // Get worktree path and snapshot
1394            let worktree_info = cx.update(|app_cx| {
1395                let worktree = worktree.read(app_cx);
1396                let path = worktree.abs_path().to_string_lossy().to_string();
1397                let snapshot = worktree.snapshot();
1398                (path, snapshot)
1399            });
1400
1401            let Ok((worktree_path, snapshot)) = worktree_info else {
1402                return WorktreeSnapshot {
1403                    worktree_path: String::new(),
1404                    git_state: None,
1405                };
1406            };
1407
1408            let repo_info = git_store
1409                .update(cx, |git_store, cx| {
1410                    git_store
1411                        .repositories()
1412                        .values()
1413                        .find(|repo| repo.read(cx).worktree_id == snapshot.id())
1414                        .and_then(|repo| {
1415                            let repo = repo.read(cx);
1416                            Some((repo.branch().cloned(), repo.local_repository()?))
1417                        })
1418                })
1419                .ok()
1420                .flatten();
1421
1422            // Extract git information
1423            let git_state = match repo_info {
1424                None => None,
1425                Some((branch, repo)) => {
1426                    let current_branch = branch.map(|branch| branch.name.to_string());
1427                    let remote_url = repo.remote_url("origin");
1428                    let head_sha = repo.head_sha();
1429
1430                    // Get diff asynchronously
1431                    let diff = repo
1432                        .diff(git::repository::DiffType::HeadToWorktree, cx.clone())
1433                        .await
1434                        .ok();
1435
1436                    Some(GitState {
1437                        remote_url,
1438                        head_sha,
1439                        current_branch,
1440                        diff,
1441                    })
1442                }
1443            };
1444
1445            WorktreeSnapshot {
1446                worktree_path,
1447                git_state,
1448            }
1449        })
1450    }
1451
1452    pub fn to_markdown(&self, cx: &App) -> Result<String> {
1453        let mut markdown = Vec::new();
1454
1455        if let Some(summary) = self.summary() {
1456            writeln!(markdown, "# {summary}\n")?;
1457        };
1458
1459        for message in self.messages() {
1460            writeln!(
1461                markdown,
1462                "## {role}\n",
1463                role = match message.role {
1464                    Role::User => "User",
1465                    Role::Assistant => "Assistant",
1466                    Role::System => "System",
1467                }
1468            )?;
1469            for segment in &message.segments {
1470                match segment {
1471                    MessageSegment::Text(text) => writeln!(markdown, "{}\n", text)?,
1472                    MessageSegment::Thinking(text) => {
1473                        writeln!(markdown, "<think>{}</think>\n", text)?
1474                    }
1475                }
1476            }
1477
1478            for tool_use in self.tool_uses_for_message(message.id, cx) {
1479                writeln!(
1480                    markdown,
1481                    "**Use Tool: {} ({})**",
1482                    tool_use.name, tool_use.id
1483                )?;
1484                writeln!(markdown, "```json")?;
1485                writeln!(
1486                    markdown,
1487                    "{}",
1488                    serde_json::to_string_pretty(&tool_use.input)?
1489                )?;
1490                writeln!(markdown, "```")?;
1491            }
1492
1493            for tool_result in self.tool_results_for_message(message.id) {
1494                write!(markdown, "**Tool Results: {}", tool_result.tool_use_id)?;
1495                if tool_result.is_error {
1496                    write!(markdown, " (Error)")?;
1497                }
1498
1499                writeln!(markdown, "**\n")?;
1500                writeln!(markdown, "{}", tool_result.content)?;
1501            }
1502        }
1503
1504        Ok(String::from_utf8_lossy(&markdown).to_string())
1505    }
1506
1507    pub fn action_log(&self) -> &Entity<ActionLog> {
1508        &self.action_log
1509    }
1510
1511    pub fn project(&self) -> &Entity<Project> {
1512        &self.project
1513    }
1514
1515    pub fn cumulative_token_usage(&self) -> TokenUsage {
1516        self.cumulative_token_usage.clone()
1517    }
1518
1519    pub fn deny_tool_use(&mut self, tool_use_id: LanguageModelToolUseId, cx: &mut Context<Self>) {
1520        let err = Err(anyhow::anyhow!(
1521            "Permission to run tool action denied by user"
1522        ));
1523
1524        self.tool_use.insert_tool_output(tool_use_id.clone(), err);
1525
1526        cx.emit(ThreadEvent::ToolFinished {
1527            tool_use_id,
1528            pending_tool_use: None,
1529            canceled: true,
1530        });
1531    }
1532}
1533
1534#[derive(Debug, Clone)]
1535pub enum ThreadError {
1536    PaymentRequired,
1537    MaxMonthlySpendReached,
1538    Message {
1539        header: SharedString,
1540        message: SharedString,
1541    },
1542}
1543
1544#[derive(Debug, Clone)]
1545pub enum ThreadEvent {
1546    ShowError(ThreadError),
1547    StreamedCompletion,
1548    StreamedAssistantText(MessageId, String),
1549    StreamedAssistantThinking(MessageId, String),
1550    DoneStreaming,
1551    MessageAdded(MessageId),
1552    MessageEdited(MessageId),
1553    MessageDeleted(MessageId),
1554    SummaryChanged,
1555    UsePendingTools,
1556    ToolFinished {
1557        #[allow(unused)]
1558        tool_use_id: LanguageModelToolUseId,
1559        /// The pending tool use that corresponds to this tool.
1560        pending_tool_use: Option<PendingToolUse>,
1561        /// Whether the tool was canceled by the user.
1562        canceled: bool,
1563    },
1564    CheckpointChanged,
1565    ToolConfirmationNeeded,
1566}
1567
1568impl EventEmitter<ThreadEvent> for Thread {}
1569
1570struct PendingCompletion {
1571    id: usize,
1572    _task: Task<()>,
1573}