1use std::fmt::Write as _;
2use std::io::Write;
3use std::ops::Range;
4use std::sync::Arc;
5
6use anyhow::{Context as _, Result};
7use assistant_settings::AssistantSettings;
8use assistant_tool::{ActionLog, Tool, ToolWorkingSet};
9use chrono::{DateTime, Utc};
10use collections::{BTreeMap, HashMap, HashSet};
11use fs::Fs;
12use futures::future::Shared;
13use futures::{FutureExt, StreamExt as _};
14use git;
15use gpui::{App, AppContext, Context, Entity, EventEmitter, SharedString, Task, WeakEntity};
16use language_model::{
17 LanguageModel, LanguageModelCompletionEvent, LanguageModelRegistry, LanguageModelRequest,
18 LanguageModelRequestMessage, LanguageModelRequestTool, LanguageModelToolResult,
19 LanguageModelToolUseId, MaxMonthlySpendReachedError, MessageContent, PaymentRequiredError,
20 Role, StopReason, TokenUsage,
21};
22use project::git_store::{GitStore, GitStoreCheckpoint};
23use project::{Project, Worktree};
24use prompt_store::{
25 AssistantSystemPromptContext, PromptBuilder, RulesFile, WorktreeInfoForSystemPrompt,
26};
27use serde::{Deserialize, Serialize};
28use settings::Settings;
29use util::{maybe, post_inc, ResultExt as _, TryFutureExt as _};
30use uuid::Uuid;
31
32use crate::context::{attach_context_to_message, ContextId, ContextSnapshot};
33use crate::thread_store::{
34 SerializedMessage, SerializedMessageSegment, SerializedThread, SerializedToolResult,
35 SerializedToolUse,
36};
37use crate::tool_use::{PendingToolUse, ToolUse, ToolUseState};
38
39#[derive(Debug, Clone, Copy)]
40pub enum RequestKind {
41 Chat,
42 /// Used when summarizing a thread.
43 Summarize,
44}
45
46#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
47pub struct ThreadId(Arc<str>);
48
49impl ThreadId {
50 pub fn new() -> Self {
51 Self(Uuid::new_v4().to_string().into())
52 }
53}
54
55impl std::fmt::Display for ThreadId {
56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57 write!(f, "{}", self.0)
58 }
59}
60
61#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
62pub struct MessageId(pub(crate) usize);
63
64impl MessageId {
65 fn post_inc(&mut self) -> Self {
66 Self(post_inc(&mut self.0))
67 }
68}
69
70/// A message in a [`Thread`].
71#[derive(Debug, Clone)]
72pub struct Message {
73 pub id: MessageId,
74 pub role: Role,
75 pub segments: Vec<MessageSegment>,
76}
77
78impl Message {
79 pub fn push_thinking(&mut self, text: &str) {
80 if let Some(MessageSegment::Thinking(segment)) = self.segments.last_mut() {
81 segment.push_str(text);
82 } else {
83 self.segments
84 .push(MessageSegment::Thinking(text.to_string()));
85 }
86 }
87
88 pub fn push_text(&mut self, text: &str) {
89 if let Some(MessageSegment::Text(segment)) = self.segments.last_mut() {
90 segment.push_str(text);
91 } else {
92 self.segments.push(MessageSegment::Text(text.to_string()));
93 }
94 }
95
96 pub fn to_string(&self) -> String {
97 let mut result = String::new();
98 for segment in &self.segments {
99 match segment {
100 MessageSegment::Text(text) => result.push_str(text),
101 MessageSegment::Thinking(text) => {
102 result.push_str("<think>");
103 result.push_str(text);
104 result.push_str("</think>");
105 }
106 }
107 }
108 result
109 }
110}
111
112#[derive(Debug, Clone)]
113pub enum MessageSegment {
114 Text(String),
115 Thinking(String),
116}
117
118#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct ProjectSnapshot {
120 pub worktree_snapshots: Vec<WorktreeSnapshot>,
121 pub unsaved_buffer_paths: Vec<String>,
122 pub timestamp: DateTime<Utc>,
123}
124
125#[derive(Debug, Clone, Serialize, Deserialize)]
126pub struct WorktreeSnapshot {
127 pub worktree_path: String,
128 pub git_state: Option<GitState>,
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct GitState {
133 pub remote_url: Option<String>,
134 pub head_sha: Option<String>,
135 pub current_branch: Option<String>,
136 pub diff: Option<String>,
137}
138
139#[derive(Clone)]
140pub struct ThreadCheckpoint {
141 message_id: MessageId,
142 git_checkpoint: GitStoreCheckpoint,
143}
144
145#[derive(Copy, Clone, Debug)]
146pub enum ThreadFeedback {
147 Positive,
148 Negative,
149}
150
151pub enum LastRestoreCheckpoint {
152 Pending {
153 message_id: MessageId,
154 },
155 Error {
156 message_id: MessageId,
157 error: String,
158 },
159}
160
161impl LastRestoreCheckpoint {
162 pub fn message_id(&self) -> MessageId {
163 match self {
164 LastRestoreCheckpoint::Pending { message_id } => *message_id,
165 LastRestoreCheckpoint::Error { message_id, .. } => *message_id,
166 }
167 }
168}
169
170/// A thread of conversation with the LLM.
171pub struct Thread {
172 id: ThreadId,
173 updated_at: DateTime<Utc>,
174 summary: Option<SharedString>,
175 pending_summary: Task<Option<()>>,
176 messages: Vec<Message>,
177 next_message_id: MessageId,
178 context: BTreeMap<ContextId, ContextSnapshot>,
179 context_by_message: HashMap<MessageId, Vec<ContextId>>,
180 system_prompt_context: Option<AssistantSystemPromptContext>,
181 checkpoints_by_message: HashMap<MessageId, ThreadCheckpoint>,
182 completion_count: usize,
183 pending_completions: Vec<PendingCompletion>,
184 project: Entity<Project>,
185 prompt_builder: Arc<PromptBuilder>,
186 tools: Arc<ToolWorkingSet>,
187 tool_use: ToolUseState,
188 action_log: Entity<ActionLog>,
189 last_restore_checkpoint: Option<LastRestoreCheckpoint>,
190 pending_checkpoint: Option<ThreadCheckpoint>,
191 initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
192 cumulative_token_usage: TokenUsage,
193 feedback: Option<ThreadFeedback>,
194}
195
196impl Thread {
197 pub fn new(
198 project: Entity<Project>,
199 tools: Arc<ToolWorkingSet>,
200 prompt_builder: Arc<PromptBuilder>,
201 cx: &mut Context<Self>,
202 ) -> Self {
203 Self {
204 id: ThreadId::new(),
205 updated_at: Utc::now(),
206 summary: None,
207 pending_summary: Task::ready(None),
208 messages: Vec::new(),
209 next_message_id: MessageId(0),
210 context: BTreeMap::default(),
211 context_by_message: HashMap::default(),
212 system_prompt_context: None,
213 checkpoints_by_message: HashMap::default(),
214 completion_count: 0,
215 pending_completions: Vec::new(),
216 project: project.clone(),
217 prompt_builder,
218 tools: tools.clone(),
219 last_restore_checkpoint: None,
220 pending_checkpoint: None,
221 tool_use: ToolUseState::new(tools.clone()),
222 action_log: cx.new(|_| ActionLog::new()),
223 initial_project_snapshot: {
224 let project_snapshot = Self::project_snapshot(project, cx);
225 cx.foreground_executor()
226 .spawn(async move { Some(project_snapshot.await) })
227 .shared()
228 },
229 cumulative_token_usage: TokenUsage::default(),
230 feedback: None,
231 }
232 }
233
234 pub fn deserialize(
235 id: ThreadId,
236 serialized: SerializedThread,
237 project: Entity<Project>,
238 tools: Arc<ToolWorkingSet>,
239 prompt_builder: Arc<PromptBuilder>,
240 cx: &mut Context<Self>,
241 ) -> Self {
242 let next_message_id = MessageId(
243 serialized
244 .messages
245 .last()
246 .map(|message| message.id.0 + 1)
247 .unwrap_or(0),
248 );
249 let tool_use =
250 ToolUseState::from_serialized_messages(tools.clone(), &serialized.messages, |_| true);
251
252 Self {
253 id,
254 updated_at: serialized.updated_at,
255 summary: Some(serialized.summary),
256 pending_summary: Task::ready(None),
257 messages: serialized
258 .messages
259 .into_iter()
260 .map(|message| Message {
261 id: message.id,
262 role: message.role,
263 segments: message
264 .segments
265 .into_iter()
266 .map(|segment| match segment {
267 SerializedMessageSegment::Text { text } => MessageSegment::Text(text),
268 SerializedMessageSegment::Thinking { text } => {
269 MessageSegment::Thinking(text)
270 }
271 })
272 .collect(),
273 })
274 .collect(),
275 next_message_id,
276 context: BTreeMap::default(),
277 context_by_message: HashMap::default(),
278 system_prompt_context: None,
279 checkpoints_by_message: HashMap::default(),
280 completion_count: 0,
281 pending_completions: Vec::new(),
282 last_restore_checkpoint: None,
283 pending_checkpoint: None,
284 project,
285 prompt_builder,
286 tools,
287 tool_use,
288 action_log: cx.new(|_| ActionLog::new()),
289 initial_project_snapshot: Task::ready(serialized.initial_project_snapshot).shared(),
290 cumulative_token_usage: serialized.cumulative_token_usage,
291 feedback: None,
292 }
293 }
294
295 pub fn id(&self) -> &ThreadId {
296 &self.id
297 }
298
299 pub fn is_empty(&self) -> bool {
300 self.messages.is_empty()
301 }
302
303 pub fn updated_at(&self) -> DateTime<Utc> {
304 self.updated_at
305 }
306
307 pub fn touch_updated_at(&mut self) {
308 self.updated_at = Utc::now();
309 }
310
311 pub fn summary(&self) -> Option<SharedString> {
312 self.summary.clone()
313 }
314
315 pub fn summary_or_default(&self) -> SharedString {
316 const DEFAULT: SharedString = SharedString::new_static("New Thread");
317 self.summary.clone().unwrap_or(DEFAULT)
318 }
319
320 pub fn set_summary(&mut self, summary: impl Into<SharedString>, cx: &mut Context<Self>) {
321 self.summary = Some(summary.into());
322 cx.emit(ThreadEvent::SummaryChanged);
323 }
324
325 pub fn message(&self, id: MessageId) -> Option<&Message> {
326 self.messages.iter().find(|message| message.id == id)
327 }
328
329 pub fn messages(&self) -> impl Iterator<Item = &Message> {
330 self.messages.iter()
331 }
332
333 pub fn is_generating(&self) -> bool {
334 !self.pending_completions.is_empty() || !self.all_tools_finished()
335 }
336
337 pub fn tools(&self) -> &Arc<ToolWorkingSet> {
338 &self.tools
339 }
340
341 pub fn pending_tool(&self, id: &LanguageModelToolUseId) -> Option<&PendingToolUse> {
342 self.tool_use
343 .pending_tool_uses()
344 .into_iter()
345 .find(|tool_use| &tool_use.id == id)
346 }
347
348 pub fn tools_needing_confirmation(&self) -> impl Iterator<Item = &PendingToolUse> {
349 self.tool_use
350 .pending_tool_uses()
351 .into_iter()
352 .filter(|tool_use| tool_use.status.needs_confirmation())
353 }
354
355 pub fn has_pending_tool_uses(&self) -> bool {
356 !self.tool_use.pending_tool_uses().is_empty()
357 }
358
359 pub fn checkpoint_for_message(&self, id: MessageId) -> Option<ThreadCheckpoint> {
360 self.checkpoints_by_message.get(&id).cloned()
361 }
362
363 pub fn restore_checkpoint(
364 &mut self,
365 checkpoint: ThreadCheckpoint,
366 cx: &mut Context<Self>,
367 ) -> Task<Result<()>> {
368 self.last_restore_checkpoint = Some(LastRestoreCheckpoint::Pending {
369 message_id: checkpoint.message_id,
370 });
371 cx.emit(ThreadEvent::CheckpointChanged);
372 cx.notify();
373
374 let project = self.project.read(cx);
375 let restore = project
376 .git_store()
377 .read(cx)
378 .restore_checkpoint(checkpoint.git_checkpoint.clone(), cx);
379 cx.spawn(async move |this, cx| {
380 let result = restore.await;
381 this.update(cx, |this, cx| {
382 if let Err(err) = result.as_ref() {
383 this.last_restore_checkpoint = Some(LastRestoreCheckpoint::Error {
384 message_id: checkpoint.message_id,
385 error: err.to_string(),
386 });
387 } else {
388 this.truncate(checkpoint.message_id, cx);
389 this.last_restore_checkpoint = None;
390 }
391 this.pending_checkpoint = None;
392 cx.emit(ThreadEvent::CheckpointChanged);
393 cx.notify();
394 })?;
395 result
396 })
397 }
398
399 fn finalize_pending_checkpoint(&mut self, cx: &mut Context<Self>) {
400 let pending_checkpoint = if self.is_generating() {
401 return;
402 } else if let Some(checkpoint) = self.pending_checkpoint.take() {
403 checkpoint
404 } else {
405 return;
406 };
407
408 let git_store = self.project.read(cx).git_store().clone();
409 let final_checkpoint = git_store.read(cx).checkpoint(cx);
410 cx.spawn(async move |this, cx| match final_checkpoint.await {
411 Ok(final_checkpoint) => {
412 let equal = git_store
413 .read_with(cx, |store, cx| {
414 store.compare_checkpoints(
415 pending_checkpoint.git_checkpoint.clone(),
416 final_checkpoint.clone(),
417 cx,
418 )
419 })?
420 .await
421 .unwrap_or(false);
422
423 if equal {
424 git_store
425 .read_with(cx, |store, cx| {
426 store.delete_checkpoint(pending_checkpoint.git_checkpoint, cx)
427 })?
428 .detach();
429 } else {
430 this.update(cx, |this, cx| {
431 this.insert_checkpoint(pending_checkpoint, cx)
432 })?;
433 }
434
435 git_store
436 .read_with(cx, |store, cx| {
437 store.delete_checkpoint(final_checkpoint, cx)
438 })?
439 .detach();
440
441 Ok(())
442 }
443 Err(_) => this.update(cx, |this, cx| {
444 this.insert_checkpoint(pending_checkpoint, cx)
445 }),
446 })
447 .detach();
448 }
449
450 fn insert_checkpoint(&mut self, checkpoint: ThreadCheckpoint, cx: &mut Context<Self>) {
451 self.checkpoints_by_message
452 .insert(checkpoint.message_id, checkpoint);
453 cx.emit(ThreadEvent::CheckpointChanged);
454 cx.notify();
455 }
456
457 pub fn last_restore_checkpoint(&self) -> Option<&LastRestoreCheckpoint> {
458 self.last_restore_checkpoint.as_ref()
459 }
460
461 pub fn truncate(&mut self, message_id: MessageId, cx: &mut Context<Self>) {
462 let Some(message_ix) = self
463 .messages
464 .iter()
465 .rposition(|message| message.id == message_id)
466 else {
467 return;
468 };
469 for deleted_message in self.messages.drain(message_ix..) {
470 self.context_by_message.remove(&deleted_message.id);
471 self.checkpoints_by_message.remove(&deleted_message.id);
472 }
473 cx.notify();
474 }
475
476 pub fn context_for_message(&self, id: MessageId) -> Option<Vec<ContextSnapshot>> {
477 let context = self.context_by_message.get(&id)?;
478 Some(
479 context
480 .into_iter()
481 .filter_map(|context_id| self.context.get(&context_id))
482 .cloned()
483 .collect::<Vec<_>>(),
484 )
485 }
486
487 /// Returns whether all of the tool uses have finished running.
488 pub fn all_tools_finished(&self) -> bool {
489 // If the only pending tool uses left are the ones with errors, then
490 // that means that we've finished running all of the pending tools.
491 self.tool_use
492 .pending_tool_uses()
493 .iter()
494 .all(|tool_use| tool_use.status.is_error())
495 }
496
497 pub fn tool_uses_for_message(&self, id: MessageId, cx: &App) -> Vec<ToolUse> {
498 self.tool_use.tool_uses_for_message(id, cx)
499 }
500
501 pub fn tool_results_for_message(&self, id: MessageId) -> Vec<&LanguageModelToolResult> {
502 self.tool_use.tool_results_for_message(id)
503 }
504
505 pub fn tool_result(&self, id: &LanguageModelToolUseId) -> Option<&LanguageModelToolResult> {
506 self.tool_use.tool_result(id)
507 }
508
509 pub fn message_has_tool_results(&self, message_id: MessageId) -> bool {
510 self.tool_use.message_has_tool_results(message_id)
511 }
512
513 pub fn insert_user_message(
514 &mut self,
515 text: impl Into<String>,
516 context: Vec<ContextSnapshot>,
517 git_checkpoint: Option<GitStoreCheckpoint>,
518 cx: &mut Context<Self>,
519 ) -> MessageId {
520 let message_id =
521 self.insert_message(Role::User, vec![MessageSegment::Text(text.into())], cx);
522 let context_ids = context.iter().map(|context| context.id).collect::<Vec<_>>();
523 self.context
524 .extend(context.into_iter().map(|context| (context.id, context)));
525 self.context_by_message.insert(message_id, context_ids);
526 if let Some(git_checkpoint) = git_checkpoint {
527 self.pending_checkpoint = Some(ThreadCheckpoint {
528 message_id,
529 git_checkpoint,
530 });
531 }
532 message_id
533 }
534
535 pub fn insert_message(
536 &mut self,
537 role: Role,
538 segments: Vec<MessageSegment>,
539 cx: &mut Context<Self>,
540 ) -> MessageId {
541 let id = self.next_message_id.post_inc();
542 self.messages.push(Message { id, role, segments });
543 self.touch_updated_at();
544 cx.emit(ThreadEvent::MessageAdded(id));
545 id
546 }
547
548 pub fn edit_message(
549 &mut self,
550 id: MessageId,
551 new_role: Role,
552 new_segments: Vec<MessageSegment>,
553 cx: &mut Context<Self>,
554 ) -> bool {
555 let Some(message) = self.messages.iter_mut().find(|message| message.id == id) else {
556 return false;
557 };
558 message.role = new_role;
559 message.segments = new_segments;
560 self.touch_updated_at();
561 cx.emit(ThreadEvent::MessageEdited(id));
562 true
563 }
564
565 pub fn delete_message(&mut self, id: MessageId, cx: &mut Context<Self>) -> bool {
566 let Some(index) = self.messages.iter().position(|message| message.id == id) else {
567 return false;
568 };
569 self.messages.remove(index);
570 self.context_by_message.remove(&id);
571 self.touch_updated_at();
572 cx.emit(ThreadEvent::MessageDeleted(id));
573 true
574 }
575
576 /// Returns the representation of this [`Thread`] in a textual form.
577 ///
578 /// This is the representation we use when attaching a thread as context to another thread.
579 pub fn text(&self) -> String {
580 let mut text = String::new();
581
582 for message in &self.messages {
583 text.push_str(match message.role {
584 language_model::Role::User => "User:",
585 language_model::Role::Assistant => "Assistant:",
586 language_model::Role::System => "System:",
587 });
588 text.push('\n');
589
590 for segment in &message.segments {
591 match segment {
592 MessageSegment::Text(content) => text.push_str(content),
593 MessageSegment::Thinking(content) => {
594 text.push_str(&format!("<think>{}</think>", content))
595 }
596 }
597 }
598 text.push('\n');
599 }
600
601 text
602 }
603
604 /// Serializes this thread into a format for storage or telemetry.
605 pub fn serialize(&self, cx: &mut Context<Self>) -> Task<Result<SerializedThread>> {
606 let initial_project_snapshot = self.initial_project_snapshot.clone();
607 cx.spawn(async move |this, cx| {
608 let initial_project_snapshot = initial_project_snapshot.await;
609 this.read_with(cx, |this, cx| SerializedThread {
610 version: SerializedThread::VERSION.to_string(),
611 summary: this.summary_or_default(),
612 updated_at: this.updated_at(),
613 messages: this
614 .messages()
615 .map(|message| SerializedMessage {
616 id: message.id,
617 role: message.role,
618 segments: message
619 .segments
620 .iter()
621 .map(|segment| match segment {
622 MessageSegment::Text(text) => {
623 SerializedMessageSegment::Text { text: text.clone() }
624 }
625 MessageSegment::Thinking(text) => {
626 SerializedMessageSegment::Thinking { text: text.clone() }
627 }
628 })
629 .collect(),
630 tool_uses: this
631 .tool_uses_for_message(message.id, cx)
632 .into_iter()
633 .map(|tool_use| SerializedToolUse {
634 id: tool_use.id,
635 name: tool_use.name,
636 input: tool_use.input,
637 })
638 .collect(),
639 tool_results: this
640 .tool_results_for_message(message.id)
641 .into_iter()
642 .map(|tool_result| SerializedToolResult {
643 tool_use_id: tool_result.tool_use_id.clone(),
644 is_error: tool_result.is_error,
645 content: tool_result.content.clone(),
646 })
647 .collect(),
648 })
649 .collect(),
650 initial_project_snapshot,
651 cumulative_token_usage: this.cumulative_token_usage.clone(),
652 })
653 })
654 }
655
656 pub fn set_system_prompt_context(&mut self, context: AssistantSystemPromptContext) {
657 self.system_prompt_context = Some(context);
658 }
659
660 pub fn system_prompt_context(&self) -> &Option<AssistantSystemPromptContext> {
661 &self.system_prompt_context
662 }
663
664 pub fn load_system_prompt_context(
665 &self,
666 cx: &App,
667 ) -> Task<(AssistantSystemPromptContext, Option<ThreadError>)> {
668 let project = self.project.read(cx);
669 let tasks = project
670 .visible_worktrees(cx)
671 .map(|worktree| {
672 Self::load_worktree_info_for_system_prompt(
673 project.fs().clone(),
674 worktree.read(cx),
675 cx,
676 )
677 })
678 .collect::<Vec<_>>();
679
680 cx.spawn(async |_cx| {
681 let results = futures::future::join_all(tasks).await;
682 let mut first_err = None;
683 let worktrees = results
684 .into_iter()
685 .map(|(worktree, err)| {
686 if first_err.is_none() && err.is_some() {
687 first_err = err;
688 }
689 worktree
690 })
691 .collect::<Vec<_>>();
692 (AssistantSystemPromptContext::new(worktrees), first_err)
693 })
694 }
695
696 fn load_worktree_info_for_system_prompt(
697 fs: Arc<dyn Fs>,
698 worktree: &Worktree,
699 cx: &App,
700 ) -> Task<(WorktreeInfoForSystemPrompt, Option<ThreadError>)> {
701 let root_name = worktree.root_name().into();
702 let abs_path = worktree.abs_path();
703
704 // Note that Cline supports `.clinerules` being a directory, but that is not currently
705 // supported. This doesn't seem to occur often in GitHub repositories.
706 const RULES_FILE_NAMES: [&'static str; 6] = [
707 ".rules",
708 ".cursorrules",
709 ".windsurfrules",
710 ".clinerules",
711 ".github/copilot-instructions.md",
712 "CLAUDE.md",
713 ];
714 let selected_rules_file = RULES_FILE_NAMES
715 .into_iter()
716 .filter_map(|name| {
717 worktree
718 .entry_for_path(name)
719 .filter(|entry| entry.is_file())
720 .map(|entry| (entry.path.clone(), worktree.absolutize(&entry.path)))
721 })
722 .next();
723
724 if let Some((rel_rules_path, abs_rules_path)) = selected_rules_file {
725 cx.spawn(async move |_| {
726 let rules_file_result = maybe!(async move {
727 let abs_rules_path = abs_rules_path?;
728 let text = fs.load(&abs_rules_path).await.with_context(|| {
729 format!("Failed to load assistant rules file {:?}", abs_rules_path)
730 })?;
731 anyhow::Ok(RulesFile {
732 rel_path: rel_rules_path,
733 abs_path: abs_rules_path.into(),
734 text: text.trim().to_string(),
735 })
736 })
737 .await;
738 let (rules_file, rules_file_error) = match rules_file_result {
739 Ok(rules_file) => (Some(rules_file), None),
740 Err(err) => (
741 None,
742 Some(ThreadError::Message {
743 header: "Error loading rules file".into(),
744 message: format!("{err}").into(),
745 }),
746 ),
747 };
748 let worktree_info = WorktreeInfoForSystemPrompt {
749 root_name,
750 abs_path,
751 rules_file,
752 };
753 (worktree_info, rules_file_error)
754 })
755 } else {
756 Task::ready((
757 WorktreeInfoForSystemPrompt {
758 root_name,
759 abs_path,
760 rules_file: None,
761 },
762 None,
763 ))
764 }
765 }
766
767 pub fn send_to_model(
768 &mut self,
769 model: Arc<dyn LanguageModel>,
770 request_kind: RequestKind,
771 cx: &mut Context<Self>,
772 ) {
773 let mut request = self.to_completion_request(request_kind, cx);
774 request.tools = {
775 let mut tools = Vec::new();
776 tools.extend(self.tools().enabled_tools(cx).into_iter().map(|tool| {
777 LanguageModelRequestTool {
778 name: tool.name(),
779 description: tool.description(),
780 input_schema: tool.input_schema(),
781 }
782 }));
783
784 tools
785 };
786
787 self.stream_completion(request, model, cx);
788 }
789
790 pub fn used_tools_since_last_user_message(&self) -> bool {
791 for message in self.messages.iter().rev() {
792 if self.tool_use.message_has_tool_results(message.id) {
793 return true;
794 } else if message.role == Role::User {
795 return false;
796 }
797 }
798
799 false
800 }
801
802 pub fn to_completion_request(
803 &self,
804 request_kind: RequestKind,
805 cx: &App,
806 ) -> LanguageModelRequest {
807 let mut request = LanguageModelRequest {
808 messages: vec![],
809 tools: Vec::new(),
810 stop: Vec::new(),
811 temperature: None,
812 };
813
814 if let Some(system_prompt_context) = self.system_prompt_context.as_ref() {
815 if let Some(system_prompt) = self
816 .prompt_builder
817 .generate_assistant_system_prompt(system_prompt_context)
818 .context("failed to generate assistant system prompt")
819 .log_err()
820 {
821 request.messages.push(LanguageModelRequestMessage {
822 role: Role::System,
823 content: vec![MessageContent::Text(system_prompt)],
824 cache: true,
825 });
826 }
827 } else {
828 log::error!("system_prompt_context not set.")
829 }
830
831 let mut referenced_context_ids = HashSet::default();
832
833 for message in &self.messages {
834 if let Some(context_ids) = self.context_by_message.get(&message.id) {
835 referenced_context_ids.extend(context_ids);
836 }
837
838 let mut request_message = LanguageModelRequestMessage {
839 role: message.role,
840 content: Vec::new(),
841 cache: false,
842 };
843
844 match request_kind {
845 RequestKind::Chat => {
846 self.tool_use
847 .attach_tool_results(message.id, &mut request_message);
848 }
849 RequestKind::Summarize => {
850 // We don't care about tool use during summarization.
851 if self.tool_use.message_has_tool_results(message.id) {
852 continue;
853 }
854 }
855 }
856
857 if !message.segments.is_empty() {
858 request_message
859 .content
860 .push(MessageContent::Text(message.to_string()));
861 }
862
863 match request_kind {
864 RequestKind::Chat => {
865 self.tool_use
866 .attach_tool_uses(message.id, &mut request_message);
867 }
868 RequestKind::Summarize => {
869 // We don't care about tool use during summarization.
870 }
871 };
872
873 request.messages.push(request_message);
874 }
875
876 // Set a cache breakpoint at the second-to-last message.
877 // https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
878 let breakpoint_index = request.messages.len() - 2;
879 for (index, message) in request.messages.iter_mut().enumerate() {
880 message.cache = index == breakpoint_index;
881 }
882
883 if !referenced_context_ids.is_empty() {
884 let mut context_message = LanguageModelRequestMessage {
885 role: Role::User,
886 content: Vec::new(),
887 cache: false,
888 };
889
890 let referenced_context = referenced_context_ids
891 .into_iter()
892 .filter_map(|context_id| self.context.get(context_id))
893 .cloned();
894 attach_context_to_message(&mut context_message, referenced_context);
895
896 request.messages.push(context_message);
897 }
898
899 self.attached_tracked_files_state(&mut request.messages, cx);
900
901 request
902 }
903
904 fn attached_tracked_files_state(
905 &self,
906 messages: &mut Vec<LanguageModelRequestMessage>,
907 cx: &App,
908 ) {
909 const STALE_FILES_HEADER: &str = "These files changed since last read:";
910
911 let mut stale_message = String::new();
912
913 let action_log = self.action_log.read(cx);
914
915 for stale_file in action_log.stale_buffers(cx) {
916 let Some(file) = stale_file.read(cx).file() else {
917 continue;
918 };
919
920 if stale_message.is_empty() {
921 write!(&mut stale_message, "{}", STALE_FILES_HEADER).ok();
922 }
923
924 writeln!(&mut stale_message, "- {}", file.path().display()).ok();
925 }
926
927 let mut content = Vec::with_capacity(2);
928
929 if !stale_message.is_empty() {
930 content.push(stale_message.into());
931 }
932
933 if action_log.has_edited_files_since_project_diagnostics_check() {
934 content.push(
935 "When you're done making changes, make sure to check project diagnostics and fix all errors AND warnings you introduced!".into(),
936 );
937 }
938
939 if !content.is_empty() {
940 let context_message = LanguageModelRequestMessage {
941 role: Role::User,
942 content,
943 cache: false,
944 };
945
946 messages.push(context_message);
947 }
948 }
949
950 pub fn stream_completion(
951 &mut self,
952 request: LanguageModelRequest,
953 model: Arc<dyn LanguageModel>,
954 cx: &mut Context<Self>,
955 ) {
956 let pending_completion_id = post_inc(&mut self.completion_count);
957
958 let task = cx.spawn(async move |thread, cx| {
959 let stream = model.stream_completion(request, &cx);
960 let initial_token_usage =
961 thread.read_with(cx, |thread, _cx| thread.cumulative_token_usage.clone());
962 let stream_completion = async {
963 let mut events = stream.await?;
964 let mut stop_reason = StopReason::EndTurn;
965 let mut current_token_usage = TokenUsage::default();
966
967 while let Some(event) = events.next().await {
968 let event = event?;
969
970 thread.update(cx, |thread, cx| {
971 match event {
972 LanguageModelCompletionEvent::StartMessage { .. } => {
973 thread.insert_message(
974 Role::Assistant,
975 vec![MessageSegment::Text(String::new())],
976 cx,
977 );
978 }
979 LanguageModelCompletionEvent::Stop(reason) => {
980 stop_reason = reason;
981 }
982 LanguageModelCompletionEvent::UsageUpdate(token_usage) => {
983 thread.cumulative_token_usage =
984 thread.cumulative_token_usage.clone() + token_usage.clone()
985 - current_token_usage.clone();
986 current_token_usage = token_usage;
987 }
988 LanguageModelCompletionEvent::Text(chunk) => {
989 if let Some(last_message) = thread.messages.last_mut() {
990 if last_message.role == Role::Assistant {
991 last_message.push_text(&chunk);
992 cx.emit(ThreadEvent::StreamedAssistantText(
993 last_message.id,
994 chunk,
995 ));
996 } else {
997 // If we won't have an Assistant message yet, assume this chunk marks the beginning
998 // of a new Assistant response.
999 //
1000 // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
1001 // will result in duplicating the text of the chunk in the rendered Markdown.
1002 thread.insert_message(
1003 Role::Assistant,
1004 vec![MessageSegment::Text(chunk.to_string())],
1005 cx,
1006 );
1007 };
1008 }
1009 }
1010 LanguageModelCompletionEvent::Thinking(chunk) => {
1011 if let Some(last_message) = thread.messages.last_mut() {
1012 if last_message.role == Role::Assistant {
1013 last_message.push_thinking(&chunk);
1014 cx.emit(ThreadEvent::StreamedAssistantThinking(
1015 last_message.id,
1016 chunk,
1017 ));
1018 } else {
1019 // If we won't have an Assistant message yet, assume this chunk marks the beginning
1020 // of a new Assistant response.
1021 //
1022 // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
1023 // will result in duplicating the text of the chunk in the rendered Markdown.
1024 thread.insert_message(
1025 Role::Assistant,
1026 vec![MessageSegment::Thinking(chunk.to_string())],
1027 cx,
1028 );
1029 };
1030 }
1031 }
1032 LanguageModelCompletionEvent::ToolUse(tool_use) => {
1033 if let Some(last_assistant_message) = thread
1034 .messages
1035 .iter()
1036 .rfind(|message| message.role == Role::Assistant)
1037 {
1038 thread.tool_use.request_tool_use(
1039 last_assistant_message.id,
1040 tool_use,
1041 cx,
1042 );
1043 }
1044 }
1045 }
1046
1047 thread.touch_updated_at();
1048 cx.emit(ThreadEvent::StreamedCompletion);
1049 cx.notify();
1050 })?;
1051
1052 smol::future::yield_now().await;
1053 }
1054
1055 thread.update(cx, |thread, cx| {
1056 thread
1057 .pending_completions
1058 .retain(|completion| completion.id != pending_completion_id);
1059
1060 if thread.summary.is_none() && thread.messages.len() >= 2 {
1061 thread.summarize(cx);
1062 }
1063 })?;
1064
1065 anyhow::Ok(stop_reason)
1066 };
1067
1068 let result = stream_completion.await;
1069
1070 thread
1071 .update(cx, |thread, cx| {
1072 thread.finalize_pending_checkpoint(cx);
1073 match result.as_ref() {
1074 Ok(stop_reason) => match stop_reason {
1075 StopReason::ToolUse => {
1076 cx.emit(ThreadEvent::UsePendingTools);
1077 }
1078 StopReason::EndTurn => {}
1079 StopReason::MaxTokens => {}
1080 },
1081 Err(error) => {
1082 if error.is::<PaymentRequiredError>() {
1083 cx.emit(ThreadEvent::ShowError(ThreadError::PaymentRequired));
1084 } else if error.is::<MaxMonthlySpendReachedError>() {
1085 cx.emit(ThreadEvent::ShowError(
1086 ThreadError::MaxMonthlySpendReached,
1087 ));
1088 } else {
1089 let error_message = error
1090 .chain()
1091 .map(|err| err.to_string())
1092 .collect::<Vec<_>>()
1093 .join("\n");
1094 cx.emit(ThreadEvent::ShowError(ThreadError::Message {
1095 header: "Error interacting with language model".into(),
1096 message: SharedString::from(error_message.clone()),
1097 }));
1098 }
1099
1100 thread.cancel_last_completion(cx);
1101 }
1102 }
1103 cx.emit(ThreadEvent::DoneStreaming);
1104
1105 if let Ok(initial_usage) = initial_token_usage {
1106 let usage = thread.cumulative_token_usage.clone() - initial_usage;
1107
1108 telemetry::event!(
1109 "Assistant Thread Completion",
1110 thread_id = thread.id().to_string(),
1111 model = model.telemetry_id(),
1112 model_provider = model.provider_id().to_string(),
1113 input_tokens = usage.input_tokens,
1114 output_tokens = usage.output_tokens,
1115 cache_creation_input_tokens = usage.cache_creation_input_tokens,
1116 cache_read_input_tokens = usage.cache_read_input_tokens,
1117 );
1118 }
1119 })
1120 .ok();
1121 });
1122
1123 self.pending_completions.push(PendingCompletion {
1124 id: pending_completion_id,
1125 _task: task,
1126 });
1127 }
1128
1129 pub fn summarize(&mut self, cx: &mut Context<Self>) {
1130 let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
1131 return;
1132 };
1133 let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
1134 return;
1135 };
1136
1137 if !provider.is_authenticated(cx) {
1138 return;
1139 }
1140
1141 let mut request = self.to_completion_request(RequestKind::Summarize, cx);
1142 request.messages.push(LanguageModelRequestMessage {
1143 role: Role::User,
1144 content: vec![
1145 "Generate a concise 3-7 word title for this conversation, omitting punctuation. \
1146 Go straight to the title, without any preamble and prefix like `Here's a concise suggestion:...` or `Title:`. \
1147 If the conversation is about a specific subject, include it in the title. \
1148 Be descriptive. DO NOT speak in the first person."
1149 .into(),
1150 ],
1151 cache: false,
1152 });
1153
1154 self.pending_summary = cx.spawn(async move |this, cx| {
1155 async move {
1156 let stream = model.stream_completion_text(request, &cx);
1157 let mut messages = stream.await?;
1158
1159 let mut new_summary = String::new();
1160 while let Some(message) = messages.stream.next().await {
1161 let text = message?;
1162 let mut lines = text.lines();
1163 new_summary.extend(lines.next());
1164
1165 // Stop if the LLM generated multiple lines.
1166 if lines.next().is_some() {
1167 break;
1168 }
1169 }
1170
1171 this.update(cx, |this, cx| {
1172 if !new_summary.is_empty() {
1173 this.summary = Some(new_summary.into());
1174 }
1175
1176 cx.emit(ThreadEvent::SummaryChanged);
1177 })?;
1178
1179 anyhow::Ok(())
1180 }
1181 .log_err()
1182 .await
1183 });
1184 }
1185
1186 pub fn use_pending_tools(
1187 &mut self,
1188 cx: &mut Context<Self>,
1189 ) -> impl IntoIterator<Item = PendingToolUse> {
1190 let request = self.to_completion_request(RequestKind::Chat, cx);
1191 let messages = Arc::new(request.messages);
1192 let pending_tool_uses = self
1193 .tool_use
1194 .pending_tool_uses()
1195 .into_iter()
1196 .filter(|tool_use| tool_use.status.is_idle())
1197 .cloned()
1198 .collect::<Vec<_>>();
1199
1200 for tool_use in pending_tool_uses.iter() {
1201 if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
1202 if tool.needs_confirmation()
1203 && !AssistantSettings::get_global(cx).always_allow_tool_actions
1204 {
1205 self.tool_use.confirm_tool_use(
1206 tool_use.id.clone(),
1207 tool_use.ui_text.clone(),
1208 tool_use.input.clone(),
1209 messages.clone(),
1210 tool,
1211 );
1212 cx.emit(ThreadEvent::ToolConfirmationNeeded);
1213 } else {
1214 self.run_tool(
1215 tool_use.id.clone(),
1216 tool_use.ui_text.clone(),
1217 tool_use.input.clone(),
1218 &messages,
1219 tool,
1220 cx,
1221 );
1222 }
1223 } else if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
1224 self.run_tool(
1225 tool_use.id.clone(),
1226 tool_use.ui_text.clone(),
1227 tool_use.input.clone(),
1228 &messages,
1229 tool,
1230 cx,
1231 );
1232 }
1233 }
1234
1235 pending_tool_uses
1236 }
1237
1238 pub fn run_tool(
1239 &mut self,
1240 tool_use_id: LanguageModelToolUseId,
1241 ui_text: impl Into<SharedString>,
1242 input: serde_json::Value,
1243 messages: &[LanguageModelRequestMessage],
1244 tool: Arc<dyn Tool>,
1245 cx: &mut Context<Thread>,
1246 ) {
1247 let task = self.spawn_tool_use(tool_use_id.clone(), messages, input, tool, cx);
1248 self.tool_use
1249 .run_pending_tool(tool_use_id, ui_text.into(), task);
1250 }
1251
1252 fn spawn_tool_use(
1253 &mut self,
1254 tool_use_id: LanguageModelToolUseId,
1255 messages: &[LanguageModelRequestMessage],
1256 input: serde_json::Value,
1257 tool: Arc<dyn Tool>,
1258 cx: &mut Context<Thread>,
1259 ) -> Task<()> {
1260 let run_tool = tool.run(
1261 input,
1262 messages,
1263 self.project.clone(),
1264 self.action_log.clone(),
1265 cx,
1266 );
1267
1268 cx.spawn({
1269 async move |thread: WeakEntity<Thread>, cx| {
1270 let output = run_tool.await;
1271
1272 thread
1273 .update(cx, |thread, cx| {
1274 let pending_tool_use = thread
1275 .tool_use
1276 .insert_tool_output(tool_use_id.clone(), output);
1277
1278 cx.emit(ThreadEvent::ToolFinished {
1279 tool_use_id,
1280 pending_tool_use,
1281 canceled: false,
1282 });
1283 })
1284 .ok();
1285 }
1286 })
1287 }
1288
1289 pub fn attach_tool_results(
1290 &mut self,
1291 updated_context: Vec<ContextSnapshot>,
1292 cx: &mut Context<Self>,
1293 ) {
1294 self.context.extend(
1295 updated_context
1296 .into_iter()
1297 .map(|context| (context.id, context)),
1298 );
1299
1300 // Insert a user message to contain the tool results.
1301 self.insert_user_message(
1302 // TODO: Sending up a user message without any content results in the model sending back
1303 // responses that also don't have any content. We currently don't handle this case well,
1304 // so for now we provide some text to keep the model on track.
1305 "Here are the tool results.",
1306 Vec::new(),
1307 None,
1308 cx,
1309 );
1310 }
1311
1312 /// Cancels the last pending completion, if there are any pending.
1313 ///
1314 /// Returns whether a completion was canceled.
1315 pub fn cancel_last_completion(&mut self, cx: &mut Context<Self>) -> bool {
1316 let canceled = if self.pending_completions.pop().is_some() {
1317 true
1318 } else {
1319 let mut canceled = false;
1320 for pending_tool_use in self.tool_use.cancel_pending() {
1321 canceled = true;
1322 cx.emit(ThreadEvent::ToolFinished {
1323 tool_use_id: pending_tool_use.id.clone(),
1324 pending_tool_use: Some(pending_tool_use),
1325 canceled: true,
1326 });
1327 }
1328 canceled
1329 };
1330 self.finalize_pending_checkpoint(cx);
1331 canceled
1332 }
1333
1334 /// Returns the feedback given to the thread, if any.
1335 pub fn feedback(&self) -> Option<ThreadFeedback> {
1336 self.feedback
1337 }
1338
1339 /// Reports feedback about the thread and stores it in our telemetry backend.
1340 pub fn report_feedback(
1341 &mut self,
1342 feedback: ThreadFeedback,
1343 cx: &mut Context<Self>,
1344 ) -> Task<Result<()>> {
1345 let final_project_snapshot = Self::project_snapshot(self.project.clone(), cx);
1346 let serialized_thread = self.serialize(cx);
1347 let thread_id = self.id().clone();
1348 let client = self.project.read(cx).client();
1349 self.feedback = Some(feedback);
1350 cx.notify();
1351
1352 cx.background_spawn(async move {
1353 let final_project_snapshot = final_project_snapshot.await;
1354 let serialized_thread = serialized_thread.await?;
1355 let thread_data =
1356 serde_json::to_value(serialized_thread).unwrap_or_else(|_| serde_json::Value::Null);
1357
1358 let rating = match feedback {
1359 ThreadFeedback::Positive => "positive",
1360 ThreadFeedback::Negative => "negative",
1361 };
1362 telemetry::event!(
1363 "Assistant Thread Rated",
1364 rating,
1365 thread_id,
1366 thread_data,
1367 final_project_snapshot
1368 );
1369 client.telemetry().flush_events();
1370
1371 Ok(())
1372 })
1373 }
1374
1375 /// Create a snapshot of the current project state including git information and unsaved buffers.
1376 fn project_snapshot(
1377 project: Entity<Project>,
1378 cx: &mut Context<Self>,
1379 ) -> Task<Arc<ProjectSnapshot>> {
1380 let git_store = project.read(cx).git_store().clone();
1381 let worktree_snapshots: Vec<_> = project
1382 .read(cx)
1383 .visible_worktrees(cx)
1384 .map(|worktree| Self::worktree_snapshot(worktree, git_store.clone(), cx))
1385 .collect();
1386
1387 cx.spawn(async move |_, cx| {
1388 let worktree_snapshots = futures::future::join_all(worktree_snapshots).await;
1389
1390 let mut unsaved_buffers = Vec::new();
1391 cx.update(|app_cx| {
1392 let buffer_store = project.read(app_cx).buffer_store();
1393 for buffer_handle in buffer_store.read(app_cx).buffers() {
1394 let buffer = buffer_handle.read(app_cx);
1395 if buffer.is_dirty() {
1396 if let Some(file) = buffer.file() {
1397 let path = file.path().to_string_lossy().to_string();
1398 unsaved_buffers.push(path);
1399 }
1400 }
1401 }
1402 })
1403 .ok();
1404
1405 Arc::new(ProjectSnapshot {
1406 worktree_snapshots,
1407 unsaved_buffer_paths: unsaved_buffers,
1408 timestamp: Utc::now(),
1409 })
1410 })
1411 }
1412
1413 fn worktree_snapshot(
1414 worktree: Entity<project::Worktree>,
1415 git_store: Entity<GitStore>,
1416 cx: &App,
1417 ) -> Task<WorktreeSnapshot> {
1418 cx.spawn(async move |cx| {
1419 // Get worktree path and snapshot
1420 let worktree_info = cx.update(|app_cx| {
1421 let worktree = worktree.read(app_cx);
1422 let path = worktree.abs_path().to_string_lossy().to_string();
1423 let snapshot = worktree.snapshot();
1424 (path, snapshot)
1425 });
1426
1427 let Ok((worktree_path, snapshot)) = worktree_info else {
1428 return WorktreeSnapshot {
1429 worktree_path: String::new(),
1430 git_state: None,
1431 };
1432 };
1433
1434 let repo_info = git_store
1435 .update(cx, |git_store, cx| {
1436 git_store
1437 .repositories()
1438 .values()
1439 .find(|repo| repo.read(cx).worktree_id == Some(snapshot.id()))
1440 .and_then(|repo| {
1441 let repo = repo.read(cx);
1442 Some((repo.branch().cloned(), repo.local_repository()?))
1443 })
1444 })
1445 .ok()
1446 .flatten();
1447
1448 // Extract git information
1449 let git_state = match repo_info {
1450 None => None,
1451 Some((branch, repo)) => {
1452 let current_branch = branch.map(|branch| branch.name.to_string());
1453 let remote_url = repo.remote_url("origin");
1454 let head_sha = repo.head_sha();
1455
1456 // Get diff asynchronously
1457 let diff = repo
1458 .diff(git::repository::DiffType::HeadToWorktree)
1459 .await
1460 .ok();
1461
1462 Some(GitState {
1463 remote_url,
1464 head_sha,
1465 current_branch,
1466 diff,
1467 })
1468 }
1469 };
1470
1471 WorktreeSnapshot {
1472 worktree_path,
1473 git_state,
1474 }
1475 })
1476 }
1477
1478 pub fn to_markdown(&self, cx: &App) -> Result<String> {
1479 let mut markdown = Vec::new();
1480
1481 if let Some(summary) = self.summary() {
1482 writeln!(markdown, "# {summary}\n")?;
1483 };
1484
1485 for message in self.messages() {
1486 writeln!(
1487 markdown,
1488 "## {role}\n",
1489 role = match message.role {
1490 Role::User => "User",
1491 Role::Assistant => "Assistant",
1492 Role::System => "System",
1493 }
1494 )?;
1495 for segment in &message.segments {
1496 match segment {
1497 MessageSegment::Text(text) => writeln!(markdown, "{}\n", text)?,
1498 MessageSegment::Thinking(text) => {
1499 writeln!(markdown, "<think>{}</think>\n", text)?
1500 }
1501 }
1502 }
1503
1504 for tool_use in self.tool_uses_for_message(message.id, cx) {
1505 writeln!(
1506 markdown,
1507 "**Use Tool: {} ({})**",
1508 tool_use.name, tool_use.id
1509 )?;
1510 writeln!(markdown, "```json")?;
1511 writeln!(
1512 markdown,
1513 "{}",
1514 serde_json::to_string_pretty(&tool_use.input)?
1515 )?;
1516 writeln!(markdown, "```")?;
1517 }
1518
1519 for tool_result in self.tool_results_for_message(message.id) {
1520 write!(markdown, "**Tool Results: {}", tool_result.tool_use_id)?;
1521 if tool_result.is_error {
1522 write!(markdown, " (Error)")?;
1523 }
1524
1525 writeln!(markdown, "**\n")?;
1526 writeln!(markdown, "{}", tool_result.content)?;
1527 }
1528 }
1529
1530 Ok(String::from_utf8_lossy(&markdown).to_string())
1531 }
1532
1533 pub fn review_edits_in_range(
1534 &mut self,
1535 buffer: Entity<language::Buffer>,
1536 buffer_range: Range<language::Anchor>,
1537 accept: bool,
1538 cx: &mut Context<Self>,
1539 ) {
1540 self.action_log.update(cx, |action_log, cx| {
1541 action_log.review_edits_in_range(buffer, buffer_range, accept, cx)
1542 });
1543 }
1544
1545 pub fn action_log(&self) -> &Entity<ActionLog> {
1546 &self.action_log
1547 }
1548
1549 pub fn project(&self) -> &Entity<Project> {
1550 &self.project
1551 }
1552
1553 pub fn cumulative_token_usage(&self) -> TokenUsage {
1554 self.cumulative_token_usage.clone()
1555 }
1556
1557 pub fn deny_tool_use(&mut self, tool_use_id: LanguageModelToolUseId, cx: &mut Context<Self>) {
1558 let err = Err(anyhow::anyhow!(
1559 "Permission to run tool action denied by user"
1560 ));
1561
1562 self.tool_use.insert_tool_output(tool_use_id.clone(), err);
1563
1564 cx.emit(ThreadEvent::ToolFinished {
1565 tool_use_id,
1566 pending_tool_use: None,
1567 canceled: true,
1568 });
1569 }
1570}
1571
1572#[derive(Debug, Clone)]
1573pub enum ThreadError {
1574 PaymentRequired,
1575 MaxMonthlySpendReached,
1576 Message {
1577 header: SharedString,
1578 message: SharedString,
1579 },
1580}
1581
1582#[derive(Debug, Clone)]
1583pub enum ThreadEvent {
1584 ShowError(ThreadError),
1585 StreamedCompletion,
1586 StreamedAssistantText(MessageId, String),
1587 StreamedAssistantThinking(MessageId, String),
1588 DoneStreaming,
1589 MessageAdded(MessageId),
1590 MessageEdited(MessageId),
1591 MessageDeleted(MessageId),
1592 SummaryChanged,
1593 UsePendingTools,
1594 ToolFinished {
1595 #[allow(unused)]
1596 tool_use_id: LanguageModelToolUseId,
1597 /// The pending tool use that corresponds to this tool.
1598 pending_tool_use: Option<PendingToolUse>,
1599 /// Whether the tool was canceled by the user.
1600 canceled: bool,
1601 },
1602 CheckpointChanged,
1603 ToolConfirmationNeeded,
1604}
1605
1606impl EventEmitter<ThreadEvent> for Thread {}
1607
1608struct PendingCompletion {
1609 id: usize,
1610 _task: Task<()>,
1611}