1use std::io::Write;
2use std::sync::Arc;
3
4use anyhow::{Context as _, Result};
5use assistant_tool::ToolWorkingSet;
6use chrono::{DateTime, Utc};
7use collections::{BTreeMap, HashMap, HashSet};
8use futures::future::Shared;
9use futures::{FutureExt, StreamExt as _};
10use git;
11use gpui::{App, AppContext, Context, Entity, EventEmitter, SharedString, Task};
12use language_model::{
13 LanguageModel, LanguageModelCompletionEvent, LanguageModelRegistry, LanguageModelRequest,
14 LanguageModelRequestMessage, LanguageModelRequestTool, LanguageModelToolResult,
15 LanguageModelToolUseId, MaxMonthlySpendReachedError, MessageContent, PaymentRequiredError,
16 Role, StopReason, TokenUsage,
17};
18use project::Project;
19use prompt_store::{AssistantSystemPromptWorktree, PromptBuilder};
20use scripting_tool::{ScriptingSession, ScriptingTool};
21use serde::{Deserialize, Serialize};
22use util::{post_inc, ResultExt, TryFutureExt as _};
23use uuid::Uuid;
24
25use crate::context::{attach_context_to_message, ContextId, ContextSnapshot};
26use crate::thread_store::{
27 SerializedMessage, SerializedThread, SerializedToolResult, SerializedToolUse,
28};
29use crate::tool_use::{PendingToolUse, ToolUse, ToolUseState};
30
31#[derive(Debug, Clone, Copy)]
32pub enum RequestKind {
33 Chat,
34 /// Used when summarizing a thread.
35 Summarize,
36}
37
38#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
39pub struct ThreadId(Arc<str>);
40
41impl ThreadId {
42 pub fn new() -> Self {
43 Self(Uuid::new_v4().to_string().into())
44 }
45}
46
47impl std::fmt::Display for ThreadId {
48 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49 write!(f, "{}", self.0)
50 }
51}
52
53#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
54pub struct MessageId(pub(crate) usize);
55
56impl MessageId {
57 fn post_inc(&mut self) -> Self {
58 Self(post_inc(&mut self.0))
59 }
60}
61
62/// A message in a [`Thread`].
63#[derive(Debug, Clone)]
64pub struct Message {
65 pub id: MessageId,
66 pub role: Role,
67 pub text: String,
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct ProjectSnapshot {
72 pub worktree_snapshots: Vec<WorktreeSnapshot>,
73 pub unsaved_buffer_paths: Vec<String>,
74 pub timestamp: DateTime<Utc>,
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct WorktreeSnapshot {
79 pub worktree_path: String,
80 pub git_state: Option<GitState>,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct GitState {
85 pub remote_url: Option<String>,
86 pub head_sha: Option<String>,
87 pub current_branch: Option<String>,
88 pub diff: Option<String>,
89}
90
91/// A thread of conversation with the LLM.
92pub struct Thread {
93 id: ThreadId,
94 updated_at: DateTime<Utc>,
95 summary: Option<SharedString>,
96 pending_summary: Task<Option<()>>,
97 messages: Vec<Message>,
98 next_message_id: MessageId,
99 context: BTreeMap<ContextId, ContextSnapshot>,
100 context_by_message: HashMap<MessageId, Vec<ContextId>>,
101 completion_count: usize,
102 pending_completions: Vec<PendingCompletion>,
103 project: Entity<Project>,
104 prompt_builder: Arc<PromptBuilder>,
105 tools: Arc<ToolWorkingSet>,
106 tool_use: ToolUseState,
107 scripting_session: Entity<ScriptingSession>,
108 scripting_tool_use: ToolUseState,
109 initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
110 cumulative_token_usage: TokenUsage,
111}
112
113impl Thread {
114 pub fn new(
115 project: Entity<Project>,
116 tools: Arc<ToolWorkingSet>,
117 prompt_builder: Arc<PromptBuilder>,
118 cx: &mut Context<Self>,
119 ) -> Self {
120 Self {
121 id: ThreadId::new(),
122 updated_at: Utc::now(),
123 summary: None,
124 pending_summary: Task::ready(None),
125 messages: Vec::new(),
126 next_message_id: MessageId(0),
127 context: BTreeMap::default(),
128 context_by_message: HashMap::default(),
129 completion_count: 0,
130 pending_completions: Vec::new(),
131 project: project.clone(),
132 prompt_builder,
133 tools,
134 tool_use: ToolUseState::new(),
135 scripting_session: cx.new(|cx| ScriptingSession::new(project.clone(), cx)),
136 scripting_tool_use: ToolUseState::new(),
137 initial_project_snapshot: {
138 let project_snapshot = Self::project_snapshot(project, cx);
139 cx.foreground_executor()
140 .spawn(async move { Some(project_snapshot.await) })
141 .shared()
142 },
143 cumulative_token_usage: TokenUsage::default(),
144 }
145 }
146
147 pub fn deserialize(
148 id: ThreadId,
149 serialized: SerializedThread,
150 project: Entity<Project>,
151 tools: Arc<ToolWorkingSet>,
152 prompt_builder: Arc<PromptBuilder>,
153 cx: &mut Context<Self>,
154 ) -> Self {
155 let next_message_id = MessageId(
156 serialized
157 .messages
158 .last()
159 .map(|message| message.id.0 + 1)
160 .unwrap_or(0),
161 );
162 let tool_use = ToolUseState::from_serialized_messages(&serialized.messages, |name| {
163 name != ScriptingTool::NAME
164 });
165 let scripting_tool_use =
166 ToolUseState::from_serialized_messages(&serialized.messages, |name| {
167 name == ScriptingTool::NAME
168 });
169 let scripting_session = cx.new(|cx| ScriptingSession::new(project.clone(), cx));
170
171 Self {
172 id,
173 updated_at: serialized.updated_at,
174 summary: Some(serialized.summary),
175 pending_summary: Task::ready(None),
176 messages: serialized
177 .messages
178 .into_iter()
179 .map(|message| Message {
180 id: message.id,
181 role: message.role,
182 text: message.text,
183 })
184 .collect(),
185 next_message_id,
186 context: BTreeMap::default(),
187 context_by_message: HashMap::default(),
188 completion_count: 0,
189 pending_completions: Vec::new(),
190 project,
191 prompt_builder,
192 tools,
193 tool_use,
194 scripting_session,
195 scripting_tool_use,
196 initial_project_snapshot: Task::ready(serialized.initial_project_snapshot).shared(),
197 // TODO: persist token usage?
198 cumulative_token_usage: TokenUsage::default(),
199 }
200 }
201
202 pub fn id(&self) -> &ThreadId {
203 &self.id
204 }
205
206 pub fn is_empty(&self) -> bool {
207 self.messages.is_empty()
208 }
209
210 pub fn updated_at(&self) -> DateTime<Utc> {
211 self.updated_at
212 }
213
214 pub fn touch_updated_at(&mut self) {
215 self.updated_at = Utc::now();
216 }
217
218 pub fn summary(&self) -> Option<SharedString> {
219 self.summary.clone()
220 }
221
222 pub fn summary_or_default(&self) -> SharedString {
223 const DEFAULT: SharedString = SharedString::new_static("New Thread");
224 self.summary.clone().unwrap_or(DEFAULT)
225 }
226
227 pub fn set_summary(&mut self, summary: impl Into<SharedString>, cx: &mut Context<Self>) {
228 self.summary = Some(summary.into());
229 cx.emit(ThreadEvent::SummaryChanged);
230 }
231
232 pub fn message(&self, id: MessageId) -> Option<&Message> {
233 self.messages.iter().find(|message| message.id == id)
234 }
235
236 pub fn messages(&self) -> impl Iterator<Item = &Message> {
237 self.messages.iter()
238 }
239
240 pub fn is_streaming(&self) -> bool {
241 !self.pending_completions.is_empty() || !self.all_tools_finished()
242 }
243
244 pub fn tools(&self) -> &Arc<ToolWorkingSet> {
245 &self.tools
246 }
247
248 pub fn context_for_message(&self, id: MessageId) -> Option<Vec<ContextSnapshot>> {
249 let context = self.context_by_message.get(&id)?;
250 Some(
251 context
252 .into_iter()
253 .filter_map(|context_id| self.context.get(&context_id))
254 .cloned()
255 .collect::<Vec<_>>(),
256 )
257 }
258
259 /// Returns whether all of the tool uses have finished running.
260 pub fn all_tools_finished(&self) -> bool {
261 let mut all_pending_tool_uses = self
262 .tool_use
263 .pending_tool_uses()
264 .into_iter()
265 .chain(self.scripting_tool_use.pending_tool_uses());
266
267 // If the only pending tool uses left are the ones with errors, then that means that we've finished running all
268 // of the pending tools.
269 all_pending_tool_uses.all(|tool_use| tool_use.status.is_error())
270 }
271
272 pub fn tool_uses_for_message(&self, id: MessageId) -> Vec<ToolUse> {
273 self.tool_use.tool_uses_for_message(id)
274 }
275
276 pub fn scripting_tool_uses_for_message(&self, id: MessageId) -> Vec<ToolUse> {
277 self.scripting_tool_use.tool_uses_for_message(id)
278 }
279
280 pub fn tool_results_for_message(&self, id: MessageId) -> Vec<&LanguageModelToolResult> {
281 self.tool_use.tool_results_for_message(id)
282 }
283
284 pub fn scripting_tool_results_for_message(
285 &self,
286 id: MessageId,
287 ) -> Vec<&LanguageModelToolResult> {
288 self.scripting_tool_use.tool_results_for_message(id)
289 }
290
291 pub fn scripting_changed_buffers<'a>(
292 &self,
293 cx: &'a App,
294 ) -> impl ExactSizeIterator<Item = &'a Entity<language::Buffer>> {
295 self.scripting_session.read(cx).changed_buffers()
296 }
297
298 pub fn message_has_tool_results(&self, message_id: MessageId) -> bool {
299 self.tool_use.message_has_tool_results(message_id)
300 }
301
302 pub fn message_has_scripting_tool_results(&self, message_id: MessageId) -> bool {
303 self.scripting_tool_use.message_has_tool_results(message_id)
304 }
305
306 pub fn insert_user_message(
307 &mut self,
308 text: impl Into<String>,
309 context: Vec<ContextSnapshot>,
310 cx: &mut Context<Self>,
311 ) -> MessageId {
312 let message_id = self.insert_message(Role::User, text, cx);
313 let context_ids = context.iter().map(|context| context.id).collect::<Vec<_>>();
314 self.context
315 .extend(context.into_iter().map(|context| (context.id, context)));
316 self.context_by_message.insert(message_id, context_ids);
317 message_id
318 }
319
320 pub fn insert_message(
321 &mut self,
322 role: Role,
323 text: impl Into<String>,
324 cx: &mut Context<Self>,
325 ) -> MessageId {
326 let id = self.next_message_id.post_inc();
327 self.messages.push(Message {
328 id,
329 role,
330 text: text.into(),
331 });
332 self.touch_updated_at();
333 cx.emit(ThreadEvent::MessageAdded(id));
334 id
335 }
336
337 pub fn edit_message(
338 &mut self,
339 id: MessageId,
340 new_role: Role,
341 new_text: String,
342 cx: &mut Context<Self>,
343 ) -> bool {
344 let Some(message) = self.messages.iter_mut().find(|message| message.id == id) else {
345 return false;
346 };
347 message.role = new_role;
348 message.text = new_text;
349 self.touch_updated_at();
350 cx.emit(ThreadEvent::MessageEdited(id));
351 true
352 }
353
354 pub fn delete_message(&mut self, id: MessageId, cx: &mut Context<Self>) -> bool {
355 let Some(index) = self.messages.iter().position(|message| message.id == id) else {
356 return false;
357 };
358 self.messages.remove(index);
359 self.context_by_message.remove(&id);
360 self.touch_updated_at();
361 cx.emit(ThreadEvent::MessageDeleted(id));
362 true
363 }
364
365 /// Returns the representation of this [`Thread`] in a textual form.
366 ///
367 /// This is the representation we use when attaching a thread as context to another thread.
368 pub fn text(&self) -> String {
369 let mut text = String::new();
370
371 for message in &self.messages {
372 text.push_str(match message.role {
373 language_model::Role::User => "User:",
374 language_model::Role::Assistant => "Assistant:",
375 language_model::Role::System => "System:",
376 });
377 text.push('\n');
378
379 text.push_str(&message.text);
380 text.push('\n');
381 }
382
383 text
384 }
385
386 /// Serializes this thread into a format for storage or telemetry.
387 pub fn serialize(&self, cx: &mut Context<Self>) -> Task<Result<SerializedThread>> {
388 let initial_project_snapshot = self.initial_project_snapshot.clone();
389 cx.spawn(|this, cx| async move {
390 let initial_project_snapshot = initial_project_snapshot.await;
391 this.read_with(&cx, |this, _| SerializedThread {
392 summary: this.summary_or_default(),
393 updated_at: this.updated_at(),
394 messages: this
395 .messages()
396 .map(|message| SerializedMessage {
397 id: message.id,
398 role: message.role,
399 text: message.text.clone(),
400 tool_uses: this
401 .tool_uses_for_message(message.id)
402 .into_iter()
403 .chain(this.scripting_tool_uses_for_message(message.id))
404 .map(|tool_use| SerializedToolUse {
405 id: tool_use.id,
406 name: tool_use.name,
407 input: tool_use.input,
408 })
409 .collect(),
410 tool_results: this
411 .tool_results_for_message(message.id)
412 .into_iter()
413 .chain(this.scripting_tool_results_for_message(message.id))
414 .map(|tool_result| SerializedToolResult {
415 tool_use_id: tool_result.tool_use_id.clone(),
416 is_error: tool_result.is_error,
417 content: tool_result.content.clone(),
418 })
419 .collect(),
420 })
421 .collect(),
422 initial_project_snapshot,
423 })
424 })
425 }
426
427 pub fn send_to_model(
428 &mut self,
429 model: Arc<dyn LanguageModel>,
430 request_kind: RequestKind,
431 cx: &mut Context<Self>,
432 ) {
433 let mut request = self.to_completion_request(request_kind, cx);
434 request.tools = {
435 let mut tools = Vec::new();
436
437 if self.tools.is_scripting_tool_enabled() {
438 tools.push(LanguageModelRequestTool {
439 name: ScriptingTool::NAME.into(),
440 description: ScriptingTool::DESCRIPTION.into(),
441 input_schema: ScriptingTool::input_schema(),
442 });
443 }
444
445 tools.extend(self.tools().enabled_tools(cx).into_iter().map(|tool| {
446 LanguageModelRequestTool {
447 name: tool.name(),
448 description: tool.description(),
449 input_schema: tool.input_schema(),
450 }
451 }));
452
453 tools
454 };
455
456 self.stream_completion(request, model, cx);
457 }
458
459 pub fn to_completion_request(
460 &self,
461 request_kind: RequestKind,
462 cx: &App,
463 ) -> LanguageModelRequest {
464 let worktree_root_names = self
465 .project
466 .read(cx)
467 .visible_worktrees(cx)
468 .map(|worktree| {
469 let worktree = worktree.read(cx);
470 AssistantSystemPromptWorktree {
471 root_name: worktree.root_name().into(),
472 abs_path: worktree.abs_path(),
473 }
474 })
475 .collect::<Vec<_>>();
476 let system_prompt = self
477 .prompt_builder
478 .generate_assistant_system_prompt(worktree_root_names)
479 .context("failed to generate assistant system prompt")
480 .log_err()
481 .unwrap_or_default();
482
483 let mut request = LanguageModelRequest {
484 messages: vec![LanguageModelRequestMessage {
485 role: Role::System,
486 content: vec![MessageContent::Text(system_prompt)],
487 cache: true,
488 }],
489 tools: Vec::new(),
490 stop: Vec::new(),
491 temperature: None,
492 };
493
494 let mut referenced_context_ids = HashSet::default();
495
496 for message in &self.messages {
497 if let Some(context_ids) = self.context_by_message.get(&message.id) {
498 referenced_context_ids.extend(context_ids);
499 }
500
501 let mut request_message = LanguageModelRequestMessage {
502 role: message.role,
503 content: Vec::new(),
504 cache: false,
505 };
506
507 match request_kind {
508 RequestKind::Chat => {
509 self.tool_use
510 .attach_tool_results(message.id, &mut request_message);
511 self.scripting_tool_use
512 .attach_tool_results(message.id, &mut request_message);
513 }
514 RequestKind::Summarize => {
515 // We don't care about tool use during summarization.
516 }
517 }
518
519 if !message.text.is_empty() {
520 request_message
521 .content
522 .push(MessageContent::Text(message.text.clone()));
523 }
524
525 match request_kind {
526 RequestKind::Chat => {
527 self.tool_use
528 .attach_tool_uses(message.id, &mut request_message);
529 self.scripting_tool_use
530 .attach_tool_uses(message.id, &mut request_message);
531 }
532 RequestKind::Summarize => {
533 // We don't care about tool use during summarization.
534 }
535 };
536
537 request.messages.push(request_message);
538 }
539
540 if !referenced_context_ids.is_empty() {
541 let mut context_message = LanguageModelRequestMessage {
542 role: Role::User,
543 content: Vec::new(),
544 cache: false,
545 };
546
547 let referenced_context = referenced_context_ids
548 .into_iter()
549 .filter_map(|context_id| self.context.get(context_id))
550 .cloned();
551 attach_context_to_message(&mut context_message, referenced_context);
552
553 request.messages.push(context_message);
554 }
555
556 request
557 }
558
559 pub fn stream_completion(
560 &mut self,
561 request: LanguageModelRequest,
562 model: Arc<dyn LanguageModel>,
563 cx: &mut Context<Self>,
564 ) {
565 let pending_completion_id = post_inc(&mut self.completion_count);
566
567 let task = cx.spawn(|thread, mut cx| async move {
568 let stream = model.stream_completion(request, &cx);
569 let stream_completion = async {
570 let mut events = stream.await?;
571 let mut stop_reason = StopReason::EndTurn;
572 let mut current_token_usage = TokenUsage::default();
573
574 while let Some(event) = events.next().await {
575 let event = event?;
576
577 thread.update(&mut cx, |thread, cx| {
578 match event {
579 LanguageModelCompletionEvent::StartMessage { .. } => {
580 thread.insert_message(Role::Assistant, String::new(), cx);
581 }
582 LanguageModelCompletionEvent::Stop(reason) => {
583 stop_reason = reason;
584 }
585 LanguageModelCompletionEvent::UsageUpdate(token_usage) => {
586 thread.cumulative_token_usage =
587 thread.cumulative_token_usage.clone() + token_usage.clone()
588 - current_token_usage.clone();
589 current_token_usage = token_usage;
590 }
591 LanguageModelCompletionEvent::Text(chunk) => {
592 if let Some(last_message) = thread.messages.last_mut() {
593 if last_message.role == Role::Assistant {
594 last_message.text.push_str(&chunk);
595 cx.emit(ThreadEvent::StreamedAssistantText(
596 last_message.id,
597 chunk,
598 ));
599 } else {
600 // If we won't have an Assistant message yet, assume this chunk marks the beginning
601 // of a new Assistant response.
602 //
603 // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
604 // will result in duplicating the text of the chunk in the rendered Markdown.
605 thread.insert_message(Role::Assistant, chunk, cx);
606 };
607 }
608 }
609 LanguageModelCompletionEvent::ToolUse(tool_use) => {
610 if let Some(last_assistant_message) = thread
611 .messages
612 .iter()
613 .rfind(|message| message.role == Role::Assistant)
614 {
615 if tool_use.name.as_ref() == ScriptingTool::NAME {
616 thread
617 .scripting_tool_use
618 .request_tool_use(last_assistant_message.id, tool_use);
619 } else {
620 thread
621 .tool_use
622 .request_tool_use(last_assistant_message.id, tool_use);
623 }
624 }
625 }
626 }
627
628 thread.touch_updated_at();
629 cx.emit(ThreadEvent::StreamedCompletion);
630 cx.notify();
631 })?;
632
633 smol::future::yield_now().await;
634 }
635
636 thread.update(&mut cx, |thread, cx| {
637 thread
638 .pending_completions
639 .retain(|completion| completion.id != pending_completion_id);
640
641 if thread.summary.is_none() && thread.messages.len() >= 2 {
642 thread.summarize(cx);
643 }
644 })?;
645
646 anyhow::Ok(stop_reason)
647 };
648
649 let result = stream_completion.await;
650
651 thread
652 .update(&mut cx, |thread, cx| match result.as_ref() {
653 Ok(stop_reason) => match stop_reason {
654 StopReason::ToolUse => {
655 cx.emit(ThreadEvent::UsePendingTools);
656 }
657 StopReason::EndTurn => {}
658 StopReason::MaxTokens => {}
659 },
660 Err(error) => {
661 if error.is::<PaymentRequiredError>() {
662 cx.emit(ThreadEvent::ShowError(ThreadError::PaymentRequired));
663 } else if error.is::<MaxMonthlySpendReachedError>() {
664 cx.emit(ThreadEvent::ShowError(ThreadError::MaxMonthlySpendReached));
665 } else {
666 let error_message = error
667 .chain()
668 .map(|err| err.to_string())
669 .collect::<Vec<_>>()
670 .join("\n");
671 cx.emit(ThreadEvent::ShowError(ThreadError::Message(
672 SharedString::from(error_message.clone()),
673 )));
674 }
675
676 thread.cancel_last_completion();
677 }
678 })
679 .ok();
680 });
681
682 self.pending_completions.push(PendingCompletion {
683 id: pending_completion_id,
684 _task: task,
685 });
686 }
687
688 pub fn summarize(&mut self, cx: &mut Context<Self>) {
689 let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
690 return;
691 };
692 let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
693 return;
694 };
695
696 if !provider.is_authenticated(cx) {
697 return;
698 }
699
700 let mut request = self.to_completion_request(RequestKind::Summarize, cx);
701 request.messages.push(LanguageModelRequestMessage {
702 role: Role::User,
703 content: vec![
704 "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:`"
705 .into(),
706 ],
707 cache: false,
708 });
709
710 self.pending_summary = cx.spawn(|this, mut cx| {
711 async move {
712 let stream = model.stream_completion_text(request, &cx);
713 let mut messages = stream.await?;
714
715 let mut new_summary = String::new();
716 while let Some(message) = messages.stream.next().await {
717 let text = message?;
718 let mut lines = text.lines();
719 new_summary.extend(lines.next());
720
721 // Stop if the LLM generated multiple lines.
722 if lines.next().is_some() {
723 break;
724 }
725 }
726
727 this.update(&mut cx, |this, cx| {
728 if !new_summary.is_empty() {
729 this.summary = Some(new_summary.into());
730 }
731
732 cx.emit(ThreadEvent::SummaryChanged);
733 })?;
734
735 anyhow::Ok(())
736 }
737 .log_err()
738 });
739 }
740
741 pub fn use_pending_tools(&mut self, cx: &mut Context<Self>) {
742 let request = self.to_completion_request(RequestKind::Chat, cx);
743 let pending_tool_uses = self
744 .tool_use
745 .pending_tool_uses()
746 .into_iter()
747 .filter(|tool_use| tool_use.status.is_idle())
748 .cloned()
749 .collect::<Vec<_>>();
750
751 for tool_use in pending_tool_uses {
752 if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
753 let task = tool.run(tool_use.input, &request.messages, self.project.clone(), cx);
754
755 self.insert_tool_output(tool_use.id.clone(), task, cx);
756 }
757 }
758
759 let pending_scripting_tool_uses = self
760 .scripting_tool_use
761 .pending_tool_uses()
762 .into_iter()
763 .filter(|tool_use| tool_use.status.is_idle())
764 .cloned()
765 .collect::<Vec<_>>();
766
767 for scripting_tool_use in pending_scripting_tool_uses {
768 let task = match ScriptingTool::deserialize_input(scripting_tool_use.input) {
769 Err(err) => Task::ready(Err(err.into())),
770 Ok(input) => {
771 let (script_id, script_task) =
772 self.scripting_session.update(cx, move |session, cx| {
773 session.run_script(input.lua_script, cx)
774 });
775
776 let session = self.scripting_session.clone();
777 cx.spawn(|_, cx| async move {
778 script_task.await;
779
780 let message = session.read_with(&cx, |session, _cx| {
781 // Using a id to get the script output seems impractical.
782 // Why not just include it in the Task result?
783 // This is because we'll later report the script state as it runs,
784 session
785 .get(script_id)
786 .output_message_for_llm()
787 .expect("Script shouldn't still be running")
788 })?;
789
790 Ok(message)
791 })
792 }
793 };
794
795 self.insert_scripting_tool_output(scripting_tool_use.id.clone(), task, cx);
796 }
797 }
798
799 pub fn insert_tool_output(
800 &mut self,
801 tool_use_id: LanguageModelToolUseId,
802 output: Task<Result<String>>,
803 cx: &mut Context<Self>,
804 ) {
805 let insert_output_task = cx.spawn(|thread, mut cx| {
806 let tool_use_id = tool_use_id.clone();
807 async move {
808 let output = output.await;
809 thread
810 .update(&mut cx, |thread, cx| {
811 let pending_tool_use = thread
812 .tool_use
813 .insert_tool_output(tool_use_id.clone(), output);
814
815 cx.emit(ThreadEvent::ToolFinished {
816 tool_use_id,
817 pending_tool_use,
818 });
819 })
820 .ok();
821 }
822 });
823
824 self.tool_use
825 .run_pending_tool(tool_use_id, insert_output_task);
826 }
827
828 pub fn insert_scripting_tool_output(
829 &mut self,
830 tool_use_id: LanguageModelToolUseId,
831 output: Task<Result<String>>,
832 cx: &mut Context<Self>,
833 ) {
834 let insert_output_task = cx.spawn(|thread, mut cx| {
835 let tool_use_id = tool_use_id.clone();
836 async move {
837 let output = output.await;
838 thread
839 .update(&mut cx, |thread, cx| {
840 let pending_tool_use = thread
841 .scripting_tool_use
842 .insert_tool_output(tool_use_id.clone(), output);
843
844 cx.emit(ThreadEvent::ToolFinished {
845 tool_use_id,
846 pending_tool_use,
847 });
848 })
849 .ok();
850 }
851 });
852
853 self.scripting_tool_use
854 .run_pending_tool(tool_use_id, insert_output_task);
855 }
856
857 pub fn send_tool_results_to_model(
858 &mut self,
859 model: Arc<dyn LanguageModel>,
860 cx: &mut Context<Self>,
861 ) {
862 // Insert a user message to contain the tool results.
863 self.insert_user_message(
864 // TODO: Sending up a user message without any content results in the model sending back
865 // responses that also don't have any content. We currently don't handle this case well,
866 // so for now we provide some text to keep the model on track.
867 "Here are the tool results.",
868 Vec::new(),
869 cx,
870 );
871 self.send_to_model(model, RequestKind::Chat, cx);
872 }
873
874 /// Cancels the last pending completion, if there are any pending.
875 ///
876 /// Returns whether a completion was canceled.
877 pub fn cancel_last_completion(&mut self) -> bool {
878 if let Some(_last_completion) = self.pending_completions.pop() {
879 true
880 } else {
881 false
882 }
883 }
884
885 /// Reports feedback about the thread and stores it in our telemetry backend.
886 pub fn report_feedback(&self, is_positive: bool, cx: &mut Context<Self>) -> Task<Result<()>> {
887 let final_project_snapshot = Self::project_snapshot(self.project.clone(), cx);
888 let serialized_thread = self.serialize(cx);
889 let thread_id = self.id().clone();
890 let client = self.project.read(cx).client();
891
892 cx.background_spawn(async move {
893 let final_project_snapshot = final_project_snapshot.await;
894 let serialized_thread = serialized_thread.await?;
895 let thread_data =
896 serde_json::to_value(serialized_thread).unwrap_or_else(|_| serde_json::Value::Null);
897
898 let rating = if is_positive { "positive" } else { "negative" };
899 telemetry::event!(
900 "Assistant Thread Rated",
901 rating,
902 thread_id,
903 thread_data,
904 final_project_snapshot
905 );
906 client.telemetry().flush_events();
907
908 Ok(())
909 })
910 }
911
912 /// Create a snapshot of the current project state including git information and unsaved buffers.
913 fn project_snapshot(
914 project: Entity<Project>,
915 cx: &mut Context<Self>,
916 ) -> Task<Arc<ProjectSnapshot>> {
917 let worktree_snapshots: Vec<_> = project
918 .read(cx)
919 .visible_worktrees(cx)
920 .map(|worktree| Self::worktree_snapshot(worktree, cx))
921 .collect();
922
923 cx.spawn(move |_, cx| async move {
924 let worktree_snapshots = futures::future::join_all(worktree_snapshots).await;
925
926 let mut unsaved_buffers = Vec::new();
927 cx.update(|app_cx| {
928 let buffer_store = project.read(app_cx).buffer_store();
929 for buffer_handle in buffer_store.read(app_cx).buffers() {
930 let buffer = buffer_handle.read(app_cx);
931 if buffer.is_dirty() {
932 if let Some(file) = buffer.file() {
933 let path = file.path().to_string_lossy().to_string();
934 unsaved_buffers.push(path);
935 }
936 }
937 }
938 })
939 .ok();
940
941 Arc::new(ProjectSnapshot {
942 worktree_snapshots,
943 unsaved_buffer_paths: unsaved_buffers,
944 timestamp: Utc::now(),
945 })
946 })
947 }
948
949 fn worktree_snapshot(worktree: Entity<project::Worktree>, cx: &App) -> Task<WorktreeSnapshot> {
950 cx.spawn(move |cx| async move {
951 // Get worktree path and snapshot
952 let worktree_info = cx.update(|app_cx| {
953 let worktree = worktree.read(app_cx);
954 let path = worktree.abs_path().to_string_lossy().to_string();
955 let snapshot = worktree.snapshot();
956 (path, snapshot)
957 });
958
959 let Ok((worktree_path, snapshot)) = worktree_info else {
960 return WorktreeSnapshot {
961 worktree_path: String::new(),
962 git_state: None,
963 };
964 };
965
966 // Extract git information
967 let git_state = match snapshot.repositories().first() {
968 None => None,
969 Some(repo_entry) => {
970 // Get branch information
971 let current_branch = repo_entry.branch().map(|branch| branch.name.to_string());
972
973 // Get repository info
974 let repo_result = worktree.read_with(&cx, |worktree, _cx| {
975 if let project::Worktree::Local(local_worktree) = &worktree {
976 local_worktree.get_local_repo(repo_entry).map(|local_repo| {
977 let repo = local_repo.repo();
978 (repo.remote_url("origin"), repo.head_sha(), repo.clone())
979 })
980 } else {
981 None
982 }
983 });
984
985 match repo_result {
986 Ok(Some((remote_url, head_sha, repository))) => {
987 // Get diff asynchronously
988 let diff = repository
989 .diff(git::repository::DiffType::HeadToWorktree, cx)
990 .await
991 .ok();
992
993 Some(GitState {
994 remote_url,
995 head_sha,
996 current_branch,
997 diff,
998 })
999 }
1000 Err(_) | Ok(None) => None,
1001 }
1002 }
1003 };
1004
1005 WorktreeSnapshot {
1006 worktree_path,
1007 git_state,
1008 }
1009 })
1010 }
1011
1012 pub fn to_markdown(&self) -> Result<String> {
1013 let mut markdown = Vec::new();
1014
1015 if let Some(summary) = self.summary() {
1016 writeln!(markdown, "# {summary}\n")?;
1017 };
1018
1019 for message in self.messages() {
1020 writeln!(
1021 markdown,
1022 "## {role}\n",
1023 role = match message.role {
1024 Role::User => "User",
1025 Role::Assistant => "Assistant",
1026 Role::System => "System",
1027 }
1028 )?;
1029 writeln!(markdown, "{}\n", message.text)?;
1030
1031 for tool_use in self.tool_uses_for_message(message.id) {
1032 writeln!(
1033 markdown,
1034 "**Use Tool: {} ({})**",
1035 tool_use.name, tool_use.id
1036 )?;
1037 writeln!(markdown, "```json")?;
1038 writeln!(
1039 markdown,
1040 "{}",
1041 serde_json::to_string_pretty(&tool_use.input)?
1042 )?;
1043 writeln!(markdown, "```")?;
1044 }
1045
1046 for tool_result in self.tool_results_for_message(message.id) {
1047 write!(markdown, "**Tool Results: {}", tool_result.tool_use_id)?;
1048 if tool_result.is_error {
1049 write!(markdown, " (Error)")?;
1050 }
1051
1052 writeln!(markdown, "**\n")?;
1053 writeln!(markdown, "{}", tool_result.content)?;
1054 }
1055 }
1056
1057 Ok(String::from_utf8_lossy(&markdown).to_string())
1058 }
1059
1060 pub fn cumulative_token_usage(&self) -> TokenUsage {
1061 self.cumulative_token_usage.clone()
1062 }
1063}
1064
1065#[derive(Debug, Clone)]
1066pub enum ThreadError {
1067 PaymentRequired,
1068 MaxMonthlySpendReached,
1069 Message(SharedString),
1070}
1071
1072#[derive(Debug, Clone)]
1073pub enum ThreadEvent {
1074 ShowError(ThreadError),
1075 StreamedCompletion,
1076 StreamedAssistantText(MessageId, String),
1077 MessageAdded(MessageId),
1078 MessageEdited(MessageId),
1079 MessageDeleted(MessageId),
1080 SummaryChanged,
1081 UsePendingTools,
1082 ToolFinished {
1083 #[allow(unused)]
1084 tool_use_id: LanguageModelToolUseId,
1085 /// The pending tool use that corresponds to this tool.
1086 pending_tool_use: Option<PendingToolUse>,
1087 },
1088}
1089
1090impl EventEmitter<ThreadEvent> for Thread {}
1091
1092struct PendingCompletion {
1093 id: usize,
1094 _task: Task<()>,
1095}