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