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