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 checkpoint_for_message(&self, id: MessageId) -> Option<ThreadCheckpoint> {
 356        self.checkpoints_by_message.get(&id).cloned()
 357    }
 358
 359    pub fn restore_checkpoint(
 360        &mut self,
 361        checkpoint: ThreadCheckpoint,
 362        cx: &mut Context<Self>,
 363    ) -> Task<Result<()>> {
 364        self.last_restore_checkpoint = Some(LastRestoreCheckpoint::Pending {
 365            message_id: checkpoint.message_id,
 366        });
 367        cx.emit(ThreadEvent::CheckpointChanged);
 368        cx.notify();
 369
 370        let project = self.project.read(cx);
 371        let restore = project
 372            .git_store()
 373            .read(cx)
 374            .restore_checkpoint(checkpoint.git_checkpoint.clone(), cx);
 375        cx.spawn(async move |this, cx| {
 376            let result = restore.await;
 377            this.update(cx, |this, cx| {
 378                if let Err(err) = result.as_ref() {
 379                    this.last_restore_checkpoint = Some(LastRestoreCheckpoint::Error {
 380                        message_id: checkpoint.message_id,
 381                        error: err.to_string(),
 382                    });
 383                } else {
 384                    this.truncate(checkpoint.message_id, cx);
 385                    this.last_restore_checkpoint = None;
 386                }
 387                this.pending_checkpoint = None;
 388                cx.emit(ThreadEvent::CheckpointChanged);
 389                cx.notify();
 390            })?;
 391            result
 392        })
 393    }
 394
 395    fn finalize_pending_checkpoint(&mut self, cx: &mut Context<Self>) {
 396        let pending_checkpoint = if self.is_generating() {
 397            return;
 398        } else if let Some(checkpoint) = self.pending_checkpoint.take() {
 399            checkpoint
 400        } else {
 401            return;
 402        };
 403
 404        let git_store = self.project.read(cx).git_store().clone();
 405        let final_checkpoint = git_store.read(cx).checkpoint(cx);
 406        cx.spawn(async move |this, cx| match final_checkpoint.await {
 407            Ok(final_checkpoint) => {
 408                let equal = git_store
 409                    .read_with(cx, |store, cx| {
 410                        store.compare_checkpoints(
 411                            pending_checkpoint.git_checkpoint.clone(),
 412                            final_checkpoint.clone(),
 413                            cx,
 414                        )
 415                    })?
 416                    .await
 417                    .unwrap_or(false);
 418
 419                if equal {
 420                    git_store
 421                        .read_with(cx, |store, cx| {
 422                            store.delete_checkpoint(pending_checkpoint.git_checkpoint, cx)
 423                        })?
 424                        .detach();
 425                } else {
 426                    this.update(cx, |this, cx| {
 427                        this.insert_checkpoint(pending_checkpoint, cx)
 428                    })?;
 429                }
 430
 431                git_store
 432                    .read_with(cx, |store, cx| {
 433                        store.delete_checkpoint(final_checkpoint, cx)
 434                    })?
 435                    .detach();
 436
 437                Ok(())
 438            }
 439            Err(_) => this.update(cx, |this, cx| {
 440                this.insert_checkpoint(pending_checkpoint, cx)
 441            }),
 442        })
 443        .detach();
 444    }
 445
 446    fn insert_checkpoint(&mut self, checkpoint: ThreadCheckpoint, cx: &mut Context<Self>) {
 447        self.checkpoints_by_message
 448            .insert(checkpoint.message_id, checkpoint);
 449        cx.emit(ThreadEvent::CheckpointChanged);
 450        cx.notify();
 451    }
 452
 453    pub fn last_restore_checkpoint(&self) -> Option<&LastRestoreCheckpoint> {
 454        self.last_restore_checkpoint.as_ref()
 455    }
 456
 457    pub fn truncate(&mut self, message_id: MessageId, cx: &mut Context<Self>) {
 458        let Some(message_ix) = self
 459            .messages
 460            .iter()
 461            .rposition(|message| message.id == message_id)
 462        else {
 463            return;
 464        };
 465        for deleted_message in self.messages.drain(message_ix..) {
 466            self.context_by_message.remove(&deleted_message.id);
 467            self.checkpoints_by_message.remove(&deleted_message.id);
 468        }
 469        cx.notify();
 470    }
 471
 472    pub fn context_for_message(&self, id: MessageId) -> Option<Vec<ContextSnapshot>> {
 473        let context = self.context_by_message.get(&id)?;
 474        Some(
 475            context
 476                .into_iter()
 477                .filter_map(|context_id| self.context.get(&context_id))
 478                .cloned()
 479                .collect::<Vec<_>>(),
 480        )
 481    }
 482
 483    /// Returns whether all of the tool uses have finished running.
 484    pub fn all_tools_finished(&self) -> bool {
 485        // If the only pending tool uses left are the ones with errors, then
 486        // that means that we've finished running all of the pending tools.
 487        self.tool_use
 488            .pending_tool_uses()
 489            .iter()
 490            .all(|tool_use| tool_use.status.is_error())
 491    }
 492
 493    pub fn tool_uses_for_message(&self, id: MessageId, cx: &App) -> Vec<ToolUse> {
 494        self.tool_use.tool_uses_for_message(id, cx)
 495    }
 496
 497    pub fn tool_results_for_message(&self, id: MessageId) -> Vec<&LanguageModelToolResult> {
 498        self.tool_use.tool_results_for_message(id)
 499    }
 500
 501    pub fn tool_result(&self, id: &LanguageModelToolUseId) -> Option<&LanguageModelToolResult> {
 502        self.tool_use.tool_result(id)
 503    }
 504
 505    pub fn message_has_tool_results(&self, message_id: MessageId) -> bool {
 506        self.tool_use.message_has_tool_results(message_id)
 507    }
 508
 509    pub fn insert_user_message(
 510        &mut self,
 511        text: impl Into<String>,
 512        context: Vec<ContextSnapshot>,
 513        git_checkpoint: Option<GitStoreCheckpoint>,
 514        cx: &mut Context<Self>,
 515    ) -> MessageId {
 516        let message_id =
 517            self.insert_message(Role::User, vec![MessageSegment::Text(text.into())], cx);
 518        let context_ids = context.iter().map(|context| context.id).collect::<Vec<_>>();
 519        self.context
 520            .extend(context.into_iter().map(|context| (context.id, context)));
 521        self.context_by_message.insert(message_id, context_ids);
 522        if let Some(git_checkpoint) = git_checkpoint {
 523            self.pending_checkpoint = Some(ThreadCheckpoint {
 524                message_id,
 525                git_checkpoint,
 526            });
 527        }
 528        message_id
 529    }
 530
 531    pub fn insert_message(
 532        &mut self,
 533        role: Role,
 534        segments: Vec<MessageSegment>,
 535        cx: &mut Context<Self>,
 536    ) -> MessageId {
 537        let id = self.next_message_id.post_inc();
 538        self.messages.push(Message { id, role, segments });
 539        self.touch_updated_at();
 540        cx.emit(ThreadEvent::MessageAdded(id));
 541        id
 542    }
 543
 544    pub fn edit_message(
 545        &mut self,
 546        id: MessageId,
 547        new_role: Role,
 548        new_segments: Vec<MessageSegment>,
 549        cx: &mut Context<Self>,
 550    ) -> bool {
 551        let Some(message) = self.messages.iter_mut().find(|message| message.id == id) else {
 552            return false;
 553        };
 554        message.role = new_role;
 555        message.segments = new_segments;
 556        self.touch_updated_at();
 557        cx.emit(ThreadEvent::MessageEdited(id));
 558        true
 559    }
 560
 561    pub fn delete_message(&mut self, id: MessageId, cx: &mut Context<Self>) -> bool {
 562        let Some(index) = self.messages.iter().position(|message| message.id == id) else {
 563            return false;
 564        };
 565        self.messages.remove(index);
 566        self.context_by_message.remove(&id);
 567        self.touch_updated_at();
 568        cx.emit(ThreadEvent::MessageDeleted(id));
 569        true
 570    }
 571
 572    /// Returns the representation of this [`Thread`] in a textual form.
 573    ///
 574    /// This is the representation we use when attaching a thread as context to another thread.
 575    pub fn text(&self) -> String {
 576        let mut text = String::new();
 577
 578        for message in &self.messages {
 579            text.push_str(match message.role {
 580                language_model::Role::User => "User:",
 581                language_model::Role::Assistant => "Assistant:",
 582                language_model::Role::System => "System:",
 583            });
 584            text.push('\n');
 585
 586            for segment in &message.segments {
 587                match segment {
 588                    MessageSegment::Text(content) => text.push_str(content),
 589                    MessageSegment::Thinking(content) => {
 590                        text.push_str(&format!("<think>{}</think>", content))
 591                    }
 592                }
 593            }
 594            text.push('\n');
 595        }
 596
 597        text
 598    }
 599
 600    /// Serializes this thread into a format for storage or telemetry.
 601    pub fn serialize(&self, cx: &mut Context<Self>) -> Task<Result<SerializedThread>> {
 602        let initial_project_snapshot = self.initial_project_snapshot.clone();
 603        cx.spawn(async move |this, cx| {
 604            let initial_project_snapshot = initial_project_snapshot.await;
 605            this.read_with(cx, |this, cx| SerializedThread {
 606                version: SerializedThread::VERSION.to_string(),
 607                summary: this.summary_or_default(),
 608                updated_at: this.updated_at(),
 609                messages: this
 610                    .messages()
 611                    .map(|message| SerializedMessage {
 612                        id: message.id,
 613                        role: message.role,
 614                        segments: message
 615                            .segments
 616                            .iter()
 617                            .map(|segment| match segment {
 618                                MessageSegment::Text(text) => {
 619                                    SerializedMessageSegment::Text { text: text.clone() }
 620                                }
 621                                MessageSegment::Thinking(text) => {
 622                                    SerializedMessageSegment::Thinking { text: text.clone() }
 623                                }
 624                            })
 625                            .collect(),
 626                        tool_uses: this
 627                            .tool_uses_for_message(message.id, cx)
 628                            .into_iter()
 629                            .map(|tool_use| SerializedToolUse {
 630                                id: tool_use.id,
 631                                name: tool_use.name,
 632                                input: tool_use.input,
 633                            })
 634                            .collect(),
 635                        tool_results: this
 636                            .tool_results_for_message(message.id)
 637                            .into_iter()
 638                            .map(|tool_result| SerializedToolResult {
 639                                tool_use_id: tool_result.tool_use_id.clone(),
 640                                is_error: tool_result.is_error,
 641                                content: tool_result.content.clone(),
 642                            })
 643                            .collect(),
 644                    })
 645                    .collect(),
 646                initial_project_snapshot,
 647            })
 648        })
 649    }
 650
 651    pub fn set_system_prompt_context(&mut self, context: AssistantSystemPromptContext) {
 652        self.system_prompt_context = Some(context);
 653    }
 654
 655    pub fn system_prompt_context(&self) -> &Option<AssistantSystemPromptContext> {
 656        &self.system_prompt_context
 657    }
 658
 659    pub fn load_system_prompt_context(
 660        &self,
 661        cx: &App,
 662    ) -> Task<(AssistantSystemPromptContext, Option<ThreadError>)> {
 663        let project = self.project.read(cx);
 664        let tasks = project
 665            .visible_worktrees(cx)
 666            .map(|worktree| {
 667                Self::load_worktree_info_for_system_prompt(
 668                    project.fs().clone(),
 669                    worktree.read(cx),
 670                    cx,
 671                )
 672            })
 673            .collect::<Vec<_>>();
 674
 675        cx.spawn(async |_cx| {
 676            let results = futures::future::join_all(tasks).await;
 677            let mut first_err = None;
 678            let worktrees = results
 679                .into_iter()
 680                .map(|(worktree, err)| {
 681                    if first_err.is_none() && err.is_some() {
 682                        first_err = err;
 683                    }
 684                    worktree
 685                })
 686                .collect::<Vec<_>>();
 687            (AssistantSystemPromptContext::new(worktrees), first_err)
 688        })
 689    }
 690
 691    fn load_worktree_info_for_system_prompt(
 692        fs: Arc<dyn Fs>,
 693        worktree: &Worktree,
 694        cx: &App,
 695    ) -> Task<(WorktreeInfoForSystemPrompt, Option<ThreadError>)> {
 696        let root_name = worktree.root_name().into();
 697        let abs_path = worktree.abs_path();
 698
 699        // Note that Cline supports `.clinerules` being a directory, but that is not currently
 700        // supported. This doesn't seem to occur often in GitHub repositories.
 701        const RULES_FILE_NAMES: [&'static str; 6] = [
 702            ".rules",
 703            ".cursorrules",
 704            ".windsurfrules",
 705            ".clinerules",
 706            ".github/copilot-instructions.md",
 707            "CLAUDE.md",
 708        ];
 709        let selected_rules_file = RULES_FILE_NAMES
 710            .into_iter()
 711            .filter_map(|name| {
 712                worktree
 713                    .entry_for_path(name)
 714                    .filter(|entry| entry.is_file())
 715                    .map(|entry| (entry.path.clone(), worktree.absolutize(&entry.path)))
 716            })
 717            .next();
 718
 719        if let Some((rel_rules_path, abs_rules_path)) = selected_rules_file {
 720            cx.spawn(async move |_| {
 721                let rules_file_result = maybe!(async move {
 722                    let abs_rules_path = abs_rules_path?;
 723                    let text = fs.load(&abs_rules_path).await.with_context(|| {
 724                        format!("Failed to load assistant rules file {:?}", abs_rules_path)
 725                    })?;
 726                    anyhow::Ok(RulesFile {
 727                        rel_path: rel_rules_path,
 728                        abs_path: abs_rules_path.into(),
 729                        text: text.trim().to_string(),
 730                    })
 731                })
 732                .await;
 733                let (rules_file, rules_file_error) = match rules_file_result {
 734                    Ok(rules_file) => (Some(rules_file), None),
 735                    Err(err) => (
 736                        None,
 737                        Some(ThreadError::Message {
 738                            header: "Error loading rules file".into(),
 739                            message: format!("{err}").into(),
 740                        }),
 741                    ),
 742                };
 743                let worktree_info = WorktreeInfoForSystemPrompt {
 744                    root_name,
 745                    abs_path,
 746                    rules_file,
 747                };
 748                (worktree_info, rules_file_error)
 749            })
 750        } else {
 751            Task::ready((
 752                WorktreeInfoForSystemPrompt {
 753                    root_name,
 754                    abs_path,
 755                    rules_file: None,
 756                },
 757                None,
 758            ))
 759        }
 760    }
 761
 762    pub fn send_to_model(
 763        &mut self,
 764        model: Arc<dyn LanguageModel>,
 765        request_kind: RequestKind,
 766        cx: &mut Context<Self>,
 767    ) {
 768        let mut request = self.to_completion_request(request_kind, cx);
 769        request.tools = {
 770            let mut tools = Vec::new();
 771            tools.extend(self.tools().enabled_tools(cx).into_iter().map(|tool| {
 772                LanguageModelRequestTool {
 773                    name: tool.name(),
 774                    description: tool.description(),
 775                    input_schema: tool.input_schema(),
 776                }
 777            }));
 778
 779            tools
 780        };
 781
 782        self.stream_completion(request, model, cx);
 783    }
 784
 785    pub fn to_completion_request(
 786        &self,
 787        request_kind: RequestKind,
 788        cx: &App,
 789    ) -> LanguageModelRequest {
 790        let mut request = LanguageModelRequest {
 791            messages: vec![],
 792            tools: Vec::new(),
 793            stop: Vec::new(),
 794            temperature: None,
 795        };
 796
 797        if let Some(system_prompt_context) = self.system_prompt_context.as_ref() {
 798            if let Some(system_prompt) = self
 799                .prompt_builder
 800                .generate_assistant_system_prompt(system_prompt_context)
 801                .context("failed to generate assistant system prompt")
 802                .log_err()
 803            {
 804                request.messages.push(LanguageModelRequestMessage {
 805                    role: Role::System,
 806                    content: vec![MessageContent::Text(system_prompt)],
 807                    cache: true,
 808                });
 809            }
 810        } else {
 811            log::error!("system_prompt_context not set.")
 812        }
 813
 814        let mut referenced_context_ids = HashSet::default();
 815
 816        for message in &self.messages {
 817            if let Some(context_ids) = self.context_by_message.get(&message.id) {
 818                referenced_context_ids.extend(context_ids);
 819            }
 820
 821            let mut request_message = LanguageModelRequestMessage {
 822                role: message.role,
 823                content: Vec::new(),
 824                cache: false,
 825            };
 826
 827            match request_kind {
 828                RequestKind::Chat => {
 829                    self.tool_use
 830                        .attach_tool_results(message.id, &mut request_message);
 831                }
 832                RequestKind::Summarize => {
 833                    // We don't care about tool use during summarization.
 834                }
 835            }
 836
 837            if !message.segments.is_empty() {
 838                request_message
 839                    .content
 840                    .push(MessageContent::Text(message.to_string()));
 841            }
 842
 843            match request_kind {
 844                RequestKind::Chat => {
 845                    self.tool_use
 846                        .attach_tool_uses(message.id, &mut request_message);
 847                }
 848                RequestKind::Summarize => {
 849                    // We don't care about tool use during summarization.
 850                }
 851            };
 852
 853            request.messages.push(request_message);
 854        }
 855
 856        if !referenced_context_ids.is_empty() {
 857            let mut context_message = LanguageModelRequestMessage {
 858                role: Role::User,
 859                content: Vec::new(),
 860                cache: false,
 861            };
 862
 863            let referenced_context = referenced_context_ids
 864                .into_iter()
 865                .filter_map(|context_id| self.context.get(context_id))
 866                .cloned();
 867            attach_context_to_message(&mut context_message, referenced_context);
 868
 869            request.messages.push(context_message);
 870        }
 871
 872        self.attach_stale_files(&mut request.messages, cx);
 873
 874        request
 875    }
 876
 877    fn attach_stale_files(&self, messages: &mut Vec<LanguageModelRequestMessage>, cx: &App) {
 878        const STALE_FILES_HEADER: &str = "These files changed since last read:";
 879
 880        let mut stale_message = String::new();
 881
 882        for stale_file in self.action_log.read(cx).stale_buffers(cx) {
 883            let Some(file) = stale_file.read(cx).file() else {
 884                continue;
 885            };
 886
 887            if stale_message.is_empty() {
 888                write!(&mut stale_message, "{}", STALE_FILES_HEADER).ok();
 889            }
 890
 891            writeln!(&mut stale_message, "- {}", file.path().display()).ok();
 892        }
 893
 894        if !stale_message.is_empty() {
 895            let context_message = LanguageModelRequestMessage {
 896                role: Role::User,
 897                content: vec![stale_message.into()],
 898                cache: false,
 899            };
 900
 901            messages.push(context_message);
 902        }
 903    }
 904
 905    pub fn stream_completion(
 906        &mut self,
 907        request: LanguageModelRequest,
 908        model: Arc<dyn LanguageModel>,
 909        cx: &mut Context<Self>,
 910    ) {
 911        let pending_completion_id = post_inc(&mut self.completion_count);
 912
 913        let task = cx.spawn(async move |thread, cx| {
 914            let stream = model.stream_completion(request, &cx);
 915            let initial_token_usage =
 916                thread.read_with(cx, |thread, _cx| thread.cumulative_token_usage.clone());
 917            let stream_completion = async {
 918                let mut events = stream.await?;
 919                let mut stop_reason = StopReason::EndTurn;
 920                let mut current_token_usage = TokenUsage::default();
 921
 922                while let Some(event) = events.next().await {
 923                    let event = event?;
 924
 925                    thread.update(cx, |thread, cx| {
 926                        match event {
 927                            LanguageModelCompletionEvent::StartMessage { .. } => {
 928                                thread.insert_message(
 929                                    Role::Assistant,
 930                                    vec![MessageSegment::Text(String::new())],
 931                                    cx,
 932                                );
 933                            }
 934                            LanguageModelCompletionEvent::Stop(reason) => {
 935                                stop_reason = reason;
 936                            }
 937                            LanguageModelCompletionEvent::UsageUpdate(token_usage) => {
 938                                thread.cumulative_token_usage =
 939                                    thread.cumulative_token_usage.clone() + token_usage.clone()
 940                                        - current_token_usage.clone();
 941                                current_token_usage = token_usage;
 942                            }
 943                            LanguageModelCompletionEvent::Text(chunk) => {
 944                                if let Some(last_message) = thread.messages.last_mut() {
 945                                    if last_message.role == Role::Assistant {
 946                                        last_message.push_text(&chunk);
 947                                        cx.emit(ThreadEvent::StreamedAssistantText(
 948                                            last_message.id,
 949                                            chunk,
 950                                        ));
 951                                    } else {
 952                                        // If we won't have an Assistant message yet, assume this chunk marks the beginning
 953                                        // of a new Assistant response.
 954                                        //
 955                                        // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
 956                                        // will result in duplicating the text of the chunk in the rendered Markdown.
 957                                        thread.insert_message(
 958                                            Role::Assistant,
 959                                            vec![MessageSegment::Text(chunk.to_string())],
 960                                            cx,
 961                                        );
 962                                    };
 963                                }
 964                            }
 965                            LanguageModelCompletionEvent::Thinking(chunk) => {
 966                                if let Some(last_message) = thread.messages.last_mut() {
 967                                    if last_message.role == Role::Assistant {
 968                                        last_message.push_thinking(&chunk);
 969                                        cx.emit(ThreadEvent::StreamedAssistantThinking(
 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::Thinking(chunk.to_string())],
 982                                            cx,
 983                                        );
 984                                    };
 985                                }
 986                            }
 987                            LanguageModelCompletionEvent::ToolUse(tool_use) => {
 988                                if let Some(last_assistant_message) = thread
 989                                    .messages
 990                                    .iter()
 991                                    .rfind(|message| message.role == Role::Assistant)
 992                                {
 993                                    thread.tool_use.request_tool_use(
 994                                        last_assistant_message.id,
 995                                        tool_use,
 996                                        cx,
 997                                    );
 998                                }
 999                            }
1000                        }
1001
1002                        thread.touch_updated_at();
1003                        cx.emit(ThreadEvent::StreamedCompletion);
1004                        cx.notify();
1005                    })?;
1006
1007                    smol::future::yield_now().await;
1008                }
1009
1010                thread.update(cx, |thread, cx| {
1011                    thread
1012                        .pending_completions
1013                        .retain(|completion| completion.id != pending_completion_id);
1014
1015                    if thread.summary.is_none() && thread.messages.len() >= 2 {
1016                        thread.summarize(cx);
1017                    }
1018                })?;
1019
1020                anyhow::Ok(stop_reason)
1021            };
1022
1023            let result = stream_completion.await;
1024
1025            thread
1026                .update(cx, |thread, cx| {
1027                    thread.finalize_pending_checkpoint(cx);
1028                    match result.as_ref() {
1029                        Ok(stop_reason) => match stop_reason {
1030                            StopReason::ToolUse => {
1031                                cx.emit(ThreadEvent::UsePendingTools);
1032                            }
1033                            StopReason::EndTurn => {}
1034                            StopReason::MaxTokens => {}
1035                        },
1036                        Err(error) => {
1037                            if error.is::<PaymentRequiredError>() {
1038                                cx.emit(ThreadEvent::ShowError(ThreadError::PaymentRequired));
1039                            } else if error.is::<MaxMonthlySpendReachedError>() {
1040                                cx.emit(ThreadEvent::ShowError(
1041                                    ThreadError::MaxMonthlySpendReached,
1042                                ));
1043                            } else {
1044                                let error_message = error
1045                                    .chain()
1046                                    .map(|err| err.to_string())
1047                                    .collect::<Vec<_>>()
1048                                    .join("\n");
1049                                cx.emit(ThreadEvent::ShowError(ThreadError::Message {
1050                                    header: "Error interacting with language model".into(),
1051                                    message: SharedString::from(error_message.clone()),
1052                                }));
1053                            }
1054
1055                            thread.cancel_last_completion(cx);
1056                        }
1057                    }
1058                    cx.emit(ThreadEvent::DoneStreaming);
1059
1060                    if let Ok(initial_usage) = initial_token_usage {
1061                        let usage = thread.cumulative_token_usage.clone() - initial_usage;
1062
1063                        telemetry::event!(
1064                            "Assistant Thread Completion",
1065                            thread_id = thread.id().to_string(),
1066                            model = model.telemetry_id(),
1067                            model_provider = model.provider_id().to_string(),
1068                            input_tokens = usage.input_tokens,
1069                            output_tokens = usage.output_tokens,
1070                            cache_creation_input_tokens = usage.cache_creation_input_tokens,
1071                            cache_read_input_tokens = usage.cache_read_input_tokens,
1072                        );
1073                    }
1074                })
1075                .ok();
1076        });
1077
1078        self.pending_completions.push(PendingCompletion {
1079            id: pending_completion_id,
1080            _task: task,
1081        });
1082    }
1083
1084    pub fn summarize(&mut self, cx: &mut Context<Self>) {
1085        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
1086            return;
1087        };
1088        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
1089            return;
1090        };
1091
1092        if !provider.is_authenticated(cx) {
1093            return;
1094        }
1095
1096        let mut request = self.to_completion_request(RequestKind::Summarize, cx);
1097        request.messages.push(LanguageModelRequestMessage {
1098            role: Role::User,
1099            content: vec![
1100                "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:`"
1101                    .into(),
1102            ],
1103            cache: false,
1104        });
1105
1106        self.pending_summary = cx.spawn(async move |this, cx| {
1107            async move {
1108                let stream = model.stream_completion_text(request, &cx);
1109                let mut messages = stream.await?;
1110
1111                let mut new_summary = String::new();
1112                while let Some(message) = messages.stream.next().await {
1113                    let text = message?;
1114                    let mut lines = text.lines();
1115                    new_summary.extend(lines.next());
1116
1117                    // Stop if the LLM generated multiple lines.
1118                    if lines.next().is_some() {
1119                        break;
1120                    }
1121                }
1122
1123                this.update(cx, |this, cx| {
1124                    if !new_summary.is_empty() {
1125                        this.summary = Some(new_summary.into());
1126                    }
1127
1128                    cx.emit(ThreadEvent::SummaryChanged);
1129                })?;
1130
1131                anyhow::Ok(())
1132            }
1133            .log_err()
1134            .await
1135        });
1136    }
1137
1138    pub fn use_pending_tools(
1139        &mut self,
1140        cx: &mut Context<Self>,
1141    ) -> impl IntoIterator<Item = PendingToolUse> {
1142        let request = self.to_completion_request(RequestKind::Chat, cx);
1143        let messages = Arc::new(request.messages);
1144        let pending_tool_uses = self
1145            .tool_use
1146            .pending_tool_uses()
1147            .into_iter()
1148            .filter(|tool_use| tool_use.status.is_idle())
1149            .cloned()
1150            .collect::<Vec<_>>();
1151
1152        for tool_use in pending_tool_uses.iter() {
1153            if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
1154                if tool.needs_confirmation()
1155                    && !AssistantSettings::get_global(cx).always_allow_tool_actions
1156                {
1157                    self.tool_use.confirm_tool_use(
1158                        tool_use.id.clone(),
1159                        tool_use.ui_text.clone(),
1160                        tool_use.input.clone(),
1161                        messages.clone(),
1162                        tool,
1163                    );
1164                } else {
1165                    self.run_tool(
1166                        tool_use.id.clone(),
1167                        tool_use.ui_text.clone(),
1168                        tool_use.input.clone(),
1169                        &messages,
1170                        tool,
1171                        cx,
1172                    );
1173                }
1174            } else if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
1175                self.run_tool(
1176                    tool_use.id.clone(),
1177                    tool_use.ui_text.clone(),
1178                    tool_use.input.clone(),
1179                    &messages,
1180                    tool,
1181                    cx,
1182                );
1183            }
1184        }
1185
1186        pending_tool_uses
1187    }
1188
1189    pub fn run_tool(
1190        &mut self,
1191        tool_use_id: LanguageModelToolUseId,
1192        ui_text: impl Into<SharedString>,
1193        input: serde_json::Value,
1194        messages: &[LanguageModelRequestMessage],
1195        tool: Arc<dyn Tool>,
1196        cx: &mut Context<'_, Thread>,
1197    ) {
1198        let task = self.spawn_tool_use(tool_use_id.clone(), messages, input, tool, cx);
1199        self.tool_use
1200            .run_pending_tool(tool_use_id, ui_text.into(), task);
1201    }
1202
1203    fn spawn_tool_use(
1204        &mut self,
1205        tool_use_id: LanguageModelToolUseId,
1206        messages: &[LanguageModelRequestMessage],
1207        input: serde_json::Value,
1208        tool: Arc<dyn Tool>,
1209        cx: &mut Context<Thread>,
1210    ) -> Task<()> {
1211        let run_tool = tool.run(
1212            input,
1213            messages,
1214            self.project.clone(),
1215            self.action_log.clone(),
1216            cx,
1217        );
1218
1219        cx.spawn({
1220            async move |thread: WeakEntity<Thread>, cx| {
1221                let output = run_tool.await;
1222
1223                thread
1224                    .update(cx, |thread, cx| {
1225                        let pending_tool_use = thread
1226                            .tool_use
1227                            .insert_tool_output(tool_use_id.clone(), output);
1228
1229                        cx.emit(ThreadEvent::ToolFinished {
1230                            tool_use_id,
1231                            pending_tool_use,
1232                            canceled: false,
1233                        });
1234                    })
1235                    .ok();
1236            }
1237        })
1238    }
1239
1240    pub fn attach_tool_results(
1241        &mut self,
1242        updated_context: Vec<ContextSnapshot>,
1243        cx: &mut Context<Self>,
1244    ) {
1245        self.context.extend(
1246            updated_context
1247                .into_iter()
1248                .map(|context| (context.id, context)),
1249        );
1250
1251        // Insert a user message to contain the tool results.
1252        self.insert_user_message(
1253            // TODO: Sending up a user message without any content results in the model sending back
1254            // responses that also don't have any content. We currently don't handle this case well,
1255            // so for now we provide some text to keep the model on track.
1256            "Here are the tool results.",
1257            Vec::new(),
1258            None,
1259            cx,
1260        );
1261    }
1262
1263    /// Cancels the last pending completion, if there are any pending.
1264    ///
1265    /// Returns whether a completion was canceled.
1266    pub fn cancel_last_completion(&mut self, cx: &mut Context<Self>) -> bool {
1267        let canceled = if self.pending_completions.pop().is_some() {
1268            true
1269        } else {
1270            let mut canceled = false;
1271            for pending_tool_use in self.tool_use.cancel_pending() {
1272                canceled = true;
1273                cx.emit(ThreadEvent::ToolFinished {
1274                    tool_use_id: pending_tool_use.id.clone(),
1275                    pending_tool_use: Some(pending_tool_use),
1276                    canceled: true,
1277                });
1278            }
1279            canceled
1280        };
1281        self.finalize_pending_checkpoint(cx);
1282        canceled
1283    }
1284
1285    /// Returns the feedback given to the thread, if any.
1286    pub fn feedback(&self) -> Option<ThreadFeedback> {
1287        self.feedback
1288    }
1289
1290    /// Reports feedback about the thread and stores it in our telemetry backend.
1291    pub fn report_feedback(
1292        &mut self,
1293        feedback: ThreadFeedback,
1294        cx: &mut Context<Self>,
1295    ) -> Task<Result<()>> {
1296        let final_project_snapshot = Self::project_snapshot(self.project.clone(), cx);
1297        let serialized_thread = self.serialize(cx);
1298        let thread_id = self.id().clone();
1299        let client = self.project.read(cx).client();
1300        self.feedback = Some(feedback);
1301        cx.notify();
1302
1303        cx.background_spawn(async move {
1304            let final_project_snapshot = final_project_snapshot.await;
1305            let serialized_thread = serialized_thread.await?;
1306            let thread_data =
1307                serde_json::to_value(serialized_thread).unwrap_or_else(|_| serde_json::Value::Null);
1308
1309            let rating = match feedback {
1310                ThreadFeedback::Positive => "positive",
1311                ThreadFeedback::Negative => "negative",
1312            };
1313            telemetry::event!(
1314                "Assistant Thread Rated",
1315                rating,
1316                thread_id,
1317                thread_data,
1318                final_project_snapshot
1319            );
1320            client.telemetry().flush_events();
1321
1322            Ok(())
1323        })
1324    }
1325
1326    /// Create a snapshot of the current project state including git information and unsaved buffers.
1327    fn project_snapshot(
1328        project: Entity<Project>,
1329        cx: &mut Context<Self>,
1330    ) -> Task<Arc<ProjectSnapshot>> {
1331        let git_store = project.read(cx).git_store().clone();
1332        let worktree_snapshots: Vec<_> = project
1333            .read(cx)
1334            .visible_worktrees(cx)
1335            .map(|worktree| Self::worktree_snapshot(worktree, git_store.clone(), cx))
1336            .collect();
1337
1338        cx.spawn(async move |_, cx| {
1339            let worktree_snapshots = futures::future::join_all(worktree_snapshots).await;
1340
1341            let mut unsaved_buffers = Vec::new();
1342            cx.update(|app_cx| {
1343                let buffer_store = project.read(app_cx).buffer_store();
1344                for buffer_handle in buffer_store.read(app_cx).buffers() {
1345                    let buffer = buffer_handle.read(app_cx);
1346                    if buffer.is_dirty() {
1347                        if let Some(file) = buffer.file() {
1348                            let path = file.path().to_string_lossy().to_string();
1349                            unsaved_buffers.push(path);
1350                        }
1351                    }
1352                }
1353            })
1354            .ok();
1355
1356            Arc::new(ProjectSnapshot {
1357                worktree_snapshots,
1358                unsaved_buffer_paths: unsaved_buffers,
1359                timestamp: Utc::now(),
1360            })
1361        })
1362    }
1363
1364    fn worktree_snapshot(
1365        worktree: Entity<project::Worktree>,
1366        git_store: Entity<GitStore>,
1367        cx: &App,
1368    ) -> Task<WorktreeSnapshot> {
1369        cx.spawn(async move |cx| {
1370            // Get worktree path and snapshot
1371            let worktree_info = cx.update(|app_cx| {
1372                let worktree = worktree.read(app_cx);
1373                let path = worktree.abs_path().to_string_lossy().to_string();
1374                let snapshot = worktree.snapshot();
1375                (path, snapshot)
1376            });
1377
1378            let Ok((worktree_path, snapshot)) = worktree_info else {
1379                return WorktreeSnapshot {
1380                    worktree_path: String::new(),
1381                    git_state: None,
1382                };
1383            };
1384
1385            let repo_info = git_store
1386                .update(cx, |git_store, cx| {
1387                    git_store
1388                        .repositories()
1389                        .values()
1390                        .find(|repo| repo.read(cx).worktree_id == snapshot.id())
1391                        .and_then(|repo| {
1392                            let repo = repo.read(cx);
1393                            Some((repo.branch().cloned(), repo.local_repository()?))
1394                        })
1395                })
1396                .ok()
1397                .flatten();
1398
1399            // Extract git information
1400            let git_state = match repo_info {
1401                None => None,
1402                Some((branch, repo)) => {
1403                    let current_branch = branch.map(|branch| branch.name.to_string());
1404                    let remote_url = repo.remote_url("origin");
1405                    let head_sha = repo.head_sha();
1406
1407                    // Get diff asynchronously
1408                    let diff = repo
1409                        .diff(git::repository::DiffType::HeadToWorktree, cx.clone())
1410                        .await
1411                        .ok();
1412
1413                    Some(GitState {
1414                        remote_url,
1415                        head_sha,
1416                        current_branch,
1417                        diff,
1418                    })
1419                }
1420            };
1421
1422            WorktreeSnapshot {
1423                worktree_path,
1424                git_state,
1425            }
1426        })
1427    }
1428
1429    pub fn to_markdown(&self, cx: &App) -> Result<String> {
1430        let mut markdown = Vec::new();
1431
1432        if let Some(summary) = self.summary() {
1433            writeln!(markdown, "# {summary}\n")?;
1434        };
1435
1436        for message in self.messages() {
1437            writeln!(
1438                markdown,
1439                "## {role}\n",
1440                role = match message.role {
1441                    Role::User => "User",
1442                    Role::Assistant => "Assistant",
1443                    Role::System => "System",
1444                }
1445            )?;
1446            for segment in &message.segments {
1447                match segment {
1448                    MessageSegment::Text(text) => writeln!(markdown, "{}\n", text)?,
1449                    MessageSegment::Thinking(text) => {
1450                        writeln!(markdown, "<think>{}</think>\n", text)?
1451                    }
1452                }
1453            }
1454
1455            for tool_use in self.tool_uses_for_message(message.id, cx) {
1456                writeln!(
1457                    markdown,
1458                    "**Use Tool: {} ({})**",
1459                    tool_use.name, tool_use.id
1460                )?;
1461                writeln!(markdown, "```json")?;
1462                writeln!(
1463                    markdown,
1464                    "{}",
1465                    serde_json::to_string_pretty(&tool_use.input)?
1466                )?;
1467                writeln!(markdown, "```")?;
1468            }
1469
1470            for tool_result in self.tool_results_for_message(message.id) {
1471                write!(markdown, "**Tool Results: {}", tool_result.tool_use_id)?;
1472                if tool_result.is_error {
1473                    write!(markdown, " (Error)")?;
1474                }
1475
1476                writeln!(markdown, "**\n")?;
1477                writeln!(markdown, "{}", tool_result.content)?;
1478            }
1479        }
1480
1481        Ok(String::from_utf8_lossy(&markdown).to_string())
1482    }
1483
1484    pub fn action_log(&self) -> &Entity<ActionLog> {
1485        &self.action_log
1486    }
1487
1488    pub fn project(&self) -> &Entity<Project> {
1489        &self.project
1490    }
1491
1492    pub fn cumulative_token_usage(&self) -> TokenUsage {
1493        self.cumulative_token_usage.clone()
1494    }
1495
1496    pub fn deny_tool_use(&mut self, tool_use_id: LanguageModelToolUseId, cx: &mut Context<Self>) {
1497        let err = Err(anyhow::anyhow!(
1498            "Permission to run tool action denied by user"
1499        ));
1500
1501        self.tool_use.insert_tool_output(tool_use_id.clone(), err);
1502
1503        cx.emit(ThreadEvent::ToolFinished {
1504            tool_use_id,
1505            pending_tool_use: None,
1506            canceled: true,
1507        });
1508    }
1509}
1510
1511#[derive(Debug, Clone)]
1512pub enum ThreadError {
1513    PaymentRequired,
1514    MaxMonthlySpendReached,
1515    Message {
1516        header: SharedString,
1517        message: SharedString,
1518    },
1519}
1520
1521#[derive(Debug, Clone)]
1522pub enum ThreadEvent {
1523    ShowError(ThreadError),
1524    StreamedCompletion,
1525    StreamedAssistantText(MessageId, String),
1526    StreamedAssistantThinking(MessageId, String),
1527    DoneStreaming,
1528    MessageAdded(MessageId),
1529    MessageEdited(MessageId),
1530    MessageDeleted(MessageId),
1531    SummaryChanged,
1532    UsePendingTools,
1533    ToolFinished {
1534        #[allow(unused)]
1535        tool_use_id: LanguageModelToolUseId,
1536        /// The pending tool use that corresponds to this tool.
1537        pending_tool_use: Option<PendingToolUse>,
1538        /// Whether the tool was canceled by the user.
1539        canceled: bool,
1540    },
1541    CheckpointChanged,
1542}
1543
1544impl EventEmitter<ThreadEvent> for Thread {}
1545
1546struct PendingCompletion {
1547    id: usize,
1548    _task: Task<()>,
1549}