1use std::sync::Arc;
2
3use anyhow::{Context as _, Result};
4use assistant_tool::ToolWorkingSet;
5use chrono::{DateTime, Utc};
6use collections::{BTreeMap, HashMap, HashSet};
7use futures::StreamExt as _;
8use gpui::{App, AppContext, Context, Entity, EventEmitter, SharedString, Task};
9use language_model::{
10 LanguageModel, LanguageModelCompletionEvent, LanguageModelRegistry, LanguageModelRequest,
11 LanguageModelRequestMessage, LanguageModelRequestTool, LanguageModelToolResult,
12 LanguageModelToolUseId, MaxMonthlySpendReachedError, MessageContent, PaymentRequiredError,
13 Role, StopReason,
14};
15use project::Project;
16use prompt_store::{AssistantSystemPromptWorktree, PromptBuilder};
17use scripting_tool::{ScriptingSession, ScriptingTool};
18use serde::{Deserialize, Serialize};
19use util::{post_inc, ResultExt, TryFutureExt as _};
20use uuid::Uuid;
21
22use crate::context::{attach_context_to_message, ContextId, ContextSnapshot};
23use crate::thread_store::SavedThread;
24use crate::tool_use::{PendingToolUse, ToolUse, ToolUseState};
25
26#[derive(Debug, Clone, Copy)]
27pub enum RequestKind {
28 Chat,
29 /// Used when summarizing a thread.
30 Summarize,
31}
32
33#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
34pub struct ThreadId(Arc<str>);
35
36impl ThreadId {
37 pub fn new() -> Self {
38 Self(Uuid::new_v4().to_string().into())
39 }
40}
41
42impl std::fmt::Display for ThreadId {
43 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 write!(f, "{}", self.0)
45 }
46}
47
48#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
49pub struct MessageId(pub(crate) usize);
50
51impl MessageId {
52 fn post_inc(&mut self) -> Self {
53 Self(post_inc(&mut self.0))
54 }
55}
56
57/// A message in a [`Thread`].
58#[derive(Debug, Clone)]
59pub struct Message {
60 pub id: MessageId,
61 pub role: Role,
62 pub text: String,
63}
64
65/// A thread of conversation with the LLM.
66pub struct Thread {
67 id: ThreadId,
68 updated_at: DateTime<Utc>,
69 summary: Option<SharedString>,
70 pending_summary: Task<Option<()>>,
71 messages: Vec<Message>,
72 next_message_id: MessageId,
73 context: BTreeMap<ContextId, ContextSnapshot>,
74 context_by_message: HashMap<MessageId, Vec<ContextId>>,
75 completion_count: usize,
76 pending_completions: Vec<PendingCompletion>,
77 project: Entity<Project>,
78 prompt_builder: Arc<PromptBuilder>,
79 tools: Arc<ToolWorkingSet>,
80 tool_use: ToolUseState,
81 scripting_session: Entity<ScriptingSession>,
82 scripting_tool_use: ToolUseState,
83}
84
85impl Thread {
86 pub fn new(
87 project: Entity<Project>,
88 tools: Arc<ToolWorkingSet>,
89 prompt_builder: Arc<PromptBuilder>,
90 cx: &mut Context<Self>,
91 ) -> Self {
92 let scripting_session = cx.new(|cx| ScriptingSession::new(project.clone(), cx));
93
94 Self {
95 id: ThreadId::new(),
96 updated_at: Utc::now(),
97 summary: None,
98 pending_summary: Task::ready(None),
99 messages: Vec::new(),
100 next_message_id: MessageId(0),
101 context: BTreeMap::default(),
102 context_by_message: HashMap::default(),
103 completion_count: 0,
104 pending_completions: Vec::new(),
105 project,
106 prompt_builder,
107 tools,
108 tool_use: ToolUseState::new(),
109 scripting_session,
110 scripting_tool_use: ToolUseState::new(),
111 }
112 }
113
114 pub fn from_saved(
115 id: ThreadId,
116 saved: SavedThread,
117 project: Entity<Project>,
118 tools: Arc<ToolWorkingSet>,
119 prompt_builder: Arc<PromptBuilder>,
120 cx: &mut Context<Self>,
121 ) -> Self {
122 let next_message_id = MessageId(
123 saved
124 .messages
125 .last()
126 .map(|message| message.id.0 + 1)
127 .unwrap_or(0),
128 );
129 let tool_use =
130 ToolUseState::from_saved_messages(&saved.messages, |name| name != ScriptingTool::NAME);
131 let scripting_tool_use =
132 ToolUseState::from_saved_messages(&saved.messages, |name| name == ScriptingTool::NAME);
133 let scripting_session = cx.new(|cx| ScriptingSession::new(project.clone(), cx));
134
135 Self {
136 id,
137 updated_at: saved.updated_at,
138 summary: Some(saved.summary),
139 pending_summary: Task::ready(None),
140 messages: saved
141 .messages
142 .into_iter()
143 .map(|message| Message {
144 id: message.id,
145 role: message.role,
146 text: message.text,
147 })
148 .collect(),
149 next_message_id,
150 context: BTreeMap::default(),
151 context_by_message: HashMap::default(),
152 completion_count: 0,
153 pending_completions: Vec::new(),
154 project,
155 prompt_builder,
156 tools,
157 tool_use,
158 scripting_session,
159 scripting_tool_use,
160 }
161 }
162
163 pub fn id(&self) -> &ThreadId {
164 &self.id
165 }
166
167 pub fn is_empty(&self) -> bool {
168 self.messages.is_empty()
169 }
170
171 pub fn updated_at(&self) -> DateTime<Utc> {
172 self.updated_at
173 }
174
175 pub fn touch_updated_at(&mut self) {
176 self.updated_at = Utc::now();
177 }
178
179 pub fn summary(&self) -> Option<SharedString> {
180 self.summary.clone()
181 }
182
183 pub fn summary_or_default(&self) -> SharedString {
184 const DEFAULT: SharedString = SharedString::new_static("New Thread");
185 self.summary.clone().unwrap_or(DEFAULT)
186 }
187
188 pub fn set_summary(&mut self, summary: impl Into<SharedString>, cx: &mut Context<Self>) {
189 self.summary = Some(summary.into());
190 cx.emit(ThreadEvent::SummaryChanged);
191 }
192
193 pub fn message(&self, id: MessageId) -> Option<&Message> {
194 self.messages.iter().find(|message| message.id == id)
195 }
196
197 pub fn messages(&self) -> impl Iterator<Item = &Message> {
198 self.messages.iter()
199 }
200
201 pub fn is_streaming(&self) -> bool {
202 !self.pending_completions.is_empty()
203 }
204
205 pub fn tools(&self) -> &Arc<ToolWorkingSet> {
206 &self.tools
207 }
208
209 pub fn context_for_message(&self, id: MessageId) -> Option<Vec<ContextSnapshot>> {
210 let context = self.context_by_message.get(&id)?;
211 Some(
212 context
213 .into_iter()
214 .filter_map(|context_id| self.context.get(&context_id))
215 .cloned()
216 .collect::<Vec<_>>(),
217 )
218 }
219
220 /// Returns whether all of the tool uses have finished running.
221 pub fn all_tools_finished(&self) -> bool {
222 let mut all_pending_tool_uses = self
223 .tool_use
224 .pending_tool_uses()
225 .into_iter()
226 .chain(self.scripting_tool_use.pending_tool_uses());
227
228 // If the only pending tool uses left are the ones with errors, then that means that we've finished running all
229 // of the pending tools.
230 all_pending_tool_uses.all(|tool_use| tool_use.status.is_error())
231 }
232
233 pub fn tool_uses_for_message(&self, id: MessageId) -> Vec<ToolUse> {
234 self.tool_use.tool_uses_for_message(id)
235 }
236
237 pub fn scripting_tool_uses_for_message(&self, id: MessageId) -> Vec<ToolUse> {
238 self.scripting_tool_use.tool_uses_for_message(id)
239 }
240
241 pub fn tool_results_for_message(&self, id: MessageId) -> Vec<&LanguageModelToolResult> {
242 self.tool_use.tool_results_for_message(id)
243 }
244
245 pub fn scripting_tool_results_for_message(
246 &self,
247 id: MessageId,
248 ) -> Vec<&LanguageModelToolResult> {
249 self.scripting_tool_use.tool_results_for_message(id)
250 }
251
252 pub fn scripting_changed_buffers<'a>(
253 &self,
254 cx: &'a App,
255 ) -> impl ExactSizeIterator<Item = &'a Entity<language::Buffer>> {
256 self.scripting_session.read(cx).changed_buffers()
257 }
258
259 pub fn message_has_tool_results(&self, message_id: MessageId) -> bool {
260 self.tool_use.message_has_tool_results(message_id)
261 }
262
263 pub fn message_has_scripting_tool_results(&self, message_id: MessageId) -> bool {
264 self.scripting_tool_use.message_has_tool_results(message_id)
265 }
266
267 pub fn insert_user_message(
268 &mut self,
269 text: impl Into<String>,
270 context: Vec<ContextSnapshot>,
271 cx: &mut Context<Self>,
272 ) -> MessageId {
273 let message_id = self.insert_message(Role::User, text, cx);
274 let context_ids = context.iter().map(|context| context.id).collect::<Vec<_>>();
275 self.context
276 .extend(context.into_iter().map(|context| (context.id, context)));
277 self.context_by_message.insert(message_id, context_ids);
278 message_id
279 }
280
281 pub fn insert_message(
282 &mut self,
283 role: Role,
284 text: impl Into<String>,
285 cx: &mut Context<Self>,
286 ) -> MessageId {
287 let id = self.next_message_id.post_inc();
288 self.messages.push(Message {
289 id,
290 role,
291 text: text.into(),
292 });
293 self.touch_updated_at();
294 cx.emit(ThreadEvent::MessageAdded(id));
295 id
296 }
297
298 pub fn edit_message(
299 &mut self,
300 id: MessageId,
301 new_role: Role,
302 new_text: String,
303 cx: &mut Context<Self>,
304 ) -> bool {
305 let Some(message) = self.messages.iter_mut().find(|message| message.id == id) else {
306 return false;
307 };
308 message.role = new_role;
309 message.text = new_text;
310 self.touch_updated_at();
311 cx.emit(ThreadEvent::MessageEdited(id));
312 true
313 }
314
315 pub fn delete_message(&mut self, id: MessageId, cx: &mut Context<Self>) -> bool {
316 let Some(index) = self.messages.iter().position(|message| message.id == id) else {
317 return false;
318 };
319 self.messages.remove(index);
320 self.context_by_message.remove(&id);
321 self.touch_updated_at();
322 cx.emit(ThreadEvent::MessageDeleted(id));
323 true
324 }
325
326 /// Returns the representation of this [`Thread`] in a textual form.
327 ///
328 /// This is the representation we use when attaching a thread as context to another thread.
329 pub fn text(&self) -> String {
330 let mut text = String::new();
331
332 for message in &self.messages {
333 text.push_str(match message.role {
334 language_model::Role::User => "User:",
335 language_model::Role::Assistant => "Assistant:",
336 language_model::Role::System => "System:",
337 });
338 text.push('\n');
339
340 text.push_str(&message.text);
341 text.push('\n');
342 }
343
344 text
345 }
346
347 pub fn send_to_model(
348 &mut self,
349 model: Arc<dyn LanguageModel>,
350 request_kind: RequestKind,
351 cx: &mut Context<Self>,
352 ) {
353 let mut request = self.to_completion_request(request_kind, cx);
354 request.tools = {
355 let mut tools = Vec::new();
356
357 if self.tools.is_scripting_tool_enabled() {
358 tools.push(LanguageModelRequestTool {
359 name: ScriptingTool::NAME.into(),
360 description: ScriptingTool::DESCRIPTION.into(),
361 input_schema: ScriptingTool::input_schema(),
362 });
363 }
364
365 tools.extend(self.tools().enabled_tools(cx).into_iter().map(|tool| {
366 LanguageModelRequestTool {
367 name: tool.name(),
368 description: tool.description(),
369 input_schema: tool.input_schema(),
370 }
371 }));
372
373 tools
374 };
375
376 self.stream_completion(request, model, cx);
377 }
378
379 pub fn to_completion_request(
380 &self,
381 request_kind: RequestKind,
382 cx: &App,
383 ) -> LanguageModelRequest {
384 let worktree_root_names = self
385 .project
386 .read(cx)
387 .visible_worktrees(cx)
388 .map(|worktree| {
389 let worktree = worktree.read(cx);
390 AssistantSystemPromptWorktree {
391 root_name: worktree.root_name().into(),
392 abs_path: worktree.abs_path(),
393 }
394 })
395 .collect::<Vec<_>>();
396 let system_prompt = self
397 .prompt_builder
398 .generate_assistant_system_prompt(worktree_root_names)
399 .context("failed to generate assistant system prompt")
400 .log_err()
401 .unwrap_or_default();
402
403 let mut request = LanguageModelRequest {
404 messages: vec![LanguageModelRequestMessage {
405 role: Role::System,
406 content: vec![MessageContent::Text(system_prompt)],
407 cache: true,
408 }],
409 tools: Vec::new(),
410 stop: Vec::new(),
411 temperature: None,
412 };
413
414 let mut referenced_context_ids = HashSet::default();
415
416 for message in &self.messages {
417 if let Some(context_ids) = self.context_by_message.get(&message.id) {
418 referenced_context_ids.extend(context_ids);
419 }
420
421 let mut request_message = LanguageModelRequestMessage {
422 role: message.role,
423 content: Vec::new(),
424 cache: false,
425 };
426
427 match request_kind {
428 RequestKind::Chat => {
429 self.tool_use
430 .attach_tool_results(message.id, &mut request_message);
431 self.scripting_tool_use
432 .attach_tool_results(message.id, &mut request_message);
433 }
434 RequestKind::Summarize => {
435 // We don't care about tool use during summarization.
436 }
437 }
438
439 if !message.text.is_empty() {
440 request_message
441 .content
442 .push(MessageContent::Text(message.text.clone()));
443 }
444
445 match request_kind {
446 RequestKind::Chat => {
447 self.tool_use
448 .attach_tool_uses(message.id, &mut request_message);
449 self.scripting_tool_use
450 .attach_tool_uses(message.id, &mut request_message);
451 }
452 RequestKind::Summarize => {
453 // We don't care about tool use during summarization.
454 }
455 };
456
457 request.messages.push(request_message);
458 }
459
460 if !referenced_context_ids.is_empty() {
461 let mut context_message = LanguageModelRequestMessage {
462 role: Role::User,
463 content: Vec::new(),
464 cache: false,
465 };
466
467 let referenced_context = referenced_context_ids
468 .into_iter()
469 .filter_map(|context_id| self.context.get(context_id))
470 .cloned();
471 attach_context_to_message(&mut context_message, referenced_context);
472
473 request.messages.push(context_message);
474 }
475
476 request
477 }
478
479 pub fn stream_completion(
480 &mut self,
481 request: LanguageModelRequest,
482 model: Arc<dyn LanguageModel>,
483 cx: &mut Context<Self>,
484 ) {
485 let pending_completion_id = post_inc(&mut self.completion_count);
486
487 let task = cx.spawn(|thread, mut cx| async move {
488 let stream = model.stream_completion(request, &cx);
489 let stream_completion = async {
490 let mut events = stream.await?;
491 let mut stop_reason = StopReason::EndTurn;
492
493 while let Some(event) = events.next().await {
494 let event = event?;
495
496 thread.update(&mut cx, |thread, cx| {
497 match event {
498 LanguageModelCompletionEvent::StartMessage { .. } => {
499 thread.insert_message(Role::Assistant, String::new(), cx);
500 }
501 LanguageModelCompletionEvent::Stop(reason) => {
502 stop_reason = reason;
503 }
504 LanguageModelCompletionEvent::Text(chunk) => {
505 if let Some(last_message) = thread.messages.last_mut() {
506 if last_message.role == Role::Assistant {
507 last_message.text.push_str(&chunk);
508 cx.emit(ThreadEvent::StreamedAssistantText(
509 last_message.id,
510 chunk,
511 ));
512 } else {
513 // If we won't have an Assistant message yet, assume this chunk marks the beginning
514 // of a new Assistant response.
515 //
516 // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
517 // will result in duplicating the text of the chunk in the rendered Markdown.
518 thread.insert_message(Role::Assistant, chunk, cx);
519 };
520 }
521 }
522 LanguageModelCompletionEvent::ToolUse(tool_use) => {
523 if let Some(last_assistant_message) = thread
524 .messages
525 .iter()
526 .rfind(|message| message.role == Role::Assistant)
527 {
528 if tool_use.name.as_ref() == ScriptingTool::NAME {
529 thread
530 .scripting_tool_use
531 .request_tool_use(last_assistant_message.id, tool_use);
532 } else {
533 thread
534 .tool_use
535 .request_tool_use(last_assistant_message.id, tool_use);
536 }
537 }
538 }
539 }
540
541 thread.touch_updated_at();
542 cx.emit(ThreadEvent::StreamedCompletion);
543 cx.notify();
544 })?;
545
546 smol::future::yield_now().await;
547 }
548
549 thread.update(&mut cx, |thread, cx| {
550 thread
551 .pending_completions
552 .retain(|completion| completion.id != pending_completion_id);
553
554 if thread.summary.is_none() && thread.messages.len() >= 2 {
555 thread.summarize(cx);
556 }
557 })?;
558
559 anyhow::Ok(stop_reason)
560 };
561
562 let result = stream_completion.await;
563
564 thread
565 .update(&mut cx, |thread, cx| match result.as_ref() {
566 Ok(stop_reason) => match stop_reason {
567 StopReason::ToolUse => {
568 cx.emit(ThreadEvent::UsePendingTools);
569 }
570 StopReason::EndTurn => {}
571 StopReason::MaxTokens => {}
572 },
573 Err(error) => {
574 if error.is::<PaymentRequiredError>() {
575 cx.emit(ThreadEvent::ShowError(ThreadError::PaymentRequired));
576 } else if error.is::<MaxMonthlySpendReachedError>() {
577 cx.emit(ThreadEvent::ShowError(ThreadError::MaxMonthlySpendReached));
578 } else {
579 let error_message = error
580 .chain()
581 .map(|err| err.to_string())
582 .collect::<Vec<_>>()
583 .join("\n");
584 cx.emit(ThreadEvent::ShowError(ThreadError::Message(
585 SharedString::from(error_message.clone()),
586 )));
587 }
588
589 thread.cancel_last_completion();
590 }
591 })
592 .ok();
593 });
594
595 self.pending_completions.push(PendingCompletion {
596 id: pending_completion_id,
597 _task: task,
598 });
599 }
600
601 pub fn summarize(&mut self, cx: &mut Context<Self>) {
602 let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
603 return;
604 };
605 let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
606 return;
607 };
608
609 if !provider.is_authenticated(cx) {
610 return;
611 }
612
613 let mut request = self.to_completion_request(RequestKind::Summarize, cx);
614 request.messages.push(LanguageModelRequestMessage {
615 role: Role::User,
616 content: vec![
617 "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:`"
618 .into(),
619 ],
620 cache: false,
621 });
622
623 self.pending_summary = cx.spawn(|this, mut cx| {
624 async move {
625 let stream = model.stream_completion_text(request, &cx);
626 let mut messages = stream.await?;
627
628 let mut new_summary = String::new();
629 while let Some(message) = messages.stream.next().await {
630 let text = message?;
631 let mut lines = text.lines();
632 new_summary.extend(lines.next());
633
634 // Stop if the LLM generated multiple lines.
635 if lines.next().is_some() {
636 break;
637 }
638 }
639
640 this.update(&mut cx, |this, cx| {
641 if !new_summary.is_empty() {
642 this.summary = Some(new_summary.into());
643 }
644
645 cx.emit(ThreadEvent::SummaryChanged);
646 })?;
647
648 anyhow::Ok(())
649 }
650 .log_err()
651 });
652 }
653
654 pub fn use_pending_tools(&mut self, cx: &mut Context<Self>) {
655 let request = self.to_completion_request(RequestKind::Chat, cx);
656 let pending_tool_uses = self
657 .tool_use
658 .pending_tool_uses()
659 .into_iter()
660 .filter(|tool_use| tool_use.status.is_idle())
661 .cloned()
662 .collect::<Vec<_>>();
663
664 for tool_use in pending_tool_uses {
665 if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
666 let task = tool.run(tool_use.input, &request.messages, self.project.clone(), cx);
667
668 self.insert_tool_output(tool_use.id.clone(), task, cx);
669 }
670 }
671
672 let pending_scripting_tool_uses = self
673 .scripting_tool_use
674 .pending_tool_uses()
675 .into_iter()
676 .filter(|tool_use| tool_use.status.is_idle())
677 .cloned()
678 .collect::<Vec<_>>();
679
680 for scripting_tool_use in pending_scripting_tool_uses {
681 let task = match ScriptingTool::deserialize_input(scripting_tool_use.input) {
682 Err(err) => Task::ready(Err(err.into())),
683 Ok(input) => {
684 let (script_id, script_task) =
685 self.scripting_session.update(cx, move |session, cx| {
686 session.run_script(input.lua_script, cx)
687 });
688
689 let session = self.scripting_session.clone();
690 cx.spawn(|_, cx| async move {
691 script_task.await;
692
693 let message = session.read_with(&cx, |session, _cx| {
694 // Using a id to get the script output seems impractical.
695 // Why not just include it in the Task result?
696 // This is because we'll later report the script state as it runs,
697 session
698 .get(script_id)
699 .output_message_for_llm()
700 .expect("Script shouldn't still be running")
701 })?;
702
703 Ok(message)
704 })
705 }
706 };
707
708 self.insert_scripting_tool_output(scripting_tool_use.id.clone(), task, cx);
709 }
710 }
711
712 pub fn insert_tool_output(
713 &mut self,
714 tool_use_id: LanguageModelToolUseId,
715 output: Task<Result<String>>,
716 cx: &mut Context<Self>,
717 ) {
718 let insert_output_task = cx.spawn(|thread, mut cx| {
719 let tool_use_id = tool_use_id.clone();
720 async move {
721 let output = output.await;
722 thread
723 .update(&mut cx, |thread, cx| {
724 let pending_tool_use = thread
725 .tool_use
726 .insert_tool_output(tool_use_id.clone(), output);
727
728 cx.emit(ThreadEvent::ToolFinished {
729 tool_use_id,
730 pending_tool_use,
731 });
732 })
733 .ok();
734 }
735 });
736
737 self.tool_use
738 .run_pending_tool(tool_use_id, insert_output_task);
739 }
740
741 pub fn insert_scripting_tool_output(
742 &mut self,
743 tool_use_id: LanguageModelToolUseId,
744 output: Task<Result<String>>,
745 cx: &mut Context<Self>,
746 ) {
747 let insert_output_task = cx.spawn(|thread, mut cx| {
748 let tool_use_id = tool_use_id.clone();
749 async move {
750 let output = output.await;
751 thread
752 .update(&mut cx, |thread, cx| {
753 let pending_tool_use = thread
754 .scripting_tool_use
755 .insert_tool_output(tool_use_id.clone(), output);
756
757 cx.emit(ThreadEvent::ToolFinished {
758 tool_use_id,
759 pending_tool_use,
760 });
761 })
762 .ok();
763 }
764 });
765
766 self.scripting_tool_use
767 .run_pending_tool(tool_use_id, insert_output_task);
768 }
769
770 pub fn send_tool_results_to_model(
771 &mut self,
772 model: Arc<dyn LanguageModel>,
773 cx: &mut Context<Self>,
774 ) {
775 // Insert a user message to contain the tool results.
776 self.insert_user_message(
777 // TODO: Sending up a user message without any content results in the model sending back
778 // responses that also don't have any content. We currently don't handle this case well,
779 // so for now we provide some text to keep the model on track.
780 "Here are the tool results.",
781 Vec::new(),
782 cx,
783 );
784 self.send_to_model(model, RequestKind::Chat, cx);
785 }
786
787 /// Cancels the last pending completion, if there are any pending.
788 ///
789 /// Returns whether a completion was canceled.
790 pub fn cancel_last_completion(&mut self) -> bool {
791 if let Some(_last_completion) = self.pending_completions.pop() {
792 true
793 } else {
794 false
795 }
796 }
797}
798
799#[derive(Debug, Clone)]
800pub enum ThreadError {
801 PaymentRequired,
802 MaxMonthlySpendReached,
803 Message(SharedString),
804}
805
806#[derive(Debug, Clone)]
807pub enum ThreadEvent {
808 ShowError(ThreadError),
809 StreamedCompletion,
810 StreamedAssistantText(MessageId, String),
811 MessageAdded(MessageId),
812 MessageEdited(MessageId),
813 MessageDeleted(MessageId),
814 SummaryChanged,
815 UsePendingTools,
816 ToolFinished {
817 #[allow(unused)]
818 tool_use_id: LanguageModelToolUseId,
819 /// The pending tool use that corresponds to this tool.
820 pending_tool_use: Option<PendingToolUse>,
821 },
822}
823
824impl EventEmitter<ThreadEvent> for Thread {}
825
826struct PendingCompletion {
827 id: usize,
828 _task: Task<()>,
829}